0%

solidity | web3.py 的常用方法

为了当一个合格的 CV 工程师,我决定将常见的交互方法都写出来。

生成账户

1
2
3
4
5
6
from web3 import Web3
w3 = Web3(Web3.HTTPProvider(''))

def get_account():
account = w3.eth.account.create()
return account.address, account.key.hex()

交互「有无验证、有无ABI」

ERC1155 tokenID 的数量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from web3 import Web3

erc1155_abi = """
[{
"constant": true,
"inputs": [{"name": "who", "type": "address"},{"name":"id","type":"uint256"}],
"name": "balanceOf",
"outputs": [{"name": "", "type": "uint256"}],
"payable": false,
"stateMutability": "view",
"type": "function"
}]
"""

w3 = Web3(Web3.HTTPProvider(
'https://quaint-snowy-lake.base-goerli.discover.quiknode.pro/***/'))

contract = Web3.toChecksumAddress('***')
contract_ = w3.eth.contract(
address=Web3.toChecksumAddress(contract), abi=erc1155_abi)

def get_balance(address, id):
return contract_.functions.balanceOf(Web3.toChecksumAddress(address), id).call()

等待获取 log

1
2
3
4
5
from web3 import Web3
w3 = Web3(Web3.HTTPProvider(''))

def get_transaction(hash):
return w3.eth.wait_for_transaction_receipt(hash)
请我喝杯咖啡吧~