简体   繁体   English

如何在合约中设置 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

I'm starting to learn solidity, and I'm trying to build a sendEther contract where some address sends an amount of ether to another address.我开始学习solidity,我正在尝试建立一个sendEther合约,其中某个地址将一定量的以太币发送到另一个地址。 I'm building it on remix, and I'm having trouble while setting up the receiver's address.我在 remix 上构建它,我在设置接收器地址时遇到了麻烦。 This is my code so far.到目前为止,这是我的代码。

// 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");
    }
}

I'm struggling to understand how the owner.call() will send ether to receiver since receiver wasn't set to any address.我正在努力理解owner.call()将如何将以太发送到接收器,因为接收器未设置为任何地址。 That said, how should I get the desired address input from the user?也就是说,我应该如何从用户那里获得所需的地址输入?

how the owner.call() will send ether to receiver since receiver wasn't set to any address由于没有将接收者设置为任何地址,所以owner.call()将如何向接收者发送以太币

It sends an internal transaction to the owner address.它将内部交易发送到owner地址。

If you want the user specify a custom receiver, you can define the receiver address as the function param:如果您希望用户指定自定义接收器,您可以将接收器地址定义为 function 参数:

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

Mind that on the first line of the transferEther() function body, you're owerwriting the existing owner value with msg.sender (the user executing the function).请注意,在transferEther() function 主体的第一行,您正在用msg.sender (执行该函数的用户)覆盖现有的owner值。 Which effectively just sends the funds back to the sender (plus sets them as the 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}("");

You most likely wanted to omit the owner =... assigning.您很可能想省略owner =...分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM