UniswapV2Pair.sol 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. pragma solidity =0.5.16;
  2. import './interfaces/IUniswapV2Pair.sol';
  3. import './UniswapV2ERC20.sol';
  4. import './libraries/Math.sol';
  5. import './libraries/UQ112x112.sol';
  6. import './interfaces/IERC20.sol';
  7. import './interfaces/IUniswapV2Factory.sol';
  8. import './interfaces/IUniswapV2Callee.sol';
  9. contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
  10. using SafeMath for uint;
  11. using UQ112x112 for uint224;
  12. uint public constant MINIMUM_LIQUIDITY = 10**3;
  13. bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
  14. address public factory;
  15. address public token0;
  16. address public token1;
  17. uint112 private reserve0; // uses single storage slot, accessible via getReserves
  18. uint112 private reserve1; // uses single storage slot, accessible via getReserves
  19. uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
  20. uint public price0CumulativeLast;
  21. uint public price1CumulativeLast;
  22. uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
  23. uint private unlocked = 1;
  24. modifier lock() {
  25. require(unlocked == 1, 'UniswapV2: LOCKED');
  26. unlocked = 0;
  27. _;
  28. unlocked = 1;
  29. }
  30. function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
  31. _reserve0 = reserve0;
  32. _reserve1 = reserve1;
  33. _blockTimestampLast = blockTimestampLast;
  34. }
  35. function _safeTransfer(address token, address to, uint value) private {
  36. (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
  37. require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
  38. }
  39. event Mint(address sender, uint amount0, uint amount1);
  40. event Burn(address sender, uint amount0, uint amount1, address to);
  41. event Swap(
  42. address sender,
  43. uint amount0In,
  44. uint amount1In,
  45. uint amount0Out,
  46. uint amount1Out,
  47. address to
  48. );
  49. event Sync(uint112 reserve0, uint112 reserve1);
  50. constructor() public payable {
  51. factory = msg.sender;
  52. }
  53. // called once by the factory at time of deployment
  54. function initialize(address _token0, address _token1) external {
  55. require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
  56. token0 = _token0;
  57. token1 = _token1;
  58. }
  59. // update reserves and, on the first call per block, price accumulators
  60. function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
  61. require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
  62. uint32 blockTimestamp = uint32(block.timestamp % 2**32);
  63. uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
  64. if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
  65. // * never overflows, and + overflow is desired
  66. price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
  67. price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
  68. }
  69. reserve0 = uint112(balance0);
  70. reserve1 = uint112(balance1);
  71. blockTimestampLast = blockTimestamp;
  72. emit Sync(reserve0, reserve1);
  73. }
  74. // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
  75. function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
  76. address feeTo = IUniswapV2Factory(factory).feeTo();
  77. feeOn = feeTo != address(0);
  78. uint _kLast = kLast; // gas savings
  79. if (feeOn) {
  80. if (_kLast != 0) {
  81. uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
  82. uint rootKLast = Math.sqrt(_kLast);
  83. if (rootK > rootKLast) {
  84. uint numerator = totalSupply.mul(rootK.sub(rootKLast));
  85. uint denominator = rootK.mul(5).add(rootKLast);
  86. uint liquidity = numerator / denominator;
  87. if (liquidity > 0) _mint(feeTo, liquidity);
  88. }
  89. }
  90. } else if (_kLast != 0) {
  91. kLast = 0;
  92. }
  93. }
  94. // this low-level function should be called from a contract which performs important safety checks
  95. function mint(address to) external lock returns (uint liquidity) {
  96. (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
  97. uint balance0 = IERC20(token0).balanceOf(address(this));
  98. uint balance1 = IERC20(token1).balanceOf(address(this));
  99. uint amount0 = balance0.sub(_reserve0);
  100. uint amount1 = balance1.sub(_reserve1);
  101. bool feeOn = _mintFee(_reserve0, _reserve1);
  102. uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
  103. if (_totalSupply == 0) {
  104. liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
  105. _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
  106. } else {
  107. liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
  108. }
  109. require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
  110. _mint(to, liquidity);
  111. _update(balance0, balance1, _reserve0, _reserve1);
  112. if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
  113. emit Mint(msg.sender, amount0, amount1);
  114. }
  115. // this low-level function should be called from a contract which performs important safety checks
  116. function burn(address to) external lock returns (uint amount0, uint amount1) {
  117. (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
  118. address _token0 = token0; // gas savings
  119. address _token1 = token1; // gas savings
  120. uint balance0 = IERC20(_token0).balanceOf(address(this));
  121. uint balance1 = IERC20(_token1).balanceOf(address(this));
  122. uint liquidity = balanceOf[address(this)];
  123. bool feeOn = _mintFee(_reserve0, _reserve1);
  124. uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
  125. amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
  126. amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
  127. require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
  128. _burn(address(this), liquidity);
  129. _safeTransfer(_token0, to, amount0);
  130. _safeTransfer(_token1, to, amount1);
  131. balance0 = IERC20(_token0).balanceOf(address(this));
  132. balance1 = IERC20(_token1).balanceOf(address(this));
  133. _update(balance0, balance1, _reserve0, _reserve1);
  134. if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
  135. emit Burn(msg.sender, amount0, amount1, to);
  136. }
  137. // this low-level function should be called from a contract which performs important safety checks
  138. function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
  139. require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
  140. (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
  141. require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
  142. uint balance0;
  143. uint balance1;
  144. { // scope for _token{0,1}, avoids stack too deep errors
  145. address _token0 = token0;
  146. address _token1 = token1;
  147. require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
  148. if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
  149. if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
  150. if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
  151. balance0 = IERC20(_token0).balanceOf(address(this));
  152. balance1 = IERC20(_token1).balanceOf(address(this));
  153. }
  154. uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
  155. uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
  156. require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
  157. { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
  158. uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
  159. uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
  160. //require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
  161. }
  162. _update(balance0, balance1, _reserve0, _reserve1);
  163. emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
  164. }
  165. // force balances to match reserves
  166. function skim(address to) external lock {
  167. address _token0 = token0; // gas savings
  168. address _token1 = token1; // gas savings
  169. _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
  170. _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
  171. }
  172. // force reserves to match balances
  173. function sync() external lock {
  174. _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
  175. }
  176. }