There are very few Chinese materials about web3.py development on the market, and the quality of Chinese materials is also uneven, often skipping words, and it is difficult for novices to understand when they are just getting started. In addition to the prevalence of web3, everyone uses mirror and other decentralized websites instead of csdn, but compared with CSDN, it is difficult for search engines to include mirror articles, so this article is here.
RPC query: RPC Info
Third-party RPC:
- https://infura.io
- Alchemy - Blockchain API and Node Service | Ethereum, Polygon, Flow, Crypto.org + More
(Off topic, the currency issued by Alchemy has pulled 100x LOL!!)
Faucet: Coin Faucet · Ethereum Development with Go
Kovan faucet (0.01eth): kovan-testnet/faucet - Gitter
Kovan Chain-Link faucet (0.1eth; 10link): Faucets | Chainlink
Official documentation: Introduction — Web3.py 5.28.0 documentation
Chinese version documentation: Account Management — Ethereum Homestead Chinese Documentation 0.1 Documentation
0x00 Create Web3 object
from web3 import Web3,HTTPProvider
address = "0xBA56BE272416d6C2385F8e183D2647AFdE7Cf6eF"
kovan_network_rpc = "https://kovan.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"
web3 = Web3(HTTPProvider(kovan_network_rpc))
0x01 Query the main network account balance
balance = web3.fromWei(web3.eth.getBalance(address),"ether")
The smallest unit of ETH is wei, 1ETH=10^8wei
0x02 Query ERC-20-Token balance
Link-Kovan test i network contract address: 0xa36085F69e2889c224210F603D836748e7dC0088
Link's contract ABI has been searched for a long time, but I can't find it. Finally, I found out that the reason is that Link's contract is not open source on the Kovan test network. Here we can only use the standard ERC20 ABI
#返回带有EIP55校验和的给定地址
LINK_KOVAN_ADDRESS = Web3.toChecksumAddress('0xa36085F69e2889c224210F603D836748e7dC0088')
#加载abi文件,创建合约对象
token_contract = web3.eth.contract(address=LINK_KOVAN_ADDRESS,abi=ERC20_ABI)
#将wei转换为ether,并且使用call()调用abi中balanceOf函数 获取账户余额
balance = web3.fromWei(token_contract.functions.balanceOf(address).call(),"ether")
print(balance)
0x03 ETH transfer
def transfer_eth(target_address,amount,gas_price=100,gas_limit=21000):
#获取nonce nonce用于标记地址发起交易的顺序
nonce = web3.eth.getTransactionCount(address)
print(f"交易nonce:{nonce}")
payload = {
'nonce' : nonce,
'to' : target_address,
'value': web3.toWei(amount,'ether'),
'gas':gas_limit,
'gasPrice': web3.toWei(gas_price,'gwei'),
'from': address,
}
#交易签名
signed_tx = web3.eth.account.signTransaction(transaction_dict=payload,private_key=private_key)
#交易广播出去
tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)
#返回的hash是一个byte类型
return tx_hash
- value, you need to use web3.toWei() to convert to ether type data.
- gasPrice needs to use web3.toWei() to convert to gwei type data.
- web3.eth.getTransactionCount() get nonce
- web3.eth.account.signTransaction() transaction signature
- web3.eth.sendRawTransaction() broadcast transaction
ERC20-ABI: