blockchain | web3.py交互模板
exp:
from web3 import Web3
from web3.middleware import SignAndSendRawMiddlewareBuilder
import json
w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
if not w3.is_connected():
print('conn err')
exit(-1)
print('conn ok')
# 导入钱包
privateKey = '********************'
account = w3.eth.account.from_key(privateKey)
print(w3.eth.get_balance(account.address))
w3.middleware_onion.inject(SignAndSendRawMiddlewareBuilder.build(account), layer=0)
with open('contracts/Fht.json', 'r', encoding='utf-8') as f:
c = f.read()
data = json.loads(c)
abi = data['abi']
bytecode = data['bytecode']['object']
# 部署合约
option = {'from': account.address, 'gas': 1000000, 'gasPrice':10000000000}
contract = w3.eth.contract(abi=abi, bytecode=bytecode)
tx_hash = contract.constructor().transact(option)
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
# print(tx_receipt)
print(tx_receipt.contractAddress)
contract = w3.eth.contract(address=tx_receipt.contractAddress,abi=abi)
# 调用合约测试
a = [1,2,3]
b = [4,3,2,1]
tx_hash = contract.functions.EvalAdd(a, b).transact(option)
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
# print(tx_receipt)
print(contract.functions.result(0).call())
print(contract.functions.result(1).call())
print(contract.functions.result(2).call())
print(contract.functions.result(3).call())
tx_hash = contract.functions.EvalAdd([1], [99, 1]).transact(option)
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
print(contract.functions.EvalAdd([1], [99, 1]).call())
print(contract.functions.result(0).call())
print(contract.functions.result(1).call())
标签:functions,receipt,tx,py,blockchain,contract,web3,w3,print
From: https://www.cnblogs.com/Mz1-rc/p/18532638