再次,如何从智能合约中调用存款功能

时间:2020-04-17 18:21:38

标签: transactions ethereum solidity smartcontracts web3py

我正在一个项目中,我需要将以太币从用户发送到智能合约,再从智能合约发送到用户。智能合约是Solidity中的代码,我正在使用python和web3.py与之通信。

我设法做到这一点: 从用户到我的python脚本中的智能合约:

#send transaction to the smart contract
web3.eth.sendTransaction({
    'to': address,
    'from': web3.eth.defaultAccount,
    'value': 10000000000000000000
})

从智能合约到使用此功能的用户:

function sendEther(address payable recipient, int _amount) public payable {
        recipient.transfer(_amout ether);
    }

请注意,可以在智能合约中调用此功能。

但是后来我想在我的智能合约中创建功能存储(从用户到智能合约):

function deposit(uint256 amount) payable public {
        require(msg.value == amount);
        // nothing else to do!
    }

因此,基本上,如果我需要使用python脚本调用此函数,则需要这样进行:

contract.functions.deposit(10).transac({
        'to': address,
        'from': web3.eth.defaultAccount,
        'value': 10
    })

通过检查智能合约的余额,它可以正常工作。

但是,如果我想在智能合约中调用存款功能并进行从用户到智能合约的交易,该怎么办?调用内部函数时,如何解析智能合约中的“ msg.value”?那有可能吗?

非常感谢, 奥尔本

1 个答案:

答案 0 :(得分:0)

您需要从由Solidity编译器创建的ABI文件中构造一个Contract对象。

以下是如何调用合约函数的示例:

>>> tx_hash = greeter.functions.setGreeting('Nihao').transact()

https://web3py.readthedocs.io/en/stable/contracts.html#contract-deployment-example

根据您的应用程序,通常用户会通过Web浏览器调用合同,在那里他们使用web3.js连接了一个钱包。

这是一个不错的库,如何将dApp与用户钱包连接起来:

github.com/web3modal/web3modal