Uniswap V2-Core 部分智能合约代码解析

通过阅读代码导入的包,我决定将代码的阅读顺序定为:ERC20,Pair,Factory

ERC20.sol

pragma solidity=0.5.16;

import './interfaces/IUniswapV2ERC20.sol';
import './libraries/SafeMath.sol';

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; // UNI-V2总量 即流动性总量
    mapping(address => uint) public balanceOf; // 账户UNI2余额
    mapping(address => mapping(address => uint)) public allowance; // 代理金额

    bytes32 public DOMAIN_SEPARATOR; // 域分割EIP-712
    // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
    bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; // 代理message的数据结构类型的hash——树蕨结构类型的哈希是定制,跟selector算的是一个道理,因此这里可以用作常量表示
    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( //域分割符,EIP-712标准 此处计算完“DOMAIN_SEPARATOR”也可以当作常量看待了
            abi.encode(
                keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), // 对数据结构类型进行哈希
                keccak256(bytes(name)), // name,version是string类型,因此要转化成btyes类型,再统一转化成256位
                keccak256(bytes('1')),
                chainId,
                address(this)
            )
        );
    }

    // 最简单的铸币流程,即完成总数++,目标地址++
    // 不包含保护机制,铸币前后的校验邓保护机制应该是放在了非core函数里面,core函数只保留最简单最基础的操作
    function _mint(address to, uint value) internal {
        totalSupply = totalSupply.add(value);
        balanceOf[to] = balanceOf[to].add(value);
        emit Transfer(address(0), to, value);
    }

    // 最简单的销币流程,即完成总数--,目标地址持有数量--
    // 不包含保护机制,铸币前后的校验邓保护机制应该是放在了非core函数里面,core函数只保留最简单最基础的操作
    function _burn(address from, uint value) internal {
        balanceOf[from] = balanceOf[from].sub(value);
        totalSupply = totalSupply.sub(value);
        emit Transfer(from, address(0), value);
    }

    // 最简单的授权流程,给授权人(owner)的代理人(spender)总计(value)金额的额度
    function _approve(address owner, address spender, uint value) private {
        allowance[owner][spender] = value;
        emit Approval(owner, spender, value);
    }
    function approve(address spender, uint value) external returns (bool) {
        _approve(msg.sender, spender, value);
        return true;
    }

    // 最简单的转账流程,给from给to转账总计value的金额 不去判断是否拥有足够的余额转账,因为这些保护机制是外围/边缘合约的事 
    // 判断为安全了直接使用_transfer
    // from--,to++ 注意:以上均为内部调用
    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 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');
        // 转化成标准EIP-712格式的消息
        bytes32 digest = keccak256(
            abi.encodePacked(
                '\x19\x01',
                DOMAIN_SEPARATOR,
                keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
            )
        );
        // 将消息digest与已签名消息(v,r,s)传给ercecover,即可还原出签名人地址 参考博客https://blog.csdn.net/weixin_43380357/article/details/129737555?spm=1001.2014.3001.5501及其相关文献即可了解
        address recoveredAddress = ecrecover(digest, v, r, s);
        // 在应用中其实是查看最后还原出来的地址是不是msg.sender(即owner=msg.sender)
        // 如果一切正常,请将此视为ERC-20-approve
        require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE'); 
        // 通过permit方法可以在该函数使用过程中使spender获得owner的部分资产使用权限,继而在下一步就可以调用其他函数实现资金转移
        // 在一般情况下,在转移原生代币时需要用户在链上签署一笔approve交易,然后再签一笔transfer交易(通常由spender付费) 此时需要花费两笔交易手续费————解释:因为原生代币,如eth,转入合约时是没有消息抛出的,因此若eth转入交易所合约一般是需要允许交易所作为spender使用用户的资产,再将资产转移进交易所,这个过程中:交易1、用户授权;交易2、交易所转账给自己。 这存在两个问题:1、时间:交易1、2之间需要时间,而且根据用户操作时间未知;2、经济:这需要两笔手续费的钱
        // 已知:交易签名需要两次签名,一次是交易签名,一次是交易构造前的消息签名,此时可以先有用户在链下对消息签名(已完成的签名消息简称message1)
        // 此处的信息内容是进行身份确认,确定该信息是的owner是本函数的msg.sender
        // permit结束后spender即拥有了权限,可接下来spender可以替用户进行转账。 在这个过程中uniswap是将授权+转账两笔交易合成了一笔,减少了交易费用
        _approve(owner, spender, value);
        // 身份验证通过,授予资金处理额度
    }
}

Pair.sol

pragma solidity =0.5.16;

import './interfaces/IUniswapV2Pair.sol';
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IERC20.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';

contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
    using SafeMath  for uint;
    using UQ112x112 for uint224;

    uint public constant MINIMUM_LIQUIDITY = 10**3; // 池子最小限制
    bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); 

    address public factory;
    address public token0; // 代币对之token0
    address public token1; // 代币对之token1

    uint112 private reserve0;           // uses single storage slot, accessible via getReserves
    uint112 private reserve1;           // uses single storage slot, accessible via getReserves
    uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves
    // 112+112+32=256字节

    uint public price0CumulativeLast;  // token0在某段时间内的的价格总和
    uint public price1CumulativeLast;
    uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event K值计算

    uint private unlocked = 1;
    modifier lock() {
        require(unlocked == 1, 'UniswapV2: LOCKED');
        unlocked = 0;
        _;
        unlocked = 1;
    }

    // 返回储蓄池数值
    function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
        _reserve0 = reserve0; 
        _reserve1 = reserve1;
        _blockTimestampLast = blockTimestampLast;
    }


    function _safeTransfer(address token, address to, uint value) private {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); // 此处传过去的msg.sender是本合约 TODO:应该是将钱转出吧
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED'); // 要求返回数据是true且没有异常信息
    }

    event Mint(address indexed sender, uint amount0, uint amount1);
    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint amount0In,
        uint amount1In,
        uint amount0Out,
        uint amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    constructor() public {
        factory = msg.sender;
    }

    // called once by the factory at time of deployment
    // 只有factory才可以使用该函数 初始化代币地址
    function initialize(address _token0, address _token1) external {
        require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check 
        token0 = _token0;
        token1 = _token1;
    }

    // update reserves and, on the first call per block, price accumulators
    // 在每个区块第一次调用本合约时,需要更新reserve跟price
    function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
        require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
        uint32 blockTimestamp = uint32(block.timestamp % 2**32);
        uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
        if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // 如果timeElapsed不等于0,说明需要更新 价格累加器
            // * never overflows, and + overflow is desired
            price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; // 代币的价格累加器算法为本代币的储备/其他代币的储备*时间 即 =+ 汇率*时间
            price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
        }
        reserve0 = uint112(balance0); // 更新余额
        reserve1 = uint112(balance1);
        blockTimestampLast = blockTimestamp;
        emit Sync(reserve0, reserve1);
    }

    // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
    function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
        address feeTo = IUniswapV2Factory(factory).feeTo();
        feeOn = feeTo != address(0);
        uint _kLast = kLast; // gas savings
        if (feeOn) { // 如果该地址开放了
            if (_kLast != 0) { // TODO:为啥啊——刚初始化完可能为0
                uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                uint rootKLast = Math.sqrt(_kLast);
                if (rootK > rootKLast) { // 计算分配给feeTo的流动性代币
                    uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                    uint denominator = rootK.mul(5).add(rootKLast);
                    uint liquidity = numerator / denominator;
                    if (liquidity > 0) _mint(feeTo, liquidity);
                }
            }
        } else if (_kLast != 0) {
            kLast = 0; // TODO:为什么这里要归零——如果feeOn仍未出现,则不用给feeOn分成,因此清零即可? 因为沉淀下来的最终都会被流动性代币换出,如果feeTo参与了的话,那么需要将其中的一部分分给feeTo,其方式就是发送对应的UNI2
            // 此处通过将kLast清零的方式清除不需要的存储来减少合约在以太坊中状态的整体规模
        }
    }

    // this low-level function should be called from a contract which performs important safety checks
    function mint(address to) external lock returns (uint liquidity) {
        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
        // 添加流动性,通过查找本合约的余额与本合约的缓存差来确定要交换多少代币
        uint balance0 = IERC20(token0).balanceOf(address(this));
        uint balance1 = IERC20(token1).balanceOf(address(this));
        uint amount0 = balance0.sub(_reserve0);
        uint amount1 = balance1.sub(_reserve1);

        bool feeOn = _mintFee(_reserve0, _reserve1); // 铸币前先进行一次FeeTo的分红结算
        
        // 获取流动性代币总数,因为feeOn可能增加totalSupply
        uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
        
        if (_totalSupply == 0) { // 如果池子还没初始化,还没开始注入资金
            liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); // 为了提高操控池子成本,因此需要-MINIMUM_LIQUIDITY数量的UNI2代币
           _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens 将1000个UNI2代币转入0地址销毁
        } else {
            liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); // 计算添加的两种代币分别可以获得多少UNI2代币,取小的值铸造
        }
        require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');

        // 核算完成后,给目标地址铸币——朴实无华的铸币函数
        _mint(to, liquidity);   
        
        // 铸币结束更新当前reserve余额,更新价格累加器
        _update(balance0, balance1, _reserve0, _reserve1); 
        if (feeOn) kLast = uint(reserve0).mul(reserve1); // 记录下此次更新完的k值,如果feeOn为空,那么就不执行了,减少在以太坊上的存储成本
        emit Mint(msg.sender, amount0, amount1);
    }

    // this low-level function should be called from a contract which performs important safety checks
    function burn(address to) external lock returns (uint amount0, uint amount1) {
        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
        address _token0 = token0;                                // gas savings
        address _token1 = token1;                                // gas savings

        // 获取本合约的实际代币数量
        uint balance0 = IERC20(_token0).balanceOf(address(this)); 
        uint balance1 = IERC20(_token1).balanceOf(address(this));

        // 获取本合约的流动性代币——外围合约在调用之前将要燃烧的流动性转移到这个合约,这样我们就知道要燃烧多少流动性,并且我们可以确保它被burn掉。
        uint liquidity = balanceOf[address(this)]; 

        // 销币前结算FeeTo的分红
        bool feeOn = _mintFee(_reserve0, _reserve1);
        uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee

        // 根据UNI2占例计算等比例数量的token0,token1
        amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
        amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
        require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');

        // 销毁流动性代币UNI2
        _burn(address(this), liquidity);

        // 给to转账
        _safeTransfer(_token0, to, amount0);
        _safeTransfer(_token1, to, amount1);

        // 铸币结束更新当前reserve余额,更新价格累加器
        balance0 = IERC20(_token0).balanceOf(address(this));
        balance1 = IERC20(_token1).balanceOf(address(this));
        _update(balance0, balance1, _reserve0, _reserve1);

        if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
        emit Burn(msg.sender, amount0, amount1, to);
    }

    // this low-level function should be called from a contract which performs important safety checks
    // 这个低级函数应该从执行重要安全检查的合约中调用
    // 代币交换
    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
        require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'); // 要求至少一种token>0
        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // 获取两个token的reserve余额
        require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY'); // 要求swap的token<reserve 不然池子都给换空了

        // balance是实时的,reserve是池子自己记录的,会更新慢一些。balance是实时更新,reserve一般swap/mint/burn结束后才更新
        uint balance0;
        uint balance1;
        { // scope for _token{0,1}, avoids stack too deep errors
        address _token0 = token0;
        address _token1 = token1;
        require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
        if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // 假设此次转账是optimistic,因为所有限制条件在调用此函数前都通过了
        if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens

        // TODO:???
        if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
        // 获取当前余额。外围合约在调用我们进行交换之前向我们发送代币。这使得合约很容易检查它是否被欺骗,这种检查必须在核心合约中进行(因为我们可以被外围合约以外的其他实体调用)。
        balance0 = IERC20(_token0).balanceOf(address(this));
        balance1 = IERC20(_token1).balanceOf(address(this));
        }

        // 计算池子增加的数量 TODO:这个难道不是从getPrice的时候就去确定了吗 直接传入不可以吗?这个有点看不太懂
        uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; // 如果余额没有增加,那么代表输入为0,即amount0In=0
        uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
        // 简单解释:假设amount0In=10,amount0Out=0,amount1In=0,amount1Out=9.9
        // 此时 balance0 = reserve0 + amount0In, 则 balance0 > reserve0 - amount0Out 成立
        // 此时 balance1 = reserve1 - amount0Out, 则 balance1 = reserve0 - amount0Out,则balance1 > reserve0 - amount0Out不成立
        // 此时balance0 > reserve0 - amount0Out 为真, 则计算实际输入 amount0In = balance0 - reserve0 

        require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
        { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
        uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
        uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));// 扣除此次交易0.3%手续费后的余额
        // 并要求最终的K>swap前的k
        require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
        }

        _update(balance0, balance1, _reserve0, _reserve1);
        emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
    }

    // force balances to match reserves 强制balance与缓存的reserve一致,防止有人偷偷往合约转币,造成代币对价格不实
    // 一般当balance比reserve高的时候使用
    function skim(address to) external lock {
        address _token0 = token0; // gas savings
        address _token1 = token1; // gas savings
        _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
        _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
    }

    // force reserves to match balances 强制reserve与balance一致
    // 一般当balance比reserve低的时候使用
    function sync() external lock {
        _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
    }
}

Factory.sol

pragma solidity =0.5.16;

import './interfaces/IUniswapV2Factory.sol';
import './UniswapV2Pair.sol';

contract UniswapV2Factory is IUniswapV2Factory {
    address public feeTo;
    address public feeToSetter;

    mapping(address => mapping(address => address)) public getPair;
    address[] public allPairs; // allPairs[0,1,2,...]=(address)

    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    constructor(address _feeToSetter) public {
        feeToSetter = _feeToSetter;
    }

    function allPairsLength() external view returns (uint) {
        return allPairs.length;
    }

    function createPair(address tokenA, address tokenB) external returns (address pair) {
        require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
        (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
        require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
        require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
        bytes memory bytecode = type(UniswapV2Pair).creationCode;
        bytes32 salt = keccak256(abi.encodePacked(token0, token1));
        assembly {
            pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
        }
        IUniswapV2Pair(pair).initialize(token0, token1);
        getPair[token0][token1] = pair;
        getPair[token1][token0] = pair; // populate mapping in the reverse direction
        allPairs.push(pair);
        emit PairCreated(token0, token1, pair, allPairs.length);
    }

    function setFeeTo(address _feeTo) external {
        require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
        feeTo = _feeTo;
    }

    function setFeeToSetter(address _feeToSetter) external {
        require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
        feeToSetter = _feeToSetter;
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值