首先安裝 web3 API
pip install web3
正文開(kāi)始
導(dǎo)入module
from web3 import Web3, HTTPProvider
首先獲取web3實(shí)例,這里使用HTTP方式連接自己的私鏈
node_url = 'http://127.0.0.1:8545'
web3_client = Web3(HTTPProvider(node_url))
準(zhǔn)備工作完成买优,接下來(lái)進(jìn)行具體操作
1.getTransaction()
trade_hash = '0x........'? ? #你的txid
web3_client.eth.getTransaction(trade_hash)
2.getBlock()
blockNumber = 10? ? #你的blockNumber
web3_client.eth.getBlock(blockNumber)
3.查看賬戶余額 getBalance()
注意:和下一步一樣妨马,這個(gè)方法中要用到地址。而web3.py 中所有用到地址的地方杀赢,不能直接傳入地址烘跺,需要用toChecksumAddress()轉(zhuǎn)一下
address = '0x....................'? ? #你的eth地址
checksum_address = Web3.toChecksumAddress(address)
balance = web3_client.eth.getBalance(checksum_address)
4.在兩個(gè)地址之間發(fā)起轉(zhuǎn)賬 sendTransaction()
轉(zhuǎn)賬是需要用到from_address的私鑰的,在轉(zhuǎn)賬以前脂崔,需要unlockAccount(), 我們這里用 personal.sendTransaction(),理由是滤淳,在sendTransaction方法調(diào)用時(shí),from賬戶并未在節(jié)點(diǎn)中全局解鎖 (僅在該調(diào)用內(nèi)解鎖)砌左,更加安全脖咐,也因?yàn)檫@個(gè)原因,from賬戶不能用于其他RPC調(diào)用绊困。
同樣的文搂,這個(gè)方法里的from_address 和 to_address 也要用上面的 toChecksumAddress() 轉(zhuǎn)一下
from_address = '0x................'? ? #你的 from_address
to_address='0x.................'? ? #你的 to_address
private_secret = '0x............'? ? # from_address 的私鑰,在 python 腳本中使用 web3 轉(zhuǎn)賬時(shí)秤朗,這里有泄露密鑰的危險(xiǎn)煤蹭,在生產(chǎn)環(huán)境中注意配置抽離
import math
value = 0.123 * math.pow(10,18)? ? #單位是 wei, 1 ETH = 10^18 wei
web3_client.geth.personal.sendTransaction({
? ? ? ? ? ? ? ? "from":Web3.toChecksumAddress(from_address),
? ? ? ? ? ? ? ? "to":Web3.toChecksumAddress(to_address),
? ? ? ? ? ? ? ? "value":int(value)
? ? ? ? ? ? ? ? },private_secret)