在 python 中与 ganache-cli 同步

Sync with ganache-cli in python

我想测试一个简单的以太坊智能合约 ganache 以小写形式打印帐户,web3 给我一个错误:

web3.exceptions.InvalidAddress: ('Web3.py only accepts checksum addresses. The software that gave you this non-checksum address should be considered unsafe, please file it as a bug on their platform. Try using an ENS name instead. Or, if you must accept lower safety, use Web3.toChecksumAddress(lower_case_address).', '0xfcad0b19bb29d4674531d6f115237e16afce377c')

然后我使用以下方法将地址转换为混合地址:

Web3.toChecksumAddress(the_lower_case_ganache_address)

然后出现错误:

File "/usr/local/lib/python3.7/site-packages/web3/contract.py", line 1385, in call_contract_function raise BadFunctionCallOutput(msg) from e web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced? 127.0.0.1 - - [25/Jan/2019 21:35:21] "POST /blockchain/user HTTP/1.1" 500 -

这是我的 python 代码:

def check_gender(data):
    valid_list = ["male", "female"]
    if data not in valid_list:
        raise ValidationError(
            'Invalid gender. Valid choices are'+ valid_list
        )

class UserSchema(Schema):
    name = fields.String(required=True)
    gender = fields.String(required=True, validate=check_gender)


app = Flask(__name__)


# api to set new user every api call
@app.route("/blockchain/user", methods=['POST'])
def transaction():

    w3.eth.defaultAccount = w3.eth.accounts[0]
    with open("data.json", 'r') as f:
        datastore = json.load(f)
    abi = datastore["abi"]
    contract_address = datastore["contract_address"]

    # Create the contract instance with the newly-deployed address
    user = w3.eth.contract(
        address=contract_address, abi=abi,
    )
    body = request.get_json()
    result, error = UserSchema().load(body)
    if error:        
        return jsonify(error), 422
    tx_hash = user.functions.setUser(
        result['name'], result['gender']
    )
    tx_hash = tx_hash.transact()
    # Wait for transaction to be mined...
    w3.eth.waitForTransactionReceipt(tx_hash)
    user_data = user.functions.getUser().call()
    return jsonify({"data": user_data}), 200



if __name__ == '__main__':
    app.run()

` 和 json 文件:

{
    "abi": [
        {
            "constant": false,
            "inputs": [
                {
                    "name": "name",
                    "type": "string"
                },
                {
                    "name": "gender",
                    "type": "string"
                }
            ],
            "name": "setUser",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        },
        {
            "constant": false,
            "inputs": [],
            "name": "getUser",
            "outputs": [
                {
                    "name": "",
                    "type": "string"
                },
                {
                    "name": "",
                    "type": "string"
                }
            ],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }
    ],
    "contract_address": "0xFCAd0B19bB29D4674531d6f115237E16AfCE377c"
}

错误表明 Ganache 找不到要与之交互的已部署合约。

您的代码似乎有效,但错误可能发生在这一行:

tx_hash = user.functions.setUser(
    result['name'], result['gender']
)

代码尝试设置用户,但找不到与之交互的合约(即使 ABI 和合约实例有效)。

如果您使用的是 Ganache,很可能每次 运行 代码时您都在重新部署合约,因此如果您从静态文件中提取,则以下行可能无法正常工作:

contract_address = datastore["contract_address"]

每次部署都需要从Ganache动态获取合约地址