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
receive() external payableruns on bare transfers.msg.valueis the amount that arrived, in wei.address(this).balancereads the contract's own funds.
Keywords and builtins used here
addresscontractemiteventexternalfunctionmappingpayablepublicreturnreturnsthisuint256
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.
Step 2 of 3 in Ether & events, step 12 of 28 in Language basics.