0

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

1 Answers1

0

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
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • that I know, I thought maybe there's some other method to it btw thanks – Tarandeep singh Jul 08 '22 at 19:21
  • @Tarandeepsingh What do you mean by other method? Can you say in other words what you're trying to achieve? – Petr Hejda Jul 08 '22 at 20:13
  • like in web3.js we use utils to convert wei to ether I thought maybe something the same in solidity – Tarandeep singh Jul 09 '22 at 06:46
  • @Tarandeepsingh You can divide/multiply by 1e18 (which is "one and eighteen zeros") to calculate ether to/from wei. Mind that there's no decimal number type in Solidity, so that's why all units are usually in wei. I.e. you cannot use `0.1` (of ETH) so you use `100000000000000000` (of wei). – Petr Hejda Jul 09 '22 at 08:48