-1

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.

PoorMillionaire
  • 347
  • 1
  • 2
  • 8

1 Answers1

2

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.
    }
}
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • If I understand this correctly method transferIn() needs to be called, for this to work, which is not an option, because token is sent to my smart contract by third party and they wont call my transferIn() method. So basically I need to run offchain app, which will detect Transfer emit and do my stuff, correct? This is only option? – PoorMillionaire Sep 03 '22 at 17:34
  • @LukaElsner That's correct. If pulling tokens in is not an option, you'll need an offchain app. – Petr Hejda Sep 03 '22 at 18:23