SolidityIn

Payable and msg.value

Lesson 10 of 40 · Ether

Ether is the currency of Ethereum, and contracts can hold it just like accounts do. A function must be marked payable to accept ETH. If someone sends ETH to a function that is not payable, the transaction reverts.

Inside a payable function, msg.value holds the amount sent, measured in wei, and msg.sender is the caller. One ether equals 10^18 wei. Solidity has the suffixes wei, gwei and ether so you can write 0.01 ether instead of counting zeros.

A contract's own balance is address(this).balance. It grows whenever ETH arrives, even if your code does not record it. Keep your own accounting in variables, such as a mapping of deposits, and never assume the contract balance equals your records.

Always validate the amount. A minimum deposit, an exact price or a maximum cap are all common rules, and each takes one require. Remember that msg.value is in wei, so mixing up units is a frequent mistake.

Money in a contract can only leave through code you wrote. If there is no withdraw function, the ETH is stuck forever. Plan how funds will leave the contract before you deploy it.

contract Shop {
    address public immutable owner = msg.sender;
    uint256 public constant PRICE = 0.01 ether;
    mapping(address => uint256) public paid;

    function buy() external payable {
        require(msg.value == PRICE, "Send exactly 0.01 ETH");
        paid[msg.sender] += msg.value;
    }
    function donate() external payable {
        require(msg.value >= 1 gwei, "Too small");
        paid[msg.sender] += msg.value;
    }
    function contractBalance() external view returns (uint256) {
        return address(this).balance;
    }
    function collect() external {
        require(msg.sender == owner, "Not owner");
        (bool ok, ) = owner.call{value: address(this).balance}("");
        require(ok, "Transfer failed");
    }
}

Try it yourself

Add a function refund() that sends a buyer's payment back and sets paid to zero before sending. Then compile, and think about why the order of those two steps matters.

Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.

Quick check: What unit is msg.value measured in?