Developer Experience

Developer Experience

The overall interactions and feelings developers have when working with tools, platforms, and processes, influencing their productivity and satisfaction.

4Sections available
Hands-onLearning path
DXFocus
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
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:
  1. Open Remix IDE.
  2. Click the 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 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:
  1. Select ERC-20.
  2. Enter the following settings:
ParameterValue
NameSafetyRailsToken
SymbolSAFE
Premint1000
FeaturesNone
Access ControlOwnable
UpgradabilityNone
  1. Scroll up and click Open in Remix (for Remix users) or Download to use another environment.
  2. If using Remix, compile, deploy, and test the contract to confirm its ERC-20 functionality.
  3. To learn how to use Remix, refer to this tutorial.
Common Errors
  1. 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.
  2. 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
    1. internal virtual: Allows other contracts to override this function.
    2. override(ERC20): Explicitly declares which superclass function is being overridden, improving code clarity.
    3. super._beforeTokenTransfer(from, to, amount);: Calls the parent class's _beforeTokenTransfer function for potential future compatibility.
Encoding Security Requirements
  1. Prevent Transfers to the Contract Itself
    require(to != address(this), "Can't send tokens to the contract address");
            
  2. 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
  1. Freezing and unfreezing accounts (useful for compromised accounts).
  2. Asset cleanup (removing fraudulent or mistakenly sent tokens).
Implementing Freezing and Unfreezing Accounts
  1. Tracking Frozen Accounts
    mapping(address => bool) public frozenAccounts;
    
    By default, all values are false, meaning accounts are not frozen unless explicitly set.
  2. Defining Events for Transparency
  3. event AccountFrozen(address indexed _addr);
    event AccountThawed(address indexed _addr);
    Indexed events allow tracking all freeze/unfreeze actions.
  4. 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.
  5. Modifying _beforeTokenTransfer to Enforce Freezing
    require(!frozenAccounts[from], "The account is frozen");
    
    This prevents transfers from a frozen account but allows receiving funds.
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.