typestar

payable and receive in Solidity

Accepting ether is opt-in; receive catches plain sends.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// payable accepts ether; receive catches plain transfers.
contract DonationJar {
    mapping(address => uint256) public given;

    event Thanks(address indexed donor, uint256 amount);

    receive() external payable {
        given[msg.sender] += msg.value;
        emit Thanks(msg.sender, msg.value);
    }

    function jarTotal() external view returns (uint256) {
        return address(this).balance;
    }
}

How it works

  1. receive() external payable runs on bare transfers.
  2. msg.value is the amount that arrived, in wei.
  3. address(this).balance reads the contract's own funds.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
424
Tokens
74
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 74 seconds.

Type this snippet

Step 2 of 3 in Ether & events, step 12 of 28 in Language basics.

← Previous Next →