Search code examples
soliditysmartcontractserc20

Smart contract - detect erc20 token inbound


Is there any way I can detect when some ERC20 token is transfered to my smart contract?

What I would like to do:

  • for example someone transfer 100 (ERC20 token) (regular transfer to smart contract address, not through smart contract method)

  • I would split those 100 to 5 addresses (users) balances (each user gets 20) mapping(address => uint256) private _balances;

  • then each user could withdraw these tokens

Thank you for any ideas.


Solution

  • ERC-20 doesn't have any standardized way to notify a receiver contract about the incoming transfer.

    It emits the Transfer event log but these are readable only from an offchain app.

    So the easiest onchain solution is to pull the tokens while executing a custom function in your contract. Note that this approach requires previous approval from the token holder.

    pragma solidity ^0.8;
    
    import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
    
    contract MyContract {
        IERC20 public immutable token;
    
        constructor(IERC20 _token) {
            token = _token;
        }
    
        function transferIn() external {
            bool success = token.transferFrom(msg.sender, address(this), 100 * 1e18);
            // TODO set your mapping, etc.
        }
    }