[转][Uniswap v2 合约代码解析] UniswapV2 ERC20合约代码

UniswapV2ERC20合约代码总览

在Uniswap V2里面,关于ERC20的合约一共有两部分,一个是ERC20合约的接口合约,一个是接口合约对应的实现。通过对UniswapERC20合约的学习,我们可以了解如何实现一个支持ERC20的token。

IUniswapV2ERC20解析

接口合约规定了需要实现的所有ERC20标准方法,如下是接口合约的主要代码。

interface IUniswapV2ERC20 {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint);

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
  • 首先定义了两个event,这两个event分别会在授权和转账的时候触发。
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
  • 定义token名字的方法
function name() external pure returns (string memory);
  • 定义token标志的方法
function symbol() external pure returns (string memory);
  • 定义token所支持的精度位数方法
function decimals() external pure returns (uint8);
  • 定义当前token的总供应量方法
function totalSupply() external view returns (uint);
  • 定义查询当前地址余额的方法
function balanceOf(address owner) external view returns (uint);
  • 定义查询owner允许spender交易的token数量方法
function allowance(address owner, address spender) external view returns (uint);
  • 定义授权方法,token的拥有者向spender授权交易指定value数量的token
function approve(address spender, uint value) external returns (bool);
  • 定义交易方法
function transfer(address to, uint value) external returns (bool);
  • 定义授权交易方法,这个方法一般是spender调用
function transferFrom(address from, address to, uint value) external returns (bool);
  • 定义DOMAIN_SEPARATOR方法,这个方法会返回[EIP712](EIP-712: Ethereum typed structured data hashing and signing)所规定的DOMAIN_SEPARATOR值
function DOMAIN_SEPARATOR() external view returns (bytes32);
  • 定义PERMIT_TYPEHASH方法,这个方法会返回[EIP2612](EIP-2612: permit – 712-signed approvals)所规定的链下信息加密的类型
function PERMIT_TYPEHASH() external pure returns (bytes32);
  • 定义nonces方法,这个方法会返回EIP2612所规定每次授权的信息中所携带的nonce值是多少,可以方式授权过程遭受到重放攻击。
function nonces(address owner) external view returns (uint);
  • 定义permit方法,这个方法就是EIP2612进行授权交易的方法,可以用这个方法实现无gas(token的使用者不需要出gas)的token交易
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;

UniswapV2ERC20解析

UniswapV2ERC20的接口实现合约如下:

contract UniswapV2ERC20 is IUniswapV2ERC20 {
    using SafeMath for uint;

    string public constant name = 'Uniswap V2';
    string public constant symbol = 'UNI-V2';
    uint8 public constant decimals = 18;
    uint  public totalSupply;
    mapping(address => uint) public balanceOf;
    mapping(address => mapping(address => uint)) public allowance;

    bytes32 public DOMAIN_SEPARATOR;
    // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
    bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
    mapping(address => uint) public nonces;

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

    constructor() public {
        uint chainId;
        assembly {
            chainId := chainid
        }
        DOMAIN_SEPARATOR = keccak256(
            abi.encode(
                keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                keccak256(bytes(name)),
                keccak256(bytes('1')),
                chainId,
                address(this)
            )
        );
    }

    function _mint(address to, uint value) internal {
        totalSupply = totalSupply.add(value);
        balanceOf[to] = balanceOf[to].add(value);
        emit Transfer(address(0), to, value);
    }

    function _burn(address from, uint value) internal {
        balanceOf[from] = balanceOf[from].sub(value);
        totalSupply = totalSupply.sub(value);
        emit Transfer(from, address(0), value);
    }

    function _approve(address owner, address spender, uint value) private {
        allowance[owner][spender] = value;
        emit Approval(owner, spender, value);
    }

    function _transfer(address from, address to, uint value) private {
        balanceOf[from] = balanceOf[from].sub(value);
        balanceOf[to] = balanceOf[to].add(value);
        emit Transfer(from, to, value);
    }

    function approve(address spender, uint value) external returns (bool) {
        _approve(msg.sender, spender, value);
        return true;
    }

    function transfer(address to, uint value) external returns (bool) {
        _transfer(msg.sender, to, value);
        return true;
    }

    function transferFrom(address from, address to, uint value) external returns (bool) {
        if (allowance[from][msg.sender] != uint(-1)) {
            allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
        }
        _transfer(from, to, value);
        return true;
    }

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
        require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
        bytes32 digest = keccak256(
            abi.encodePacked(
                '\x19\x01',
                DOMAIN_SEPARATOR,
                keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
            )
        );
        address recoveredAddress = ecrecover(digest, v, r, s);
        require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
        _approve(owner, spender, value);
    }
}
  • 首先为unit类型加上SafeMath的方法
using SafeMath for uint;
  • 然后定义一些所需要变量以及常量
// token的名字
string public constant name = 'Uniswap V2';
// token的symbol
string public constant symbol = 'UNI-V2';
// token所支持的精度
uint8 public constant decimals = 18;
// token的总供应量
uint  public totalSupply;
// 地址与余额之间的映射
mapping(address => uint) public balanceOf;
// 授权交易与授权交易数额之间的映射
mapping(address => mapping(address => uint)) public allowance;

// EIP712所规定的DOMAIN_SEPARATOR值,会在构造函数中进行赋值
bytes32 public DOMAIN_SEPARATOR;
// EIP712所规定的TYPEHASH,这里直接硬编码的keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")所得到的值
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
// 地址与nonce之间的映射
mapping(address => uint) public nonces;
  • 定义event
// 授权event
event Approval(address indexed owner, address indexed spender, uint value);
// 交易event
event Transfer(address indexed from, address indexed to, uint value);
  • 构造函数
constructor() public {
    // 当前运行的链的标识
    uint chainId;
    assembly {
        // 内联汇编,获取链的标识
        chainId := chainid
    }
    // 获取DOMAIN_SEPARATOR
    DOMAIN_SEPARATOR = keccak256(
        abi.encode(
            keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
            keccak256(bytes(name)),
            keccak256(bytes('1')),
            chainId,
            address(this)
        )
    );
}
  • 铸币方法 这个方法主要的目的是向某个地址发送一定数量的token。
function _mint(address to, uint value) internal {
    totalSupply = totalSupply.add(value);
    balanceOf[to] = balanceOf[to].add(value);
    emit Transfer(address(0), to, value);
}
  • 销毁方法 这个方法主要的目的是销毁某个地址的所持有的token。
function _burn(address from, uint value) internal {
    balanceOf[from] = balanceOf[from].sub(value);
    totalSupply = totalSupply.sub(value);
    emit Transfer(from, address(0), value);
}
  • 授权私有方法 这个方法的逻辑也非常简单,就是修改allowance对应的映射并发出event
function _approve(address owner, address spender, uint value) private {
    allowance[owner][spender] = value;
    emit Approval(owner, spender, value);
}
  • approve授权方法 直接调用的授权的私有方法,并返回true
function approve(address spender, uint value) external returns (bool) {
    _approve(msg.sender, spender, value);
    return true;
}
  • permit授权方法 该方法的参数具体含义可以查询[EIP2612](EIP-2612: permit – 712-signed approvals)中的定义。
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
    // 检查时效时间是否超时
    require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
    // 构建电子签
    bytes32 digest = keccak256(
        abi.encodePacked(
            '\x19\x01',
            DOMAIN_SEPARATOR,
            keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
        )
    );
    // 验证签名并获取签名信息的地址
    address recoveredAddress = ecrecover(digest, v, r, s);
    // 确保地址不是0地址并且等于token的owner
    require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
    // 进行授权
    _approve(owner, spender, value);
}
  • 转账私有方法 该方法实现了一个转账的逻辑,具体逻辑也非常简单,就是将from对应的banlanceOf减去valueto对应的balanceOf加上value,最后发出Transferevent
function _transfer(address from, address to, uint value) private {
    balanceOf[from] = balanceOf[from].sub(value);
    balanceOf[to] = balanceOf[to].add(value);
    emit Transfer(from, to, value);
}
  • 转账方法 token的拥有这直接调用的方法,将token从拥有者身上转到to地址上去
function transfer(address to, uint value) external returns (bool) {
    _transfer(msg.sender, to, value);
    return true;
}
  • 授权转账方法 在执行该方法之前,需要通过approve授权方法或者permit授权方法进行授权。 转账之前需要确认msg.sender在allowance中是否有值,如果有值就减去对应的金额。
function transferFrom(address from, address to, uint value) external returns (bool) {

    if (allowance[from][msg.sender] != uint(-1)) {
        // 减去对应的授权额度
        allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
    }
    _transfer(from, to, value);
    return true;
}

实际上在Uniswap中并没有直接使用上述ERC20合约,在网络上部署的是`UniswapV2Pair.sol`合约,pair合约继承了上述合约。

你可能感兴趣的:(以太坊,区块链,数字货币)