smartcontractstransferether

Transfer Eth through smart contract to other account?


In the below code eth will be transferred in the form of Wei by default, but I want the amount will transfer in the form of Ether, how can I do that?

function (uint amount) public payable {
someaddress.transfer(amount);
}

Solution

  • Wei is the smallest unit of Ether, specifically 1 ETH == 1,000,000,000,000,000,000 (or 1e18) wei.

    The transfer() function always accepts the amount in wei. So if you want to pass just 1 as the input param, meaning that you want to send 1 full ETH, you can multiply the value by 1e18 effectively converting ETH to wei.

    function (uint ethAmount) public payable {
        uint weiAmount = ethAmount * 1e18;
        someaddress.transfer(weiAmount);
    }
    

    Note: There's also the ether global unit, but in the current Solidity version (0.8), this can be used only in combination with number literals - not with variables.

    uint weiAmount = 1 ether; // ok
    
    uint weiAmount = ethAmount ether; // syntax error