【问题标题】:Eth, how to call a deposit function from a smart contractEth,如何从智能合约中调用存款功能
【发布时间】:2020-07-31 08:10:54
【问题描述】:

我正在做一个项目,我需要将以太币从用户发送到智能合约,然后从智能合约发送到用户。智能合约是 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”?这可能吗?

非常感谢, 阿尔班

【问题讨论】:

    标签: transactions ethereum solidity smartcontracts web3py


    【解决方案1】:

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

    这里是一个如何调用合约函数的例子:

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

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

    根据您的应用程序,通常用户通过他们的网络浏览器调用合约,他们在其中使用 web3.js 连接了钱包。

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

    github.com/web3modal/web3modal

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2018-10-18
      • 2021-12-17
      • 2021-08-28
      • 2018-09-23
      • 2022-08-23
      • 2022-07-06
      • 1970-01-01
      • 2021-09-12
      相关资源
      最近更新 更多