記得朋友圈看到過一句話,如果Defi是以太坊的皇冠,那么Uniswap就是這頂皇冠中的明珠,Uniswap目前已經是V2版本,相對V1,它的功能更加全面優化,然而其合約原始碼卻并不復雜,本文為個人學習UniswapV2原始碼的系列記錄文章,
UniswapV2的周邊合約主要用做外部賬號和核心合約之間的橋梁,也就是用戶 => 周邊合約 => 核心合約,UniswapV2周邊合約主要包含介面定義,工具庫、Router和示例實作這四部分, 這次我們先來學習它的工具庫,
UniswapV2周邊合約的工具庫包含兩個部分,一部分是直接寫在專案里的,有三個合約:SafeMath,UniswapV2Library和UniswapV2OracleLibrary,另外一部分是Node.js依賴庫,需要使用yarn安裝的,也包含幾個庫,這其中SafeMath就是簡單的防溢位庫,在前面的系列學習中已經講過,這里不再學習研究,
建議讀者在開始學習之前閱讀我的另一篇文章:UniswapV2介紹 來對UniswapV2的整體機制有個大致了解,這樣更有助于理解原始碼,
一、UniswapV2Library
1.1、原始碼
該庫的原始碼也只有82行,相對比較簡單,照例先貼原始碼:
pragma solidity >=0.5.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import "./SafeMath.sol";
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
1.2、學習
首先,我們要注意到該庫中所有的函式都是internal型別的,為什么呢,因為所有外部庫函式呼叫都是真實的EVM函式呼叫,它會有額外的開銷 ,當然外部庫函式呼叫的引數型別更廣泛,
- 第一行用來指定Solidity版本高于或者等于0.5.0
- 第二行用來匯入
IUniswapV2Pair.sol,也就是交易對的介面,注意它是使用Node.js的module匯入的, - 第三行匯入
SafeMath,注意它是正常使用相對路徑匯入的 - 第四行,
library *UniswapV2Library* {庫定義, - 第五行,在Uint型別上使用
SafeMath, sortTokens函式,對地址進行從小到大排序并驗證不能為零地址,pairFor函式,注釋中已經指出它是計算生成的交易對的地址的,具體計算方法可以分為鏈下計算和鏈上合約計算,合約計算的方法在學習核心合約factory時已經講了,這里需要注意的是init code hash的計算,會有個小坑喲,鏈下計算方法及坑是什么我這里賣個關子就不講了,大家有興趣的可以在github上看一下Issues,記得關閉的也要看的,看完就可以明白了,getReserves函式,獲取某個交易對中恒定乘積的各資產的值,因為回傳的資產值是排序過的,而輸入引數是不會有排序的,所以函式的最后一行做了處理,quote函式,根據比例由一種資產計算另一種資產的值,很好理解,getAmountOut函式,A/B交易對中賣出A資產,計算買進的B資產的數量,注意,賣出的資產扣除了千之分三的交易手續費,getAmountIn函式,A/B交易對中買進B資產,計算賣出的A資產的數量,注意,它也考慮了手續費,它和getAmountOut函式的區別是一個指定賣出的數量,一個是指定買進的數量,因為是恒定乘積演算法,價格是非線性的,所以會有兩種計算方式,getAmountsOut函式,計算鏈式交易中賣出某資產,得到的中間資產和最終資產的數量,例如 A/B => B/C 賣出A,得到BC的數量,getAmountsIn函式,計算鏈式交易中買進某資產,需要賣出的中間資產和初始資產數量,例如 A/B => B/C 買進C,得到AB的數量,因為從買進推導賣出是反向進行的,所以資料是反向遍歷的,
二、UniswapV2OracleLibrary
2.1、原始碼
該庫的原始碼很短,只有35行,只有兩個函式,
pragma solidity >=0.5.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/lib/contracts/libraries/FixedPoint.sol';
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
2.2、學習
- 第一行用來指定Solidity版本高于或者等于0.5.0
- 接下來兩行匯入陳述句分別匯入交易對合約介面和自定義的浮點數庫,合約介面見核心合約學習相關文章,浮點數庫在下面介紹,
- 接下來的注釋闡述了該庫的用處,計算當前累計價格,同時避免同步呼叫,節省手續費,
library UniswapV2OracleLibrary {庫定義using FixedPoint for *;在所有資料型別上使用FixedPoint庫,從中可以看出庫中也可以使用別的庫,語法是一樣的,currentBlockTimestamp獲取當前區塊時間,注意這里和交易對合約中的處理方式一樣,取模操作,然而就算溢位了,直接進行型別轉換也會得到和取模操作相同的值,這個問題我在核心合約學習三中已經更新過了,開發者給出答案了,currentCumulativePrices函式,計算當前區塊累積價格,如果當前區塊交易對合約已經計算過了(兩個區塊時間一致),則跳過;如果沒有,則加上去,注意它是view函式,并未更新任何狀態變數,這個累計值是計算出來的,
三、FixedPoint庫
因為UniswapV2OracleLibrary庫的原始碼中使用了FixedPoint庫,所以我們順便也學習一下該庫,注意,該庫并不是以撰寫原始碼的方式保存為檔案直接匯入的,而是通過Node.js模塊匯入,屬于依賴庫,查看其周邊合約的README.md可以看到,運行yarn命令來安裝所有依賴,
3.1、原始碼
下面是該庫的原始碼:
pragma solidity >=0.4.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
}
3.2、學習
- 第一行指定了使用的Solidity版本
- 第二行是庫定義,注意庫沒有繼承,
- 接下來定義兩個資料結構,一個是uq112x112,加起來就是224位,所以它的欄位只有一個uint224的
_x,一個是uq144x112,加起來就是256位,所以它的欄位為uint的_x,注意它的注釋分別代表取值范圍和精度(小數), uint8 private constant RESOLUTION = 112;定義不同大小資料轉換時左移或者右移的位數,encode函式,將uint112轉成uq112x112結構,encode144函式,將uint112轉成uq114x112結構,div函式,一個uq112x112型別除于一個uint112,注意先uint112轉化成了uint224,結果也是一個uq112x112,(兩個112位分別代表數值和精度),mul函式,將一個uq112x112和一個uint相乘法,注意,做了防溢位處理,結果是一個uq144x112,相比uq112x112,最左邊的32位是保存的相對uint224的溢位位,fraction函式,用來在兩個uint112相除時提高精度,將分子左移112位,那么結果的左邊112位就是值,右邊的112位相當于小數位,用于UniswapV2的價格計算當中,decode函式,將一個uq112x112(uint224)右移112位并將結果轉換成uint112,相當于右邊112位小數位被截斷了,decode144函式,同上,只是資料型別變成了uq144x112(uint256),
因為本庫主要功能是提高價格計算時的精度,在UniswapV2周邊合約中,該庫的絕大部分函式僅在預言機示例合約中使用,
四、TransferHelper庫
有個簡單的庫也要提一下,它就是TransferHelper庫,它也是通過依賴安裝匯入的,主要目的是用來統一處理標準ERC20代幣和非標準ERC20代幣之間部分函式的回傳值問題(主要是轉移代幣和授權的回傳值),它通過使用一個低級的call函式呼叫來代替正常的合約呼叫,并對執行結果和回傳值做處理,這樣處理的目的見UniswapV2介紹,
注意:使用call呼叫合約必須提供函式的選擇器(如果存在),計算方式注釋中已經寫明了,
4.1、原始碼
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
4.2、學習
safeApprove授權函式,被呼叫函式可以有回傳值(為true)或者無回傳值,均會被視為成功,safeTransfer直接轉移代幣函式,回傳值處理同上,safeTransferFrom授權轉移代幣函式,回傳值處理同上,safeTransferETH發送ETH,注意等式右邊的語法:(bool success,) = to.call{value:value}(new bytes(0));,value代表發送的ETH數量(單位為wei),new bytes(0)代表為空資料payload,
注意:這里有點小瑕疵,雖然本庫代碼第一行指定了Solidity版本為>=0.6.0,但是(bool success,) = to.call{value:value}(new bytes(0));使用的語法在0.6.2版本才能編譯通過,不過單獨看有這么一點小問題,但是因為使用該庫的合約原始碼均指定Solidity版本為0.6.6,所以聯合使用起來使用沒有問題,當然如果能將pragma solidity >=0.6.0;換成pragma solidity >=0.6.2;就更精確了,
五、其它依賴
node_modules/@uniswap/lib/contracts/libraries/目錄下還有其它一些依賴庫,主要是進行一些字串或者字符操作,這里就不一一學習了,需要提到一點的是在PairNamer.sol原始碼中,出現了string private constant TOKEN_SYMBOL_PREFIX = '🦄';那個獨角獸圖示其實是一個Unicode字符,在Solidity中,字串字面值是支持unicode的,🦄字符從UniswapV1起開始使用,它的詳細說明網址為:https://emojipedia.org/unicorn/,當然如果你愿意,可以挑選一個你喜歡的其它Unicode字符來替換它,
不過這里同樣存在編譯器版本的問題,在PairNamer.sol原始碼中,給出了pragma solidity >=0.5.0;,但實際上在0.7.0后,在有效的UTF-8序列中插入Unicode字符需要增加unicode前綴,例如:
string memory a = unicode"Hello 😃";
UniswapV2未使用Solidity 0.7.0以上版本,所以這里不需要,如果使用加unicode的新語法,Solidity版本必須0.7.0以上,
最后一點,庫其實只用部署一次,在編譯時將它的地址鏈接到使用的合約即可(使用一些工具自動部署時看不出來,可以使用truffle進行手動部署庫再進行鏈接),但是庫原始碼一般都不大,一個新專案基本上都會重新部署一個相同的庫(例如SafeMath),而不會重用以前部署好的庫,
這次的學習就到此結束了,由于個人能力有限,難免有理解錯誤或者不正確的地方,還請大家多多留言指正,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/168113.html
標籤:其他
