Michael.W基于Foundry精读Openzeppelin第56期——VestingWallet.sol

2024-06-05 00:04

本文主要是介绍Michael.W基于Foundry精读Openzeppelin第56期——VestingWallet.sol,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Michael.W基于Foundry精读Openzeppelin第56期——VestingWallet.sol

      • 0. 版本
        • 0.1 VestingWallet.sol
      • 1. 目标合约
      • 2. 代码精读
        • 2.1 constructor()
        • 2.2 beneficiary() && start() && duration() && receive() payable
        • 2.3 released() && releasable() && vestedAmount(uint64 timestamp) && release()
        • 2.4 released(address token) && releasable(address token) && vestedAmount(address token, uint64 timestamp) && release(address token)

0. 版本

[openzeppelin]:v4.8.3,[forge-std]:v1.5.6

0.1 VestingWallet.sol

Github: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.3/contracts/finance/VestingWallet.sol

VestingWallet库可以给指定的受益人地址按照时间线性释放锁在合约内的Eth和Erc20 token。任何转移至本合约的token都必须遵循释放模型。开发者可通过重写函数vestedAmount(uint64 timestamp)vestedAmount(address token, uint64 timestamp)来自定义token释放模型。

1. 目标合约

VestingWallet合约可直接部署。

全部foundry测试合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/finance/VestingWallet/VestingWallet.t.sol

测试使用的物料合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/finance/VestingWallet/MockERC20.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;import "openzeppelin-contracts/contracts/token/ERC20/ERC20.sol";contract MockERC20 is ERC20 {constructor(string memory name, string memory symbol)ERC20(name, symbol) {}function mint(address account, uint amount) external {_mint(account, amount);}
}

2. 代码精读

2.1 constructor()
    event EtherReleased(uint256 amount);event ERC20Released(address indexed token, uint256 amount);// 已释放的eth总量uint256 private _released;// 记录已释放的各erc20总量(key为erc20地址)mapping(address => uint256) private _erc20Released;// 受益人地址address private immutable _beneficiary;// 释放开始时间戳uint64 private immutable _start;// 释放总时长uint64 private immutable _duration;constructor(address beneficiaryAddress,uint64 startTimestamp,uint64 durationSeconds) payable {// 受益人地址必须是非0地址require(beneficiaryAddress != address(0), "VestingWallet: beneficiary is zero address");// 设置受益人地址_beneficiary = beneficiaryAddress;// 设置领取开始时间戳_start = startTimestamp;// 设置释放总时长_duration = durationSeconds;}

foundry代码验证:

contract VestingWalletTest is Test {VestingWallet private _testing;address private _beneficiary = address(1024);uint64 private _startTimestamp = 100;uint64 private _durationSeconds = 1000;function setUp() external {_testing = new VestingWallet(_beneficiary,_startTimestamp,_durationSeconds);}function test_Constructor() external {assertEq(_testing.beneficiary(), _beneficiary);assertEq(_testing.start(), _startTimestamp);assertEq(_testing.duration(), _durationSeconds);// revert with zero address of beneficiaryvm.expectRevert("VestingWallet: beneficiary is zero address");new VestingWallet(address(0), _startTimestamp, _durationSeconds);}
}
2.2 beneficiary() && start() && duration() && receive() payable
  • beneficiary():返回受益人地址;
  • start():返回释放开始时间戳;
  • duration():返回释放总时长;
  • receive() payable:当合约接收到eth时执行该函数。
    function beneficiary() public view virtual returns (address) {return _beneficiary;}function start() public view virtual returns (uint256) {return _start;}function duration() public view virtual returns (uint256) {return _duration;}receive() external payable virtual {}
2.3 released() && releasable() && vestedAmount(uint64 timestamp) && release()
  • released():返回本合约已释放给收益人的eth总量;
  • releasable():返回当前可释放给收益人的eth数量;
  • vestedAmount(uint64 timestamp):计算处于时间点timestamp,理论上受益人可获得的eth总量;
  • release():释放eth给受益人。
    function released() public view virtual returns (uint256) {return _released;}function releasable() public view virtual returns (uint256) {// 返回值为:截止到目前,理论上应释放的eth数量 - 截止到目前,已释放给受益人的eth数量return vestedAmount(uint64(block.timestamp)) - released();}function vestedAmount(uint64 timestamp) public view virtual returns (uint256) {// 使用时间线性的释放模型。模型输入总量为当前该合约名下全部eth数量与已释放eth数量之和,计算的基准时间点为timestampreturn _vestingSchedule(address(this).balance + released(), timestamp);}function release() public virtual {// 获得当前可释放给收益人的eth数量uint256 amount = releasable();// 本合约已释放给收益人的eth总量自增amount_released += amount;// 抛出事件emit EtherReleased(amount);// 使用Address库,将数量为amount的eth从本合约转给受益人Address.sendValue(payable(beneficiary()), amount);}// 释放模型,当前代码实现为时间线性模型。// - totalAllocation:总的应释放数量// - timestamp:计算的基准时间点function _vestingSchedule(uint256 totalAllocation, uint64 timestamp) internal view virtual returns (uint256) {if (timestamp < start()) {// 如果当前时间戳未到开始时间,返回0return 0;} else if (timestamp > start() + duration()) {// 如果当前时间戳超过了释放期,返回totalAllocationreturn totalAllocation;} else {// 如果当前时间戳处于释放期内,返回 totalAllocation * 从释放开始到现在流逝时间 / 总释放时长return (totalAllocation * (timestamp - start())) / duration();}}

foundry代码验证:

contract VestingWalletTest is Test {VestingWallet private _testing;address private _beneficiary = address(1024);uint64 private _startTimestamp = 100;uint64 private _durationSeconds = 1000;uint private _initialAmount = 10000;function setUp() external {_testing = new VestingWallet(_beneficiary,_startTimestamp,_durationSeconds);// set eth balancevm.deal(address(_testing), _initialAmount);}event EtherReleased(uint amount);function test_releaseEth() external {// case 1: before start timeuint64 currentTimestamp = uint64(block.timestamp);assertEq(currentTimestamp, 1);// test released()assertEq(_testing.released(), 0);// test releasable()assertEq(_testing.releasable(), 0);// test vestedAmount(uint64 timestamp)assertEq(_testing.vestedAmount(currentTimestamp), 0);// at the start timevm.warp(_startTimestamp);assertEq(_testing.released(), 0);assertEq(_testing.releasable(), 0);assertEq(_testing.vestedAmount(_startTimestamp), 0);// in the duration (first release)currentTimestamp = _startTimestamp + 200;vm.warp(currentTimestamp);uint amountToRelease = _initialAmount * 200 / _durationSeconds;assertEq(_testing.released(), 0);assertEq(_testing.releasable(), amountToRelease);assertEq(_testing.vestedAmount(currentTimestamp), _initialAmount * 200 / _durationSeconds);// test release()assertEq(address(_testing).balance, _initialAmount);vm.expectEmit(address(_testing));emit EtherReleased(amountToRelease);_testing.release();assertEq(address(_testing).balance, _initialAmount - amountToRelease);assertEq(_beneficiary.balance, amountToRelease);assertEq(_testing.released(), amountToRelease);assertEq(_testing.releasable(), 0);assertEq(_testing.vestedAmount(currentTimestamp), amountToRelease);// in the duration (second release)currentTimestamp = currentTimestamp + 400;vm.warp(currentTimestamp);uint released = amountToRelease;amountToRelease = _initialAmount * 400 / _durationSeconds;assertEq(_testing.released(), released);assertEq(_testing.releasable(), amountToRelease);assertEq(_testing.vestedAmount(currentTimestamp), released + amountToRelease);// test release()assertEq(address(_testing).balance, _initialAmount - released);_testing.release();assertEq(address(_testing).balance, _initialAmount - released - amountToRelease);assertEq(_beneficiary.balance, released + amountToRelease);assertEq(_testing.released(), released + amountToRelease);assertEq(_testing.releasable(), 0);assertEq(_testing.vestedAmount(currentTimestamp), released + amountToRelease);// after end timecurrentTimestamp = _startTimestamp + _durationSeconds + 1;vm.warp(currentTimestamp);released += amountToRelease;amountToRelease = _initialAmount - released;assertEq(_testing.released(), released);assertEq(_testing.releasable(), amountToRelease);assertEq(_testing.vestedAmount(currentTimestamp), _initialAmount);// test release()assertEq(address(_testing).balance, _initialAmount - released);_testing.release();assertEq(address(_testing).balance, 0);assertEq(_beneficiary.balance, _initialAmount);assertEq(_testing.released(), _initialAmount);assertEq(_testing.releasable(), 0);assertEq(_testing.vestedAmount(currentTimestamp), _initialAmount);}
}
2.4 released(address token) && releasable(address token) && vestedAmount(address token, uint64 timestamp) && release(address token)
  • released(address token):返回本合约已释放给受益人的erc20总量(erc20地址是token);
  • releasable(address token):返回当前可释放给收益人的地址为token的erc20数量;
  • vestedAmount(address token, uint64 timestamp):计算处于时间点timestamp,理论上受益人可获得的地址为token的erc20总量;
  • release(address token):释放地址为token的erc20给受益人。
    function released(address token) public view virtual returns (uint256) {return _erc20Released[token];}function releasable(address token) public view virtual returns (uint256) {// 返回值为:截止到目前,理论上应释放的地址为token的erc20数量 - 截止到目前,已释放给受益人的地址为token的erc20数量return vestedAmount(token, uint64(block.timestamp)) - released(token);}function vestedAmount(address token, uint64 timestamp) public view virtual returns (uint256) {// 使用时间线性的释放模型。模型输入总量为当前该合约名下地址为token的erc20数量与已释放的该token总量之和,计算的基准时间点为timestampreturn _vestingSchedule(IERC20(token).balanceOf(address(this)) + released(token), timestamp);}function release(address token) public virtual {// 获得当前可释放给收益人的地址为token的erc20的数量uint256 amount = releasable(token);// 本合约已释放给受益人的erc20总量(erc20地址是token)自增amount_erc20Released[token] += amount;// 抛出事件emit ERC20Released(token, amount);// 使用SafeERC20库,将数量为amount的地址为token的erc20转给受益人SafeERC20.safeTransfer(IERC20(token), beneficiary(), amount);}

foundry代码验证:

contract VestingWalletTest is Test {VestingWallet private _testing;MockERC20 private _erc20 = new MockERC20("test name", "test symbol");address private _beneficiary = address(1024);uint64 private _startTimestamp = 100;uint64 private _durationSeconds = 1000;uint private _initialAmount = 10000;function setUp() external {_testing = new VestingWallet(_beneficiary,_startTimestamp,_durationSeconds);// set erc20 balance_erc20.mint(address(_testing), _initialAmount);}event ERC20Released(address indexed token, uint amount);function test_releaseErc20() external {address erc20Address = address(_erc20);// case 1: before start timeuint64 currentTimestamp = uint64(block.timestamp);assertEq(currentTimestamp, 1);// test released(address token)assertEq(_testing.released(erc20Address), 0);// test releasable(address token)assertEq(_testing.releasable(erc20Address), 0);// test vestedAmount(address token, uint64 timestamp)assertEq(_testing.vestedAmount(erc20Address, currentTimestamp), 0);// at the start timevm.warp(_startTimestamp);assertEq(_testing.released(erc20Address), 0);assertEq(_testing.releasable(erc20Address), 0);assertEq(_testing.vestedAmount(erc20Address, _startTimestamp), 0);// in the duration (first release)currentTimestamp = _startTimestamp + 200;vm.warp(currentTimestamp);uint amountToRelease = _initialAmount * 200 / _durationSeconds;assertEq(_testing.released(erc20Address), 0);assertEq(_testing.releasable(erc20Address), amountToRelease);assertEq(_testing.vestedAmount(erc20Address, currentTimestamp), _initialAmount * 200 / _durationSeconds);// test release(address token)assertEq(_erc20.balanceOf(address(_testing)), _initialAmount);vm.expectEmit(address(_testing));emit ERC20Released(erc20Address, amountToRelease);_testing.release(erc20Address);assertEq(_erc20.balanceOf(address(_testing)), _initialAmount - amountToRelease);assertEq(_erc20.balanceOf(_beneficiary), amountToRelease);assertEq(_testing.released(erc20Address), amountToRelease);assertEq(_testing.releasable(erc20Address), 0);assertEq(_testing.vestedAmount(erc20Address, currentTimestamp), amountToRelease);// in the duration (second release)currentTimestamp = currentTimestamp + 400;vm.warp(currentTimestamp);uint released = amountToRelease;amountToRelease = _initialAmount * 400 / _durationSeconds;assertEq(_testing.released(erc20Address), released);assertEq(_testing.releasable(erc20Address), amountToRelease);assertEq(_testing.vestedAmount(erc20Address, currentTimestamp), released + amountToRelease);// test release(address token)assertEq(_erc20.balanceOf(address(_testing)), _initialAmount - released);_testing.release(erc20Address);assertEq(_erc20.balanceOf(address(_testing)), _initialAmount - released - amountToRelease);assertEq(_erc20.balanceOf(_beneficiary), released + amountToRelease);assertEq(_testing.released(erc20Address), released + amountToRelease);assertEq(_testing.releasable(erc20Address), 0);assertEq(_testing.vestedAmount(erc20Address, currentTimestamp), released + amountToRelease);// after end timecurrentTimestamp = _startTimestamp + _durationSeconds + 1;vm.warp(currentTimestamp);released += amountToRelease;amountToRelease = _initialAmount - released;assertEq(_testing.released(erc20Address), released);assertEq(_testing.releasable(erc20Address), amountToRelease);assertEq(_testing.vestedAmount(erc20Address, currentTimestamp), _initialAmount);// test release(address token)assertEq(_erc20.balanceOf(address(_testing)), _initialAmount - released);_testing.release(erc20Address);assertEq(_erc20.balanceOf(address(_testing)), 0);assertEq(_erc20.balanceOf(_beneficiary), _initialAmount);assertEq(_testing.released(erc20Address), _initialAmount);assertEq(_testing.releasable(erc20Address), 0);assertEq(_testing.vestedAmount(erc20Address, currentTimestamp), _initialAmount);}
}

ps:
本人热爱图灵,热爱中本聪,热爱V神。
以下是我个人的公众号,如果有技术问题可以关注我的公众号来跟我交流。
同时我也会在这个公众号上每周更新我的原创文章,喜欢的小伙伴或者老伙计可以支持一下!
如果需要转发,麻烦注明作者。十分感谢!

在这里插入图片描述

公众号名称:后现代泼痞浪漫主义奠基人

这篇关于Michael.W基于Foundry精读Openzeppelin第56期——VestingWallet.sol的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1031501

相关文章

SpringBoot集成SOL链的详细过程

《SpringBoot集成SOL链的详细过程》Solanaj是一个用于与Solana区块链交互的Java库,它为Java开发者提供了一套功能丰富的API,使得在Java环境中可以轻松构建与Solana... 目录一、什么是solanaj?二、Pom依赖三、主要类3.1 RpcClient3.2 Public

BERT 论文逐段精读【论文精读】

BERT: 近 3 年 NLP 最火 CV: 大数据集上的训练好的 NN 模型,提升 CV 任务的性能 —— ImageNet 的 CNN 模型 NLP: BERT 简化了 NLP 任务的训练,提升了 NLP 任务的性能 BERT 如何站在巨人的肩膀上的?使用了哪些 NLP 已有的技术和思想?哪些是 BERT 的创新? 1标题 + 作者 BERT: Pre-trainin

论文精读-Supervised Raw Video Denoising with a Benchmark Dataset on Dynamic Scenes

论文精读-Supervised Raw Video Denoising with a Benchmark Dataset on Dynamic Scenes 优势 1、构建了一个用于监督原始视频去噪的基准数据集。为了多次捕捉瞬间,我们手动为对象s创建运动。在高ISO模式下捕获每一时刻的噪声帧,并通过对多个噪声帧进行平均得到相应的干净帧。 2、有效的原始视频去噪网络(RViDeNet),通过探

天然药物化学史话:“四大光谱”在天然产物结构鉴定中的应用-文献精读46

天然药物化学史话:“四大光谱”在天然产物结构鉴定中的应用,天然产物化学及其生物合成必备基础知识~ 摘要 天然产物化学研究在药物研发中起着非常重要的作用,结构研究又是天然产物化学研究中最重要的工作之一。在天然药物化学史话系列文章的基础上,对在天然产物结构研究中起绝对主导作用的“四大光谱”分析技术,即红外光谱、紫外光谱、质谱、核磁共振波谱在天然产物结构鉴定中的应用历史进行回顾与总结,并对其发展

56. Merge Interval

题目: 解答: 常规的合并,根据前后interval是否有交集判定。 代码: /*** Definition for an interval.* struct Interval {* int start;* int end;* Interval() : start(0), end(0) {}* Interval(int s, int e) : start

Spark Core源码精读计划7 | Spark执行环境的初始化

推荐阅读 《Spark源码精度计划 | SparkConf》 《Spark Core源码精读计划 | SparkContext组件初始化》 《Spark Core源码精读计划3 | SparkContext辅助属性及后初始化》 《Spark Core源码精读计划4 | SparkContext提供的其他功能》 《Spark Core源码精读计划5 | 事件总线及ListenerBus》 《Spa

Spark Core源码精读计划3 | SparkContext辅助属性及后初始化

推荐阅读 《关于MQ面试的几件小事 | 消息队列的用途、优缺点、技术选型》         《关于MQ面试的几件小事 | 如何保证消息队列高可用和幂等》 《关于MQ面试的几件小事 | 如何保证消息不丢失》 《关于MQ面试的几件小事 | 如何保证消息按顺序执行》 《关于MQ面试的几件小事 | 消息积压在消息队列里怎么办》 《关于Redis的几件小事 | 使用目的与问题及线程模型》 《关于Red

error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL_ errno 10054解决方法

error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054解决方法 不敢保证一定能解决,通过搜索多方博客尝试寻找解决方案,最后clone成功。(PS:不保证能成功) http://www.wangxianfeng.cn/wordpress/2018/07/14/git使用过程中常见错误解决/ https:

【文献精读】基于驱动力表的无人车终端无约束预测纵向控制(TVT)

写在前面: 🌟 欢迎光临 清流君 的博客小天地,这里是我分享技术与心得的温馨角落。📝 个人主页:清流君_CSDN博客,期待与您一同探索 移动机器人 领域的无限可能。 🔍 本文系 清流君 原创之作,荣幸在CSDN首发🐒 若您觉得内容有价值,还请评论告知一声,以便更多人受益。 转载请注明出处,尊重原创,从我做起。 👍 点赞、评论、收藏,三连走一波,让我们一起养成好习惯😜 在这里,您将

向沐神学习笔记:GPT,GPT-2,GPT-3 论文精读【论文精读】GPT部分

系列文章目录 例如: 文章目录 系列文章目录一、GPT1、Abstract 二、1、2、3、 三、1、2、3、 四、1、2、3、 五、1、2、3、 六、1、2、3、 七、1、2、3、 八、1、2、3、 一、GPT 同样模型大小,比如一个亿模型大小的时候,bert的性能表现优于gpt,也就是未来的工作更愿意用bert这篇文章,因为我咬咬牙还能跑起来,但是gpt的实验实