Developer Experience
1. Tutorial List
A curated compilation of instructional materials designed to guide learners through specific topics or skills in a step-by-step manner.
Welcome to our curated list of community-managed tutorials.
Tutorial Categories
- Beginner
- Intermediate
- Advanced
ERC-20 Security Assurance
Introduction
One of N42's strengths is the absence of a centralized entity that can modify or cancel transactions. However, this also means that no authority can correct user mistakes or remove illicit transactions. In this article, you'll learn about common errors N42 users make when using ERC-20 tokens and how to create ERC-20 contracts that help users avoid these mistakes. Additionally, we'll explore how to grant centralized authorities certain powers, such as freezing accounts.
Note: While we use the OpenZeppelin ERC-20 token contract, this article does not cover it in detail. You can find the full information here.
If you want to view the full source code:
- Open Remix IDE.
- Click the Clone GitHub icon.
- Clone the GitHub repository:
https://github.com/qbzzt/20220815-erc20-safety-rails - Open contracts > erc20-safety-rails.sol.
Creating an ERC-20 Contract
Before adding security features, we need a base ERC-20 contract. In this article, we use the OpenZeppelin Contract Wizard. Open it in another browser and follow these steps: - Select ERC-20.
- Enter the following settings:
| Parameter | Value |
|---|---|
| Name | SafetyRailsToken |
| Symbol | SAFE |
| Premint | 1000 |
| Features | None |
| Access Control | Ownable |
| Upgradability | None |
- Scroll up and click Open in Remix (for Remix users) or Download to use another environment.
- If using Remix, compile, deploy, and test the contract to confirm its ERC-20 functionality.
- To learn how to use Remix, refer to this tutorial.
Common Errors
- Sending Tokens to the Wrong Address
Users sometimes send tokens to incorrect addresses. This often occurs in two ways:- Sending tokens to the contract's own address. Example: The Optimism OP token lost over 120,000 tokens this way in under two months.
- Sending tokens to an empty address. Some users send tokens to addresses that do not belong to an external account or smart contract, leading to irreversible loss.
- Preventing Transfers to Invalid Addresses The OpenZeppelin ERC-20 contract includes a hook _beforeTokenTransfer, which is triggered before a token transfer occurs. By default, it does nothing, but we can modify it to prevent common mistakes.
Implementing _beforeTokenTransfer Hook
Add the following function after the constructor:function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20) { super._beforeTokenTransfer(from, to, amount);Breaking Down the Code- internal virtual: Allows other contracts to override this function.
- override(ERC20): Explicitly declares which superclass function is being overridden, improving code clarity.
- super._beforeTokenTransfer(from, to, amount);: Calls the parent class's _beforeTokenTransfer function for potential future compatibility.
Encoding Security Requirements
- Prevent Transfers to the Contract Itself
require(to != address(this), "Can't send tokens to the contract address"); - Validate to Address
To ensure tokens are sent to valid addresses, we check:- If the address is an externally owned account (EOA): While EOAs cannot be directly checked, we assume they have a nonzero ETH balance.
- If the address is a smart contract: We check the external code size using Solidity's low-level assembly.
Checking if to is a Contract
bool isToContract;
assembly {
isToContract := gt(extcodesize(to), 0)
}
- extcodesize(to) > 0 confirms the address is a contract.
- assembly is used because Solidity does not have a built-in function for extcodesize().
Final Security Check
require(to.balance != 0 || isToContract, "Can't send tokens to an empty address");
This ensures the recipient is either a contract or an active EOA. Managing Access Control
In some cases, having an administrator with rollback authority is beneficial. To reduce abuse risk, an admin role should be multi-signature, requiring multiple approvals for an action. Two Administrative Features
- Freezing and unfreezing accounts (useful for compromised accounts).
- Asset cleanup (removing fraudulent or mistakenly sent tokens).
Implementing Freezing and Unfreezing Accounts
- Tracking Frozen Accounts
mapping(address => bool) public frozenAccounts;
By default, all values are false, meaning accounts are not frozen unless explicitly set. - Defining Events for Transparency
- Freezing an Account
function freezeAccount(address addr) public onlyOwner { require(!frozenAccounts[addr], "Account already frozen"); frozenAccounts[addr] = true; emit AccountFrozen(addr); }- The onlyOwner modifier ensures only the contract owner can call this function.
- The function prevents re-freezing an already frozen account.
- Modifying _beforeTokenTransfer to Enforce Freezing
require(!frozenAccounts[from], "The account is frozen");
This prevents transfers from a frozen account but allows receiving funds.
event AccountFrozen(address indexed _addr); event AccountThawed(address indexed _addr);Indexed events allow tracking all freeze/unfreeze actions.
Asset Cleanup
To remove ERC-20 tokens mistakenly sent to the contract, we use the transfer function: function cleanupERC20(address erc20, address dest) public onlyOwner {
IERC20 token = IERC20(erc20);
uint balance = token.balanceOf(address(this));
token.transfer(dest, balance);
}
This automatically transfers all stored tokens to a designated address. Conclusion
This approach does not completely eliminate user mistakes, but it significantly reduces the risk of common errors. Account freezing, while powerful, can help mitigate hacking attempts and unauthorized transfers. Proper governance mechanisms, such as multi-signature admin controls, can ensure responsible use of these features.