Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

solidity
ethereum
communitycreator

How to receive ethers inside a smart contract

Dario Vincenzo Tarantini

In order to receive ethers in Solidity (or any other native coin in any EVM blockchain), we need to create a receive() function with the payable modifier.


This shot is written for Solidity versions newer than 0.6. It may not work on older versions.


Parameters and return value

The receive() function does not take parameters, has no return value, and must be external.

This function will be called every time we send ethers to the contract.


If no receive function is provided, a fallback function should be defined to handle everything.


Below is a visual representation of the workflow of a transaction.

Code

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.9.0;

// This contract keeps all Ether sent to it with no way
// to get it back.
contract HelloWorld {
    event Received(address, uint);
    receive() external payable {
        emit Received(msg.sender, msg.value);
    }
}

RELATED TAGS

solidity
ethereum
communitycreator

CONTRIBUTOR

Dario Vincenzo Tarantini
RELATED COURSES

View all Courses

Keep Exploring