Skip to main content

ERC-20 with Safety Rails

erc-20
Beginner
Ori Pomerantz
August 15, 2022
8 minute read minute read

Introduction

One of the great things about Ethereum is that there is no central authority that can modify or undo your transactions. One of the great problems with Ethereum is that there is no central authority with the power to undo user mistakes or illicit transactions. In this article you learn about some of the common mistakes that users commit with ERC-20 tokens, as well as how to create ERC-20 contracts that help users to avoid those mistakes, or that give a central authority some power (for example to freeze accounts).

Note that while we will use the OpenZeppelin ERC-20 token contract(opens in a new tab), this article does not explain it in great details. You can find this information here.

If you want to see the complete source code:

  1. Open the Remix IDE(opens in a new tab).
  2. Click the clone github icon (clone github icon).
  3. Clone the github repository https://github.com/qbzzt/20220815-erc20-safety-rails.
  4. Open contracts > erc20-safety-rails.sol.

Creating an ERC-20 contract

Before we can add the safety rail functionality we need an ERC-20 contract. In this article we'll use the OpenZeppelin Contracts Wizard(opens in a new tab). Open it in another browser and follow these instructions:

  1. Select ERC20.

  2. Enter these settings:

    ParameterValue
    NameSafetyRailsToken
    SymbolSAFE
    Premint1000
    FeaturesNone
    Access ControlOwnable
    UpgradabilityNone
  3. Scroll up and click Open in Remix (for Remix) or Download to use a different environment. I'm going to assume you're using Remix, if you use something else just make the appropriate changes.

  4. We now have a fully functional ERC-20 contract. You can expand .deps > npm to see the imported code.

  5. Compile, deploy, and play with the contract to see that it functions as an ERC-20 contract. If you need to learn how to use Remix, use this tutorial(opens in a new tab).

Common mistakes

The mistakes

Users sometimes send tokens to the wrong address. While we cannot read their minds to know what they meant to do, there are two error types that happen a lot and are easy to detect:

  1. Sending the tokens to the contract's own address. For example, Optimism's OP token(opens in a new tab) managed to accumulate over 120,000(opens in a new tab) OP tokens in less than two months. This represents a significant amount of wealth that presumably people just lost.

  2. Sending the tokens to an empty address, one that doesn't correspond to an externally owned account or a smart contract. While I don't have statistics on how often this happens, one incident could have cost 20,000,000 tokens(opens in a new tab).

Preventing transfers

The OpenZeppelin ERC-20 contract includes a hook, _beforeTokenTransfer(opens in a new tab), that is called before a token is transferred. By default this hook does not do anything, but we can hang our own functionality on it, such as checks that revert if there's a problem.

To use the hook, add this function after the constructor:

1 function _beforeTokenTransfer(address from, address to, uint256 amount)
2 internal virtual
3 override(ERC20)
4 {
5 super._beforeTokenTransfer(from, to, amount);
6 }
Copy

Some parts of this function may be new if you aren't very familiar with Solidity:

1 internal virtual
Copy

The virtual keyword means that just as we inherited functionality from ERC20 and overrode this function, other contracts can inherit from us and override this function.

1 override(ERC20)
Copy

We have to specify explicitly that we're overriding(opens in a new tab) the ERC20 token definition of _beforeTokenTransfer. In general, explicit definitions are a lot better, from the security standpoint, than implicit ones - you cannot forget that you've done something if it's right in front of you. That is also the reason we need to specify which superclass's _beforeTokenTransfer we are overriding.

1 super._beforeTokenTransfer(from, to, amount);
Copy

This line calls the _beforeTokenTransfer function of the contract or contracts from which we inherited which have it. In this case, that is only ERC20, Ownable does not have this hook. Even though currently ERC20._beforeTokenTransfer doesn't do anything, we call it in case functionality is added in the future (and we then decide to redeploy the contract, because contracts don't change after deployment).

Coding the requirements

We want to add these requirements to the function:

Lets go over the new code line by line:

1 require(to != address(this), "Can't send tokens to the contract address");
Copy

This is the first requirement, check that to and this(address) are not the same thing.

1 bool isToContract;
2 assembly {
3 isToContract := gt(extcodesize(to), 0)
4 }
Copy

This is how we check if an address is a contract. We cannot receive output directly from Yul, so instead we define a variable to hold the result (isToContract in this case). The way Yul works is that every opcode is considered a function. So first we call EXTCODESIZE(opens in a new tab) to get the contract size, and then use GT(opens in a new tab) to check it is not zero (we are dealing with unsigned integers, so of course it can't be negative). We then write the result to isToContract.

1 require(to.balance != 0 || isToContract, "Can't send tokens to an empty address");
Copy

And finally, we have the actual check for empty addresses.

Administrative access

Sometimes it is useful to have an administrator that can undo mistakes. To reduce the potential for abuse, this administrator can be a multisig(opens in a new tab) so multiple people have to agree on an action. In this article we'll have two administrative features:

  1. Freezing and unfreezing accounts. This can be useful, for example, when an account might be compromised.

  2. Asset cleanup.

    Sometimes frauds send fraudulent tokens to the real token's contract to gain legitimacy. For example, see here(opens in a new tab). The legitimate ERC-20 contract is 0x4200....0042(opens in a new tab). The scam that pretends to be it is 0x234....bbe(opens in a new tab).

    It is also possible that people send legitimate ERC-20 tokens to our contract by mistake, which is another reason to want to have a way to get them out.

OpenZeppelin provides two mechanisms to enable administrative access:

For the sake of simplicity, in this article we use Ownable.

Freezing and thawing contracts

Freezing and thawing contracts requires several changes:

Asset cleanup

To release ERC-20 tokens held by this contract we need to call a function on the token contract to which they belong, either transfer(opens in a new tab) or approve(opens in a new tab). There's no point wasting gas in this case on allowances, we might as well transfer directly.

1 function cleanupERC20(
2 address erc20,
3 address dest
4 )
5 public
6 onlyOwner
7 {
8 IERC20 token = IERC20(erc20);
Copy

This is the syntax to create an object for a contract when we receive the address. We can do this because we have the definition for ERC20 tokens as part of the source code (see line 4), and that file includes the definition for IERC20(opens in a new tab), the interface for an OpenZeppelin ERC-20 contract.

1 uint balance = token.balanceOf(address(this));
2 token.transfer(dest, balance);
3 }
Copy

This is a cleanup function, so presumably we don't want to leave any tokens. Instead of getting the balance from the user manually, we might as well automate the process.

Conclusion

This is not a perfect solution - there is no perfect solution for the "user made a mistake" problem. However, using these kinds of checks can at least prevent some mistakes. The ability to freeze accounts, while dangerous, can be used to limit the damage of certain hacks by denying the hacker the stolen funds.

Last edit: @omahs(opens in a new tab), February 17, 2024

Was this tutorial helpful?