Web3.py
API文档:https://web3py.readthedocs.io/en/stable/index.html
1. 安装
注意安装时如果出错,可能需要先安装c++
pip install web3
2. 使用
2.1 连接
- RPC
RPC是远端过程调用。每个类evm的公链都有很多RPC,当你不知道某公链的RPC,可以去 chainlist.org 搜索,连接小狐狸钱包即可很快速的添加你想要的公链RPC。
Chain | RPC |
---|---|
Ethereum | https://cloudflare-eth.com |
Ploygon | https://rpc-mainnet.matic.network |
BSC | https://bsc-dataseed1.binance.org:443 |
from web3 import Web3
rpc = "填入rpc地址"
web3 = Web3(Web3.HTTPProvider(rpc))
# 查看链接状态 返回bool值
print(web3.isConnected())
2.2 查询余额
from web3 import Web3
rpc = '填入rpc地址'
web3 = Web3(Web3.HTTPProvider(rpc))
address = '查询的钱包地址'
balance = web3.fromWei(web3.eth.getBalance(address), "ether")
print(balance)
2.3 查询 ERC-20 Token
from web3 import Web3
import json
rpc = '填入rpc地址'
web3 = Web3(Web3.HTTPProvider(rpc))
address = '查询的钱包地址'
contract_address = Web3.toChecksumAddress('合约地址(hash值)')
contract_abi = json.loads('合约的ABI')
token_contract = web3.eth.contract(address=contract_address, abi=contract_abi)
balance = web3.fromWei(token_contract.functions.balanceOf(address).call(), "ether")
print(balance)
- ERC20代币非常多,所以如果要查询代币余额,首先要有该代币的合约地址,代币合约地址我相信大部分人都会查询,可以查询自己的钱包记录,也可以去cmc等网站查询代币合约地址。
然后我们还需要一些代币的ABI,这个ABI如何找呢,我们可以通过代币地址的合约代码去查看。
2.4 转账
rpc = '填入rpc地址'
web3 = Web3(Web3.HTTPProvider(rpc))
# 将地址1的钱转到地址2
send_address = "地址1"
private_key = "..." # 地址1的 private_key
target_address = "地址2"
nonce = web3.eth.getTransactionCount(send_address)
params = {
'nonce': nonce,
'to': target_address,
'value': web3.toWei(amount, 'ether'),
'gas': gas_limit,
'gasPrice': web3.toWei(gas_price, 'gwei'),
'from': send_address
}
# 'from'可以省略
# sign transaction
signed_tx = web3.eth.account.signTransaction(params, private_key=private_key)
# send transaction
tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)
# get transaction hash
web3.toHex(tx_hash)
target_address就是转账目标的地址也就是收款方,amount就是转账数量,gas_price和 gas_limit是用来计算gas使用。其他网络gas费用浮动较大,需要查看当时的gas来填写。
nonce你可以理解为是你的钱包的一个顺序,我们可以按一定的顺序发送交易,也可以覆盖交易。
private_key参数就是你的钱包私钥。一定要找一个不常用的钱包哦,因为复制私钥十分危险,一定要安全第一。
最后我们会获得一个tx_hash,这个就是区块链记录的哈希值了。我们可以等待交易成功后,查看该tx的记录。
2.4 转账 ERC20的Token
rpc = '填入rpc地址'
web3 = Web3(Web3.HTTPProvider(rpc))
params = {
"nonce": web3.eth.getTransactionCount(send_address),
"value": 0,
'gasPrice': web3.toWei(gas_price, 'gwei'),
"gas": gas_limit,
"from": send_address
}
func = token_contract.functions.transfer(target_address, web3.toWei(amount, "ether"))
tx = func.buildTransaction(params)
signed_tx = web3.eth.account.sign_transaction(tx, private_key=private_key)
tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)
2.5 访问合约
# 简单的合约
pragma solidity ^8.0.0
contract Test {
string public words;
function f1() public {
words = "Hello World";
}
function setF2(string _words) public {
words = _words;
}
function getF1() view public return (string) {
return words;
}
}
# .py
rpc = "代理节点"
web3 = Web3(Web3.HTTPProvider(rpc))
web3.eth.defaultAccount = web3.eth.accounts[0] # 发送者,ganache账号,已经解锁了秘钥
abi = json.load('合约的 abi')
address = web3.toChecksumAddress("合约地址0x") # 此处检查格式
contract = web3.eth.contract(address=address, abi=abi)
contract.functions.getF1().call() # 呼叫合约方法,getF1()为合约内的方法.(用于呼叫一些查询方法)
tx_hash = contract.functions.setF2('input something').transact() # 写入方法,setF2()为合约内能接收的方法
web3.eth.waitForTransactionReceipt(tx_hash) # 等待接收到hash后
print('Updated: {}'.format(
contract.functions.getF1().call()
))