1

I know when my smart contract has a payable fallback function, I can record who have sent ether to the contract and how much ether each of them have sent by storing the msg.sender and msg.value data in an array or something. However I wonder if I may achieve similar function with erc20 tokens. So that when someone transfers a certain erc20 token to the smart contract address, it will record it so later I can check who have sent tokens to my contract and the amount of token each of them has sent.

1

No, but with a caveat...

No, you can't get called upon token transfer with just plain old ERC20.

However the extensions in ERC223 support this via the mandated check to your tokenFallback() function.

Plan B

However any ERC20 token will be required to emit a Transfer event upon processing a token transfer, so you can listen for them, rather than logging your own.

  • +1 for correctness and answer-speed. ;-) – ivicaa Apr 8 '18 at 20:36
  • Plan B involves using external off-chain applications right, as far as I see I can only listen to the events with something like web3 or plain old JSON-RPC. I want the smart contract itself to know who have sent it erc20 tokens without the need to interact with off-chain programs, so I wonder is it possible for the smart contract itself to access the event logs? Thanks. – hellopeach Apr 9 '18 at 10:53
  • Well, not necessarily since if you want to just record who has sent that amount of tokens, the event log is sufficient. If you want to take action in response to a deposit of tokens, then yes, Plan B will require an off chain application. – norganna Apr 10 '18 at 9:33
1

According to this question it's not possible for your contract to listen to the ERC20 contract directly.

But it's possible to write an external application that listens for events from the ERC20 token and relays data to your contract.

1

If the sender is using the transfer function, your contract will not get notified of the transfer, since it can not react on the Transfer event from the ERC20 contract.

If you use approve/transferFrom then you can let the sender of tokens approve your contract to initiate the transfer. When the sender calls your contract, your contract is initiating the transfer, so it will know that it took place.

Moreover, there are other token specifications, which allow sending a transfer notification to receiving contracts (->ERC-223).

I can recommend reading this blog post if you want to learn more on features/pitfalls of currently available fungible token specifications: http://blockchainers.org/index.php/2018/02/08/token-erc-comparison-for-fungible-tokens/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.