当前位置:   article > 正文

Michael.W基于Foundry精读Openzeppelin第47期——SafeERC20.sol

Michael.W基于Foundry精读Openzeppelin第47期——SafeERC20.sol

0. 版本

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

0.1 SafeERC20.sol

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

SafeERC20库封装了ERC20的操作,使各操作执行失败时触发revert。因为标准IERC20的转账和授权等需通过一个bool返回值来表示操作是否成功,可能实现合约内部没有设置revert机制。有的ERC20合约的授权或转账的实现并无返回值(以太坊上的USDT合约),此时可通过本库与其交互。

注:通过using SafeERC20 for IERC20使用本库。

1. 目标合约

封装SafeERC20 library成为一个可调用合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/src/token/ERC20/utils/MockSafeERC20.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-contracts/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";

contract MockSafeERC20 {
    using SafeERC20 for IERC20;
    using SafeERC20 for IERC20Permit;

    function safeTransfer(
        IERC20 token,
        address to,
        uint value
    ) external {
        token.safeTransfer(to, value);
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint value
    ) external {
        token.safeTransferFrom(from, to, value);
    }

    function safeApprove(
        IERC20 token,
        address spender,
        uint value
    ) external {
        token.safeApprove(spender, value);
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint value
    ) external {
        token.safeIncreaseAllowance(spender, value);
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) external {
        token.safeDecreaseAllowance(spender, value);
    }

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external {
        token.safePermit(owner, spender, value, deadline, v, r, s);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65

全部foundry测试合约:

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

测试使用的物料合约:

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/token/ERC20/utils/SafeERC20/MockERC20ReturnTrue.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";

contract MockERC20ReturnTrue is IERC20 {
    // avoid compiling warnings
    uint private _slotValue;

    function transfer(address to, uint amount) external returns (bool){
        emit Transfer(msg.sender, to, amount);
        return true;
    }

    function approve(address spender, uint amount) external returns (bool){
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint amount
    ) external returns (bool){
        emit Transfer(from, to, amount);
        return true;
    }

    function allowance(address, address spender) external view returns (uint){
        if (spender == address(1024)) {
            // return non-zero
            return _slotValue + 1;
        }

        return 0;
    }

    function totalSupply() external view returns (uint){
        return _slotValue;
    }

    function balanceOf(address) external view returns (uint){
        return _slotValue;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/token/ERC20/utils/SafeERC20/MockERC20ReturnFalse.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";

contract MockERC20ReturnFalse is IERC20 {
    // avoid compiling warnings
    uint private _slotValue;

    function transfer(address to, uint amount) external returns (bool){
        emit Transfer(msg.sender, to, amount);
        return false;
    }

    function approve(address spender, uint amount) external returns (bool){
        emit Approval(msg.sender, spender, amount);
        return false;
    }

    function transferFrom(
        address from,
        address to,
        uint amount
    ) external returns (bool){
        emit Transfer(from, to, amount);
        return false;
    }

    function allowance(address, address spender) external view returns (uint){
        if (spender == address(1024)) {
            // return non-zero
            return _slotValue + 1;
        }

        return 0;
    }

    function totalSupply() external view returns (uint){
        return _slotValue;
    }

    function balanceOf(address) external view returns (uint){
        return _slotValue;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/token/ERC20/utils/SafeERC20/MockERC20ReturnNone.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

contract MockERC20ReturnNone {
    // avoid compiling warnings
    uint private _slotValue;

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    function transfer(address to, uint amount) external {
        emit Transfer(msg.sender, to, amount);
    }

    function approve(address spender, uint amount) external {
        emit Approval(msg.sender, spender, amount);
    }

    function transferFrom(
        address from,
        address to,
        uint amount
    ) external {
        emit Transfer(from, to, amount);
    }

    function allowance(address, address spender) external view returns (uint){
        if (spender == address(1024)) {
            // return non-zero
            return _slotValue + 1;
        }

        return 0;
    }

    function totalSupply() external view returns (uint){
        return _slotValue;
    }

    function balanceOf(address) external view returns (uint){
        return _slotValue;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/token/ERC20/utils/SafeERC20/MockERC20ReturnNonBool.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

contract MockERC20ReturnNonBool {
    // avoid compiling warnings
    uint private _slotValue;

    function transfer(address, uint) external returns (address){
        _slotValue = 1024;
        // neither 0 nor 1
        return address(2);
    }

    function approve(address, uint) external returns (uint){
        _slotValue = 1024;
        // neither 0 nor 1
        return 2;
    }

    function transferFrom(
        address,
        address,
        uint
    ) external returns (string memory){
        _slotValue = 1024;
        return "MockERC20ReturnNonBool: transferFrom";
    }

    function allowance(address, address spender) external view returns (uint){
        if (spender == address(1024)) {
            // return non-zero
            return _slotValue + 1;
        }

        return 0;
    }

    function totalSupply() external view returns (uint){
        return _slotValue;
    }

    function balanceOf(address) external view returns (uint){
        return _slotValue;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/token/ERC20/utils/SafeERC20/MockERC20Revert.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";

contract MockERC20Revert is IERC20 {
    address private constant _REVERT_FLAG = address(1024);
    // avoid compiling warnings
    uint private _slotValue;

    function transfer(address to, uint amount) external returns (bool){
        require(to != _REVERT_FLAG, "MockERC20ReturnRevert: transfer");
        emit Transfer(msg.sender, to, amount);
        return true;
    }

    function approve(address spender, uint amount) external returns (bool){
        require(spender != _REVERT_FLAG, "MockERC20ReturnRevert: approve");
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint amount
    ) external returns (bool){
        emit Transfer(from, to, amount);
        require(from != _REVERT_FLAG, "MockERC20ReturnRevert: transferFrom");
        return true;
    }

    function allowance(address, address) external view returns (uint){
        return _slotValue + 1;
    }

    function totalSupply() external view returns (uint){
        return _slotValue;
    }

    function balanceOf(address) external view returns (uint){
        return _slotValue;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/token/ERC20/utils/SafeERC20/MockERC20Permit.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import "openzeppelin-contracts/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";

contract MockERC20Permit is IERC20Permit {
    uint private _nonce;
    bool private _nonceIncreases = true;
    bool private _revertInPermit;
    bool private _revertInNonces;

    event Approval(address indexed owner, address indexed spender, uint256 value);

    function permit(
        address owner,
        address spender,
        uint value,
        uint,
        uint8,
        bytes32,
        bytes32
    ) external {
        require(!_revertInPermit, "MockERC20Permit: permit");
        if (_nonceIncreases) {
            _nonce += 1;
        }

        emit Approval(owner, spender, value);
    }

    function nonces(address) external view returns (uint){
        require(!_revertInNonces, "MockERC20Permit: nonces");
        return _nonce;
    }

    function setNonceIncreases(bool b) external {
        _nonceIncreases = b;
    }

    function setRevertInNonces(bool b) external {
        _revertInNonces = b;
    }

    function setRevertInPermit(bool b) external {
        _revertInPermit = b;
    }

    function DOMAIN_SEPARATOR() external view returns (bytes32){
        return bytes32(_nonce);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

2. 代码精读

2.1 safeTransfer(IERC20 token, address to, uint256 value) internal

ERC20的安全转账。

	// 对address类型使用utils/Address库
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
    	// 调用_callOptionalReturn()方法进行call及返回值检查。
    	// call对象为token合约,calldata为IERC20.transfer(to, value)的calldata
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }
    
    // 参数data作为calldata来call ERC20合约token。该函数会做两个检查:
    // 1. call过程不能发生revert;
    // 2. 如果call有返回值,要求decode后为true
    // 如果不通过检查,直接revert。
    // 注:函数内部是通过底层call的方式模拟solidity的high-level调用
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
		// 使用Address库的functionCall()方法,使用data作为calldata来call合约token。如果call的过程revert或token地址为EOA地址(即地址下没有code)会触发revert
		// Address库的functionCall()方法详解参见:https://learnblockchain.cn/article/6098
        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
        	// 如果call存在返回值
            // 要求该返回值必须为true,否则revert
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

foundry代码验证:

contract SafeERC20Test is Test {
    address private constant _REVERT_FLAG = address(1024);

    MockSafeERC20 private _testing = new MockSafeERC20();
    MockERC20ReturnTrue private _mockERC20ReturnTrue = new MockERC20ReturnTrue();
    MockERC20ReturnFalse private _mockERC20ReturnFalse = new MockERC20ReturnFalse();
    IERC20 private _mockERC20ReturnNonBool = IERC20(address(new MockERC20ReturnNonBool()));
    IERC20 private _mockERC20ReturnNone = IERC20(address(new MockERC20ReturnNone()));
    MockERC20Revert private _mockERC20Revert = new MockERC20Revert();
    IERC20 private _mockERC20NoCode = IERC20(address(0));

    event Transfer(address indexed from, address indexed to, uint value);

    function test_SafeTransfer() external {
        address to = address(this);

        // case 1: pass if token returns true
        vm.expectEmit(true, true, false, true, address(_mockERC20ReturnTrue));
        emit Transfer(address(_testing), to, 1);
        _testing.safeTransfer(_mockERC20ReturnTrue, to, 1);

        // case 2: pass if token has no return
        vm.expectEmit(true, true, false, true, address(_mockERC20ReturnNone));
        emit Transfer(address(_testing), to, 1);
        _testing.safeTransfer(_mockERC20ReturnNone, to, 1);

        // case 3: revert if token returns false
        vm.expectRevert("SafeERC20: ERC20 operation did not succeed");
        _testing.safeTransfer(_mockERC20ReturnFalse, to, 1);

        // case 4: revert if token returns non-bool
        vm.expectRevert();
        _testing.safeTransfer(_mockERC20ReturnNonBool, to, 1);

        // case 5: revert if reverts in token
        vm.expectRevert("MockERC20ReturnRevert: transfer");
        _testing.safeTransfer(_mockERC20Revert, _REVERT_FLAG, 1);

        // case 6: revert if token has no code
        vm.expectRevert("Address: call to non-contract");
        _testing.safeTransfer(_mockERC20NoCode, to, 1);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
2.2 safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal

ERC20的安全授权转账。

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
    	// 调用_callOptionalReturn()方法进行call及返回值检查。
    	// call对象为token合约,calldata为IERC20.transferFrom(from, to, value)的calldata
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

foundry代码验证:

contract SafeERC20Test is Test {
    address private constant _REVERT_FLAG = address(1024);

    MockSafeERC20 private _testing = new MockSafeERC20();
    MockERC20ReturnTrue private _mockERC20ReturnTrue = new MockERC20ReturnTrue();
    MockERC20ReturnFalse private _mockERC20ReturnFalse = new MockERC20ReturnFalse();
    IERC20 private _mockERC20ReturnNonBool = IERC20(address(new MockERC20ReturnNonBool()));
    IERC20 private _mockERC20ReturnNone = IERC20(address(new MockERC20ReturnNone()));
    MockERC20Revert private _mockERC20Revert = new MockERC20Revert();
    IERC20 private _mockERC20NoCode = IERC20(address(0));

    event Transfer(address indexed from, address indexed to, uint value);

    function test_SafeTransferFrom() external {
        address from = address(1);
        address to = address(this);

        // case 1: pass if token returns true
        vm.expectEmit(true, true, false, true, address(_mockERC20ReturnTrue));
        emit Transfer(from, to, 1);
        _testing.safeTransferFrom(_mockERC20ReturnTrue, from, to, 1);

        // case 2: pass if token has no return
        vm.expectEmit(true, true, false, true, address(_mockERC20ReturnNone));
        emit Transfer(from, to, 1);
        _testing.safeTransferFrom(_mockERC20ReturnNone, from, to, 1);

        // case 3: revert if token returns false
        vm.expectRevert("SafeERC20: ERC20 operation did not succeed");
        _testing.safeTransferFrom(_mockERC20ReturnFalse, from, to, 1);

        // case 4: revert if token returns non-bool
        vm.expectRevert();
        _testing.safeTransferFrom(_mockERC20ReturnNonBool, from, to, 1);

        // case 5: revert if reverts in token
        vm.expectRevert("MockERC20ReturnRevert: transferFrom");
        _testing.safeTransferFrom(_mockERC20Revert, _REVERT_FLAG, to, 1);

        // case 6: revert if token has no code
        vm.expectRevert("Address: call to non-contract");
        _testing.safeTransferFrom(_mockERC20NoCode, from, to, 1);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
2.3 safeApprove(IERC20 token, address spender, uint256 value) internal

ERC20的安全授权。本方法同样存在IERC20-approve的授权额度覆盖问题,目前已弃用。如有需求,请使用本库的safeIncreaseAllowance()safeDecreaseAllowance()

注:如果想为一个地址设置初始授权额度或授权额度清零可以使用本方法。

    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // 要求value值为0(授权额度清0)或本合约地址在token上没有授予spender任何额度(设置初始授权额度),否则revert
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
    	// 调用_callOptionalReturn()方法进行call及返回值检查。
    	// call对象为token合约,calldata为IERC20.approve(spender, value)的calldata
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

foundry代码验证:

contract SafeERC20Test is Test {
    address private constant _REVERT_FLAG = address(1024);

    MockSafeERC20 private _testing = new MockSafeERC20();
    MockERC20ReturnTrue private _mockERC20ReturnTrue = new MockERC20ReturnTrue();
    MockERC20ReturnFalse private _mockERC20ReturnFalse = new MockERC20ReturnFalse();
    IERC20 private _mockERC20ReturnNonBool = IERC20(address(new MockERC20ReturnNonBool()));
    IERC20 private _mockERC20ReturnNone = IERC20(address(new MockERC20ReturnNone()));
    MockERC20Revert private _mockERC20Revert = new MockERC20Revert();
    IERC20 private _mockERC20NoCode = IERC20(address(0));

    event Approval(address indexed owner, address indexed spender, uint value);

    function test_SafeApprove() external {
        address spenderSomeAllowance = address(1024);
        address spenderZeroAllowance = address(2048);

        // 1. token returns true
        // case 1: pass if clear allowance && token returns true
        assertNotEq(_mockERC20ReturnTrue.allowance(address(_testing), spenderSomeAllowance), 0);
        vm.expectEmit(true, true, false, true, address(_mockERC20ReturnTrue));
        emit Approval(address(_testing), spenderSomeAllowance, 0);
        _testing.safeApprove(_mockERC20ReturnTrue, spenderSomeAllowance, 0);

        // case 2: pass if initial allowance setting && token returns true
        assertEq(_mockERC20ReturnTrue.allowance(address(_testing), spenderZeroAllowance), 0);
        vm.expectEmit(true, true, false, true, address(_mockERC20ReturnTrue));
        emit Approval(address(_testing), spenderZeroAllowance, 1);
        _testing.safeApprove(_mockERC20ReturnTrue, spenderZeroAllowance, 1);

        // case 3: revert if some allowance && non-zero value && token returns true
        vm.expectRevert("SafeERC20: approve from non-zero to non-zero allowance");
        _testing.safeApprove(_mockERC20ReturnTrue, spenderSomeAllowance, 1);

        // 2. token returns false
        // case 1: revert if clear allowance && token returns false
        vm.expectRevert("SafeERC20: ERC20 operation did not succeed");
        _testing.safeApprove(_mockERC20ReturnFalse, spenderSomeAllowance, 0);

        // case 2: revert if initial allowance setting && token returns false
        vm.expectRevert("SafeERC20: ERC20 operation did not succeed");
        _testing.safeApprove(_mockERC20ReturnFalse, spenderZeroAllowance, 1);

        // case 3: revert if some allowance && non-zero value && token returns false
        vm.expectRevert("SafeERC20: approve from non-zero to non-zero allowance");
        _testing.safeApprove(_mockERC20ReturnFalse, spenderSomeAllowance, 1);

        // 3. token returns None
        // case 1: pass if clear allowance && token returns none
        vm.expectEmit(true, true, false, true, address(_mockERC20ReturnNone));
        emit Approval(address(_testing), spenderSomeAllowance, 0);
        _testing.safeApprove(_mockERC20ReturnNone, spenderSomeAllowance, 0);

        // case 2: pass if initial allowance setting && token returns none
        vm.expectEmit(true, true, false, true, address(_mockERC20ReturnNone));
        emit Approval(address(_testing), spenderZeroAllowance, 1);
        _testing.safeApprove(_mockERC20ReturnNone, spenderZeroAllowance, 1);

        // case 3: revert if some allowance && non-zero value && token returns none
        vm.expectRevert("SafeERC20: approve from non-zero to non-zero allowance");
        _testing.safeApprove(_mockERC20ReturnNone, spenderSomeAllowance, 1);

        // 4. token returns non-bool
        // case 1: revert if clear allowance && token returns non-bool
        vm.expectRevert();
        _testing.safeApprove(_mockERC20ReturnNonBool, spenderSomeAllowance, 0);

        // case 2: revert if initial allowance setting && token returns non-bool
        vm.expectRevert();
        _testing.safeApprove(_mockERC20ReturnNonBool, spenderZeroAllowance, 1);

        // case 3: revert if some allowance && non-zero value && token returns non-bool
        vm.expectRevert("SafeERC20: approve from non-zero to non-zero allowance");
        _testing.safeApprove(_mockERC20ReturnNonBool, spenderSomeAllowance, 1);

        // 5. token reverts
        // case 1: revert if pass allowance && value check && token reverts
        vm.expectRevert("MockERC20ReturnRevert: approve");
        _testing.safeApprove(_mockERC20Revert, _REVERT_FLAG, 0);

        // case 2: revert if not pass allowance && value check
        vm.expectRevert("SafeERC20: approve from non-zero to non-zero allowance");
        _testing.safeApprove(_mockERC20ReturnNonBool, spenderSomeAllowance, 1);

        // 6. token has no code
        // revert via allowance's check
        vm.expectRevert();
        _testing.safeApprove(_mockERC20NoCode, spenderSomeAllowance, 1);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
2.4 safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal

ERC20的安全增加授权额度,增量为value。

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
    	// 计算增加授权后的额度:本合约授予spender的当前剩余额度 + 增量value
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        // 调用_callOptionalReturn()方法进行call及返回值检查。
    	// call对象为token合约,calldata为IERC20.approve(spender, newAllowance)的calldata
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

foundry代码验证:

contract SafeERC20Test is Test {
    address private constant _REVERT_FLAG = address(1024);

    MockSafeERC20 private _testing = new MockSafeERC20();
    MockERC20ReturnTrue private _mockERC20ReturnTrue = new MockERC20ReturnTrue();
    MockERC20ReturnFalse private _mockERC20ReturnFalse = new MockERC20ReturnFalse();
    IERC20 private _mockERC20ReturnNonBool = IERC20(address(new MockERC20ReturnNonBool()));
    IERC20 private _mockERC20ReturnNone = IERC20(address(new MockERC20ReturnNone()));
    MockERC20Revert private _mockERC20Revert = new MockERC20Revert();
    IERC20 private _mockERC20NoCode = IERC20(address(0));

    event Approval(address indexed owner, address indexed spender, uint value);

    function test_SafeIncreaseAllowance() external {
        address spender = address(this);

        // case 1: pass if token returns true
        assertEq(_mockERC20ReturnTrue.allowance(address(_testing), spender), 0);
        vm.expectEmit(true, true, false, true, address(_mockERC20ReturnTrue));
        emit Approval(address(_testing), spender, 0 + 1);
        _testing.safeIncreaseAllowance(_mockERC20ReturnTrue, spender, 1);

        // case 2: revert if token returns false
        vm.expectRevert("SafeERC20: ERC20 operation did not succeed");
        _testing.safeIncreaseAllowance(_mockERC20ReturnFalse, spender, 1);

        // case 3: pass if token returns none
        assertEq(_mockERC20ReturnNone.allowance(address(_testing), spender), 0);
        vm.expectEmit(true, true, false, true, address(_mockERC20ReturnNone));
        emit Approval(address(_testing), spender, 0 + 1);
        _testing.safeIncreaseAllowance(_mockERC20ReturnNone, spender, 1);

        // case 4: revert if token returns non-bool
        vm.expectRevert();
        _testing.safeIncreaseAllowance(_mockERC20ReturnNonBool, spender, 1);

        // case 5: revert if token reverts
        vm.expectRevert("MockERC20ReturnRevert: approve");
        _testing.safeIncreaseAllowance(_mockERC20Revert, _REVERT_FLAG, 1);

        // case 6: revert if token has no code
        vm.expectRevert();
        _testing.safeIncreaseAllowance(_mockERC20NoCode, spender, 1);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
2.5 safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal

ERC20的安全减少授权额度,减量为value。

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
    	// 关闭solidity 0.8的整数运算溢出检查
        unchecked {
        	// 本合约授予spender的当前剩余额度
            uint256 oldAllowance = token.allowance(address(this), spender);
            // 要求减量够减,否则revert 
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            // 计算减后的授权额度
            uint256 newAllowance = oldAllowance - value;
            // 调用_callOptionalReturn()方法进行call及返回值检查。
    		// call对象为token合约,calldata为IERC20.approve(spender, newAllowance)的calldata
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

foundry代码验证:

contract SafeERC20Test is Test {
    address private constant _REVERT_FLAG = address(1024);

    MockSafeERC20 private _testing = new MockSafeERC20();
    MockERC20ReturnTrue private _mockERC20ReturnTrue = new MockERC20ReturnTrue();
    MockERC20ReturnFalse private _mockERC20ReturnFalse = new MockERC20ReturnFalse();
    IERC20 private _mockERC20ReturnNonBool = IERC20(address(new MockERC20ReturnNonBool()));
    IERC20 private _mockERC20ReturnNone = IERC20(address(new MockERC20ReturnNone()));
    MockERC20Revert private _mockERC20Revert = new MockERC20Revert();
    IERC20 private _mockERC20NoCode = IERC20(address(0));

    event Approval(address indexed owner, address indexed spender, uint value);

    function test_SafeDecreaseAllowance() external {
        address spenderSomeAllowance = address(1024);

        // 1. token returns true
        // case 1: pass if token returns true && value <= old allowance
        assertEq(_mockERC20ReturnTrue.allowance(address(_testing), spenderSomeAllowance), 1);
        vm.expectEmit(true, true, false, true, address(_mockERC20ReturnTrue));
        emit Approval(address(_testing), spenderSomeAllowance, 1 - 1);
        _testing.safeDecreaseAllowance(_mockERC20ReturnTrue, spenderSomeAllowance, 1);

        // case 2: revert if token returns true && value > old allowance
        vm.expectRevert("SafeERC20: decreased allowance below zero");
        _testing.safeDecreaseAllowance(_mockERC20ReturnTrue, spenderSomeAllowance, 1 + 1);

        // 2. token returns false
        // case 1: revert if token returns false && value <= old allowance
        assertEq(_mockERC20ReturnFalse.allowance(address(_testing), spenderSomeAllowance), 1);
        vm.expectRevert("SafeERC20: ERC20 operation did not succeed");
        _testing.safeDecreaseAllowance(_mockERC20ReturnFalse, spenderSomeAllowance, 1);

        // case 2: revert if token returns false && value > old allowance
        vm.expectRevert("SafeERC20: decreased allowance below zero");
        _testing.safeDecreaseAllowance(_mockERC20ReturnFalse, spenderSomeAllowance, 1 + 1);

        // 3. token returns none
        // case 1: pass if token returns none && value <= old allowance
        assertEq(_mockERC20ReturnNone.allowance(address(_testing), spenderSomeAllowance), 1);
        vm.expectEmit(true, true, false, true, address(_mockERC20ReturnNone));
        emit Approval(address(_testing), spenderSomeAllowance, 1 - 1);
        _testing.safeDecreaseAllowance(_mockERC20ReturnNone, spenderSomeAllowance, 1);

        // case 2: revert if token returns none && value > old allowance
        vm.expectRevert("SafeERC20: decreased allowance below zero");
        _testing.safeDecreaseAllowance(_mockERC20ReturnNone, spenderSomeAllowance, 1 + 1);

        // 4. token returns non-bool
        // case 1: revert if token returns non-bool && value <= old allowance
        assertEq(_mockERC20ReturnNonBool.allowance(address(_testing), spenderSomeAllowance), 1);
        vm.expectRevert();
        _testing.safeDecreaseAllowance(_mockERC20ReturnNonBool, spenderSomeAllowance, 1);

        // case 2: revert if token returns non-bool && value > old allowance
        vm.expectRevert("SafeERC20: decreased allowance below zero");
        _testing.safeDecreaseAllowance(_mockERC20ReturnNonBool, spenderSomeAllowance, 1 + 1);

        // 5. token reverts
        // case 1: revert if token reverts && value <= old allowance
        assertEq(_mockERC20Revert.allowance(address(_testing), _REVERT_FLAG), 1);
        vm.expectRevert("MockERC20ReturnRevert: approve");
        _testing.safeDecreaseAllowance(_mockERC20Revert, _REVERT_FLAG, 1);

        // case 2: revert if token reverts && value > old allowance
        vm.expectRevert("SafeERC20: decreased allowance below zero");
        _testing.safeDecreaseAllowance(_mockERC20Revert, _REVERT_FLAG, 1 + 1);

        // 6. token has no code
        // revert via getting allowance
        vm.expectRevert();
        _testing.safeDecreaseAllowance(_mockERC20NoCode, spenderSomeAllowance, 1);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
2.6 safePermit(IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) internal

ERC20Permit的安全permit授权。

注:IERC20Permit.permit授权详解参见:https://learnblockchain.cn/article/7085

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
    	// 获取目标ERC20Permit合约中owner的当前nonce值
        uint256 nonceBefore = token.nonces(owner);
        // 调用目标ERC20Permit合约的permit的方法
        token.permit(owner, spender, value, deadline, v, r, s);
        // 调用后,获取目标ERC20Permit合约中owner的nonce值
        uint256 nonceAfter = token.nonces(owner);
        // 要求目标ERC20Permit合约中,owner的nonce值在permit()调用前后有递增1,否则revert
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

foundry代码验证:

contract SafeERC20Test is Test {
    MockSafeERC20 private _testing = new MockSafeERC20();
    MockERC20Permit private _mockERC20Permit = new MockERC20Permit();

    event Approval(address indexed owner, address indexed spender, uint value);

    function test_SafePermit() external {
        address owner = address(1);
        address spender = address(2);
        uint value = 1024;

        // case 1: pass if nonce increases && no revert in {permit} and {nonces}
        vm.expectEmit(true, true, false, true, address(_mockERC20Permit));
        emit Approval(owner, spender, value);
        _testing.safePermit(
            _mockERC20Permit,
            owner,
            spender,
            value,
            0,
            0,
            0,
            0
        );

        // case 2: revert if nonce not increases
        _mockERC20Permit.setNonceIncreases(false);
        vm.expectRevert("SafeERC20: permit did not succeed");
        _testing.safePermit(
            _mockERC20Permit,
            owner,
            spender,
            value,
            0,
            0,
            0,
            0
        );

        // case 3: revert if reverts in token's {nonces}
        _mockERC20Permit.setNonceIncreases(true);
        _mockERC20Permit.setRevertInNonces(true);
        vm.expectRevert("MockERC20Permit: nonces");
        _testing.safePermit(
            _mockERC20Permit,
            owner,
            spender,
            value,
            0,
            0,
            0,
            0
        );

        // case 4: revert if reverts in token's {permit}
        _mockERC20Permit.setRevertInNonces(false);
        _mockERC20Permit.setRevertInPermit(true);
        vm.expectRevert("MockERC20Permit: permit");
        _testing.safePermit(
            _mockERC20Permit,
            owner,
            spender,
            value,
            0,
            0,
            0,
            0
        );
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70

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

在这里插入图片描述
公众号名称:后现代泼痞浪漫主义奠基人

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/137109
推荐阅读
相关标签
  

闽ICP备14008679号