Skip to content

CodesenSys/ERC20-Solady-Foundry

Repository files navigation

CodesenSys ERC20 Implementation (Foundry | Solady)

A production-grade, security-first ERC20 token implementation built by CodesenSys using Foundry and Solady.
It is designed as a reference-grade, extensible, auditable ERC20 codebase suitable for real-world deployments.

The focus is on:

  • Correctness
  • Security
  • Gas efficiency
  • Testability
  • Upgrade-readiness
  • Professional engineering standards

Why This Repository Exists

Most ERC20 examples stop at "it compiles and transfers tokens".

This implementation goes further:

  • Models real production concerns
  • Enforces strict invariants
  • Uses Foundry's testing, fuzzing, and tooling
  • Separates business logic from mechanics
  • Documents design decisions explicitly
  • Provides a clean base for further token systems (vesting, staking, governance, bridges, etc.)

This is intended to be:

  • A starting point for serious token projects
  • A learning reference for professional Solidity engineers
  • A baseline for audits and production deployments

Built With

  • Foundry - Blazing fast, portable and modular toolkit for Ethereum application development
  • Solady - Gas-optimized Solidity libraries by Vectorized
    • Core ERC20 implementation inherits from Solady's highly optimized contracts

Architecture Overview

The system is structured around:

  • Core ERC20 storage and accounting
  • Explicit allowance and approval mechanics
  • Internal mint/burn primitives
  • Strict invariant enforcement:
    • Total supply consistency
    • Balance conservation
    • Allowance correctness
  • Clear separation between:
    • Public API
    • Internal mechanics
    • Policy layers (who can mint, burn, pause, etc.)

Design goals:

  • Predictable storage layout
  • Minimal branching in hot paths
  • Explicit revert reasons
  • Zero ambiguity in accounting logic

ERC20 Features Implemented

  • Standard ERC20 interface:
    • totalSupply()
    • balanceOf()
    • transfer()
    • approve()
    • transferFrom()
    • allowance()
  • Internal primitives:
    • _mint()
    • _burn()
    • _transfer()
    • _approve()
  • Full event compliance:
    • Transfer
    • Approval
  • Safety checks:
    • Zero address protection
    • Underflow/overflow safety (Solidity ^0.8)
    • Allowance spending correctness
  • Gas-optimized flow for:
    • Transfers
    • Allowance updates
    • Supply changes

Engineering Principles

1. Correctness Over Convenience

Every state mutation is explicit. No hidden side effects. No magical flows.

2. Invariants First

The implementation is written around invariants:

  • Sum of balances == totalSupply
  • Transfers do not create or destroy value
  • Mint and burn are the only supply-changing operations

3. Minimal Surface Area

No unnecessary features in the core layer. Policy features (roles, caps, pauses, etc.) are intended to be layered on top.

4. Audit-First Design

The code is structured to be:

  • Readable
  • Traceable
  • Verifiable
  • Easy to reason about in formal or manual audits

Testing Strategy (Foundry)

This repository uses Foundry for:

  • Unit tests
  • Invariant tests
  • Fuzz testing
  • Gas profiling

Test categories include:

  • Transfer correctness
  • Allowance behavior
  • Mint/Burn supply invariants
  • Edge cases:
    • Zero amounts
    • Self-transfers
    • Boundary values
    • Full allowance spending
  • Fuzzing:
    • Randomized transfer sequences
    • Randomized allowance consumption
    • Randomized mint/burn operations

This ensures:

  • No silent balance corruption
  • No supply drift
  • No allowance desync

Project Structure

src/
├── core/
│   ├── BaseERC20.sol          # Abstract ERC20 base; adds zero-address/amount guards
│   ├── Constants.sol          # Token metadata, INITIAL_SUPPLY, MAX_SUPPLY
│   ├── Errors.sol             # Centralised custom error definitions
│   └── Modifiers.sol          # Immutable OWNER and onlyOwner modifier
├── interfaces/
│   └── IERC20.sol             # Full EIP-20 interface + mint/burn extensions
├── tokens/
│   └── CodesenSysToken.sol    # Main token: owner-gated mint, open burn, cap enforced
└── extensions/                # Reserved for future policy layers (roles, pausing, etc.)

test/
├── unit/
│   ├── BaseTest.t.sol         # Shared setUp — deploys token with makeAddr owner
│   ├── Transfer.t.sol         # transfer() unit and fuzz tests
│   ├── Allowance.t.sol        # approve() / transferFrom() unit and fuzz tests
│   └── MintBurn.t.sol         # mint() / burn() unit and fuzz tests
├── fuzz/
│   └── ERC20Fuzz.t.sol        # Stateless multi-step fuzz properties
└── invariant/
    └── ERC20Invariant.t.sol   # Stateful invariant suite with Handler contract

script/
└── Deploy.s.sol               # Foundry deployment script

Extending This Implementation

This base is intentionally clean and minimal.

It is designed to be extended with:

  • Capped supply
  • Role-based minting
  • Pausable transfers
  • Vesting systems
  • Staking systems
  • Governance voting power
  • Bridging adapters
  • Upgradeable proxies

Without modifying the core accounting engine.


Getting Started

Prerequisites

Installation

# Clone the repository
git clone https://github.com/CodesenSys/erc20-implementation.git
cd erc20-implementation

# Install dependencies
forge install

Build

forge build

Test

# Run all tests
forge test

# Run tests with gas reporting
forge test --gas-report

# Run specific test file
forge test --match-path test/ERC20.t.sol

# Run with verbosity
forge test -vvv

Format

forge fmt

Gas Snapshots

forge snapshot

Deploy

forge script script/Deploy.s.sol:DeployScript --rpc-url <your_rpc_url> --private-key <your_private_key>

Foundry Toolkit

Foundry consists of:

  • Forge: Ethereum testing framework (like Truffle, Hardhat and DappTools)
  • Cast: Swiss army knife for interacting with EVM smart contracts, sending transactions and getting chain data
  • Anvil: Local Ethereum node, akin to Ganache, Hardhat Network
  • Chisel: Fast, utilitarian, and verbose solidity REPL

Useful Commands

# Get help
forge --help
anvil --help
cast --help

# Start local node
anvil

# Interact with contracts
cast <subcommand>

For more details, see the Foundry Book.


Security Considerations

This implementation follows security best practices:

  • ✅ Uses Solidity ^0.8 for built-in overflow protection
  • ✅ Inherits from battle-tested Solady libraries
  • ✅ Extensive test coverage including fuzz and invariant tests
  • ✅ Explicit error handling with custom errors
  • ✅ Zero address checks on critical operations
  • ✅ Follows checks-effects-interactions pattern

However, before deploying to production:

  • Conduct a professional security audit
  • Review all extension/policy layers added on top
  • Test thoroughly on testnets
  • Consider formal verification for high-value deployments

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Please ensure:

  • All tests pass
  • Code is formatted with forge fmt
  • New features include tests
  • Documentation is updated

License & Attribution

This project is licensed under the MIT License

Third-Party Dependencies

This implementation builds upon:

  • Solady by Vectorized
    Licensed under the MIT License
    Copyright (c) 2022 Solady Contributors

Special thanks to the Solady team for their highly optimized and gas-efficient Solidity libraries.


Disclaimer

This software is provided "as is", without warranty of any kind. Use at your own risk. Always conduct thorough testing and professional audits before deploying to production environments.


Contact

CodesenSys

For questions or support, please open an issue on GitHub.


Built with ❤️ by CodesenSys

About

A production-ready, security-focused ERC20 token implementation by CodesenSys using Foundry. Includes modular architecture, comprehensive test suite, gas-optimized design, and extensibility patterns suitable for real-world token deployments.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors