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.
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
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.
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.
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
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/