区块链 区块链技术 比特币公众号手机端

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

liumuhui 1年前 (2024-06-20) 阅读数 185 #技术

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

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

版权声明

本文仅代表作者观点,不代表区块链技术网立场。
本文系作者授权本站发表,未经许可,不得转载。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门