EIPs Explained

ERC-5827 · Stagnant(停滞) · ERC · 2022-10-22

ERC-5827: Auto-renewable allowance extension

一个 ERC-20 扩展,授权额度会以每秒固定的速率自动回填直至上限,无需无限授权即可实现订阅和支出限额。

它解决什么问题?

ERC-20 的授权额度(allowance)是一个固定数值。对于周期性支付(订阅、工资、定期定额买入),这很不方便:要么用户每个周期重新授权,要么 dapp 请求一个巨大甚至无限的额度。当合约是恶意的或被攻击时,无限授权是用户损失资金的常见原因。

ERC-5827 增加了可续期授权额度:用户授权一个最大额度和一个恢复速率。花费方用掉一部分之后,额度会以该速率向最大值回升。它的工作方式类似信用卡或借记卡限额,例如"最多 100 USDC,每 30 天恢复 100 USDC"。

它如何运作

  • approveRenewable(spender, value, recoveryRate) 把初始额度和上限都设为 value;recoveryRate 是每秒的代币数。如果 recoveryRate > value,它应当(SHOULD)回滚,并且必须(MUST)触发 RenewableApproval(owner, spender, value, recoveryRate)。
  • renewableAllowance(owner, spender) 返回上限和恢复速率。
  • allowance(owner, spender) 被重写为返回此刻可花费的额度:剩余额度加上自上次花费以来已恢复的部分,且不超过上限。
  • transferFrom 从这个恢复后的额度中扣除,如果额度太小,应当以 InsufficientRenewableAllowance(available) 回滚。
  • 普通的 approve 仍然可用,并把恢复速率设为 0(普通的、不会续期的额度)。
  • supportsInterface(0x93cd7af6) 必须返回 true。

可选的附加接口:IERC5827Proxy 让现有的 ERC-20 可以把额度的强制执行委托给代理合约,IERC5827Expirable 则为可续期授权增加一个到期时间戳。

示例代码

核心恢复逻辑与客户端调用(ethers v6):

struct Renewable { uint256 maxAmount; uint256 recoveryRate; uint256 remaining; uint64 lastUpdated; }
mapping(address => mapping(address => Renewable)) internal _rAllowance;

function allowance(address owner, address spender) public view returns (uint256) {
    Renewable memory a = _rAllowance[owner][spender];
    uint256 recovered = a.recoveryRate * (block.timestamp - a.lastUpdated);
    uint256 total = a.remaining + recovered;
    return total > a.maxAmount ? a.maxAmount : total;
}

function _spendAllowance(address owner, address spender, uint256 amount) internal {
    uint256 available = allowance(owner, spender);
    if (available < amount) revert InsufficientRenewableAllowance(available);
    Renewable storage a = _rAllowance[owner][spender];
    a.remaining = available - amount;
    a.lastUpdated = uint64(block.timestamp);
}
import { parseUnits } from "ethers";

// Allow a subscription contract to pull up to 100 tokens, refilling over 30 days
const cap = parseUnits("100", 18);
const perSecond = cap / BigInt(30 * 24 * 60 * 60);
await token.approveRenewable(subscriptionContract, cap, perSecond);

需要注意

  • 状态:Stagnant。原生实现它的代币很少;对现有代币来说,代理版本才是现实的途径。
  • 恢复是连续的,而不是按离散周期进行。如果每秒速率很高,花费方仍然可以通过多笔交易提走很多。
  • 不了解 ERC-5827 的工具可能会把 allowance() 或 Approval 事件解读为花费方最多能拿走的数额。而对于可续期额度,花费方随时间推移可以拿走更多。
  • 相关思路:ERC-2612(签名授权)和 ERC-7674(临时的、单笔交易内的授权)。

#erc20 #allowance #subscription #payments #extension

详细信息

作者
zlace (@zlace0x), zhongfu (@zhongfu), edison0xyz (@edison0xyz)
状态
Stagnant(停滞)
类型
Standards Track / ERC
创建日期
2022-10-22
依赖的提案

机器可读数据: Markdown · JSON