本文要求读者有基本的区块链知识背景,知道以太坊和ERC20,使用过或知道如何使用uniswap。
官网:https://uniswap.org/
github:https://github.com/Uniswap
白皮书:https://uniswap.org/whitepaper.pdf (对理解合约帮助特别大,建议对照着白皮书看合约)
uniswap的合约只有三个(不包含接口和库)
UniswapV2ERC20.sol
UniswapV2Factory.sol
UniswapV2Pair.sol
下面依次分析
1.UniswapV2ERC20.sol
合约名称显而易见,这是一个ERC20合约,除了transfer等基础方法外,还多了一个permit方法,功能和approval相似,就是可以线下签好名然后发给第三方,让第三方帮你做approval的操作,花费第三方的gas。这个方法在eip-2612中提出:
eip-2612标准参考:https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2612.md?ref=learnblockchain.cn
讲解:https://zhuanlan.zhihu.com/p/268699937
这里不展开讲解perimit。除此之外就是普通的ERC20方法,考虑到本合约并不是UNISWAP的核心机制合约,只是一个独立的ERC20合约,这方面的讲解已经很多了,因此不再赘述,感兴趣的同学可以自己去查ERC20。
2.UniswapV2Factory.sol
此合约只有三个核心方法
createPair
setFeeTo
setFeeToSetter
先介绍简单的两个:
1.setFeeTo
function setFeeTo(address _feeTo) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeTo = _feeTo;
}
用于设置feeTo地址,只有feeToSetter才可以设置。
uniswap中每次交易代币会收取0.3%的手续费,目前全部分给了LQ,若此地址不为0时,将会分出手续费中的1/6给这个地址(这部分逻辑没有体现在factory里面)
2.setFeeToSetter
function setFeeToSetter(address _feeToSetter) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeToSetter = _feeToSetter;
}
用于设置feeToSetter地址,必须是现任feeToSetter才可以设置。
接下来重点看看createPair函数:
function createPair(address tokenA, address tokenB) external returns (address pair) {
//必须是两个不一样的ERC20合约地址
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
//让tokenA和tokenB的地址从小到大排列
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
//token地址不能是0
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
//必须是uniswap中未创建过的pair
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
//获取模板合约UniswapV2Pair的creationCode
bytes memory bytecode = type(UniswapV2Pair).creationCode;
//以两个token的地址作为种子生产salt
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
//直接调用汇编创建合约
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
//初始化刚刚创建的合约
IUniswapV2Pair(pair).initialize(token0, token1);
//记录刚刚创建的合约对应的pair
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
3.UniswapV2Pair.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';
//此合约继承了IUniswapV2Pair和UniswapV2ERC20,因此也是ERC20代币。
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
//获取transfer方法的bytecode前四个字节
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public 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
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
//一个锁,使用该modifier的函数在unlocked==1时才可以进入,
//第一个调用者进入后,会将unlocked置为0,此使第二个调用者无法再进入
//执行完_部分的代码后,才会再将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 {
//调用transfer方法,把地址token中的value个代币转账给to
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
//检查返回值,必须成功否则报错
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
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);
//部署此合约时将msg.sender设置为factory,后续初始化时会用到这个值
constructor() public {
factory = msg.sender;
}
//在UniswapV2Factory.sol的createPair中调用过
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
//这个函数是用来更新价格oracle的,计算累计价格
// update reserves and, on the first call per block, price accumulators
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
//计算时间加权的累计价格,256位中,前112位用来存整数,后112位用来存小数,多的32位用来存溢出的值
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
//更新reserve值
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) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
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;
}
}
// 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
//合约里两种token的当前的balance
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
//获得当前balance和上一次缓存的余额的差值
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
//计算手续费
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
//第一次铸币,也就是第一次注入流动性,值为根号k减去MINIMUM_LIQUIDITY
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
//把MINIMUM_LIQUIDITY赋给地址0,永久锁住
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
//计算增量的token占总池子的比例,作为新铸币的数量
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
//铸币,修改to的token数量及totalsupply
_mint(to, liquidity);
//更新时间加权平均价格
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
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
//分别获取本合约地址中token0、token1和本合约代币的数量
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
//此时用户的LP token已经被转移至合约地址,因此这里取合约地址中的LP Token余额就是等下要burn掉的量
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
//根据liquidity占比获取两个代币的实际数量
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');
//销毁LP Token
_burn(address(this), liquidity);
//将token0和token1转给地址to
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
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);
}
// force balances to match reserves
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
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
4. 补充知识:
1.modifier中的_用来代表,使用该modifier的函数代码,
参考:https://learnblockchain.cn/question/1541
https://ethereum.stackexchange.com/questions/5861/are-underscores-in-modifiers-code-or-are-they-just-meant-to-look-cool
2.abi.encodeWithSelector
https://blog.csdn.net/qq_35434814/article/details/104682616
3.price0CumulativeLast
https://kuaibao.qq.com/s/20200706A043PC00?refer=spider_map
https://medium.com/@epheph/using-uniswap-v2-oracle-with-storage-proofs-3530e699e1d3
4.其他讲解uniswap合约的blog
https://blog.csdn.net/weixin_39430411/article/details/108965855
作者:CodeIsLaw
链接:https://www.jianshu.com/p/4ee9fabbece5
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处