如何使用Python和web3.py调用智能合约功能 [英] How to call a Smart Contract function using Python and web3.py

查看:242
本文介绍了如何使用Python和web3.py调用智能合约功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a contract deployed on Ethereum test network which has some functions in it and they all happen to work while using the Remix interface. When trying to call those functions using web3.py in Python, I'm able to call only for public functions and that part works fine. The problem is calling a function with a "restriction" such as having an "owner requirement", meaning only the address which created the contract can call that specific function. I've Googled it but no luck. I'm guessing that I am supposed to use both the "address" and the "password" for that Ethereum account as parameters when calling the function but I have no idea how to do it. Function is called "set()" and it takes only 2 string values.

此处是Solidity代码的一部分,该部分使函数"set()"仅可由该合同的所有者访问.

Here is the part of Solidity code which makes the function "set()" accessible only by the owner of this contract.

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;
}

这是我正在使用的python函数,用于从我未包括的其他2个函数中获取返回值:

Here is the python function which i'm using to get the return values from the other 2 functions which i've not included:

data = contract.functions.getFullHash().call()

该函数称为"getFullHash()".给定的Python代码不适用于功能"set()".

Function is called "getFullHash()". Given Python code doesn't work with the function "set()".

推荐答案

由于我的原始评论已删除,因此我将在最后一次发布.

Since my original comment got deleted I'll post it one last time.

我已经按照

I've managed to do it with the instructions provided on this link. Here is the code that worked for me:

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)

我在某处读到Infura仅接受原始签名的交易,不确定它是否属实,但这种方式起作用.

I read somewhere that Infura only accepts raw signed transactions, not sure if its true but it worked this way.

这篇关于如何使用Python和web3.py调用智能合约功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆