:2026-03-05 19:45 点击:1
Python赋能以太坊:轻松实现与区块链的交互**
以太坊作为全球领先的智能合约平台,其去中心化应用(DApps)和代币生态系统的蓬勃发展,吸引了开发者的广泛关注,而Python,以其简洁的语法、丰富的库生态和强大的社区支持,成为了与以太坊区块链进行交互的热门选择,本文将详细介绍如何使用Python访问以太坊,涵盖环境搭建、连接节点、读取数据以及发送交易等核心操作。
在开始之前,我们先了解一下为何Python在以太坊开发中备受青睐:
要使用Python访问以太坊,我们需要准备以下环境和工具:
Python环境:确保你的系统已安装Python 3.6或更高版本,推荐使用虚拟环境(如venv或conda)来管理项目依赖。
python -m venv eth_env source eth_env/bin/activate # Linux/Mac # 或 eth_env\Scripts\activate # Windows
以太坊节点:
https://mainnet.infura.io/v3/YOUR_PROJECT_ID)。Python库安装:最核心的库是web3.py,它提供了与以太坊节点进行JSON-RPC通信的完整接口。
pip install web3
根据你的需求,可能还需要安装其他辅助库,如eth-account用于签名交易,py-solc-x用于编译Solidity智能合约等。
web3.py是Python访问以太坊的基石,我们需要创建一个Web3实例并连接到以太坊节点。
from web3 import Web3
infura_url = "https://mainnet.infura.io/v3/YOUR_PROJECT_ID"
# 或者本地节点
# local_node_url = "http://127.0.0.1:8545"
# 创建Web3实例
w3 = Web3(Web3.HTTPProvider(infura_url))
# 检查连接是否成功
if w3.is_connected():
print("成功连接到以太坊节点!")
print(f"当前区块号: {w3.eth.block_number}")
else:
print("连接失败!")
连接成功后,我们可以轻松读取以太坊上的各种数据:
获取账户余额:
# 替换为要查询的以太坊地址
address = "0x742d35Cc6634C0532925a3b844Bc9e7595f8e9A8"
# 地址需要是校验过的格式(checksummed)
checksum_address = w3.to_checksum_address(address)
# 获取余额(单位:Wei)
balance_wei = w3.eth.get_balance(checksum_address)
# 将Wei转换为Ether
balance_eth = w3.from_wei(balance_wei, 'ether')
print(f"地址 {checksum_address} 的余额是: {balance_eth} ETH")
获取交易信息:
# 替换为交易哈希
tx_hash = "0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060"
tx = w3.eth.get_transaction(tx_hash)
print(f"交易发送方: {tx['from']}")
print(f"交易接收方: {tx['to']}")
print(f"交易金额: {w3.from_wei(tx['value'], 'ether')} ETH")
print(f"Gas价格: {w3.from_wei(tx['gasPrice'], 'gwei')} Gwei")
获取区块信息:
# 获取最新区块信息
latest_block = w3.eth.get_block('latest')
print(f"最新区块号: {latest_block.number}")
print(f"最新区块时间戳: {latest_block.timestamp}")
print(f"最新区块交易数量: {len(latest_block.transactions)}")
# 获取特定区块号的信息
block_number = 12345678 # 替换为感兴趣的区块号
specific_block = w3.eth.get_block(block_number)
print(f"区块 {block_number} 的哈希: {specific_block.hash.hex()}")
与智能合约交互(读取): 要与智能合约交互,需要合约的ABI(Application Binary Interface)和合约地址。
# 假设我们有一个简单的ERC20代币合约
contract_address = "0xYourContractAddress" # 替换为合约地址
contract_abi = [...] # 替换为合约ABI,这是一个JSON格式的列表
# 创建合约实例
contract = w3.eth.contract(address=contract_address, abi=contract_abi)
# 调用合约的读取方法(不消耗Gas)
# 调用totalSupply()方法
total_supply = contract.functions.totalSupply().call()
print(f"代币总供应量: {w3.from_wei(total_supply, 'ether')} Token")
# 调用balanceOf(address)方法
user_balance = contract.functions.balanceOf(checksum_address).call()
print(f"地址 {checksum_address} 的代币余额: {w3.from_wei(user_balance, 'ether')} Token")
除了读取数据,Python还可以用来发送交易,从而修改以太坊的状态(转账、调用合约的写入方法),发送交易需要签名,通常需要私钥。
⚠️ 警告:私钥极度敏感,切勿泄露或在代码中硬编码!建议使用环境变量或安全的密钥管理工具。
发送ETH转账:
from eth_account import Account
# 替换为发送方的私钥(仅用于演示,实际请妥善保管!)
private_key = "0xYourPrivateKey"
sender_address = Account.from_key(private_key).address
sender_address_checksum = w3.to_checksum_address(sender_address)
# 接收方地址
receiver_address = w3.to_checksum_address("0xReceiverAddress")
# 获取nonce(确保交易唯一性)
nonce = w3.eth.get_transaction_count(sender_address_checksum)
# 构建交易
tx = {
'nonce': nonce,
'to': receiver_address,
'value': w3.to_wei(0.01, 'ether'), # 转账0.01 ETH
'gas': 21000, # 转账ETH的最低Gas limit
'gasPrice': w3.to_wei(20, 'gwei'), # Gas价格,可根据网络状况调整
'chainId': 1, # 主网chainId,测试网请对应修改(如Ropsten为3)
}
# 签名交易
signed_tx = w3.eth.account.sign_transaction(tx, private_key)
# 发送交易
tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
# 等待交易被打包
print(f"交易已发送,哈希: {tx_hash.hex()}")
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
print(f"交易收据: {receipt}")
调用智能合约的写入方法: 调用合约的写入方法(会修改状态)也需要发送交易。
# 使用前面创建的合约实例
# 假设合约有一个transfer(to, amount)方法
# 接收代币的地址和转账数量(以合约的最小单位表示)
to_address = w3.to_checksum_address("0xAnotherAddress")
transfer_amount = 1000 * 10**
本文由用户投稿上传,若侵权请提供版权资料并联系删除!