【问题标题】:How to set the receiver of ETH in a contract to send ETH from one address to another with solidity usign call() in remix IDE如何在合约中设置 ETH 的接收者,以在 remix IDE 中使用solidity usign call() 将 ETH 从一个地址发送到另一个地址
【发布时间】:2021-12-25 20:59:46
【问题描述】:

我开始学习solidity,并且我正在尝试构建一个sendEther 合约,其中某个地址将一定数量的以太币发送到另一个地址。我在 remix 上构建它,但在设置接收器地址时遇到了麻烦。这是我目前的代码。

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;

contract sendEther {
    address payable public owner;
    address payable public receiver;
    uint256 public value;

    error insufficientBalance();
    error transferAlreadyCalled();

    event Log(string message);

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

    modifier inBalance(address owner_) {
        if (owner.balance < value) {
            emit Log("Insufficient balance");
            revert insufficientBalance();
            _;
        }
    }

    function transferEther() external payable {
        owner = payable(msg.sender);
        (
            bool sent, /* bytes memory data */

        ) = owner.call{value: msg.value}("");
        require(sent, "Failed to send Ether");
    }
}

我很难理解owner.call() 将如何将以太币发送到接收器,因为接收器没有设置为任何地址。也就是说,我应该如何从用户那里获得所需的地址输入?

【问题讨论】:

    标签: blockchain ethereum solidity web3


    【解决方案1】:

    owner.call() 将如何向接收者发送以太币,因为接收者未设置为任何地址

    它将内部事务发送到owner 地址。

    如果希望用户指定自定义接收者,可以将接收者地址定义为函数的参数:

    function transferEther(address receiver) external payable {
        payable(receiver).call{value: msg.value}("");
    }
    

    请注意,在transferEther() 函数体的第一行,您正在用msg.sender(执行函数的用户)覆盖现有的owner 值。这实际上只是将资金发送回发送者(加上​​将它们设置为所有者)。

    address payable public owner;
    
    function transferEther() external payable {
        // overwrite the existing `owner`
        owner = payable(msg.sender);
    
        // ...
    
        // send ETH to the (new) `owner`
        owner.call{value: msg.value}("");
    

    您很可能希望省略 owner = ... 分配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 2023-03-12
      • 2018-09-16
      • 1970-01-01
      • 2020-10-25
      • 2022-12-03
      • 1970-01-01
      • 2022-11-25
      相关资源
      最近更新 更多