0

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
pjlangley
  • 364
  • 4
  • 10

1 Answers1

1

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;
    }
}
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • Thanks. The docs state that the receive function can only rely on 2300 gas being available, so I might have to bear that in mind and keep the code to a minimum. Do you have any experience with this? – pjlangley May 17 '22 at 14:06
  • @PeterJLangley The 2300 limit is used only in some cases, for example when another contract invokes your `receive()` function from their snippet `payable(yourContract).transfer(amount);`... If you just send the amount from an end address, the limit is not applied. – Petr Hejda May 17 '22 at 14:28
  • Thanks for the extra information. This is exactly what I was looking for. – pjlangley May 17 '22 at 14:32