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.
3 Answers
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.
-
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. Commented Apr 9, 2018 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. Commented Apr 10, 2018 at 9:33
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.
-
relaying data back to the contract would involve a transaction and fees right? Commented Dec 23, 2020 at 3:44
-
@shivamDev31 Yes, I think that sending data to a contract would usually imply gas fees. Commented Dec 23, 2020 at 4:28
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/