如何使用 Python 和 web3.py 调用智能合约函数

Mol*_*owa 4 python blockchain ethereum web3-donotuse

我在以太坊测试网络上部署了一个合约,其中包含一些功能,并且它们在使用 Remix 界面时都可以正常工作。当尝试在 Python 中使用 web3.py 调用这些函数时,我只能调用公共函数并且该部分工作正常。问题是调用具有“限制”的函数,例如具有“所有者要求”,这意味着只有创建合约的地址才能调用该特定函数。我已经谷歌搜索但没有运气。我猜我应该在调用该函数时同时使用该以太坊帐户的“地址”和“密码”作为参数,但我不知道该怎么做。函数称为“set()”,它只需要 2 个字符串值。

这是 Solidity 代码的一部分,它使函数“set()”只能由该合约的所有者访问。

constructor() public {
    owner = msg.sender;
}

modifier onlyOwner() {
    require(msg.sender == owner);
    _;
}

function set(string memory _lastHash,
             string memory _fullHash) public onlyOwner {
    lastHash = _lastHash;
    fullHash = _fullHash;
}
Run Code Online (Sandbox Code Playgroud)

这是我用来从我没有包括的其他 2 个函数中获取返回值的 python 函数:

data = contract.functions.getFullHash().call()
Run Code Online (Sandbox Code Playgroud)

函数称为“getFullHash()”。给定的 Python 代码不适用于函数“set()”。

Mol*_*owa 5

因为我原来的评论被删除了,所以我会最后发一次。

我已经按照此链接上提供的说明设法做到了。这是对我有用的代码:

transaction = contract.functions.set(
    'string1',
    'string2' ).buildTransaction({
    'gas': 70000,
    'gasPrice': web3.toWei('1', 'gwei'),
    'from': adress,
    'nonce': nonce
    }) 
private_key = "enter_your_key_here" 
signed_txn = web3.eth.account.signTransaction(transaction, private_key=private_key)
web3.eth.sendRawTransaction(signed_txn.rawTransaction)
Run Code Online (Sandbox Code Playgroud)

我在某处读到 Infura 只接受原始签名交易,不确定它是否属实,但它是这样工作的。