pip install 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()
account = w3.eth.account.create() print(account.address)
效果与 web3 一致,安装web3.py会自动安装 eth-account
from eth_account import Account account = Account.create() print(account.address) # 账户的私钥 print(account.key.hex())
from eth_account import Account import json key = ... account = Account.from_key(key) print(account.address)
accounts = w3.eth.accounts
w3.eth.default_account
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 = w3.eth.getTransactionCount(account)
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())