ERC-7410 · Draft(草案) · ERC · 2023-07-26
ERC-7410: ERC-20 Update Allowance By Spender
一个草案的 ERC-20 扩展,允许被授权的 spender(而不只是所有者)减少或撤销自己获得的额度,在所有者是响应缓慢的多签或金库时很有用。
它解决什么问题?
在 ERC-20 中,只有代币所有者可以修改授权额度。当所有者是金库或多签,并且授予了 spender 远超所需的额度时,这就成了问题:缩减授权需要收集签名并协调,耗时较长。与此同时,spender(可能是协议合约或服务账户)也许知道自己已不再需要这笔额度,或者担心自己的密钥有风险。
ERC-7410 让 spender 可以自行交还权限,在不改变所有者任何操作的前提下,增加了一个快速的安全阀。
它如何运作
代币增加一个函数:
function decreaseAllowanceBySpender(address owner, uint256 subtractedValue) external;
- 调用者是 spender;它将
allowance(owner, msg.sender)减少subtractedValue。 - 如果
subtractedValue大于或等于当前额度,额度变为 0。 - 如果当前额度为
type(uint256).max("无限"授权),任何调用都会将其设为 0。无法对无限授权进行部分减少。 - 必须触发标准的 ERC-20
Approval事件,并带上新值。 - 代币必须实现 ERC-165,并对接口 ID
0x12860fba返回true。
示例代码
为 OpenZeppelin ERC-20 添加该扩展:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
contract SpenderRevocableToken is ERC20, ERC165 {
constructor() ERC20("Demo", "DEMO") { _mint(msg.sender, 1e24); }
function decreaseAllowanceBySpender(address owner, uint256 subtractedValue) external {
uint256 current = allowance(owner, msg.sender);
uint256 next = (current == type(uint256).max || subtractedValue >= current)
? 0
: current - subtractedValue;
_approve(owner, msg.sender, next, true); // emits Approval
}
function supportsInterface(bytes4 id) public view override returns (bool) {
return id == 0x12860fba || super.supportsInterface(id);
}
}
以 spender 身份调用(ethers v6):
import { Contract, MaxUint256, parseUnits } from "ethers";
const token = new Contract(tokenAddr, ["function decreaseAllowanceBySpender(address,uint256)"], spenderWallet);
await token.decreaseAllowanceBySpender(treasuryAddr, parseUnits("500", 18)); // shrink by 500
await token.decreaseAllowanceBySpender(treasuryAddr, MaxUint256); // revoke fully
需要注意
- 状态为 Draft。
- 它只适用于实现了它的代币;已有的 ERC-20 代币无法事后改造。
- spender 可以取消所有者本想保留的额度(例如用于定期付款)。规范接受这一点,因为放弃权利比使用权利的危害小,但集成方不应假定额度会保持稳定。
- 实现更安全授权的相关方法还有 ERC-2612 的
permit,它可以避免长期存在的额度。