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.

Background

ERC-5827 proposes an ERC-20 allowance that recovers over time after the spender uses it. This article explains how that can support payments such as subscriptions and payroll.

This article explains and expands on the proposal below.

I also cover other EIPs here.

Overview

ERC-5827 adds renewable allowances to ERC-20 approvals. A renewable allowance uses recoveryRate to specify how much spending authorization returns per second, up to the original maximum.

Motivation

Under ERC-20, an owner can allow a particular spender to use up to a specified amount of tokens. A fixed allowance is awkward for recurring payments such as subscriptions, salary payments, and scheduled investments.

Many dapps work around this by asking users for a larger allowance than they immediately need, or for unlimited approval. A malicious spender can immediately withdraw assets up to its allowance, and users may not realize how much authority they have granted.

Why use renewable allowances?

A renewable allowance is similar to a credit limit or a prepaid balance that replenishes over time. An owner can set rules such as the following.

  • Allow a spender to use up to a given number of tokens per day.
  • Replenish the amount available to spend automatically over time.

A maximum and a recovery rate can support recurring payments while limiting how much a spender can take at once. Recovery is continuous, so the amount already available at the start of a day can be spent in addition to the amount recovered during that day.

Specification

ERC-5827 defines IERC5827, an interface that extends ERC-20 so the available portion of an allowance can recover automatically.

The proposal also specifies a proxy interface that adds the feature to existing ERC-20 tokens, and an expiring version, IERC5827Expirable, that can end an allowance at a specified time.

js
pragma solidity ^0.8.0;

interface IERC5827 /* is ERC20, ERC165 */ {
    /*
     * Note: the ERC-165 identifier for this interface is 0x93cd7af6.
     * 0x93cd7af6 ===
     *   bytes4(keccak256('approveRenewable(address,uint256,uint256)')) ^
     *   bytes4(keccak256('renewableAllowance(address,address)')) ^
     *   bytes4(keccak256('approve(address,uint256)') ^
     *   bytes4(keccak256('transferFrom(address,address,uint256)') ^
     *   bytes4(keccak256('allowance(address,address)') ^
     */

    /**
     * @notice  Thrown when the available allowance is less than the transfer amount.
     * @param   available       allowance available; 0 if unset
     */
    error InsufficientRenewableAllowance(uint256 available);

    /**
     * @notice  Emitted when any allowance is set.
     * @dev     MUST be emitted even if a non-renewable allowance is set; if so, the
     * @dev     `_recoveryRate` MUST be 0.
     * @param   _owner          owner of token
     * @param   _spender        allowed spender of token
     * @param   _value          initial and maximum allowance granted to spender
     * @param   _recoveryRate   recovery amount per second
     */
    event RenewableApproval(
        address indexed _owner,
        address indexed _spender,
        uint256 _value,
        uint256 _recoveryRate
    );

    /**
     * @notice  Grants an allowance of `_value` to `_spender` initially, which recovers over time 
     * @notice  at a rate of `_recoveryRate` up to a limit of `_value`.
     * @dev     SHOULD cause `allowance(address _owner, address _spender)` to return `_value`, 
     * @dev     SHOULD throw when `_recoveryRate` is larger than `_value`, and MUST emit a 
     * @dev     `RenewableApproval` event.
     * @param   _spender        allowed spender of token
     * @param   _value          initial and maximum allowance granted to spender
     * @param   _recoveryRate   recovery amount per second
     */
    function approveRenewable(
        address _spender,
        uint256 _value,
        uint256 _recoveryRate
    ) external returns (bool success);

    /**
     * @notice  Returns approved max amount and recovery rate of allowance granted to `_spender` 
     * @notice  by `_owner`.
     * @dev     `amount` MUST also be the initial approval amount when a non-renewable allowance 
     * @dev     has been granted, e.g. with `approve(address _spender, uint256 _value)`.
     * @param    _owner         owner of token
     * @param   _spender        allowed spender of token
     * @return  amount initial and maximum allowance granted to spender
     * @return  recoveryRate recovery amount per second
     */
    function renewableAllowance(address _owner, address _spender)
        external
        view
        returns (uint256 amount, uint256 recoveryRate);

    /// Overridden ERC-20 functions

    /**
     * @notice  Grants a (non-increasing) allowance of _value to _spender and clears any existing 
     * @notice  renewable allowance.
     * @dev     MUST clear set `_recoveryRate` to 0 on the corresponding renewable allowance, if 
     * @dev     any.
     * @param   _spender        allowed spender of token
     * @param   _value          allowance granted to spender
     */
    function approve(address _spender, uint256 _value)
        external
        returns (bool success);

    /**
    * @notice   Moves `amount` tokens from `from` to `to` using the caller's allowance.
    * @dev      When deducting `amount` from the caller's allowance, the allowance amount used 
    * @dev      SHOULD include the amount recovered since the last transfer, but MUST NOT exceed 
    * @dev      the maximum allowed amount returned by `renewableAllowance(address _owner, address 
    * @dev      _spender)`. 
    * @dev      SHOULD also throw `InsufficientRenewableAllowance` when the allowance is 
    * @dev      insufficient.
    * @param    from            token owner address
    * @param    to              token recipient
    * @param    amount          amount of token to transfer
    */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);

    /**
     * @notice  Returns amount currently spendable by `_spender`.
     * @dev     The amount returned MUST be as of `block.timestamp`, if a renewable allowance 
     * @dev     for the `_owner` and `_spender` is present.
     * @param   _owner         owner of token
     * @param   _spender       allowed spender of token
     * @return  remaining allowance at the current point in time
     */
    function allowance(address _owner, address _spender)
        external
        view
        returns (uint256 remaining);
}

Core features

Renewable allowances (IERC5827)

IERC5827 adds a recoveryRate parameter to approvals. The available allowance recovers each second at that rate until it reaches the configured maximum.

js
approveRenewable(address _spender, uint256 _value, uint256 _recoveryRate)
  • Grants _spender an allowance with an initial and maximum amount of _value. The allowance recovers by _recoveryRate per second.
  • The interface recommends rejecting a _recoveryRate greater than _value.
  • A successful call emits RenewableApproval.
js
renewableAllowance(address _owner, address _spender)
  • Returns the maximum allowance and the recovery rate that _owner granted to _spender.

This lets an owner authorize recurring expenses, such as subscription fees or scheduled investments, without granting unlimited approval.

Compatibility with existing ERC-20 approvals

Applications can still call the standard ERC-20 function approve(address _spender, uint256 _value). A standard approval resets the recovery rate to zero.

An implementation also needs to update allowance() and transferFrom() so they account for renewable allowances.

Proxy contract (IERC5827Proxy)

js
interface IERC5827Proxy /* is IERC5827 */ {

    /*
     * Note: the ERC-165 identifier for this interface is 0xc55dae63.
     * 0xc55dae63 ===
     *   bytes4(keccak256('baseToken()')
     */

    /**
     * @notice   Get the underlying base token being proxied.
     * @return   baseToken address of the base token
     */
    function baseToken() external view returns (address);
}

A proxy lets users use renewable allowances with existing tokens without modifying the original token contract.

  • baseToken()
    • Returns the address of the underlying ERC-20 token.
  • transfer()
    • Performs the transfer using the underlying token. The proxy does not emit another Transfer event because the token already emits one.

This adds renewable allowances while keeping the underlying ERC-20 token intact.

Expiring allowances (IERC5827Expirable)

js
interface IERC5827Expirable /* is IERC5827 */ {
    /*
     * Note: the ERC-165 identifier for this interface is 0x46c5b619.
     * 0x46c5b619 ===
     *   bytes4(keccak256('approveRenewable(address,uint256,uint256,uint64)')) ^
     *   bytes4(keccak256('renewableAllowance(address,address)')) ^
     */

    /**
     * @notice  Grants an allowance of `_value` to `_spender` initially, which recovers over time 
     * @notice  at a rate of `_recoveryRate` up to a limit of `_value` and expires at 
     * @notice  `_expiration`.
     * @dev     SHOULD throw when `_recoveryRate` is larger than `_value`, and MUST emit 
     * @dev     `RenewableApproval` event.
     * @param   _spender        allowed spender of token
     * @param   _value          initial allowance granted to spender
     * @param   _recoveryRate   recovery amount per second
     * @param   _expiration     Unix time (in seconds) at which the allowance expires
     */
    function approveRenewable(
        address _spender,
        uint256 _value,
        uint256 _recoveryRate,
        uint64 _expiration
    ) external returns (bool success);

    /**
     * @notice  Returns approved max amount, recovery rate, and expiration timestamp.
     * @return  amount initial and maximum allowance granted to spender
     * @return  recoveryRate recovery amount per second
     * @return  expiration Unix time (in seconds) at which the allowance expires
     */
    function renewableAllowance(address _owner, address _spender)
        external
        view
        returns (uint256 amount, uint256 recoveryRate, uint64 expiration);
}

This extension adds an expiration time so a renewable allowance can end automatically.

js
approveRenewable(address _spender, uint256 _value, uint256 _recoveryRate, uint64 _expiration)
  • Grants _spender an initial allowance of _value. It recovers at _recoveryRate and expires at _expiration.
js
renewableAllowance(address _owner, address _spender)
  • Returns the maximum allowance, recovery rate, and expiration timestamp.

An expiration can limit a payment authorization to one month, for example, and prevent it from remaining active after it is no longer needed.

Rationale

One way to implement recurring allowances would be to reset the balance at fixed intervals. A continuous recoveryRate gives owners more flexibility.

The available amount recovers steadily without relying on a scheduled reset at each period boundary.

Compatibility

ERC-5827 does not require issuing a new version of an existing ERC-20 token. A proxy that implements IERC5827Proxy can add renewable allowances on top of an already issued token.

Reference Implementation

The proposal supplies a minimal reference implementation.

ERC5827.sol
// SPDX-License-Identifier: CC0-1.0
pragma solidity 0.8.17;

import "openzeppelin-contracts/token/ERC20/ERC20.sol";
import "./IERC5827.sol";

contract ERC5827 is ERC20, IERC5827 {
    struct RenewableAllowance {
        uint256 amount;
        uint192 recoveryRate;
        uint64 lastUpdated;
    }

    // owner => spender => renewableAllowance
    mapping(address => mapping(address => RenewableAllowance))
        private rAllowance;

    constructor(
        string memory name_,
        string memory symbol_
    ) ERC20(name_, symbol_) {}

    function approve(
        address _spender,
        uint256 _value
    ) public override(ERC20, IERC5827) returns (bool success) {
        address owner = _msgSender();
        _approve(owner, _spender, _value, 0);
        return true;
    }

    function approveRenewable(
        address _spender,
        uint256 _value,
        uint256 _recoveryRate
    ) public override returns (bool success) {
        address owner = _msgSender();
        _approve(owner, _spender, _value, _recoveryRate);
        return true;
    }

    function _approve(
        address _owner,
        address _spender,
        uint256 _value,
        uint256 _recoveryRate
    ) internal virtual {
        require(
            _recoveryRate <= _value,
            "recoveryRate must be less than or equal to value"
        );

        rAllowance[_owner][_spender] = RenewableAllowance({
            amount: _value,
            recoveryRate: uint192(_recoveryRate),
            lastUpdated: uint64(block.timestamp)
        });

        _approve(_owner, _spender, _value);
        emit RenewableApproval(_owner, _spender, _value, _recoveryRate);
    }

    /// @notice fetch amounts spendable by _spender
    /// @return remaining allowance at the current point in time
    function allowance(
        address _owner,
        address _spender
    ) public view override(ERC20, IERC5827) returns (uint256 remaining) {
        return _remainingAllowance(_owner, _spender);
    }

    /// @dev returns the sum of two uint256 values, saturating at 2**256 - 1
    function saturatingAdd(
        uint256 a,
        uint256 b
    ) internal pure returns (uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return type(uint256).max;
            return c;
        }
    }

    function _remainingAllowance(
        address _owner,
        address _spender
    ) private view returns (uint256) {
        RenewableAllowance memory a = rAllowance[_owner][_spender];
        uint256 remaining = super.allowance(_owner, _spender);

        uint256 recovered = uint256(a.recoveryRate) *
            uint64(block.timestamp - a.lastUpdated);
        uint256 remainingAllowance = saturatingAdd(remaining, recovered);
        return remainingAllowance > a.amount ? a.amount : remainingAllowance;
    }

    /// @notice fetch approved max amount and recovery rate
    /// @return amount initial and maximum allowance given to spender
    /// @return recoveryRate recovery amount per second
    function renewableAllowance(
        address _owner,
        address _spender
    ) public view returns (uint256 amount, uint256 recoveryRate) {
        RenewableAllowance memory a = rAllowance[_owner][_spender];
        return (a.amount, uint256(a.recoveryRate));
    }

    /// @notice transfers base token with renewable allowance logic applied
    /// @param from owner of base token
    /// @param to recipient of base token
    /// @param amount amount to transfer
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public override(ERC20, IERC5827) returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual override {
        (uint256 maxAllowance, ) = renewableAllowance(owner, spender);
        if (maxAllowance != type(uint256).max) {
            uint256 currentAllowance = _remainingAllowance(owner, spender);
            if (currentAllowance < amount) {
                revert InsufficientRenewableAllowance({
                    available: currentAllowance
                });
            }

            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
            rAllowance[owner][spender].lastUpdated = uint64(block.timestamp);
        }
    }

    function supportsInterface(
        bytes4 interfaceId
    ) public view virtual returns (bool) {
        return interfaceId == type(IERC5827).interfaceId;
    }
}

Security Considerations

ERC-5827 can restrict spending more tightly than an unlimited ERC-20 allowance, but a high recoveryRate still lets a spender transfer a large amount in a short time.

Applications without ERC-5827 support may interpret the result of allowance() or an amount in an Approval event as a fixed spending ceiling. With a renewable allowance, the available amount can recover over time. Applications that calculate or display spending limits need to account for the distinction between the currently available allowance and the configured maximum and recovery rate.

Citation

zlace (@zlace0x), zhongfu (@zhongfu), edison0xyz (@edison0xyz), "ERC-5827: Auto-renewable allowance extension [DRAFT]," Ethereum Improvement Proposals, no. 5827, October 2022. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-5827.

Conclusion

ERC-5827 adds a renewable ERC-20 allowance that recovers at a specified rate after it has been used, up to a maximum set by the owner.

Questions are welcome via direct message.

Twitter @cardene777

You can find more of my work at these links.

https://chaldene.net/