pragma solidity = 0.5.16; import { EnergiswapPairsManagerAutoProxy } from '../energiswapPairsManager/EnergiswapPairsManagerAutoProxy.sol'; import { Math } from '../libraries/Math.sol'; import { SafeMath } from '../libraries/SafeMath.sol'; import { UQ112x112 } from '../libraries/UQ112x112.sol'; import { IEnergiswapPairsManagerUpgrade } from './interfaces/IEnergiswapPairsManagerUpgrade.sol'; import { IEnergiswapPairsERC20Upgrade } from './interfaces/IEnergiswapPairsERC20Upgrade.sol'; import { IEnergiswapPairProxy } from '../energiswapPair/IEnergiswapPairProxy.sol'; import { IERC20 } from '../interfaces/IERC20.sol'; import { IEnergiswapFactory } from '../energiswapFactory/IEnergiswapFactory.sol'; import { IUniswapV2Callee } from '../interfaces/IUniswapV2Callee.sol'; import { IPairStorage } from '../energiswapPair/IPairStorage.sol'; import { IERC20Storage } from "../energiswapPair/IERC20Storage.sol"; import { IEnergiswapPairsManagerStorage } from "../energiswapPairsManager/IEnergiswapPairsManagerStorage.sol"; import { IEnergiswapPairsERC20Storage } from "../energiswapPairsManager/IEnergiswapPairsERC20Storage.sol"; import { IGovernedContract } from '../interfaces/IGovernedContract.sol'; import { IStorageBase } from "../interfaces/IStorageBase.sol"; contract EnergiswapPairsManagerUpgrade is EnergiswapPairsManagerAutoProxy, IEnergiswapPairsManagerUpgrade { using SafeMath for uint; using UQ112x112 for uint224; address public _storage; address public pairsERC20; uint public constant MINIMUM_LIQUIDITY = 1000; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); event Mint(address indexed pair, address indexed sender, uint amount0, uint amount1, address indexed to); event Burn(address indexed pair, address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed pair, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(address indexed pair, address indexed sender, uint112 reserve0, uint112 reserve1); modifier lock() { require(IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getUnlocked() == 1, 'EnergiswapPairsManager: LOCKED'); IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).setUnlocked(0); _; IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).setUnlocked(1); } modifier requireProxy() { require(msg.sender == proxy, 'EnergiswapPairsManager: FORBIDDEN, not proxy'); _; } modifier requirePairsERC20() { require(msg.sender == pairsERC20, 'EnergiswapPairsManager: FORBIDDEN, not pairsERC20'); _; } constructor( address _proxy, address __storage, address _pairsERC20Upgrade ) public EnergiswapPairsManagerAutoProxy(_proxy, address(this), address(uint160(0)), address(0)) { _storage = __storage; pairsERC20 = _pairsERC20Upgrade; } // This function must be called in order to upgrade to new EnergiswapPairsManager and EnergiswapPairsERC20 implementations function destroy(address _newImpl) external requireProxy { // Updates EnergiswapPairsManagerStorage contract with new EnergiswapPairsManager implementation address as owner IStorageBase(_storage).setOwner(_newImpl); // Updates EnergiswapFactory contract with new EnergiswapPairsManager implementation address IEnergiswapFactory(IEnergiswapPairsManagerStorage(_storage).getFactoryProxy()).setPairsManager(_newImpl); // Calls destroy() function on EnergiswapPairsERC20 contract IEnergiswapPairsERC20Upgrade(pairsERC20).destroy(_newImpl, IEnergiswapPairsManagerStorage(_storage).getFactoryProxy()); // Updates all deployed pairs' PairStorage contracts with new v implementation address for (uint i = 0; i < IEnergiswapPairsManagerStorage(_storage).allPairsLength(); i++) { IPairStorage( IEnergiswapPairsManagerStorage(_storage).getPairStorage( IEnergiswapPairsManagerStorage(_storage).allPairs(i) ) ).setPairsManager(_newImpl); } // Self-destruct _destroy(_newImpl); } // This function (placeholder) would be called on the new implementation if necessary for the upgrade function migrate(address _oldImpl) external requireProxy { _migrate(_oldImpl); } // Register a new pair's proxy address, PairStorage address and ERC20Storage address function registerPair(address _pairProxy, address _pairStorage, address _erc20Storage) external requireProxy { IEnergiswapPairsManagerStorage(_storage).setPairStorage(_pairProxy, _pairStorage); IEnergiswapPairsManagerStorage(_storage).pushPair(_pairProxy); // Calls EnergiswapPairsERC20 registerPair() function IEnergiswapPairsERC20Upgrade(pairsERC20).registerPair(_pairProxy, _erc20Storage); } // Pair proxy holds pair assets, proxy safeTransfer function is called by the EnergiswapPairsManager to perform transfers function _safeTransfer(address token, address to, uint value) private { IEnergiswapPairProxy(address(uint160(msg.sender))).safeTransfer(token, to, value, SELECTOR); } // 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), 'EnergiswapPair: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); ( , , uint32 blockTimestampLast) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getReserves(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { (uint price0CumulativeLast, uint price1CumulativeLast) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getCumulativePrices(); // * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).setCumulativePrices(price0CumulativeLast, price1CumulativeLast); } blockTimestampLast = blockTimestamp; IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).setReserves(uint112(balance0), uint112(balance1), blockTimestampLast); emit Sync(msg.sender, tx.origin, uint112(balance0), uint112(balance1)); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(address pair, uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IEnergiswapFactory(IEnergiswapPairsManagerStorage(_storage).getFactoryProxy()).feeTo(); feeOn = feeTo != address(0); uint _kLast = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(pair)).getKLast(); // 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 = IERC20Storage( IEnergiswapPairsERC20Storage( IEnergiswapPairsERC20Upgrade(pairsERC20)._storage() ).getERC20Storage(pair) ).getTotalSupply().mul(rootK.sub(rootKLast)); uint denominator = rootK.mul(5).add(rootKLast); uint liquidity = numerator / denominator; if (liquidity > 0) IEnergiswapPairsERC20Upgrade(pairsERC20)._mint(pair, feeTo, liquidity); } } } else if (_kLast != 0) { IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(pair)).setKLast(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,) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getReserves(); // gas savings (address _token0, address _token1) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getTokens(); uint balance0 = IERC20(_token0).balanceOf(msg.sender); uint balance1 = IERC20(_token1).balanceOf(msg.sender); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(msg.sender, _reserve0, _reserve1); uint _totalSupply = IERC20Storage( IEnergiswapPairsERC20Storage( IEnergiswapPairsERC20Upgrade(pairsERC20)._storage() ).getERC20Storage(msg.sender) ).getTotalSupply(); // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); IEnergiswapPairsERC20Upgrade(pairsERC20)._mint(msg.sender, address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'EnergiswapPair: INSUFFICIENT_LIQUIDITY_MINTED'); IEnergiswapPairsERC20Upgrade(pairsERC20)._mint(msg.sender, to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); (_reserve0, _reserve1,) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getReserves(); // gas savings if (feeOn) IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).setKLast(uint(_reserve0).mul(_reserve1)); // _reserve0 and _reserve1 are up-to-date emit Mint(msg.sender, tx.origin, amount0, amount1, to); // Mint(pairProxy, userAddress, amount0, amount1, to) } // 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,) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getReserves(); // gas savings (address _token0, address _token1) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getTokens(); uint balance0 = IERC20(_token0).balanceOf(msg.sender); uint balance1 = IERC20(_token1).balanceOf(msg.sender); uint liquidity = IERC20Storage( IEnergiswapPairsERC20Storage( IEnergiswapPairsERC20Upgrade(pairsERC20)._storage() ).getERC20Storage(msg.sender) ).getBalance(msg.sender); bool feeOn = _mintFee(msg.sender, _reserve0, _reserve1); uint _totalSupply = IERC20Storage( IEnergiswapPairsERC20Storage( IEnergiswapPairsERC20Upgrade(pairsERC20)._storage() ).getERC20Storage(msg.sender) ).getTotalSupply(); // 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, 'EnergiswapPair: INSUFFICIENT_LIQUIDITY_BURNED'); IEnergiswapPairsERC20Upgrade(pairsERC20)._burn(msg.sender, msg.sender, liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20(_token0).balanceOf(msg.sender); balance1 = IERC20(_token1).balanceOf(msg.sender); _update(balance0, balance1, _reserve0, _reserve1); (_reserve0, _reserve1,) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getReserves(); // gas savings if (feeOn) IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).setKLast(uint(_reserve0).mul(_reserve1)); // _reserve0 and _reserve1 are up-to-date emit Burn(msg.sender, tx.origin, amount0, amount1, to); // Burn(pairProxy, userAddress, amount0, amount1, to) } // 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 lock { require(amount0Out > 0 || amount1Out > 0, 'EnergiswapPair: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'EnergiswapPair: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors (address _token0, address _token1) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getTokens(); require(to != _token0 && to != _token1, 'EnergiswapPair: 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) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(msg.sender); balance1 = IERC20(_token1).balanceOf(msg.sender); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'EnergiswapPair: 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), 'EnergiswapPair: K'); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { (uint112 _reserve0, uint112 _reserve1,) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getReserves(); // gas savings (address _token0, address _token1) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getTokens(); _safeTransfer(_token0, to, IERC20(_token0).balanceOf(msg.sender).sub(_reserve0)); _safeTransfer(_token1, to, IERC20(_token1).balanceOf(msg.sender).sub(_reserve1)); } // force reserves to match balances function sync() external lock { (uint112 _reserve0, uint112 _reserve1,) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getReserves(); // gas savings (address _token0, address _token1) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getTokens(); _update(IERC20(_token0).balanceOf(msg.sender), IERC20(_token1).balanceOf(msg.sender), _reserve0, _reserve1); } // Forward calls to PairsERC20 contract function approve(address spender, uint value) external returns (bool result) { address owner = tx.origin; address pair = msg.sender; result = IEnergiswapPairsERC20Upgrade(pairsERC20).approve(pair, owner, spender, value); } function transfer(address to, uint value) external returns (bool result) { address from = tx.origin; address pair = msg.sender; result = IEnergiswapPairsERC20Upgrade(pairsERC20).transfer(pair, from, to, value); } function transferFrom(address from, address to, uint value) external returns (bool result) { address spender = tx.origin; address pair = msg.sender; result = IEnergiswapPairsERC20Upgrade(pairsERC20).transferFrom(pair, spender, from, to, value); } // This function is called by EnergiswapRouter through pair proxy function redeemLiquidity(address router, address owner, uint value) external returns (bool result) { address pair = msg.sender; // pair proxy result = IEnergiswapPairsERC20Upgrade(pairsERC20).transferFrom(pair, router, owner, pair, value); } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { address pair = msg.sender; IEnergiswapPairsERC20Upgrade(pairsERC20).permit(pair, owner, spender, value, deadline, v, r, s); } // Event emitter functions are called by EnergiswapPairsERC20 and forward calls to EnergiswapPairProxy function emitApproval(address pair, address owner, address spender, uint value) external requirePairsERC20 { IEnergiswapPairProxy(address(uint160(pair))).emitApproval(owner, spender, value); } function emitTransfer(address pair, address from, address to, uint value) external requirePairsERC20 { IEnergiswapPairProxy(address(uint160(pair))).emitTransfer(from, to, value); } // Expose getter functions function factory() external view returns (address _factory) { _factory = IEnergiswapPairsManagerStorage(_storage).getFactoryProxy(); } function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { (_reserve0, _reserve1, _blockTimestampLast) = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getReserves(); } function token0() external view returns (address _token0) { _token0 = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getToken0(); } function token1() external view returns (address _token1) { _token1 = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getToken1(); } function price0CumulativeLast() external view returns (uint _price0CumulativeLast) { _price0CumulativeLast = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getCumulativePrice0(); } function price1CumulativeLast() external view returns (uint _price1CumulativeLast) { _price1CumulativeLast = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getCumulativePrice1(); } function kLast() external view returns (uint _kLast) { _kLast = IPairStorage(IEnergiswapPairsManagerStorage(_storage).getPairStorage(msg.sender)).getKLast(); } function nonce(address owner) external view returns(uint _nonce) { _nonce = IEnergiswapPairsERC20Upgrade(pairsERC20).nonce(msg.sender, owner); } // Expose ERC20 getter functions function name() external view returns(string memory _name) { _name = IEnergiswapPairsERC20Upgrade(pairsERC20).name(); } function symbol() external view returns(string memory _symbol) { _symbol = IEnergiswapPairsERC20Upgrade(pairsERC20).symbol(); } function decimals() external view returns(uint8 _decimals) { _decimals = IEnergiswapPairsERC20Upgrade(pairsERC20).decimals(); } function totalSupply() external view returns (uint _totalSupply) { _totalSupply = IEnergiswapPairsERC20Upgrade(pairsERC20).totalSupply(msg.sender); } function balanceOf(address account) external view returns (uint _balance) { _balance = IEnergiswapPairsERC20Upgrade(pairsERC20).balanceOf(msg.sender, account); } function allowance(address owner, address spender) external view returns (uint _allowance) { _allowance = IEnergiswapPairsERC20Upgrade(pairsERC20).allowance(msg.sender, owner, spender); } }