Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Day 25 - Fallback and receive Functions
Vedant Chainani
Vedant Chainani

Posted on • Edited on

     

Day 25 - Fallback and receive Functions

GitHub logo Envoy-VC / 30-Days-of-Solidity

30 Days of Solidity step-by-step guide to learn Smart Contract Development.

This is Day25 of30 in Solidity Series
Today I Learned About fallback and receive Functions in Solidity.

The solidity fallback function is executed if none of the other functions match the function identifier or no data was provided with the function call. Only one unnamed function can be assigned to a contract and it is executed whenever the contract receives plain Ether without any data. To receive Ether and add it to the total balance of the contract, the fallback function must be marked payable. If no such function exists, the contract cannot receive Ether through regular transactions and will throw an exception.

Properties of a fallback function:

  • Has no name or arguments.
  • If it is not marked payable, the contract will throw an exception if it receives plain ether without data.
  • Can not return anything.
  • Can be defined once per contract.
  • It is also executed if the caller meant to call a function that is not available
  • It is mandatory to mark it external.
  • It is limited to 2300 gas when called by another function. It is so for as to make this function call as cheap as possible.
// SPDX-License-Identifier: MITpragma solidity ^0.8.7;contract Receiver{    mapping(address => uint) public addressToAmount;    receive() external payable {        addressToAmount[msg.sender] += msg.value;    }}contract Sender {    uint amount = 1 ether;    address payable _receiver = payable(0xcD6a42782d230D7c13A74ddec5dD140e55499Df9);    function sendEther() public payable {        _receiver.transfer(amount);    }}
Enter fullscreen modeExit fullscreen mode

fallback()

This function is called for all messages sent to this contract, except plain Ether transfers (there is no other function except the receive function). Any call with non-empty calldata to this contract will execute

receive()

This function is called for plain Ether transfers, i.e. for every call with empty calldata.


Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Web3 Technical Writer ✍️ | ⛓️ Blockchain Enthusiast
  • Location
    India
  • Joined

More fromVedant Chainani

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp