Solidity – Creating Smart Contracts That Receive Only One Token

soliditytokens

Is it possible to forbid to a smart-contract to receive all erc20 tokens and ether except my own token that was created in another contract? I mean I want my contract to receive only tokens from previously known address of smart-contract.
I tried to compare token.balanceOf(msg.sender) >= msg.value where ERC20Detailed token = ERC20Detailed(_address); but as I understood when you send tokens msg.value is always 0

Best Answer

Transferring tokens is basically to change the entries in a variable in the token contract. This means that there is nothing actually moved.

Assume a user with address A, a token contract B and another contract (yours) with address C.

If A decides to sent x tokens to your contract C what happens is that a transaction is sent to B. B has a mapping with the balances of all the users, and subtract x tokens from the balance of A and adds x tokens to the balance of C. This means that C never get to know that a transfer of x tokens was sent to it.

This is why you can't forbid tokens to be sent to your contract because transferring tokens to your contract do not involve your contract at all.

However, there is an option. ERC20 standard implements a function approveAndCall which allows users (for instance A) to approve your contract (C) to move x amount of tokens from their balance in (B). This function will actually call your contract and you will see the address of the token. If the call is from your token contract you can just transfer from the x tokens to you contract using transferFrom and execute your code. If the call is from another contract you just revert.

For the rest, if someone does normal transactions to your contract, you do not need to worry, your contract will will never know.

Hope this helps.

Related Topic