本文要求讀者有基本的區(qū)塊鏈知識(shí)背景,知道以太坊和ERC20,使用過(guò)或知道如何使用uniswap酒甸。
官網(wǎng):https://uniswap.org/
github:https://github.com/Uniswap
白皮書(shū):https://uniswap.org/whitepaper.pdf (對(duì)理解合約幫助特別大堆巧,建議對(duì)照著白皮書(shū)看合約)
uniswap的合約只有三個(gè)(不包含接口和庫(kù))
UniswapV2ERC20.sol
UniswapV2Factory.sol
UniswapV2Pair.sol
下面依次分析
1.UniswapV2ERC20.sol
合約名稱(chēng)顯而易見(jiàn),這是一個(gè)ERC20合約牍颈,除了transfer等基礎(chǔ)方法外迄薄,還多了一個(gè)permit方法,功能和approval相似煮岁,就是可以線下簽好名然后發(fā)給第三方讥蔽,讓第三方幫你做approval的操作,花費(fèi)第三方的gas画机。這個(gè)方法在eip-2612中提出:
eip-2612標(biāo)準(zhǔn)參考:https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2612.md?ref=learnblockchain.cn
講解:https://zhuanlan.zhihu.com/p/268699937
這里不展開(kāi)講解perimit冶伞。除此之外就是普通的ERC20方法,考慮到本合約并不是UNISWAP的核心機(jī)制合約步氏,只是一個(gè)獨(dú)立的ERC20合約响禽,這方面的講解已經(jīng)很多了,因此不再贅述荚醒,感興趣的同學(xué)可以自己去查ERC20芋类。
2.UniswapV2Factory.sol
此合約只有三個(gè)核心方法
createPair
setFeeTo
setFeeToSetter
先介紹簡(jiǎn)單的兩個(gè):
1.setFeeTo
function setFeeTo(address _feeTo) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeTo = _feeTo;
}
用于設(shè)置feeTo地址,只有feeToSetter才可以設(shè)置界阁。
uniswap中每次交易代幣會(huì)收取0.3%的手續(xù)費(fèi)侯繁,目前全部分給了LQ,若此地址不為0時(shí)泡躯,將會(huì)分出手續(xù)費(fèi)中的1/6給這個(gè)地址(這部分邏輯沒(méi)有體現(xiàn)在factory里面)
2.setFeeToSetter
function setFeeToSetter(address _feeToSetter) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeToSetter = _feeToSetter;
}
用于設(shè)置feeToSetter地址贮竟,必須是現(xiàn)任feeToSetter才可以設(shè)置。
接下來(lái)重點(diǎn)看看createPair函數(shù):
function createPair(address tokenA, address tokenB) external returns (address pair) {
//必須是兩個(gè)不一樣的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中未創(chuàng)建過(guò)的pair
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
//獲取模板合約UniswapV2Pair的creationCode
bytes memory bytecode = type(UniswapV2Pair).creationCode;
//以?xún)蓚€(gè)token的地址作為種子生產(chǎn)salt
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
//直接調(diào)用匯編創(chuàng)建合約
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
//初始化剛剛創(chuàng)建的合約
IUniswapV2Pair(pair).initialize(token0, token1);
//記錄剛剛創(chuàng)建的合約對(duì)應(yīng)的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前四個(gè)字節(jié)
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;
//一個(gè)鎖,使用該modifier的函數(shù)在unlocked==1時(shí)才可以進(jìn)入写穴,
//第一個(gè)調(diào)用者進(jìn)入后顷级,會(huì)將unlocked置為0,此使第二個(gè)調(diào)用者無(wú)法再進(jìn)入
//執(zhí)行完_部分的代碼后确垫,才會(huì)再將unlocked置1弓颈,重新將鎖打開(kāi)
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
//用于獲取兩個(gè)代幣在池子中的數(shù)量和最后更新的時(shí)間
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 {
//調(diào)用transfer方法帽芽,把地址token中的value個(gè)代幣轉(zhuǎn)賬給to
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
//檢查返回值,必須成功否則報(bào)錯(cuò)
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);
//部署此合約時(shí)將msg.sender設(shè)置為factory翔冀,后續(xù)初始化時(shí)會(huì)用到這個(gè)值
constructor() public {
factory = msg.sender;
}
//在UniswapV2Factory.sol的createPair中調(diào)用過(guò)
// 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;
}
//這個(gè)函數(shù)是用來(lái)更新價(jià)格oracle的导街,計(jì)算累計(jì)價(jià)格
// 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
//計(jì)算時(shí)間加權(quán)的累計(jì)價(jià)格,256位中纤子,前112位用來(lái)存整數(shù)搬瑰,后112位用來(lái)存小數(shù),多的32位用來(lái)存溢出的值
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的當(dāng)前的balance
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
//獲得當(dāng)前balance和上一次緩存的余額的差值
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
//計(jì)算手續(xù)費(fèi)
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
//第一次鑄幣控硼,也就是第一次注入流動(dòng)性泽论,值為根號(hào)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 {
//計(jì)算增量的token占總池子的比例卡乾,作為新鑄幣的數(shù)量
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
//鑄幣翼悴,修改to的token數(shù)量及totalsupply
_mint(to, liquidity);
//更新時(shí)間加權(quán)平均價(jià)格
_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和本合約代幣的數(shù)量
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
//此時(shí)用戶(hù)的LP token已經(jīng)被轉(zhuǎn)移至合約地址幔妨,因此這里取合約地址中的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
//根據(jù)liquidity占比獲取兩個(gè)代幣的實(shí)際數(shù)量
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');
//銷(xiāo)毀LP Token
_burn(address(this), liquidity);
//將token0和token1轉(zhuǎn)給地址to
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
//更新時(shí)間加權(quán)平均價(jià)格
_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);
}
}
補(bǔ)充知識(shí):
1.modifier中的_用來(lái)代表鹦赎,使用該modifier的函數(shù)代碼,
參考: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
下次學(xué)習(xí):AAVE