2

I have a contract defined in solidity and I want to make it so that when a specific function is called, the overall cost of the contract increases by 1 ether. I am a little fuzzy on how to use ether in practice. Would I just use a normal int for this? Where does the keyword ether come into play?

logankilpatrick
  • 13,148
  • 7
  • 44
  • 125

1 Answers1

5

As you probably know, 1 ether == 1000000000000000000 (or 10^18) wei.

You can access the transaction value in a global variable msg.value that returns amount of wei sent with the transaction.

So you can make a simple validation that checks whether the transaction calling your function has a value of 1 ETH.

function myFunc() external payable {
    require(msg.value == 1 ether, 'Need to send 1 ETH');
}

It's the same as comparing to 10^18 wei

function myFunc() external payable {
    require(msg.value == 1000000000000000000, 'Need to send 1 ETH');
}

function myFunc() external payable {
    require(msg.value == 1e18, 'Need to send 1 ETH');
}

There's also a short paragraph on the Solidity docs that shows more examples: https://docs.soliditylang.org/en/v0.8.2/units-and-global-variables.html#ether-units

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100