如何在合同中设置 ETH 的接收者,以在 remix IDE 中使用 solidity usign call() 将 ETH 从一个地址发送到另一个地址

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

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

// 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() 将如何向接收方发送以太币,因为接收方未设置任何地址。也就是说,我应该如何从用户那里获得所需的地址输入?

how the owner.call() will send ether to receiver since receiver wasn't set to any address

它将内部交易发送到 owner 地址。

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

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

请注意,在 transferEther() 函数体的第一行,您将现有的 owner 值写入 msg.sender(执行该函数的用户)。这实际上只是将资金发回给发件人(加上将他们设置为所有者)。

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 = ... 分配。