uniswap v2合約詳解

本文要求讀者有基本的區(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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末误堡,一起剝皮案震驚了整個(gè)濱河市古话,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌锁施,老刑警劉巖陪踩,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異悉抵,居然都是意外死亡肩狂,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)基跑,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)婚温,“玉大人描焰,你說(shuō)我怎么就攤上這事媳否。” “怎么了荆秦?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵篱竭,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我步绸,道長(zhǎng)掺逼,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任瓤介,我火速辦了婚禮吕喘,結(jié)果婚禮上赘那,老公的妹妹穿的比我還像新娘。我一直安慰自己氯质,他們只是感情好募舟,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著闻察,像睡著了一般拱礁。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上辕漂,一...
    開(kāi)封第一講書(shū)人閱讀 51,754評(píng)論 1 307
  • 那天呢灶,我揣著相機(jī)與錄音,去河邊找鬼钉嘹。 笑死鸯乃,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的隧期。 我是一名探鬼主播飒责,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼仆潮!你這毒婦竟也來(lái)了宏蛉?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤性置,失蹤者是張志新(化名)和其女友劉穎拾并,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體鹏浅,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡嗅义,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了隐砸。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片之碗。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖季希,靈堂內(nèi)的尸體忽然破棺而出褪那,到底是詐尸還是另有隱情,我是刑警寧澤式塌,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布博敬,位于F島的核電站,受9級(jí)特大地震影響峰尝,放射性物質(zhì)發(fā)生泄漏偏窝。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望祭往。 院中可真熱鬧伦意,春花似錦、人聲如沸硼补。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)括勺。三九已至缆八,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間疾捍,已是汗流浹背奈辰。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留乱豆,地道東北人奖恰。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像宛裕,于是被迫代替她去往敵國(guó)和親瑟啃。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容