blockchain | web3.py交互模板
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())
本文来自博客园,作者:Mz1,转载请注明原文链接:https://www.cnblogs.com/Mz1-rc/p/18532638
如果有问题可以在下方评论或者email:mzi_mzi@163.com
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)