当前位置: 首页 > article >正文

Web3.py 入门笔记

Web3.py 学习笔记 📚

https://web3py.readthedocs.io/en/stable/

1. Web3.py 简介 🌟

Web3.py 是一个 Python 库,用于与以太坊区块链进行交互。它就像是连接 Python 程序和以太坊网络的桥梁。

官方文档

1.1 主要功能

  • 查询区块链数据(余额、交易等)
  • 发送交易
  • 与智能合约交互
  • 管理以太坊账户

2. 安装和配置 🔧

2.1 安装

# 使用 pip 安装
pip install web3

# 或使用 conda 安装
conda install -c conda-forge web3

2.2 基础配置

from web3 import Web3

# 连接到以太坊网络(这里使用 Infura 提供的节点)
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID'))

# 检查是否连接成功
print(f"是否连接成功: {w3.is_connected()}")

3. 基础操作示例 💡

3.1 查询账户余额

def check_eth_balance(address):
    # 确保地址格式正确
    if not w3.is_address(address):
        return "无效的以太坊地址"
    
    # 获取余额(单位:Wei)
    balance_wei = w3.eth.get_balance(address)
    # 转换为 ETH(1 ETH = 10^18 Wei)
    balance_eth = w3.from_wei(balance_wei, 'ether')
    
    return f"地址余额: {balance_eth} ETH"

# 使用示例
address = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e"
print(check_eth_balance(address))

3.2 创建新钱包

from eth_account import Account
import secrets

def create_new_wallet():
    # 生成随机私钥
    private_key = secrets.token_hex(32)
    account = Account.from_key(private_key)
    
    return {
        "address": account.address,
        "private_key": private_key
    }

# 使用示例
wallet = create_new_wallet()
print(f"钱包地址: {wallet['address']}")
print(f"私钥: {wallet['private_key']}")

3.3 查询区块信息

def get_block_info(block_number='latest'):
    # 获取区块信息
    block = w3.eth.get_block(block_number)
    
    info = {
        "区块号": block.number,
        "时间戳": block.timestamp,
        "交易数量": len(block.transactions),
        "矿工地址": block.miner,
        "难度": block.difficulty
    }
    
    return info

# 使用示例
print(get_block_info())

4. 实用工具函数 🛠️

4.1 单位转换

# Wei 转换为 ETH
wei_amount = 1000000000000000000  # 1 ETH
eth_amount = w3.from_wei(wei_amount, 'ether')
print(f"{wei_amount} Wei = {eth_amount} ETH")

# ETH 转换为 Wei
eth_amount = 2.5
wei_amount = w3.to_wei(eth_amount, 'ether')
print(f"{eth_amount} ETH = {wei_amount} Wei")

4.2 地址验证

def is_valid_address(address):
    """验证以太坊地址是否有效"""
    return w3.is_address(address)

# 使用示例
address = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e"
print(f"地址是否有效: {is_valid_address(address)}")

5. 监控交易示例 👀

def monitor_transactions(address, num_blocks=10):
    """监控指定地址的最近交易"""
    current_block = w3.eth.block_number
    
    for block_num in range(current_block - num_blocks, current_block + 1):
        block = w3.eth.get_block(block_num, full_transactions=True)
        
        for tx in block.transactions:
            if tx['from'].lower() == address.lower() or tx['to'].lower() == address.lower():
                print(f"\n发现交易:")
                print(f"交易哈希: {tx['hash'].hex()}")
                print(f"从: {tx['from']}")
                print(f"到: {tx['to']}")
                print(f"数量: {w3.from_wei(tx['value'], 'ether')} ETH")

# 使用示例
address = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e"
monitor_transactions(address)

6. 注意事项 ⚠️

  1. 安全提示:

    • 永远不要在代码中直接写入私钥
    • 使用环境变量存储敏感信息
    • 重要操作先在测试网络验证
  2. 性能建议:

    • 批量查询时注意请求频率
    • 适当使用缓存
    • 处理好异常情况
  3. 成本考虑:

    • 注意 gas 费用
    • 监控网络拥堵情况
    • 合理设置 gas 价格

7. 常见问题解答 ❓

  1. 连接失败:

    • 检查网络连接
    • 验证 Infura Project ID
    • 确认节点服务是否可用
  2. 交易失败:

    • 确保有足够的 ETH 支付 gas
    • 检查 nonce 值是否正确
    • 验证 gas 价格是否合理

8. 学习资源 📚

  1. 官方文档:

    • Web3.py 文档
    • 以太坊开发者文档
  2. 工具网站:

    • Etherscan - 交易浏览器
    • Infura - 节点服务
    • Remix - 在线 IDE
  3. 测试网络:

    • Goerli
    • Sepolia
    • Mumbai(Polygon 测试网)

http://www.kler.cn/a/566529.html

相关文章:

  • 用大白话解释基础框架Spring Boot——像“装修套餐”一样简单
  • 2025年如何实现安卓、iOS、鸿蒙跨平台开发
  • vscode中使用PlatformIO创建工程加载慢
  • xss自动化扫描工具-DALFox
  • 阿里云的 ECS(Elastic Compute Service)实例
  • CD9.【C++ Dev】对“auto替换为变量实际的类型”的解释
  • AI大模型-提示工程学习笔记18—推理与行动的协同 (ReAct)
  • Go语言学习笔记(四)
  • idea导入新项目pom报错设置
  • PHP面试题--后端部分
  • MyBatis教程
  • 本地部署Deepseek+Cherry Studio
  • sklearn中的决策树-分类树:实例-分类树在合成数据集上的表现
  • 【MySQL】服务正在启动或停止中,请稍候片刻后再试一次【解决方案】
  • 2025中建二测笔试考什么?北森题库考点复习|附精华备考面试攻略
  • TCP/IP 5层协议簇:物理层
  • 重构清洁想象,石头科技首创五轴仿生机械手打破传统清洁边界
  • 自回归与自监督分别是什么,区别是什么
  • MySQL 索引介绍
  • 15.14 QLoRA量化低秩适配微调:华盛顿大学的显存优化革命