Michael.W基于Foundry精读Openzeppelin第53期——ERC20PresetFixedSupply.sol

  • Michael.W
  • 更新于 2024-03-27 10:53
  • 阅读 649

ERC20PresetFixedSupply库是一种带预铸造功能的ERC20实现,即在合约部署时直接将全部流通量都铸造给某一地址且部署后无法增发。该库同时继承了ERC20Burnable库,支持销毁和委托销毁功能。

0. 版本

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

0.1 ERC20PresetFixedSupply.sol

Github: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.3/contracts/token/ERC20/presets/ERC20PresetFixedSupply.sol

ERC20PresetFixedSupply库是一种带预铸造功能的ERC20实现,即在合约部署时直接将全部流通量都铸造给某一地址且部署后无法增发。该库同时继承了ERC20Burnable库,支持销毁和委托销毁功能。ERC20Burnable库详解参见:https://learnblockchain.cn/article/7038

1. 目标合约

ERC20PresetFixedSupply合约可直接部署。

全部foundry测试合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/token/ERC20/preset/ERC20PresetFixedSupply.t.sol

2. 代码精读

2.1 constructor()

    constructor(
        string memory name,
        string memory symbol,
        uint256 initialSupply,
        address owner
    ) ERC20(name, symbol) {
        // 在合约部署时,将全部的流通量都铸造给owner
        _mint(owner, initialSupply);
    }

foundry代码验证:

contract ERC20PresetFixedSupplyTest is Test {
    uint private _initialSupply = 100;
    address private _owner = address(this);
    ERC20PresetFixedSupply private _testing = new ERC20PresetFixedSupply("test name", "test symbol", _initialSupply, _owner);

    function test_Constructor() external {
        assertEq(_testing.totalSupply(), _initialSupply);
        assertEq(_testing.balanceOf(_owner), _initialSupply);

        // support {burn} && {burnFrom} of ERC20Burnable
        // test {burn}
        uint amountToBurn = 1;
        _testing.burn(amountToBurn);
        assertEq(_testing.totalSupply(), _initialSupply - amountToBurn);
        assertEq(_testing.balanceOf(_owner), _initialSupply - amountToBurn);

        // test {burnFrom}
        address spender = address(1);
        _testing.approve(spender, amountToBurn);
        vm.prank(spender);
        _testing.burnFrom(_owner, amountToBurn);
        assertEq(_testing.totalSupply(), _initialSupply - amountToBurn - amountToBurn);
        assertEq(_testing.balanceOf(_owner), _initialSupply - amountToBurn - amountToBurn);
    }
}

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

1.jpeg

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

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

0 条评论

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