通过阅读代码导入的包,我决定将代码的阅读顺序定为: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-approverequire(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; // 代币对之token0address public token1; // 代币对之token1uint112 private reserve0;           // uses single storage slot, accessible via getReservesuint112 private reserve1;           // uses single storage slot, accessible via getReservesuint32  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跟pricefunction _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 desiredif (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // 如果timeElapsed不等于0,说明需要更新 价格累加器// * never overflows, and + overflow is desiredprice0CumulativeLast += 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 savingsif (feeOn) { // 如果该地址开放了if (_kLast != 0) { // TODO:为啥啊——刚初始化完可能为0uint 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 checksfunction 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可能增加totalSupplyuint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFeeif (_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 checksfunction burn(address to) external lock returns (uint amount0, uint amount1) {(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savingsaddress _token0 = token0;                                // gas savingsaddress _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,token1amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distributionamount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distributionrequire(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-dateemit 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 errorsaddress _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=0uint 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 errorsuint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));// 扣除此次交易0.3%手续费后的余额// 并要求最终的K>swap前的krequire(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 savingsaddress _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 sufficientbytes 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 directionallPairs.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;}
}

Uniswap V2-Core 部分智能合约代码解析相关推荐

  1. 【许晓笛】 EOS智能合约案例解析(1)

    详解 EOS 智能合约的 hpp 文件 为了帮助大家熟悉 EOS 智能合约,EOS 官方提供了一个代币(资产)智能合约 Demo -- eosio.token.eosio.token 智能合约目前还不 ...

  2. 【许晓笛】 EOS 智能合约案例解析(2)

    详解 EOS 智能合约的 cpp 文件 之前的文章介绍了 eosio.token 智能合约的 hpp 文件,这次向大家介绍 eosio.token.cpp 文件,cpp 文件即 C++ 代码文件,智能 ...

  3. 【许晓笛】 EOS智能合约案例解析(1) 1

    详解 EOS 智能合约的 hpp 文件 为了帮助大家熟悉 EOS 智能合约,EOS 官方提供了一个代币(资产)智能合约 Demo -- eosio.token.eosio.token 智能合约目前还不 ...

  4. 【许晓笛】EOS 智能合约案例解析(2)

    详解 EOS 智能合约的 cpp 文件 之前的文章介绍了 eosio.token 智能合约的 hpp 文件,这次向大家介绍 eosio.token.cpp 文件,cpp 文件即 C++ 代码文件,智能 ...

  5. 【许晓笛】EOS智能合约案例解析(1)

    为了帮助大家熟悉 EOS 智能合约,EOS 官方提供了一个代币(资产)智能合约 Demo -- eosio.token.eosio.token 智能合约目前还不是特别完善,个别功能还没有完成.但这个示 ...

  6. usdt智能合约代码

    以太链usdt智能合约代码 /***Submitted for verification at Etherscan.io on 2017-11-28 */pragma solidity ^0.4.17 ...

  7. EOS智能合约案例解析(下)

    这次向大家介绍 eosio.token 智能合约的最后一个文件 -- abi文件.ABI 全称 Application Binary Interface,中文名"应用程序二进制接口" ...

  8. 【Solidity】零基础入门Solidity编写智能合约代码

    如果你有其他语言基础,可以很快入门,如果新手建议了解即可,以下是课程目录: 1.智能合约概述 2.区块链基础 3.以太坊虚拟机 4.安装Solidity编译器 5.从源代码编译 6.CMake参数 7 ...

  9. bsc heco eth浏览器开源智能合约代码,图文说明

    文章目录 配置 基本配置 其他配置 library 构造参数 方式一 方式二 开源流程示例 情况1 基本配置都正确,没有构造参数和library 情况2 补上library,不填构造参数 情况3 填写 ...

最新文章

  1. Assembly--软件PBcR和Canu
  2. Java Servlet完全教程
  3. Jackson注解学习参考
  4. 黑马程序员C语言基础(第八天)复合类型(自定义类型)(结构体)、共用体(联合体)、枚举enum、 typedef
  5. maven web项目保存log4j日志到WEB-INF
  6. 疫情期间用掉了1400亿个!二维码会被人类扫完吗?
  7. python之简单爬虫(爬取豆瓣出版社)
  8. 神经网络与深度学习——TensorFlow2.0实战(笔记)(四)(python列表与元组)
  9. 题库明细 C#语言和SQL Server
  10. JVM对象内存分配详细过程(栈上分配->TLAB->老年代->Eden区)
  11. Oracle VM + Windows2003 Server 配置
  12. sublime后缀_提高数据分析工作效率-Sublime如何设置默认打开文件格式
  13. 【PAT乙】1001 害死人不偿命的(3n+1)猜想 (15分) 模拟,水水更健康
  14. 2013-07-23 IT 要闻速记快想
  15. Java 堆栈-用数组实现堆栈
  16. 微积分公式与运算法则
  17. 安卓手机上编程开发环境
  18. 带您了解耳机常用麦克风
  19. Unity打包的PC项目生成一个EXE文件
  20. 虚拟机VMware Workstation安装使用教程

热门文章

  1. Android APP存储路径和缓存清理规范
  2. 微信H5、公众号开发,域名重定向
  3. 中国杀软套路深:CIA怼遍全世界竟然干不过它
  4. 【CF 513F2】
  5. Bootstrap 表格内容水平、垂直居中
  6. Numpy 数组切片
  7. markdown的各种操作
  8. python学法用法 自动刷分_使用python对微信小游戏跳一跳刷分
  9. 吸血鬼数字java_吸血鬼数字
  10. 推荐一款非常好用的效率APP