ERC-1620 · Stagnant(停滞) · ERC · 2018-11-24
ERC-1620: Money Streaming
一种资金流式支付标准:付款方把 ERC-20 代币锁定在合约中,收款方可随着区块推进持续提取,把工资和订阅变成按使用付费的资金流。
它解决什么问题?
工资、房租和订阅通常按月分批支付,因为传统支付渠道频繁使用的成本很高。这就迫使一方必须信任另一方:员工工作一个月后才拿到报酬,或者订阅者提前预付一个月。
在区块链上,“随时间变化的资金”是可行的。ERC-1620 标准化了这样一种合约:资金逐个区块地从发送方流向接收方。接收方可以随时提取已累计的部分,任何一方都可以停止资金流并公平地分配余额。
它如何运作
一个主合约保存许多条资金流。每个 Stream 记录:
sender、recipient和tokenAddress(一种 ERC-20 代币;不应接受以太币),balance:仍在资金流中的资金,timeframe:start和stop区块号,rate:每隔interval个区块释放payment。
流程:
create(recipient, token, startBlock, stopBlock, payment, interval):发送方存入足够支付整个期间的代币。一个发送方可以并行运行多条资金流。balanceOf(streamId, addr):显示各方当前有权获得的金额。接收方的份额大致按支付速率 × (当前区块 − 起始区块)增长。withdraw(streamId, amount):只有接收方可以提取已累计的资金。redeem(streamId):任何一方都可以提前结束资金流。已累计的资金归接收方,其余退回发送方。- 更新:更改代币、结束区块或速率需要所有各方确认;任何一方都可以撤销待处理的更新。
事件(LogCreate、LogWithdraw、LogRedeem、LogConfirmUpdate、LogRevokeUpdate、LogExecuteUpdate)记录每一步。
示例代码
用现代 Solidity 表示的一条资金流的核心记账(简化版,仅作演示):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
struct Stream {
address sender;
address recipient;
address token;
uint256 deposit;
uint256 withdrawn;
uint256 startBlock;
uint256 stopBlock;
uint256 payment; // tokens released per interval
uint256 interval; // blocks per interval
}
library StreamMath {
/// Amount the recipient has earned so far but not yet withdrawn.
function recipientBalance(Stream memory s) internal view returns (uint256) {
if (block.number <= s.startBlock) return 0;
uint256 end = block.number < s.stopBlock ? block.number : s.stopBlock;
uint256 earned = ((end - s.startBlock) / s.interval) * s.payment;
if (earned > s.deposit) earned = s.deposit;
return earned - s.withdrawn;
}
/// What the sender would get back if the stream were redeemed now.
function senderBalance(Stream memory s) internal view returns (uint256) {
return s.deposit - s.withdrawn - recipientBalance(s);
}
}
需要注意
- 状态为 Stagnant。该规范是早期的草图,其方法列表存在不一致(例如
confirmUpdate和revokeUpdate下给出的签名与标题不符)。请把它当作一个概念,而不是完成的接口。 - 区块号被用来代替时间。如果平均出块时间改变,资金流在现实时间中会比预期更早或更晚结束。规范对此做了大量讨论,建议通过
update重新协商,或使用来自预言机的时间戳。改用block.timestamp是常见的替代方案。 - 请提前锁定全部存款。否则,接收方已累计的余额只是一个承诺。
- 规范提到了未来的“多跳”资金流(A 到 B 再到 C),但没有定义它们。