Contract-Invocation
Web3.py - 當 solc 不起作用時如何在 python 中使用 abi
我有一個智能合約,我用松露(使用 Javascript)部署到 Ropsten 測試網路。我希望能夠從我用 Python 編寫的伺服器向它發送事務。我一直在嘗試關注:http ://web3py.readthedocs.io/en/stable/web3.eth.html#web3.eth.Eth.contract
from web3 import Web3, HTTPProvider import json provider = HTTPProvider('https://ropsten.infura.io/<Redacted Key>') w3 = Web3(provider) assert w3.isConnected() pdb.set_trace() abi = str(<Here I am pasting my abi in. How should I do this, since I didn't build the contract in Python?> escrow = w3.eth.contract(address='0x8850259566e9d03a1524e35687db2c78d4003409', abi=abi)
…當我到達這一行時,程序崩潰了:
File "/usr/local/lib/python3.6/dist-packages/web3/eth.py", line 351, in contract ContractFactory = ContractFactoryClass.factory(self.web3, **kwargs) File "/usr/local/lib/python3.6/dist-packages/web3/contract.py", line 225, in factory normalizers=normalizers) File "/usr/local/lib/python3.6/dist-packages/web3/utils/datatypes.py", line 36, in __new__ namespace) File "cytoolz/functoolz.pyx", line 236, in cytoolz.functoolz.curry.__call__ File "cytoolz/functoolz.pyx", line 232, in cytoolz.functoolz.curry.__call__ File "/usr/local/lib/python3.6/dist-packages/eth_utils/functional.py", line 22, in inner return callback(fn(*args, **kwargs)) File "/usr/local/lib/python3.6/dist-packages/web3/utils/formatters.py", line 69, in apply_formatters_to_dict raise type(exc)("Could not format value %r as field %r" % (item, key)) from exc TypeError: __init__() missing 2 required positional arguments: 'doc' and 'pos'
您需要將 abi 作為字典而不是字元串提供。由於 ABI 是 json 編碼的,因此您需要使用
json.loads
或類似的方式對其進行解析。您還應該直接從 truffle 生成的合約 json 文件中讀取它。這可確保您不會意外使用舊的 ABI。這是我所做的:
from web3 import Web3, HTTPProvider import json with open("build/Contracts/YourContract.json") as f: info_json = json.load(f) abi = info_json["abi"] w3 = Web3(HTTPProvider("https://...")) escrow = w3.eth.contract(address='0x8850259566e9d03a1524e35687db2c78d4003409', abi=abi)