Web3.py 区块链开发指南:web3.eth API 详解

Web3.py 区块链开发指南:web3.eth API 详解

【免费下载链接】web3.py A python interface for interacting with the Ethereum blockchain and ecosystem. 【免费下载链接】web3.py 项目地址: https://gitcode.com/gh_mirrors/we/web3.py

概述

Web3.py 是区块链生态中最重要的 Python 开发库之一,其中的 web3.eth 模块提供了与区块链网络交互的核心功能。本文将深入解析 web3.eth 模块的属性和方法,帮助开发者更好地理解和使用这一强大的工具。

核心特性

AttributeDict 数据结构

web3.eth 模块返回的数据默认采用 AttributeDict 结构,这是一种特殊的字典类型:

block = web3.eth.get_block('latest')
print(block.number)  # 属性访问方式
print(block['number'])  # 字典访问方式

特点:

  • 支持属性式访问(如 block.number
  • 不可变性(防止意外修改数据)
  • 基于 AttributeDictMiddleware 中间件实现

注意:属性访问方式会破坏类型提示,对类型敏感的应用建议使用字典访问方式或移除中间件。

主要属性

基础配置属性

  1. default_account:默认交易发送地址
  2. default_block:默认区块标识符(默认为 'latest')

区块链状态属性

  1. syncing:返回节点同步状态(False 或同步进度字典)

    {
        'currentBlock': 2177557,
        'highestBlock': 2211611,
        'startingBlock': 2177365
    }
    
  2. max_priority_fee:动态交易的建议优先费(Wei)

  3. gas_price:当前 gas 价格(Wei)

  4. accounts:节点管理的账户列表

  5. block_number:最新区块号(get_block_number() 的别名)

  6. chain_id:当前链 ID(EIP-155 引入)

新增属性

blob_base_fee:获取下一个区块中 blob 的预期基础费用(Wei)

核心方法

账户相关方法

  1. get_balance(account, block_identifier):获取账户余额

    • 支持 ENS 名称
    • 可指定区块
  2. get_storage_at(account, position, block_identifier):读取合约存储

    • 返回指定存储位置的值
  3. get_code(account, block_identifier):获取合约字节码

    • 普通账户返回 '0x'

区块相关方法

  1. get_block(block_identifier, full_transactions=False):获取区块信息

    • full_transactions 控制返回完整交易还是仅哈希
    • 自动识别区块号或哈希
  2. get_block_transaction_count(block_identifier):获取区块交易数

    • 支持区块号或哈希
  3. get_uncle_by_block(block_identifier, uncle_index)(已弃用):获取叔块信息

高级功能

  1. get_proof(account, positions, block_identifier):获取 Merkle 证明
    • 返回账户状态和存储证明
    • 可用于验证状态数据
proof = web3.eth.get_proof(contract_address, [0], block_number)
# 使用 py-trie 验证证明
verify_eth_get_proof(proof, block.stateRoot)

最佳实践

  1. 链 ID 缓存:频繁访问 chain_id 时可启用请求缓存

    w3.provider.cache_allowed_requests = True
    
  2. 区块查询优化:明确指定需要的数据(如是否获取完整交易)

  3. 状态验证:使用 get_proof 进行轻客户端验证时,确保正确实现验证逻辑

总结

web3.eth 模块是 Web3.py 与区块链交互的核心,提供了从基础查询到高级验证的完整功能集。理解这些 API 的特性和最佳实践,将帮助开发者构建更高效、可靠的区块链应用。随着区块链技术的演进,API 也会不断更新,建议开发者关注最新变化以利用新特性。

【免费下载链接】web3.py A python interface for interacting with the Ethereum blockchain and ecosystem. 【免费下载链接】web3.py 项目地址: https://gitcode.com/gh_mirrors/we/web3.py

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值