Search code examples
ethereumsoliditydecentralized-applications

How do I access a plain Ether transaction event in a Solidity Ethereum smart contract dApp?


When a user sends some Ether to a smart contract/dApp address, is there a way I can access that transaction in my smart contract? Like a built-in method that's invoked, that I can add some code to?

My ideal work flow, if it's possible:

  1. User sends Ether to my dApp address.
  2. A function is invoked in my smart contract code.
  3. Within that function, I can create some logic, like add their address to some state, etc.

Ideally, I want to avoid a user having to invoke a particular public function of the contract, but instead just send Ether to the dApp address.

If the user has to invoke a particular function, I have to start thinking about services like MEW, or I have to build a web2 frontend app that integrates with the MetaMask browser extension or something. This seems like a lot of work, but is this the way it has to be?


Solution

  • There is the receive() special function that gets executed when you send ETH to the contract address and not specify any function to execute (i.e. the data field of the transaction is empty).

    You can get the sender address through the msg.sender global variable and the amount through msg.value.

    pragma solidity ^0.8;
    
    contract MyContract {
        mapping (address => uint256) contributions;
    
        receive() external payable {
            contributions[msg.sender] += msg.value;
        }
    }