Web3.py使用详解
作者:互联网
1、安装
pip install web3
2、使用Web3
测试提供商
from web3 import Web3, EthereumTesterProvider w3 = Web3(EthereumTesterProvider())
本地提供商
from web3 import Web3 # IPCProvider: w3 = Web3(Web3.IPCProvider(./path/to/geth.ipc)) # HTTPProvider: w3 = Web3(Web3.HTTPProvider(http://127.0.0.1:8545)) # WebsocketProvider: w3 = Web3(Web3.WebsocketProvider(wss://127.0.0.1:8546))
远程提供商
与以太坊区块链交互的最快方法是使用远程节点提供商,如Infura、Alchemy或QuickNode。您可以通过指定端点连接到远程节点,就像本地节点一样:
from web3 import Web3 w3 = Web3(Web3.HTTPProvider(https://<your-provider-url>)) w3 = Web3(Web3.WebsocketProvider(wss://<your-provider-url>))
判断连接状态
w3.isConnected()
3、创建账户
使用web3创建账户
account = w3.eth.account.create() print(account.address)
使用eth_account创建账户
效果与 web3 一致,安装web3.py会自动安装 eth-account
from eth_account import Account account = Account.create() print(account.address) # 账户的私钥 print(account.key.hex())
通过private_key导入账户
from eth_account import Account import json key = ... account = Account.from_key(key) print(account.address)
获取账户列表
accounts = w3.eth.accounts
获取默认账户
w3.eth.default_account
4、常用方法
获取最新区块
w3.eth.get_block(latest)
获取区块数量
w3.eth.block_number
获取区块交易
w3.eth.get_transaction_by_block(46147, 0)
获取余额
balance = w3.eth.getBalance(account)
发送转账交易
params = { from:accounts[0], to:accounts[1], value:w3.toWei(1, "ether") } tx_hash = w3.eth.sendTransaction(params)
获取交易信息
tx = w3.eth.getTransaction(tx_hash)
获取交易收据
如果交易处于pending状态,则返回null。
tx = w3.eth.getTransactionReceipt(tx_hash)
获取Nonce
nonce = w3.eth.getTransactionCount(account)
5、合约调用
合约实例化
filePath = "../contracts/usdt.json" text = open(filePath, encoding=utf-8).read() jsonObj = json.loads(text) usdt_contract_addr = 合约地址 usdt = w3.eth.contract(address=usdt_contract_addr, abi=jsonObj[abi])
合约读操作
balance = usdt.functions.balanceOf(accounts[0]).call()
合约写操作
option = { from: accounts[0], gas: 1000000 } usdt.functions.approve(usdt_contract_addr, 2000000).transact(option)
带签名的合约写操作
options = { gas: 1000000, gasPrice: w3.toWei(21, gwei), from: account.address, nonce: w3.eth.getTransactionCount(account.address) } tx = usdt.functions.approve(usdt_contract_addr, 2000000).buildTransaction(options) signed = account.signTransaction(tx) # 用账户对交易签名 tx_id = w3.eth.sendRawTransaction(signed.rawTransaction) # 交易发送并获取交易id print(tx_id.hex())