How to prevent stuck tokens in contracts
And other use cases for the popular EIP-165

Do you remember the beginning of the Dark Forest story? If not, let's look at it again:
Somebody sent tokens to a smart contract that was not intended to receive tokens. This perfectly illustrates one of the issues not only with ERC-20 tokens, but generally with smart contracts. How can we find out if a contract actually supports being the receiver or owner of some interface/token?
You can send tokens to any smart contract, but they will mostly just be locked and not usable. This is because a smart contract (in contrast to an EOA) is not able to do arbitrary calls to other smart contracts. It only supports the functionality that actually has been implemented.
This has resulted in a lot of tokens being lost. Just take a look at following token contracts. Those are all ERC-20 contracts where users sent the token directly to the contract itself, forever locking them:
- GNT, $35,000 lost (see on Etherscan)
- DGD, $62,000 lost (see on Etherscan)
- OMG, $82,000 lost (see on Etherscan)
- ZRX, $92,000 lost (see on Etherscan)
This is where EIP-165 comes in. Let's take a closer look at it.
What is EIP-165?
At its core it's actually just one function:
interface ERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
Now a contract can implement this interface and return true for every supported interfaceID
.
What is an interfaceID?
The given interface ID is an identifier that is computed as the XOR (explicit OR) of all function selectors that are part of the interface.
How do you calculate the id?
Previously you had to do a calculation as shown on the right. This would calculate the required XOR from all ERC20 functions. The order here doesn't matter for the result, yet every function will affect every single bit in the final result.
Since Solidity 0.7.2 you can now write type(IERC20).interfaceId
.
function calcErc20InterfaceId() returns (bytes4) {
return ERC20.transfer.selector
^ ERC20.transferFrom.selector
^ ERC20.approve.selector
^ ERC20.allowance.selector
^ ERC20.totalSupply.selector
^ ERC20.balanceOf.selector;
}
Why is the interfaceId of type bytes4?
First of all a function selector is of type bytes4. Now we still could have created a way to compute larger interface ID's out of it. But bytes4 still gives 2^32-1 = 4,294,967,295 different interface IDs. With bytes4 we also can store multiple supported interfaces in very space efficient mapping(bytes4 => bool)
.
Although we also want to avoid collisions. Maybe you've heard of the birthday paradox? Let's do an interesting short excursion...

No, we don't mean this paradox.
The birthday paradox states you don't need to have a lot of people in the same room for two of them to have the same birthday, despite there being 365 days in a year. In fact, just 23 people in one room will have a 50% chance to have at least one match.
Transferred to our scenario, you can use a calculator: https://instacalc.com/28845 to compute collisions for our interface IDs.


Given 10,000 different interfaces, there is a 98.84% chance of no collisions, while 100,000 will yield only 31%. However this is likely still good enough, because to really be a problem not only needs there be a collision, but somebody actually has to use exactly the two colliding interfaces by accident interchangeably. Think of it as it's okay to have people with the same birthdays in the world, just not in the same room.
Base EIP-165 Implementation
contract ERC165Implementation is ERC165 {
mapping(bytes4 => bool) private supportedInterfaces;
constructor() {
supportedInterfaces[this.supportsInterface.selector] = true;
}
function supportsInterface(bytes4 interfaceID) external view returns (bool) {
return supportedInterfaces[interfaceID];
}
}
Like this the contract is not yet any useful. Let's see how you could use it today with the latest tools using:
- Solidity 0.7.2+
- v3.2 Openzeppelin contracts for Solidity 0.7
- Truffle, Buidler or Remix
Example Usage for ERC-20 tokens
1a. Adding EIP-165 to your ERC-20
Let's see how we can use EIP-165 with ERC-20 tokens. Since Solidity v0.7.2 there is built-in EIP-165 support.
- Start a project with Truffle, Buidler or Remix, you can follow the instructions here if you need to.
- Install the openzeppelin contracts. Since we require Solidity 0.7, we need the newest pre-release.
- When using Truffle/Buidler, install via
npm using npm install @openzeppelin/contracts@solc-0.7
. - When using Remix simply import the contracts via Github urls. You can see below how to import all required contracts in Remix.
- Create a
TestERC20
token contract as shown on the right.
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/introspection/ERC165.sol";
contract TestERC20 is ERC20, ERC165 {
constructor() ERC20("","") {
_registerInterface(type(IERC20).interfaceId);
_registerInterface(ERC20.name.selector);
_registerInterface(ERC20.symbol.selector);
_registerInterface(ERC20.decimals.selector);
}
}
As you can see, we can
// import in Remix
import "http://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.2.1-solc-0.7/contracts/token/ERC20/ERC20.sol";
import "http://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.2.1-solc-0.7/contracts/introspection/ERC165.sol";
import "http://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.2.1-solc-0.7/contracts/introspection/ERC165Checker.sol";
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/introspection/ERC165Checker.sol";
contract UsingTestERC20 {
using ERC165Checker for address;
function addToken(address test) external {
require(
test.supportsInterface(type(IERC20).interfaceId),
'Address is not supported'
);
// store token now
}
}
1b. Checking for implemented ERC-20 interfaces
This now allows us to see if an address is actually an ERC-20 token. Inside the addToken function, we will only accept actual ERC-20 addresses ensuring to only add expected ERC-20 addresses. This means we can later use those and call ERC-20 functions without failures.
Note: Of course this only works for ERC-20 tokens that have implemented EIP-165, so you will get false negatives, but you will never get any false positives.
2a. Adding EIP-165 to a token storage contract
Now remember back the issue with money lost for tokens being sent to a non-supporting contract. Let's see how we can solve this problem.
Let's use a storage contract that contains a withdrawToOwner
function. Given this withdraw function, we can send any ERC-20 tokens to this smart contract without the funds getting lost.
Once again, to use the EIP-165 we just register the interface in the constructor. And we implement a simple withdrawToOwner
function.
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/introspection/ERC165.sol";
interface ArbitraryTokenStorage {
function withdrawToOwner(IERC20 token) external;
}
contract ERC20Storage is ERC165, ArbitraryTokenStorage {
address public owner;
constructor() {
owner = msg.sender;
_registerInterface(type(ArbitraryTokenStorage).interfaceId);
}
function withdrawToOwner(IERC20 token) external override {
uint256 balance = token.balanceOf(address(this));
require(balance > 0, "Contract has no balance");
require(token.transfer(owner, balance), "Transfer failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/introspection/ERC165Checker.sol";
contract UsingTestERC20 {
using ERC165Checker for address;
function secureSendToken(IERC20 token, address to, uint256 amount) external {
require(
to.supportsInterface(type(ArbitraryTokenStorage).interfaceId),
'Address is not supported'
);
require(token.transfer(to, amount), "Transfer failed");
}
}
2b. Checking for implemented token storage interfaces
Now we implement a second contract with a secureSendToken
function. We send tokens from our contract to some other contract, but only if it is in fact an ArbitraryTokenStorage
contract.
If it's any other contract or not a contract, the function will revert. Ensuring we don't sent tokens to an invalid (not supporting) address.
What's next?
Now that you know EIP-165, consider using it in your contracts. It's not always necessary in my opinion. But in fact EIP-165 is already used in quite a few other standards including the known ERC-721 and ERC-777.
Actually ERC-777 is using the newer EIP-1820 which has backwards compatibility to EIP-165, but adds additional functionality for non-contract addresses to register an interface. We will look at EIP-1820 and ERC-777 in more details in the future.
What's your take on EIP-165? Have you already used it?
Solidity Developer
More great blog posts from Markus Waas
How to use ChatGPT with Solidity
Using the Solidity Scholar and other GPT tips
How to integrate Uniswap 4 and create custom hooks
Let's dive into Uniswap v4's new features and integration
How to integrate Wormhole in your smart contracts
Entering a New Era of Blockchain Interoperability
Solidity Deep Dive: New Opcode 'Prevrandao'
All you need to know about the latest opcode addition
How Ethereum scales with Arbitrum Nitro and how to use it
A blockchain on a blockchain deep dive
The Ultimate Merkle Tree Guide in Solidity
Everything you need to know about Merkle trees and their future
The New Decentralized The Graph Network
What are the new features and how to use it
zkSync Guide - The future of Ethereum scaling
How the zero-knowledge tech works and how to use it
Exploring the Openzeppelin CrossChain Functionality
What is the new CrossChain support and how can you use it.
Deploying Solidity Contracts in Hedera
What is Hedera and how can you use it.
Writing ERC-20 Tests in Solidity with Foundry
Blazing fast tests, no more BigNumber.js, only Solidity
ERC-4626: Extending ERC-20 for Interest Management
How the newly finalized standard works and can help you with Defi
Advancing the NFT standard: ERC721-Permit
And how to avoid the two step approve + transferFrom with ERC721-Permit (EIP-4494)
Moonbeam: The EVM of Polkadot
Deploying and onboarding users to Moonbeam or Moonriver
Advanced MultiSwap: How to better arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
Deploying Solidity Smart Contracts to Solana
What is Solana and how can you deploy Solidity smart contracts to it?
Smock 2: The powerful mocking tool for Hardhat
Features of smock v2 and how to use them with examples
How to deploy on Evmos: The first EVM chain on Cosmos
Deploying and onboarding users to Evmos
EIP-2535: A standard for organizing and upgrading a modular smart contract system.
Multi-Facet Proxies for full control over your upgrades
MultiSwap: How to arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
The latest tech for scaling your contracts: Optimism
How the blockchain on a blockchain works and how to use it
Ultimate Performance: The Aurora Layer2 Network
Deploying and onboarding users to the Aurora Network powered by NEAR Protocol
What is ecrecover in Solidity?
A dive into the waters of signatures for smart contracts
How to use Binance Smart Chain in your Dapp
Deploying and onboarding users to the Binance Smart Chain (BSC)
Using the new Uniswap v3 in your contracts
What's new in Uniswap v3 and how to integrate Uniswap v3
What's coming in the London Hardfork?
Looking at all the details of the upcoming fork
Welcome to the Matrix of blockchain
How to get alerted *before* getting hacked and prevent it
The Ultimate Ethereum Mainnet Deployment Guide
All you need to know to deploy to the Ethereum mainnet
SushiSwap Explained!
Looking at the implementation details of SushiSwap
Solidity Fast Track 2: Continue Learning Solidity Fast
Continuing to learn Solidity fast with the advanced basics
What's coming in the Berlin Hardfork?
Looking at all the details of the upcoming fork
Using 1inch ChiGas tokens to reduce transaction costs
What are gas tokens and example usage for Uniswap v2
Openzeppelin Contracts v4 in Review
Taking a look at the new Openzeppelin v4 Release
EIP-3156: Creating a standard for Flash Loans
A new standard for flash loans unifying the interface + wrappers for existing ecosystems
Tornado.cash: A story of anonymity and zk-SNARKs
What is Tornado.cash, how to use it and the future
High Stakes Roulette on Ethereum
Learn by Example: Building a secure High Stakes Roulette
How to implement generalized meta transactions
We'll explore a powerful design for meta transactions based on 0x
Utilizing Bitmaps to dramatically save on Gas
A simple pattern which can save you a lot of money
Using the new Uniswap v2 as oracle in your contracts
How does the Uniswap v2 oracle function and how to integrate with it
Smock: The powerful mocking tool for Hardhat
Features of smock and how to use them with examples
How to build and use ERC-721 tokens in 2021
An intro for devs to the uniquely identifying token standard and its future
Trustless token management with Set Protocol
How to integrate token sets in your contracts
Exploring the new Solidity 0.8 Release
And how to upgrade your contracts to Solidity 0.8
How to build and use ERC-1155 tokens
An intro to the new standard for having many tokens in one
Leveraging the power of Bitcoins with RSK
Learn how RSK works and how to deploy your smart contracts to it
Solidity Fast Track: Learn Solidity Fast
'Learn X in Y minutes' this time with X = Solidity 0.7 and Y = 20
Sourcify: The future of a Decentralized Etherscan
Learn how to use the new Sourcify infrastructure today
Integrating the 0x API into your contracts
How to automatically get the best prices via 0x
How to build and use ERC-777 tokens
An intro to the new upgraded standard for ERC-20 tokens
COMP Governance Explained
How Compound's Decentralized Governance is working under the hood
Understanding the World of Automated Smart Contract Analyzers
What are the best tools today and how can you use them?
A Long Way To Go: On Gasless Tokens and ERC20-Permit
And how to avoid the two step approve + transferFrom with ERC20-Permit (EIP-2612)!
Smart Contract Testing with Waffle 3
What are the features of Waffle and how to use them.
How to use xDai in your Dapp
Deploying and onboarding users to xDai to avoid the high gas costs
Stack Too Deep
Three words of horror
Integrating the new Chainlink contracts
How to use the new price feeder oracles
TheGraph: Fixing the Web3 data querying
Why we need TheGraph and how to use it
Adding Typescript to Truffle and Buidler
How to use TypeChain to utilize the powers of Typescript in your project
Integrating Balancer in your contracts
What is Balancer and how to use it
Navigating the pitfalls of securely interacting with ERC20 tokens
Figuring out how to securely interact might be harder than you think
Why you should automatically generate interests from user funds
How to integrate Aave and similar systems in your contracts
How to use Polygon (Matic) in your Dapp
Deploying and onboarding users to Polygon to avoid the high gas costs
Migrating from Truffle to Buidler
And why you should probably keep both.
Contract factories and clones
How to deploy contracts within contracts as easily and gas-efficient as possible
How to use IPFS in your Dapp?
Using the interplanetary file system in your frontend and contracts
Downsizing contracts to fight the contract size limit
What can you do to prevent your contracts from getting too large?
Using EXTCODEHASH to secure your systems
How to safely integrate anyone's smart contract
Using the new Uniswap v2 in your contracts
What's new in Uniswap v2 and how to integrate Uniswap v2
Solidity and Truffle Continuous Integration Setup
How to setup Travis or Circle CI for Truffle testing along with useful plugins.
Upcoming Devcon 2021 and other events
The Ethereum Foundation just announced the next Devcon in 2021 in Colombia
The Year of the 20: Creating an ERC20 in 2020
How to use the latest and best tools to create an ERC-20 token contract
How to get a Solidity developer job?
There are many ways to get a Solidity job and it might be easier than you think!
Design Pattern Solidity: Mock contracts for testing
Why you should make fun of your contracts
Kickstart your Dapp frontend development with create-eth-app
An overview on how to use the app and its features
The big picture of Solidity and Blockchain development in 2020
Overview of the most important technologies, services and tools that you need to know
Design Pattern Solidity: Free up unused storage
Why you should clean up after yourself
How to setup Solidity Developer Environment on Windows
What you need to know about developing on Windows
Avoiding out of gas for Truffle tests
How you do not have to worry about gas in tests anymore
Design Pattern Solidity: Stages
How you can design stages in your contract
Web3 1.2.5: Revert reason strings
How to use the new feature
Gaining back control of the internet
How Ocelot is decentralizing cloud computing
Devcon 5 - Review
Impressions from the conference
Devcon 5 - Information, Events, Links, Telegram
What you need to know
Design Pattern Solidity: Off-chain beats on-chain
Why you should do as much as possible off-chain
Design Pattern Solidity: Initialize Contract after Deployment
How to use the Initializable pattern
Consensys Blockchain Jobs Report
What the current blockchain job market looks like
Provable — Randomness Oracle
How the Oraclize random number generator works
Solidity Design Patterns: Multiply before Dividing
Why the correct order matters!
Devcon 5 Applications closing in one week
Devcon 5 Applications closing
Randomness and the Blockchain
How to achieve secure randomness for Solidity smart contracts?