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

  • Michael.W
  • 更新于 2024-06-04 18:02
  • 阅读 1401

VestingWallet库可给指定的受益人按时间线性释放锁在合约内的Eth或Erc20 token。任何转移至本合约的token都必须遵循释放模型。开发者可通过重写vestedAmount(uint64)vestedAmount(address,uint64)来自定义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 beneficiary
        vm.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数量之和,计算的基准时间点为timestamp
        return _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()) {
            // 如果当前时间戳未到开始时间,返回0
            return 0;
        } else if (timestamp > start() + duration()) {
            // 如果当前时间戳超过了释放期,返回totalAllocation
            return 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 balance
        vm.deal(address(_testing), _initialAmount);
    }

    event EtherReleased(uint amount);

    function test_releaseEth() external {
        // case 1: before start time
        uint64 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 time
        vm.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 time
        currentTimestamp = _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总量之和,计算的基准时间点为timestamp
        return _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 time
        uint64 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 time
        vm.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 time
        currentTimestamp = _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神。 以下是我个人的公众号,如果有技术问题可以关注我的公众号来跟我交流。 同时我也会在这个公众号上每周更新我的原创文章,喜欢的小伙伴或者老伙计可以支持一下! 如果需要转发,麻烦注明作者。十分感谢!

1.jpeg

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

点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
Michael.W
Michael.W
0x93E7...0000
狂热的区块链爱好者