在上一章跟我一起阅读并修复源码(3:编译工程,源码分析)之四_lixiaodog的博客-CSDN博客中我们分析了contract MdexERC20,在本章中我们将分析contract MdexPair,我们注意到本合约与MdexERC20合约非常相似,相同的函数我们将不再分析。
using SafeMath for uint;
using UQ112x112 for uint224;
把SafeMath,UQ112x112附加到相应的数据结构上,这样只要数据类型为uint,uint224就可以以var.libfun()的形式直接调库函数。而libaray是一组逻辑代码。在库中只处理数据的逻辑,而不关心数据的存储。利用这种特性,在实际开发中可以把数据和逻辑分离。
为什么要赋予unit224
类型新的方法?这是因为在Solidity里面没有非整型的类型,但是token
的数量肯定会出现小数位,使用UQ112x112
的库去模拟浮点数类型。将unit224
中的112位当作浮点数的整数部分,另外112位当作浮点数的小数部分 , 剩余的32位主要是存放blockTimestampLast
变量,该变量的作用以及更新会在后面讲到。
uint public override constant MINIMUM_LIQUIDITY = 10 ** 3;
定义了流动性的最小量
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
这个定义了一个函数索引,这个索引可以直接被CALL,DELEGATECALL,CALLCODE等函数直接调用,事实上在使用WEB3模块与智能合约交互时,在交易字段中,前4个字节就是所要调函数的索引。
在下面函数中直接使用了token.call来调用SELECTOR 定义的函数。
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'MdexSwap: TRANSFER_FAILED');
}
address public override factory;
address public override token0;
address public override token1;
分别定义了工厂合约地址,交易对中的A,B两个TOKEN地址。
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
定义了当前PAIR分别持有两个TOKEN的数量, blockTimestampLast主要用来区分是不是第一笔交易。
uint public override price0CumulativeLast;
uint public override price1CumulativeLast;
uint public override kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
这里的价格最后累计,是用于预言机上,该数值会在每个区块的第一笔调用进行更新。
kLast
这个变量在没有开启是等于0的,只有当开启时候,这个值才等于k值,因为一般开启,那么k值就不会一直等于两个储备量向乘的结果来。
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external override {
require(msg.sender == factory, 'MdexSwap: FORBIDDEN');
// sufficient check
token0 = _token0;
token1 = _token1;
}
初始化函数,当factory布署合约时调用一次。
// 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), 'MdexSwap: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2 ** 32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// overflow is desired
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;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
在此函数中更新了此PAIR的中两个TOKEN的剩余数量与更新时间。
function mint(address to) external override 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);
uint totalSupply = _totalSupply;
// gas savings, must be defined here since totalSupply can update in _mintFee
if (totalSupply == 0) {
liquidity = SafeMath.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY);
// permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = SafeMath.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'MdexSwap: INSUFFICIENT_LIQUIDITY_MINTED');
_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);
}
mint
函数是一个比较关键的函数,它的输入为一个地址to
,输出为该地址所提供的流动性,在MDEXSWAP中,流动性也被体现成token
即LP token
。 生成token流程发生在router
合约向pair
合约发送代币之后,因此此次的储备量和合约的token
余额是不相等的,因为此时pair中的储备量还没有更新,在调用_update之后,才会更新到一致。中间的差值就是需要生成的token数量
,即amount0
和amount1
。这部分代码会在后面进行解释。然后获取总的流动性的供应量totoalSupply
,如果totalSupply
等于0的话,就代表是首次添加流动性。添加流动性后用户会获的LP,而token0,和token1的余额则会进入PAIR中。
function burn(address to) external override lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves();
// gas savings
address _token0 = token0;
// gas savings
address _token1 = token1;
// gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
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
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, 'MdexSwap: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_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);
}
上一个函数是创造流动性token,这个函数则是回收流动性token,当用户取回流动性时会调用此函数,首先根据用户提供的LP数量即此时的_balanceOf[address(this)],然后根据LP的数量计算出应该返回用户的token1与token2的数量。当返还这完成后调用_burn(address(this), liquidity),销毁此次消耗的lp数量。然后更新流动动池的储备量。并触发burn事件。
// 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 override lock {
require(amount0Out > 0 || amount1Out > 0, 'MdexSwap: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves();
// gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'MdexSwap: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{// scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'MdexSwap: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out);
// optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out);
// optimistically transfer tokens
if (data.length > 0) IHswapV2Callee(to).hswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'MdexSwap: INSUFFICIENT_INPUT_AMOUNT');
{// scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000 ** 2), 'MdexSwap: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
交换token
方法一般通过路由合约调用,功能是交换token
,需要的参数包括:amount0Out
:token0
要交换出的数额;amount1Out
:token1
要交换出的数额,to
:交换token
要发到的地址,一般是其它pair
合约地址;data
用于回调使用。
首先确认amount0Out
或者amount1Out
有一个大于0,然后确保储备量大于要取出的数量。
然后确保address(to)
不等于对应的token
地址。然后发送token
到对应的地址上,在下一章
跟我一起阅读并修复源码(3:编译工程,源码分析)之六_lixiaodog的博客-CSDN博客
中我们将修复MDEX的所有BUG,完成编译,以便尽快进行下一步,合同部署。