If I'm writing an Ethereum smart contract in Solidity and I know I have an ERC20
address
variable (let's call it some_erc20_token
), but I don't know whether this address implements the interface of an ERC20
extension EIP (for instance ERC1404 with its detectTransferRestriction
function) how do I check if the address implements that function so I can call it?
If this were Java I would use the instanceof
operator to check for this, something like
void wagTail(Animal animal) {
if (animal instanceof Dog) {
animal = (Dog)animal;
animal.wagDogTail();
} else if (animal instance of Cat) {
animal = (Cat)animal;
animal.wagCatTail();
}
}
In my solidity contract I want to do something of the form
if (some_erc20_token.detectTransferRestriction != 0) { // this function exists!
some_erc20_token.detectTransferRestriction(to, from , amount);
}
However that doesn't compile and I get the compiler error: TypeError: Member "detectTransferRestriction" not found or not visible after argument-dependent lookup in contract MyContract.
Best Answer
You can implement a helper function in your contract, which will try to call
detectTransferRestriction
and return success or failure:There you go:
I declared the helper function
public
in order to test it, but you don't have to do that of course.Here is a Truffle 4.x test:
And a couple of dummy contracts that the test above relies on:
I believe that in solc 0.5.x or higher, you can do it in a single Solidity line (no assembly involved).
An update following your request (in a comment) on how this can be done off-chain: