Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

ERC-7818 proposes a mechanism for managing ERC-20 tokens with expiration dates.

This article translates, summarizes, and expands on the proposal below.

Other EIP explanations are available here:

Overview

ERC-7818 proposes adding contract-level expiration management and enforcement while maintaining compatibility with the ERC-20 standard.

For an introduction to ERC-20, see the following article.

https://chaldene.net/erc20

Expiration dates are particularly useful in the following scenarios:

  • Time-limited bonds and financial instruments.
    • Examples: tokenized government and corporate bonds with redemption deadlines.
  • In-game items or currencies that can be used only during a specified period.
  • Loyalty programs with expiration dates.
    • Examples: expiring points and coupons.
  • Prepaid credits and services.
    • Examples: mobile data, cashback, fuel, and computing resources.
  • Postpaid mobile data packages.
    • Example: mobile data plans that reset every month.
  • Electronic money usable only within a particular ecosystem.
    • Examples: public transport, food courts, and retailers.

Motivation

The proposal addresses the need for time-limited tokens. Under the existing ERC-20 standard, tokens are generally valid indefinitely. Many use cases, however, can be managed more appropriately by introducing expiration dates.

Use cases

Financial instruments and bonds

One application is tokenized bonds that mature after a specified period. The tokens can become invalid after maturity as part of the redemption process.

In-game assets

Event-exclusive items and time-limited in-game currencies can use expiration to help maintain the balance of a game's economy.

Loyalty programs

Expiring points can be managed to encourage redemption within a specified period.

Examples include credit card cashback and frequent flyer miles.

Prepaid and postpaid services

Prepaid data packages, fuel, and cloud computing credits can be configured to expire if they are not used within a specified period. One example is a mobile carrier's data plan that resets monthly.

Electronic money (e-money)

The mechanism can be applied to electronic money usable only on public transport, at food courts, or in retail stores. Introducing time-limited payment instruments can encourage users to spend them within a short period.

Specification

Epoch Mechanism

An epoch is a specified time interval or range of blocks used to manage token validity. The mechanism allows tokens to remain valid for a certain period or number of blocks, after which they expire.

There are two ways to define an epoch:

  • Block-based

    • A fixed number of blocks (for example, 1,000 blocks) constitutes one epoch.
    • Token validity is evaluated as epochs advance.
    • When block production intervals vary in Proof of Work (PoW) or Proof of Stake (PoS) systems, measuring epochs in blocks rather than time may be appropriate in some cases.
  • Time-based

    • A fixed number of seconds (for example, 1,000 seconds) constitutes one epoch.
    • The contract uses the block timestamp to determine the validity period.

Tokens associated with a particular epoch remain valid while that epoch is within the active validity window. Once it expires, those tokens can no longer be transferred or used.

Balance Look Back Over Epochs

This epoch mechanism can consult the current epoch and previous epochs to calculate the available balance.

  1. Check valid tokens from the current epoch back to n epochs ago.
  2. Calculate the available balance as the sum of tokens that have not expired.
  3. Adjust how far back tokens remain valid using the configured value of n.

This allows the total valid balance within a specified range (up to n epochs ago) to be calculated.

Example

Epoch Balance
1 100
2 150
3 200
  • Current epoch.
    • 3
  • Include valid tokens up to one epoch ago (n=1).
  • Available balance.
    • 150 (Epoch 2) + 200 (Epoch 3) = 350

By retrieving valid tokens up to n epochs ago, this mechanism provides flexible balance management for time-limited tokens.

Contract requirements

To keep the extension compatible with ERC-20, the following conditions need to be satisfied:

  • Inherit the standard ERC-20 interface

    • Support all basic ERC-20 functions, including balanceOf, transfer, and approve.
  • Implement epoch management

    • Manage the epoch.
    • Manage the balance associated with each epoch.
    • Invalidate tokens as epochs advance.
  • Calculate valid balances

    • Retrieve valid tokens up to n epochs ago.
    • Implement the usableBalanceOf(address, n) function.

The epoch mechanism allows tokens to be designed with limited validity periods, simplifying automatic expiration and the management of expiring assets.

Interface

js
// SPDX-License-Identifier: CC0-1.0
pragma solidity >=0.8.0 <0.9.0;

/**
 * @title ERC-7818 interface
 * @dev Interface for adding expirable functionality to ERC20 tokens.
 */

import "./IERC20.sol";

interface IERC7818 is IERC20 {
    /**
     * @dev Enum represents the types of `epoch` that can be used.
     * @notice The implementing contract may use one of these types to define how the `epoch` is measured.
     */
    enum EPOCH_TYPE {
        BLOCKS_BASED, // measured in the number of blocks (e.g., 1000 blocks)
        TIME_BASED // measured in seconds (UNIX time) (e.g., 1000 seconds)
    }

    /**
     * @dev Retrieves the balance of a specific `epoch` owned by an account.
     * @param epoch The `epoch for which the balance is checked.
     * @param account The address of the account.
     * @return uint256 The balance of the specified `epoch`.
     * @notice "MUST" return 0 if the specified `epoch` is expired.
     */
    function balanceOfAtEpoch(
        uint256 epoch,
        address account
    ) external view returns (uint256);

    /**
     * @dev Retrieves the latest epoch currently tracked by the contract.
     * @return uint256 The latest epoch of the contract.
     */
    function currentEpoch() external view returns (uint256);

    /**
     * @dev Retrieves the duration of a single epoch.
     * @return uint256 The duration of a single epoch.
     * @notice The unit of the epoch length is determined by the `validityPeriodType` function.
     */
    function epochLength() external view returns (uint256);

    /**
     * @dev Returns the type of the epoch.
     * @return EPOCH_TYPE  Enum value indicating the unit of an epoch.
     */
    function epochType() external view returns (EPOCH_TYPE);
    
    /**
     * @dev Retrieves the validity duration in `epoch` counts.
     * @return uint256 The validity duration in `epoch` counts.
     */
    function validityDuration() external view returns (uint256);

    /**
     * @dev Checks whether a specific `epoch` is expired.
     * @param epoch The `epoch` to check.
     * @return bool True if the token is expired, false otherwise.
     * @notice Implementing contracts "MUST" define and document the logic for determining expiration,
     * typically by comparing the latest epoch with the given `epoch` value,
     * based on the `EPOCH_TYPE` measurement (e.g., block count or time duration).
     */
    function isEpochExpired(uint256 epoch) external view returns (bool);

    /**
     * @dev Transfers a specific `epoch` and value to a recipient.
     * @param epoch The `epoch` for the transfer.
     * @param to The recipient address.
     * @param value The amount to transfer.
     * @return bool True if the transfer succeeded, otherwise false.
     */
    function transferAtEpoch(
        uint256 epoch,
        address to,
        uint256 value
    ) external returns (bool);

    /**
     * @dev Transfers a specific `epoch` and value from one account to another.
     * @param epoch The `epoch` for the transfer.
     * @param from The sender's address.
     * @param to The recipient's address.
     * @param value The amount to transfer.
     * @return bool True if the transfer succeeded, otherwise false.
     */
    function transferFromAtEpoch(
        uint256 epoch,
        address from,
        address to,
        uint256 value
    ) external returns (bool);
}

EPOCH_TYPE

js
enum EPOCH_TYPE {
    BLOCKS_BASED, // measured in the number of blocks (e.g., 1000 blocks)
    TIME_BASED // measured in seconds (UNIX time) (e.g., 1000 seconds)
}

Overview

An enumeration that defines how epochs are measured. Depending on the contract implementation, epochs can be calculated in two ways.

Details

  • BLOCKS_BASED

Defines an epoch by the number of blocks. For example, if every 1000 blocks count as 1 epoch, the epoch advances whenever another 1000 blocks are produced. This approach is useful when block intervals are not constant.

  • TIME_BASED

Defines an epoch using UNIX time in seconds. For example, if every 1000 seconds count as 1 epoch, the epoch advances every 1000 seconds. This allows consistent time management even when block production intervals fluctuate.


balanceOfAtEpoch

js
function balanceOfAtEpoch(uint256 epoch, address account) external view returns (uint256);

Overview

Retrieves an account's token balance for a specified epoch.

Details

The function returns the account's balance within the specified epoch. If that epoch has expired, it returns 0. For example, if epoch 5 has expired, balanceOfAtEpoch(5, address) returns 0.

Parameters

  • epoch
    • The epoch number to query.
  • account
    • The address whose balance is queried.

Return value

  • uint256
    • The token balance at the specified epoch.
    • 0 if the epoch has expired.

currentEpoch

js
function currentEpoch() external view returns (uint256);

Overview

Retrieves the current epoch tracked by the contract.

Details

Returns the current epoch number. Epochs advance according to either blocks or time, as determined by epochType().

Return value

  • uint256
    • The current epoch number.

epochLength

js
function epochLength() external view returns (uint256);

Overview

Retrieves the length of a single epoch.

Details

Returns the duration according to the unit used to measure epochs. If epochType() is BLOCKS_BASED, the duration is measured in blocks. If it is TIME_BASED, the duration is measured in seconds.

Return value

  • uint256
    • The length of one epoch in blocks or seconds.

epochType

js
function epochType() external view returns (EPOCH_TYPE);

Overview

Retrieves the unit used to measure epochs: blocks or time.

Details

Returns the epoch type as a member of the EPOCH_TYPE enumeration.

Return value

  • EPOCH_TYPE
    • The epoch type (BLOCKS_BASED or TIME_BASED).

validityDuration

js
function validityDuration() external view returns (uint256);

Overview

Retrieves the token validity period in epochs.

Details

Returns the number of epochs for which tokens remain valid. For example, if validityDuration() returns 10, tokens expire after 10 epochs.

Return value

  • uint256
    • The token validity period in epochs.

isEpochExpired

js
function isEpochExpired(uint256 epoch) external view returns (bool);

Overview

Determines whether a specified epoch has expired.

Details

Returns whether the specified epoch has expired relative to the current epoch. Typically, the implementation uses validityDuration() to determine the validity period and compares it with the current epoch.

Parameters

  • epoch
    • The epoch number to check.

Return value

  • bool
    • true
      • Expired.
    • false
      • Valid.

transferAtEpoch

js
function transferAtEpoch(uint256 epoch, address to, uint256 value) external returns (bool);

Overview

Transfers tokens from a specified epoch to another address.

Details

Transfers tokens belonging to the specified epoch. An attempt to transfer expired tokens causes the transaction to revert or the function to return false.

Parameters

  • epoch
    • The epoch to which the tokens being transferred belong.
  • to
    • The recipient address.
  • value
    • The amount of tokens to transfer.

Return value

  • bool
    • true
      • Transfer succeeded.
    • false
      • Transfer failed (for example, an attempt to transfer expired tokens).

transferFromAtEpoch

js
function transferFromAtEpoch(uint256 epoch, address from, address to, uint256 value) external returns (bool);

Overview

Transfers tokens from a specified epoch on behalf of another address.

Details

This is the version of transferAtEpoch() that takes a from address, allowing transfers of tokens held by an address other than msg.sender. An attempt to transfer expired tokens causes the transaction to revert or the function to return false. Typically, msg.sender must first receive an allowance through approve.

Parameters

  • epoch
    • The epoch to which the tokens being transferred belong.
  • from
    • The sender address.
  • to
    • The recipient address.
  • value
    • The amount of tokens to transfer.

Return value

  • bool
    • true
      • Transfer succeeded.
    • false
      • Transfer failed (for example, an attempt to transfer expired tokens).

Optional functions

getEpochBalance

Retrieves the token balance for a specified epoch. This function can retrieve balances even for expired epochs.

getEpochInfo

Retrieves the start and end times or block numbers of a specified epoch. This allows callers to determine when a particular epoch begins and ends.

getNearestExpiryOf

Retrieves information about the tokens closest to expiration. Users can use this information to decide which tokens to spend first.

getRemainingDurationBeforeEpochChange

Retrieves the time or number of blocks remaining before the current epoch ends.

  • For BLOCKS_BASED, calculate it from the current block and epoch length in blocks.
  • For TIME_BASED, calculate it from the current timestamp and epoch length in seconds.

Users can call this function to determine when the next epoch begins.

Additional considerations

The abstraction and flexibility of epochs

An epoch is an abstract concept that leaves room for a range of implementations. Introducing epochs allows both fine-grained control and bulk management of token expiration. Implementations can choose among the following approaches.

More granular tracking

Epochs allow tokens to be managed at a more granular level within each epoch.

For example:

  • Assign different epochs to tokens and manage their validity periods separately.
  • Configure dynamic epoch durations to adjust validity periods according to a token's purpose.

This mechanism allows tokens to be valid only under conditions appropriate to their use.

  • Staking rewards can be issued as tokens with different expiration dates depending on when the rewards were earned.
  • Subscription-based tokens (for example, monthly game subscriptions) can have different expiration dates based on their issuance dates.

Bulk Expiration

Epochs also allow batches of tokens to expire together. Under this approach, all tokens in a batch expire at the same specified epoch.

Possible applications include:

  • Seasonal currency resets in games
    • Example: invalidate all Season 1 currency when Season 2 begins.
  • Promotional points
    • Example: expire all points issued during a particular campaign after the campaign ends.
  • Government or corporate coupons
    • Example: invalidate coupons issued over a specified period (one year) at the end of the fiscal year.

This approach can reduce gas costs compared with managing each token's expiration date separately.

Introducing Lazy Expiry

Epoch-based token management makes lazy expiration possible. Rather than explicitly updating token expiration dates, the contract can determine expiration by consulting its current epoch.

Conventional expiration management may require users or administrators to update expired tokens manually or perform periodic write operations to change token status.

With epochs, expiration can instead be determined by comparing a token's epoch with the current epoch. Token validity is managed automatically without explicit state writes to mark expiration. This can reduce gas costs and improve management efficiency.

Benefits of Lazy Expiry

  • Lower gas costs
    • Calculate the value of currentEpoch() rather than repeatedly writing expiration status.
  • Flexible expiration management
    • Users and administrators do not need to change token expiration dates manually; the contract manages validity as epochs advance.
  • No external expiration service required
    • Off-chain services are sometimes used to process expiration periodically. Epochs can eliminate that requirement.

How Lazy Expiry works

  1. Token expiration is determined by the advancement of epochs.
  2. When an earlier epoch (for example, 10) falls outside the validity window relative to the current epoch (for example, 15), its tokens are considered expired.
  3. Without any write operation, calling isEpochExpired(10) returns true if the epoch is expired.

Compatibility

ERC-7818 is designed to be fully compatible with ERC-20.

Reference implementation

Reference implementations are available below.

Security

Denial of Service (DoS)

When tokens are managed by epoch, transferring small balances distributed across many epochs may sharply increase a transaction's gas consumption.

Example

Suppose a user tries to send tokens spread across 100 epochs in a single transfer. Checking every epoch can result in high gas consumption. Repeated calls to balanceOfAtEpoch(epoch, user) inside a loop can also consume substantial gas, particularly when epochs have accumulated over a long period.

Mitigations

  • Limit batch processing
    • Restrict the number of epochs that a single transaction can process.
    • Example: cap the number of epochs processed at once at 10.
  • Optimize gas usage
    • Skip expired epochs to reduce computation.
    • Avoid loops wherever possible to reduce computational work.
  • Use Lazy Expiry
    • Reduce explicit write operations and manage expiration by epoch to lower gas consumption.

Gas limit vulnerabilities

Blockchains impose a limit on the gas that can be consumed within one block. The original article, dated February 18, 2025, cites a limit of 30 million gas on Ethereum L1. A transaction exceeding the applicable block gas limit cannot be included in a block while that limit remains in effect.

Example

  • A token managing many epochs (for example, 10,000 epochs) may exceed the gas limit when balanceOf(account) has to access every epoch.
  • If a liquidity pool holds a large number of tokens managed by epoch, checking all the epoch information during a transfer can exceed the gas limit.

Mitigations

  • Efficient data management
    • Use a mapping and avoid accessing unnecessary epoch data.
    • For example, manage balances by epoch using a structure such as mapping(uint256 => uint256).
  • Account for the block gas limit
    • Limit the amount of data processed in a single transaction.
    • Use gasleft() to stop processing early if the transaction is close to running out of gas.
  • Use off-chain processing
    • Manage expiration off-chain and send only the minimum required data to the contract.

Risks of using block values as a substitute for time

Time-based epochs commonly use block.timestamp. When a network stops producing blocks, however, block.timestamp stops updating.

Example

  • Ethereum or an L2 network stops for several hours
    • block.timestamp stops advancing, freezing token expiration management.
  • Validators on a PoS chain stop producing blocks for fear of slashing penalties
    • During that period, block.timestamp is not updated and epoch management stops functioning.

As a result, tokens that should have expired may remain valid, potentially disrupting the balance of liquidity pools or games.

Mitigations

  • Consider both time and blocks

    • Design logic that considers block numbers as well as block.timestamp.

    • Example:

      js
      uint256 estimatedTime = block.number * AVERAGE_BLOCK_TIME;
  • Use off-chain oracles

    • Retrieve external time information through oracles such as Chainlink or Pyth.
  • Provide a manual expiration management option

    • Allow administrators to advance the epoch manually as a way to mitigate risks associated with network disruptions.

Fairness concerns

If all tokens expire simultaneously, some users may be treated unfairly.

Example

  • Game event rewards issued as tokens with a shared expiration date
    • Some players can use their tokens just before the deadline, while others are unable to use them before expiration.
  • Economic attacks exploiting bulk expiration
    • Tokens could be deliberately sold just before expiration, leaving other users with worthless tokens.

Mitigations

  • Randomize expiration dates across tokens
    • Example: configure validityDuration individually when issuing tokens.
  • Introduce expiration warnings
    • Add an event such as onExpirationWarning() to notify users.

Risks in liquidity pools

If expiring tokens are deposited into a DEX liquidity pool (such as Uniswap), they may expire while still in the pool and become untradeable.

Mitigations

  • Introduce a mechanism to remove expired tokens automatically.
  • Restrict trading of tokens that have expired within the liquidity pool.
  • Design the pool so that expired tokens do not adversely affect LP tokens.

Conclusion

This article examined ERC-7818, a proposal for managing ERC-20 tokens with expiration dates.

If you have questions, feel free to get in touch by direct message on Twitter.

Twitter @cardene777

I also publish articles on the following platforms:

https://chaldene.net/