zellic-audit
Initial commit
f998fcd
raw
history blame
141 kB
{
"language": "Solidity",
"sources": {
"contracts/MuffinHub.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport \"./interfaces/hub/IMuffinHub.sol\";\nimport \"./interfaces/IMuffinHubCallbacks.sol\";\nimport \"./libraries/utils/SafeTransferLib.sol\";\nimport \"./libraries/utils/PathLib.sol\";\nimport \"./libraries/math/Math.sol\";\nimport \"./libraries/Pools.sol\";\nimport \"./MuffinHubBase.sol\";\n\ncontract MuffinHub is IMuffinHub, MuffinHubBase {\n using Math for uint256;\n using Pools for Pools.Pool;\n using Pools for mapping(bytes32 => Pools.Pool);\n using PathLib for bytes;\n\n error InvalidTokenOrder();\n error NotAllowedSqrtGamma();\n error InvalidSwapPath();\n error NotEnoughIntermediateOutput();\n error NotEnoughFundToWithdraw();\n\n /// @dev To reduce bytecode size of this contract, we offload position-related functions, governance functions and\n /// various view functions to a second contract (i.e. MuffinHubPositions.sol) and use delegatecall to call it.\n address internal immutable positionController;\n\n constructor(address _positionController) {\n positionController = _positionController;\n governance = msg.sender;\n }\n\n /*===============================================================\n * ACCOUNTS\n *==============================================================*/\n\n /// @inheritdoc IMuffinHubActions\n function deposit(\n address recipient,\n uint256 recipientAccRefId,\n address token,\n uint256 amount,\n bytes calldata data\n ) external {\n uint256 balanceBefore = getBalanceAndLock(token);\n IMuffinHubCallbacks(msg.sender).muffinDepositCallback(token, amount, data);\n checkBalanceAndUnlock(token, balanceBefore + amount);\n\n accounts[token][getAccHash(recipient, recipientAccRefId)] += amount;\n emit Deposit(recipient, recipientAccRefId, token, amount, msg.sender);\n }\n\n /// @inheritdoc IMuffinHubActions\n function withdraw(\n address recipient,\n uint256 senderAccRefId,\n address token,\n uint256 amount\n ) external {\n bytes32 accHash = getAccHash(msg.sender, senderAccRefId);\n uint256 balance = accounts[token][accHash];\n if (balance < amount) revert NotEnoughFundToWithdraw();\n unchecked {\n accounts[token][accHash] = balance - amount;\n }\n SafeTransferLib.safeTransfer(token, recipient, amount);\n emit Withdraw(msg.sender, senderAccRefId, token, amount, recipient);\n }\n\n /*===============================================================\n * CREATE POOL / TIER\n *==============================================================*/\n\n /// @notice Check if the given sqrtGamma is allowed to be used to create a pool or tier\n /// @dev It first checks if the sqrtGamma is in the whitelist, then check if the pool hasn't had that fee tier created.\n function isSqrtGammaAllowed(bytes32 poolId, uint24 sqrtGamma) public view returns (bool) {\n uint24[] storage allowed = poolAllowedSqrtGammas[poolId].length != 0\n ? poolAllowedSqrtGammas[poolId]\n : defaultAllowedSqrtGammas;\n unchecked {\n for (uint256 i; i < allowed.length; i++) {\n if (allowed[i] == sqrtGamma) {\n Tiers.Tier[] storage tiers = pools[poolId].tiers;\n for (uint256 j; j < tiers.length; j++) if (tiers[j].sqrtGamma == sqrtGamma) return false;\n return true;\n }\n }\n }\n return false;\n }\n\n /// @inheritdoc IMuffinHubActions\n function createPool(\n address token0,\n address token1,\n uint24 sqrtGamma,\n uint128 sqrtPrice,\n uint256 senderAccRefId\n ) external returns (bytes32 poolId) {\n if (token0 >= token1 || token0 == address(0)) revert InvalidTokenOrder();\n\n Pools.Pool storage pool;\n (pool, poolId) = pools.getPoolAndId(token0, token1);\n if (!isSqrtGammaAllowed(poolId, sqrtGamma)) revert NotAllowedSqrtGamma();\n\n uint8 tickSpacing = poolDefaultTickSpacing[poolId];\n if (tickSpacing == 0) tickSpacing = defaultTickSpacing;\n (uint256 amount0, uint256 amount1) = pool.initialize(sqrtGamma, sqrtPrice, tickSpacing, defaultProtocolFee);\n accounts[token0][getAccHash(msg.sender, senderAccRefId)] -= amount0;\n accounts[token1][getAccHash(msg.sender, senderAccRefId)] -= amount1;\n\n emit PoolCreated(token0, token1, poolId);\n emit UpdateTier(poolId, 0, sqrtGamma, sqrtPrice, 1);\n pool.unlock();\n underlyings[poolId] = Pair(token0, token1);\n }\n\n /// @inheritdoc IMuffinHubActions\n function addTier(\n address token0,\n address token1,\n uint24 sqrtGamma,\n uint256 senderAccRefId\n ) external returns (uint8 tierId) {\n (Pools.Pool storage pool, bytes32 poolId) = pools.getPoolAndId(token0, token1);\n if (!isSqrtGammaAllowed(poolId, sqrtGamma)) revert NotAllowedSqrtGamma();\n\n uint256 amount0;\n uint256 amount1;\n (amount0, amount1, tierId) = pool.addTier(sqrtGamma);\n accounts[token0][getAccHash(msg.sender, senderAccRefId)] -= amount0;\n accounts[token1][getAccHash(msg.sender, senderAccRefId)] -= amount1;\n\n emit UpdateTier(poolId, tierId, sqrtGamma, pool.tiers[tierId].sqrtPrice, 0);\n pool.unlock();\n }\n\n /*===============================================================\n * SWAP\n *==============================================================*/\n\n /// @inheritdoc IMuffinHubActions\n function swap(\n address tokenIn,\n address tokenOut,\n uint256 tierChoices,\n int256 amountDesired,\n address recipient,\n uint256 recipientAccRefId,\n uint256 senderAccRefId,\n bytes calldata data\n ) external returns (uint256 amountIn, uint256 amountOut) {\n Pools.Pool storage pool;\n (pool, , amountIn, amountOut) = _computeSwap(\n tokenIn,\n tokenOut,\n tierChoices,\n amountDesired,\n SwapEventVars(senderAccRefId, recipient, recipientAccRefId)\n );\n _transferSwap(tokenIn, tokenOut, amountIn, amountOut, recipient, recipientAccRefId, senderAccRefId, data);\n pool.unlock();\n }\n\n /// @inheritdoc IMuffinHubActions\n function swapMultiHop(SwapMultiHopParams calldata p) external returns (uint256 amountIn, uint256 amountOut) {\n bytes memory path = p.path;\n if (path.invalid()) revert InvalidSwapPath();\n\n bool exactIn = p.amountDesired > 0;\n bytes32[] memory poolIds = new bytes32[](path.hopCount());\n unchecked {\n int256 amtDesired = p.amountDesired;\n SwapEventVars memory evtData = exactIn\n ? SwapEventVars(p.senderAccRefId, msg.sender, p.senderAccRefId)\n : SwapEventVars(p.senderAccRefId, p.recipient, p.recipientAccRefId);\n\n for (uint256 i; i < poolIds.length; i++) {\n if (exactIn) {\n if (i == poolIds.length - 1) {\n evtData.recipient = p.recipient;\n evtData.recipientAccRefId = p.recipientAccRefId;\n }\n } else {\n if (i == 1) {\n evtData.recipient = msg.sender;\n evtData.recipientAccRefId = p.senderAccRefId;\n }\n }\n\n (address tokenIn, address tokenOut, uint256 tierChoices) = path.decodePool(i, exactIn);\n\n // For an \"exact output\" swap, it's possible to not receive the full desired output amount. therefore, in\n // the 2nd (and following) swaps, we request more token output so as to ensure we get enough tokens to pay\n // for the previous swap. The extra token is not refunded and thus results in an extra cost (small in common\n // token pairs).\n uint256 amtIn;\n uint256 amtOut;\n (, poolIds[i], amtIn, amtOut) = _computeSwap(\n tokenIn,\n tokenOut,\n tierChoices,\n (exactIn || i == 0) ? amtDesired : amtDesired - Pools.SWAP_AMOUNT_TOLERANCE,\n evtData\n );\n\n if (exactIn) {\n if (i == 0) amountIn = amtIn;\n amtDesired = int256(amtOut);\n } else {\n if (i == 0) amountOut = amtOut;\n else if (amtOut < uint256(-amtDesired)) revert NotEnoughIntermediateOutput();\n amtDesired = -int256(amtIn);\n }\n }\n if (exactIn) {\n amountOut = uint256(amtDesired);\n } else {\n amountIn = uint256(-amtDesired);\n }\n }\n (address _tokenIn, address _tokenOut) = path.tokensInOut(exactIn);\n _transferSwap(_tokenIn, _tokenOut, amountIn, amountOut, p.recipient, p.recipientAccRefId, p.senderAccRefId, p.data);\n unchecked {\n for (uint256 i; i < poolIds.length; i++) pools[poolIds[i]].unlock();\n }\n }\n\n /// @dev Data to emit in \"Swap\" event in \"_computeSwap\" function\n struct SwapEventVars {\n uint256 senderAccRefId;\n address recipient;\n uint256 recipientAccRefId;\n }\n\n function _computeSwap(\n address tokenIn,\n address tokenOut,\n uint256 tierChoices,\n int256 amountDesired, // Desired swap amount (positive: exact input, negative: exact output)\n SwapEventVars memory evtData\n )\n internal\n returns (\n Pools.Pool storage pool,\n bytes32 poolId,\n uint256 amountIn,\n uint256 amountOut\n )\n {\n bool isExactIn = tokenIn < tokenOut;\n bool isToken0 = (amountDesired > 0) == isExactIn; // i.e. isToken0In == isExactIn\n (pool, poolId) = isExactIn ? pools.getPoolAndId(tokenIn, tokenOut) : pools.getPoolAndId(tokenOut, tokenIn);\n Pools.SwapResult memory result = pool.swap(isToken0, amountDesired, tierChoices, poolId);\n\n emit Swap(\n poolId,\n msg.sender,\n evtData.recipient,\n evtData.senderAccRefId,\n evtData.recipientAccRefId,\n result.amount0,\n result.amount1,\n result.amountInDistribution,\n result.amountOutDistribution,\n result.tierData\n );\n\n unchecked {\n // overflow is acceptable and protocol is expected to collect protocol fee before overflow\n if (result.protocolFeeAmt != 0) tokens[tokenIn].protocolFeeAmt += uint248(result.protocolFeeAmt);\n (amountIn, amountOut) = isExactIn\n ? (uint256(result.amount0), uint256(-result.amount1))\n : (uint256(result.amount1), uint256(-result.amount0));\n }\n }\n\n function _transferSwap(\n address tokenIn,\n address tokenOut,\n uint256 amountIn,\n uint256 amountOut,\n address recipient,\n uint256 recipientAccRefId,\n uint256 senderAccRefId,\n bytes calldata data\n ) internal {\n if (tokenIn == tokenOut) {\n (amountIn, amountOut) = amountIn.subUntilZero(amountOut);\n }\n if (recipientAccRefId == 0) {\n SafeTransferLib.safeTransfer(tokenOut, recipient, amountOut);\n } else {\n accounts[tokenOut][getAccHash(recipient, recipientAccRefId)] += amountOut;\n }\n if (senderAccRefId != 0) {\n bytes32 accHash = getAccHash(msg.sender, senderAccRefId);\n (accounts[tokenIn][accHash], amountIn) = accounts[tokenIn][accHash].subUntilZero(amountIn);\n }\n if (amountIn > 0) {\n uint256 balanceBefore = getBalanceAndLock(tokenIn);\n IMuffinHubCallbacks(msg.sender).muffinSwapCallback(tokenIn, tokenOut, amountIn, amountOut, data);\n checkBalanceAndUnlock(tokenIn, balanceBefore + amountIn);\n }\n }\n\n /*===============================================================\n * VIEW FUNCTIONS\n *==============================================================*/\n\n /// @inheritdoc IMuffinHubView\n function getDefaultParameters() external view returns (uint8 tickSpacing, uint8 protocolFee) {\n return (defaultTickSpacing, defaultProtocolFee);\n }\n\n /// @inheritdoc IMuffinHubView\n function getPoolParameters(bytes32 poolId) external view returns (uint8 tickSpacing, uint8 protocolFee) {\n Pools.Pool storage pool = pools[poolId];\n return (pool.tickSpacing, pool.protocolFee);\n }\n\n /// @inheritdoc IMuffinHubView\n function getTier(bytes32 poolId, uint8 tierId) external view returns (Tiers.Tier memory) {\n return pools[poolId].tiers[tierId];\n }\n\n /// @inheritdoc IMuffinHubView\n function getTiersCount(bytes32 poolId) external view returns (uint256) {\n return pools[poolId].tiers.length;\n }\n\n /// @inheritdoc IMuffinHubView\n function getTick(\n bytes32 poolId,\n uint8 tierId,\n int24 tick\n ) external view returns (Ticks.Tick memory) {\n return pools[poolId].ticks[tierId][tick];\n }\n\n /// @inheritdoc IMuffinHubView\n function getPosition(\n bytes32 poolId,\n address owner,\n uint256 positionRefId,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper\n ) external view returns (Positions.Position memory) {\n return Positions.get(pools[poolId].positions, owner, positionRefId, tierId, tickLower, tickUpper);\n }\n\n /// @inheritdoc IMuffinHubView\n function getStorageAt(bytes32 slot) external view returns (bytes32 word) {\n assembly {\n word := sload(slot)\n }\n }\n\n /*===============================================================\n * FALLBACK TO POSITION CONTROLLER\n *==============================================================*/\n\n /// @dev Adapted from openzepplin v4.4.1 proxy implementation\n fallback() external {\n address _positionController = positionController;\n assembly {\n calldatacopy(0, 0, calldatasize())\n let result := delegatecall(gas(), _positionController, 0, calldatasize(), 0, 0)\n returndatacopy(0, 0, returndatasize())\n switch result\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n}\n"
},
"contracts/interfaces/hub/IMuffinHub.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.0;\n\nimport \"./IMuffinHubBase.sol\";\nimport \"./IMuffinHubEvents.sol\";\nimport \"./IMuffinHubActions.sol\";\nimport \"./IMuffinHubView.sol\";\n\ninterface IMuffinHub is IMuffinHubBase, IMuffinHubEvents, IMuffinHubActions, IMuffinHubView {}\n"
},
"contracts/interfaces/IMuffinHubCallbacks.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.0;\n\ninterface IMuffinHubCallbacks {\n /// @notice Called by Muffin hub to request for tokens to finish deposit\n /// @param token Token that you are depositing\n /// @param amount Amount that you are depositing\n /// @param data Arbitrary data initially passed by you\n function muffinDepositCallback(\n address token,\n uint256 amount,\n bytes calldata data\n ) external;\n\n /// @notice Called by Muffin hub to request for tokens to finish minting liquidity\n /// @param token0 Token0 of the pool\n /// @param token1 Token1 of the pool\n /// @param amount0 Token0 amount you are owing to Muffin\n /// @param amount1 Token1 amount you are owing to Muffin\n /// @param data Arbitrary data initially passed by you\n function muffinMintCallback(\n address token0,\n address token1,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external;\n\n /// @notice Called by Muffin hub to request for tokens to finish swapping\n /// @param tokenIn Input token\n /// @param tokenOut Output token\n /// @param amountIn Input token amount you are owing to Muffin\n /// @param amountOut Output token amount you have just received\n /// @param data Arbitrary data initially passed by you\n function muffinSwapCallback(\n address tokenIn,\n address tokenOut,\n uint256 amountIn,\n uint256 amountOut,\n bytes calldata data\n ) external;\n}\n"
},
"contracts/libraries/utils/SafeTransferLib.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @dev Adapted from Rari's Solmate https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol\n/// Edited from using error message to custom error for lower bytecode size.\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)\n/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.\nlibrary SafeTransferLib {\n error FailedTransferETH();\n error FailedTransfer();\n error FailedTransferFrom();\n error FailedApprove();\n\n /*///////////////////////////////////////////////////////////////\n ETH OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function safeTransferETH(address to, uint256 amount) internal {\n bool callStatus;\n\n assembly {\n // Transfer the ETH and store if it succeeded or not.\n callStatus := call(gas(), to, amount, 0, 0, 0, 0)\n }\n\n if (!callStatus) revert FailedTransferETH();\n }\n\n /*///////////////////////////////////////////////////////////////\n ERC20 OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function safeTransferFrom(\n address token,\n address from,\n address to,\n uint256 amount\n ) internal {\n bool callStatus;\n\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata to memory piece by piece:\n mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.\n mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"from\" argument.\n mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"to\" argument.\n mstore(add(freeMemoryPointer, 68), amount) // Finally append the \"amount\" argument. No mask as it's a full 32 byte value.\n\n // Call the token and store if it succeeded or not.\n // We use 100 because the calldata length is 4 + 32 * 3.\n callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)\n }\n\n if (!didLastOptionalReturnCallSucceed(callStatus)) revert FailedTransferFrom();\n }\n\n function safeTransfer(\n address token,\n address to,\n uint256 amount\n ) internal {\n bool callStatus;\n\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata to memory piece by piece:\n mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.\n mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"to\" argument.\n mstore(add(freeMemoryPointer, 36), amount) // Finally append the \"amount\" argument. No mask as it's a full 32 byte value.\n\n // Call the token and store if it succeeded or not.\n // We use 68 because the calldata length is 4 + 32 * 2.\n callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)\n }\n\n if (!didLastOptionalReturnCallSucceed(callStatus)) revert FailedTransfer();\n }\n\n function safeApprove(\n address token,\n address to,\n uint256 amount\n ) internal {\n bool callStatus;\n\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata to memory piece by piece:\n mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector.\n mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the \"to\" argument.\n mstore(add(freeMemoryPointer, 36), amount) // Finally append the \"amount\" argument. No mask as it's a full 32 byte value.\n\n // Call the token and store if it succeeded or not.\n // We use 68 because the calldata length is 4 + 32 * 2.\n callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)\n }\n\n if (!didLastOptionalReturnCallSucceed(callStatus)) revert FailedApprove();\n }\n\n /*///////////////////////////////////////////////////////////////\n INTERNAL HELPER LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) {\n assembly {\n // If the call reverted:\n if iszero(callStatus) {\n // Copy the revert message into memory.\n returndatacopy(0, 0, returndatasize())\n\n // Revert with the same message.\n revert(0, returndatasize())\n }\n\n switch returndatasize()\n case 32 {\n // Copy the return data into memory.\n returndatacopy(0, 0, returndatasize())\n\n // Set success to whether it returned true.\n success := iszero(iszero(mload(0)))\n }\n case 0 {\n // There was no return data.\n success := 1\n }\n default {\n // It returned some malformed input.\n success := 0\n }\n }\n }\n}\n"
},
"contracts/libraries/utils/PathLib.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.0;\n\nlibrary PathLib {\n uint256 internal constant ADDR_BYTES = 20;\n uint256 internal constant ADDR_UINT16_BYTES = ADDR_BYTES + 2;\n uint256 internal constant PATH_MAX_BYTES = ADDR_UINT16_BYTES * 256 + ADDR_BYTES; // 256 pools (i.e. 5652 bytes)\n\n function invalid(bytes memory path) internal pure returns (bool) {\n unchecked {\n return\n path.length > PATH_MAX_BYTES ||\n path.length <= ADDR_BYTES ||\n (path.length - ADDR_BYTES) % ADDR_UINT16_BYTES != 0;\n }\n }\n\n /// @dev Assume the path is valid\n function hopCount(bytes memory path) internal pure returns (uint256) {\n unchecked {\n return path.length / ADDR_UINT16_BYTES;\n }\n }\n\n /// @dev Assume the path is valid\n function decodePool(\n bytes memory path,\n uint256 poolIndex,\n bool exactIn\n )\n internal\n pure\n returns (\n address tokenIn,\n address tokenOut,\n uint256 tierChoices\n )\n {\n unchecked {\n uint256 offset = ADDR_UINT16_BYTES * poolIndex;\n tokenIn = _readAddressAt(path, offset);\n tokenOut = _readAddressAt(path, ADDR_UINT16_BYTES + offset);\n tierChoices = _readUint16At(path, ADDR_BYTES + offset);\n if (!exactIn) (tokenIn, tokenOut) = (tokenOut, tokenIn);\n }\n }\n\n /// @dev Assume the path is valid\n function tokensInOut(bytes memory path, bool exactIn) internal pure returns (address tokenIn, address tokenOut) {\n unchecked {\n tokenIn = _readAddressAt(path, 0);\n tokenOut = _readAddressAt(path, path.length - ADDR_BYTES);\n if (!exactIn) (tokenIn, tokenOut) = (tokenOut, tokenIn);\n }\n }\n\n function _readAddressAt(bytes memory data, uint256 offset) internal pure returns (address addr) {\n assembly {\n addr := mload(add(add(data, 20), offset))\n }\n }\n\n function _readUint16At(bytes memory data, uint256 offset) internal pure returns (uint16 value) {\n assembly {\n value := mload(add(add(data, 2), offset))\n }\n }\n}\n"
},
"contracts/libraries/math/Math.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.0;\n\nlibrary Math {\n /// @dev Compute z = x + y, where z must be non-negative and fit in a 96-bit unsigned integer\n function addInt96(uint96 x, int96 y) internal pure returns (uint96 z) {\n unchecked {\n uint256 s = x + uint256(int256(y)); // overflow is fine here\n assert(s <= type(uint96).max);\n z = uint96(s);\n }\n }\n\n /// @dev Compute z = x + y, where z must be non-negative and fit in a 128-bit unsigned integer\n function addInt128(uint128 x, int128 y) internal pure returns (uint128 z) {\n unchecked {\n uint256 s = x + uint256(int256(y)); // overflow is fine here\n assert(s <= type(uint128).max);\n z = uint128(s);\n }\n }\n\n function max(uint256 x, uint256 y) internal pure returns (uint256 z) {\n z = x > y ? x : y;\n }\n\n /// @dev Subtract an amount from x until the amount reaches y or all x is subtracted (i.e. the result reches zero).\n /// Return the subtraction result and the remaining amount to subtract (if there's any)\n function subUntilZero(uint256 x, uint256 y) internal pure returns (uint256 z, uint256 r) {\n unchecked {\n if (x >= y) z = x - y;\n else r = y - x;\n }\n }\n\n // ----- cast -----\n\n function toUint128(uint256 x) internal pure returns (uint128 z) {\n assert(x <= type(uint128).max);\n z = uint128(x);\n }\n\n function toUint96(uint256 x) internal pure returns (uint96 z) {\n assert(x <= type(uint96).max);\n z = uint96(x);\n }\n\n function toInt256(uint256 x) internal pure returns (int256 z) {\n assert(x <= uint256(type(int256).max));\n z = int256(x);\n }\n\n function toInt96(uint96 x) internal pure returns (int96 z) {\n assert(x <= uint96(type(int96).max));\n z = int96(x);\n }\n\n // ----- checked arithmetic -----\n // (these functions are for using checked arithmetic in an unchecked scope)\n\n function add(uint256 x, uint256 y) internal pure returns (uint256 z) {\n z = x + y;\n }\n\n function add(int256 x, int256 y) internal pure returns (int256 z) {\n z = x + y;\n }\n\n function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n z = x - y;\n }\n\n function sub(int256 x, int256 y) internal pure returns (int256 z) {\n z = x - y;\n }\n}\n"
},
"contracts/libraries/Pools.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport \"./math/TickMath.sol\";\nimport \"./math/SwapMath.sol\";\nimport \"./math/UnsafeMath.sol\";\nimport \"./math/Math.sol\";\nimport \"./Tiers.sol\";\nimport \"./Ticks.sol\";\nimport \"./TickMaps.sol\";\nimport \"./Positions.sol\";\nimport \"./Settlement.sol\";\n\nlibrary Pools {\n using Math for uint96;\n using Math for uint128;\n using Tiers for Tiers.Tier;\n using Ticks for Ticks.Tick;\n using TickMaps for TickMaps.TickMap;\n using Positions for Positions.Position;\n\n error InvalidAmount();\n error InvalidTierChoices();\n error InvalidTick();\n error InvalidTickRangeForLimitOrder();\n error NoLiquidityForLimitOrder();\n error PositionAlreadySettled();\n error PositionNotSettled();\n\n uint24 internal constant MAX_SQRT_GAMMA = 100_000;\n uint96 internal constant BASE_LIQUIDITY_D8 = 100; // tier's base liquidity, scaled down 2^8. User pays it when adding a tier\n int256 internal constant SWAP_AMOUNT_TOLERANCE = 100; // tolerance between desired and actual swap amounts\n\n uint256 internal constant AMOUNT_DISTRIBUTION_BITS = 256 / MAX_TIERS; // i.e. 42 if MAX_TIERS is 6\n uint256 internal constant AMOUNT_DISTRIBUTION_RESOLUTION = AMOUNT_DISTRIBUTION_BITS - 1;\n\n /// @param unlocked Reentrancy lock\n /// @param tickSpacing Tick spacing. Only ticks that are multiples of the tick spacing can be used\n /// @param protocolFee Protocol fee with base 255 (e.g. protocolFee = 51 for 20% protocol fee)\n /// @param tiers Array of tiers\n /// @param tickMaps Bitmap for each tier to store which ticks are initializated\n /// @param ticks Mapping of tick states of each tier\n /// @param settlements Mapping of settlements for token{0,1} singled-sided positions\n /// @param positions Mapping of position states\n /// @param limitOrderTickSpacingMultipliers Tick spacing of limit order for each tier, as multiples of the pool's tick spacing\n struct Pool {\n bool unlocked;\n uint8 tickSpacing;\n uint8 protocolFee;\n Tiers.Tier[] tiers;\n mapping(uint256 => TickMaps.TickMap) tickMaps;\n mapping(uint256 => mapping(int24 => Ticks.Tick)) ticks;\n mapping(uint256 => mapping(int24 => Settlement.Info[2])) settlements;\n mapping(bytes32 => Positions.Position) positions;\n uint8[MAX_TIERS] limitOrderTickSpacingMultipliers;\n }\n\n function lock(Pool storage pool) internal {\n require(pool.unlocked);\n pool.unlocked = false;\n }\n\n function unlock(Pool storage pool) internal {\n pool.unlocked = true;\n }\n\n function getPoolAndId(\n mapping(bytes32 => Pool) storage pools,\n address token0,\n address token1\n ) internal view returns (Pool storage pool, bytes32 poolId) {\n poolId = keccak256(abi.encode(token0, token1));\n pool = pools[poolId];\n }\n\n /*===============================================================\n * INITIALIZATION\n *==============================================================*/\n\n function initialize(\n Pool storage pool,\n uint24 sqrtGamma,\n uint128 sqrtPrice,\n uint8 tickSpacing,\n uint8 protocolFee\n ) internal returns (uint256 amount0, uint256 amount1) {\n require(pool.tickSpacing == 0); // ensure not initialized\n require(TickMath.MIN_SQRT_P <= sqrtPrice && sqrtPrice <= TickMath.MAX_SQRT_P);\n require(tickSpacing > 0);\n\n pool.tickSpacing = tickSpacing;\n pool.protocolFee = protocolFee;\n\n (amount0, amount1) = _addTier(pool, sqrtGamma, sqrtPrice);\n\n // default enable limit order on first tier\n pool.limitOrderTickSpacingMultipliers[0] = 1;\n\n // BE AWARE the pool is locked. Please unlock it after token transfer is done.\n }\n\n function addTier(Pool storage pool, uint24 sqrtGamma)\n internal\n returns (\n uint256 amount0,\n uint256 amount1,\n uint8 tierId\n )\n {\n lock(pool);\n require((tierId = uint8(pool.tiers.length)) > 0);\n (amount0, amount1) = _addTier(pool, sqrtGamma, pool.tiers[0].sqrtPrice); // use 1st tier sqrt price as reference\n\n // BE AWARE the pool is locked. Please unlock it after token transfer is done.\n }\n\n function _addTier(\n Pool storage pool,\n uint24 sqrtGamma,\n uint128 sqrtPrice\n ) internal returns (uint256 amount0, uint256 amount1) {\n uint256 tierId = pool.tiers.length;\n require(tierId < MAX_TIERS);\n require(sqrtGamma <= MAX_SQRT_GAMMA);\n\n // initialize tier\n Tiers.Tier memory tier = Tiers.Tier({\n liquidity: uint128(BASE_LIQUIDITY_D8) << 8,\n sqrtPrice: sqrtPrice,\n sqrtGamma: sqrtGamma,\n tick: TickMath.sqrtPriceToTick(sqrtPrice),\n nextTickBelow: TickMath.MIN_TICK,\n nextTickAbove: TickMath.MAX_TICK,\n feeGrowthGlobal0: 0,\n feeGrowthGlobal1: 0\n });\n if (sqrtPrice == TickMath.MAX_SQRT_P) tier.tick--; // max tick is never crossed\n pool.tiers.push(tier);\n\n // initialize min tick & max tick\n Ticks.Tick storage lower = pool.ticks[tierId][TickMath.MIN_TICK];\n Ticks.Tick storage upper = pool.ticks[tierId][TickMath.MAX_TICK];\n (lower.liquidityLowerD8, lower.nextBelow, lower.nextAbove) = (\n BASE_LIQUIDITY_D8,\n TickMath.MIN_TICK,\n TickMath.MAX_TICK\n );\n (upper.liquidityUpperD8, upper.nextBelow, upper.nextAbove) = (\n BASE_LIQUIDITY_D8,\n TickMath.MIN_TICK,\n TickMath.MAX_TICK\n );\n\n // initialize tick map\n pool.tickMaps[tierId].set(TickMath.MIN_TICK);\n pool.tickMaps[tierId].set(TickMath.MAX_TICK);\n\n // calculate tokens to take for full-range base liquidity\n amount0 = UnsafeMath.ceilDiv(uint256(BASE_LIQUIDITY_D8) << (72 + 8), sqrtPrice);\n amount1 = UnsafeMath.ceilDiv(uint256(BASE_LIQUIDITY_D8) * sqrtPrice, 1 << (72 - 8));\n }\n\n /*===============================================================\n * SETTINGS\n *==============================================================*/\n\n function setPoolParameters(\n Pool storage pool,\n uint8 tickSpacing,\n uint8 protocolFee\n ) internal {\n require(pool.unlocked);\n require(tickSpacing > 0);\n pool.tickSpacing = tickSpacing;\n pool.protocolFee = protocolFee;\n }\n\n function setTierParameters(\n Pool storage pool,\n uint8 tierId,\n uint24 sqrtGamma,\n uint8 limitOrderTickSpacingMultiplier\n ) internal {\n require(pool.unlocked);\n require(tierId < pool.tiers.length);\n require(sqrtGamma <= MAX_SQRT_GAMMA);\n pool.tiers[tierId].sqrtGamma = sqrtGamma;\n pool.limitOrderTickSpacingMultipliers[tierId] = limitOrderTickSpacingMultiplier;\n }\n\n /*===============================================================\n * SWAP\n *==============================================================*/\n\n uint256 private constant Q64 = 0x10000000000000000;\n uint256 private constant Q128 = 0x100000000000000000000000000000000;\n\n /// @notice Emitted when limit order settlement occurs during a swap\n /// @dev Normally, we emit events from hub contract instead of from this pool library, but bubbling up the event\n /// data back to hub contract comsumes gas significantly, therefore we simply emit the \"settle\" event here.\n event Settle(\n bytes32 indexed poolId,\n uint8 indexed tierId,\n int24 indexed tickEnd,\n int24 tickStart,\n uint96 liquidityD8\n );\n\n struct SwapCache {\n bool zeroForOne;\n bool exactIn;\n uint8 protocolFee;\n uint256 protocolFeeAmt;\n uint256 tierChoices;\n TickMath.Cache tmCache;\n int256[MAX_TIERS] amounts;\n bytes32 poolId;\n }\n\n struct TierState {\n uint128 sqrtPTick;\n uint256 amountIn;\n uint256 amountOut;\n bool crossed;\n }\n\n /// @dev Struct returned by the \"swap\" function\n /// @param amount0 Pool's token0 balance change\n /// @param amount1 Pool's token1 balance change\n /// @param amountInDistribution Percentages of input amount routed to each tier (for logging)\n /// @param tierData Array of tier's liquidity and sqrt price after the swap (for logging)\n /// @param protocolFeeAmt Amount of input token as protocol fee\n struct SwapResult {\n int256 amount0;\n int256 amount1;\n uint256 amountInDistribution;\n uint256 amountOutDistribution;\n uint256[] tierData;\n uint256 protocolFeeAmt;\n }\n\n /// @notice Perform a swap in the pool\n /// @param pool Pool storage pointer\n /// @param isToken0 True if amtDesired refers to token0\n /// @param amtDesired Desired swap amount (positive: exact input, negative: exact output)\n /// @param tierChoices Bitmap to allow which tiers to swap\n /// @param poolId Pool id, only used for emitting settle event. Can pass in zero to skip emitting event\n /// @return result Swap result\n function swap(\n Pool storage pool,\n bool isToken0,\n int256 amtDesired,\n uint256 tierChoices,\n bytes32 poolId // only used for `Settle` event\n ) internal returns (SwapResult memory result) {\n lock(pool);\n Tiers.Tier[] memory tiers;\n TierState[MAX_TIERS] memory states;\n unchecked {\n // truncate tierChoices\n uint256 tiersCount = pool.tiers.length;\n uint256 maxTierChoices = (1 << tiersCount) - 1;\n tierChoices &= maxTierChoices;\n\n if (amtDesired == 0 || amtDesired == SwapMath.REJECTED) revert InvalidAmount();\n if (tierChoices == 0) revert InvalidTierChoices();\n\n // only load tiers that are allowed by users\n if (tierChoices == maxTierChoices) {\n tiers = pool.tiers;\n } else {\n tiers = new Tiers.Tier[](tiersCount);\n for (uint256 i; i < tiers.length; i++) {\n if (tierChoices & (1 << i) != 0) tiers[i] = pool.tiers[i];\n }\n }\n }\n\n SwapCache memory cache = SwapCache({\n zeroForOne: isToken0 == (amtDesired > 0),\n exactIn: amtDesired > 0,\n protocolFee: pool.protocolFee,\n protocolFeeAmt: 0,\n tierChoices: tierChoices,\n tmCache: TickMath.Cache({tick: type(int24).max, sqrtP: 0}),\n amounts: _emptyInt256Array(),\n poolId: poolId\n });\n\n int256 initialAmtDesired = amtDesired;\n int256 amountA; // pool's balance change of the token which \"amtDesired\" refers to\n int256 amountB; // pool's balance change of the opposite token\n\n while (true) {\n // calculate the swap amount for each tier\n cache.amounts = cache.exactIn\n ? SwapMath.calcTierAmtsIn(tiers, isToken0, amtDesired, cache.tierChoices)\n : SwapMath.calcTierAmtsOut(tiers, isToken0, amtDesired, cache.tierChoices);\n\n // compute the swap for each tier\n for (uint256 i; i < tiers.length; ) {\n (int256 amtAStep, int256 amtBStep) = _swapStep(pool, isToken0, cache, states[i], tiers[i], i);\n amountA += amtAStep;\n amountB += amtBStep;\n unchecked {\n i++;\n }\n }\n\n // check if we meet the stopping criteria\n amtDesired = initialAmtDesired - amountA;\n unchecked {\n if (\n (cache.exactIn ? amtDesired <= SWAP_AMOUNT_TOLERANCE : amtDesired >= -SWAP_AMOUNT_TOLERANCE) ||\n cache.tierChoices == 0\n ) break;\n }\n }\n\n result.protocolFeeAmt = cache.protocolFeeAmt;\n unchecked {\n (result.amountInDistribution, result.amountOutDistribution, result.tierData) = _updateTiers(\n pool,\n states,\n tiers,\n uint256(cache.exactIn ? amountA : amountB),\n uint256(cache.exactIn ? -amountB : -amountA)\n );\n }\n (result.amount0, result.amount1) = isToken0 ? (amountA, amountB) : (amountB, amountA);\n\n // BE AWARE the pool is locked. Please unlock it after token transfer is done.\n }\n\n function _swapStep(\n Pool storage pool,\n bool isToken0,\n SwapCache memory cache,\n TierState memory state,\n Tiers.Tier memory tier,\n uint256 tierId\n ) internal returns (int256 amtAStep, int256 amtBStep) {\n if (cache.amounts[tierId] == SwapMath.REJECTED) return (0, 0);\n\n // calculate sqrt price of the next tick\n if (state.sqrtPTick == 0)\n state.sqrtPTick = TickMath.tickToSqrtPriceMemoized(\n cache.tmCache,\n cache.zeroForOne ? tier.nextTickBelow : tier.nextTickAbove\n );\n\n unchecked {\n // calculate input & output amts, new sqrt price, and fee amt for this swap step\n uint256 feeAmtStep;\n (amtAStep, amtBStep, tier.sqrtPrice, feeAmtStep) = SwapMath.computeStep(\n isToken0,\n cache.exactIn,\n cache.amounts[tierId],\n tier.sqrtPrice,\n state.sqrtPTick,\n tier.liquidity,\n tier.sqrtGamma\n );\n if (amtAStep == SwapMath.REJECTED) return (0, 0);\n\n // cache input & output amounts for later event logging (locally)\n if (cache.exactIn) {\n state.amountIn += uint256(amtAStep);\n state.amountOut += uint256(-amtBStep);\n } else {\n state.amountIn += uint256(amtBStep);\n state.amountOut += uint256(-amtAStep);\n }\n\n // update protocol fee amt (locally)\n uint256 protocolFeeAmt = (feeAmtStep * cache.protocolFee) / type(uint8).max;\n cache.protocolFeeAmt += protocolFeeAmt;\n feeAmtStep -= protocolFeeAmt;\n\n // update fee growth (locally) (realistically assume feeAmtStep < 2**192)\n uint80 feeGrowth = uint80((feeAmtStep << 64) / tier.liquidity);\n if (cache.zeroForOne) {\n tier.feeGrowthGlobal0 += feeGrowth;\n } else {\n tier.feeGrowthGlobal1 += feeGrowth;\n }\n }\n\n // handle cross tick, which updates a tick state\n if (tier.sqrtPrice == state.sqrtPTick) {\n int24 tickCross = cache.zeroForOne ? tier.nextTickBelow : tier.nextTickAbove;\n\n // skip crossing tick if reaches the end of the supported price range\n if (tickCross == TickMath.MIN_TICK || tickCross == TickMath.MAX_TICK) {\n cache.tierChoices &= ~(1 << tierId);\n return (amtAStep, amtBStep);\n }\n\n // clear cached tick price, so as to calculate a new one in next loop\n state.sqrtPTick = 0;\n state.crossed = true;\n\n // flip the direction of tick's data (effect)\n Ticks.Tick storage cross = pool.ticks[tierId][tickCross];\n cross.flip(tier.feeGrowthGlobal0, tier.feeGrowthGlobal1);\n unchecked {\n // update tier's liquidity and next ticks (locally)\n (uint128 liqLowerD8, uint128 liqUpperD8) = (cross.liquidityLowerD8, cross.liquidityUpperD8);\n if (cache.zeroForOne) {\n tier.liquidity = tier.liquidity + (liqUpperD8 << 8) - (liqLowerD8 << 8);\n tier.nextTickBelow = cross.nextBelow;\n tier.nextTickAbove = tickCross;\n } else {\n tier.liquidity = tier.liquidity + (liqLowerD8 << 8) - (liqUpperD8 << 8);\n tier.nextTickBelow = tickCross;\n tier.nextTickAbove = cross.nextAbove;\n }\n }\n\n // settle single-sided positions (i.e. filled limit orders) if neccessary\n if (cache.zeroForOne ? cross.needSettle0 : cross.needSettle1) {\n (int24 tickStart, uint96 liquidityD8Settled) = Settlement.settle(\n pool.settlements[tierId],\n pool.ticks[tierId],\n pool.tickMaps[tierId],\n tier,\n tickCross,\n cache.zeroForOne\n );\n if (cache.poolId != 0) {\n emit Settle(cache.poolId, uint8(tierId), tickCross, tickStart, liquidityD8Settled);\n }\n }\n }\n }\n\n /// @dev Apply the post-swap data changes from memory to storage, also prepare data for event logging\n function _updateTiers(\n Pool storage pool,\n TierState[MAX_TIERS] memory states,\n Tiers.Tier[] memory tiers,\n uint256 amtIn,\n uint256 amtOut\n )\n internal\n returns (\n uint256 amtInDistribution,\n uint256 amtOutDistribution,\n uint256[] memory tierData\n )\n {\n tierData = new uint256[](tiers.length);\n unchecked {\n bool amtInNoOverflow = amtIn < (1 << (256 - AMOUNT_DISTRIBUTION_RESOLUTION));\n bool amtOutNoOverflow = amtOut < (1 << (256 - AMOUNT_DISTRIBUTION_RESOLUTION));\n\n for (uint256 i; i < tiers.length; i++) {\n TierState memory state = states[i];\n // we can safely assume tier data is unchanged when there's zero input amount and no crossing tick,\n // since we would have rejected the tier if such case happened.\n if (state.amountIn > 0 || state.crossed) {\n Tiers.Tier memory tier = tiers[i];\n // calculate current tick:\n // if tier's price is equal to tick's price (let say the tick is T), the tier is expected to be in\n // the upper tick space [T, T+1]. Only if the tier's next upper crossing tick is T, the tier is in\n // the lower tick space [T-1, T].\n tier.tick = TickMath.sqrtPriceToTick(tier.sqrtPrice);\n if (tier.tick == tier.nextTickAbove) tier.tick--;\n\n pool.tiers[i] = tier;\n\n // prepare data for logging\n tierData[i] = (uint256(tier.sqrtPrice) << 128) | tier.liquidity;\n if (amtIn > 0) {\n amtInDistribution |= (\n amtInNoOverflow\n ? (state.amountIn << AMOUNT_DISTRIBUTION_RESOLUTION) / amtIn\n : state.amountIn / ((amtIn >> AMOUNT_DISTRIBUTION_RESOLUTION) + 1)\n ) << (i * AMOUNT_DISTRIBUTION_BITS); // prettier-ignore\n }\n if (amtOut > 0) {\n amtOutDistribution |= (\n amtOutNoOverflow\n ? (state.amountOut << AMOUNT_DISTRIBUTION_RESOLUTION) / amtOut\n : state.amountOut / ((amtOut >> AMOUNT_DISTRIBUTION_RESOLUTION) + 1)\n ) << (i * AMOUNT_DISTRIBUTION_BITS); // prettier-ignore\n }\n }\n }\n }\n }\n\n function _emptyInt256Array() internal pure returns (int256[MAX_TIERS] memory) {}\n\n /*===============================================================\n * UPDATE LIQUIDITY\n *==============================================================*/\n\n function _checkTickInputs(int24 tickLower, int24 tickUpper) internal pure {\n if (tickLower >= tickUpper || TickMath.MIN_TICK > tickLower || tickUpper > TickMath.MAX_TICK) {\n revert InvalidTick();\n }\n }\n\n /// @notice Update a position's liquidity\n /// @param owner Address of the position owner\n /// @param positionRefId Reference id of the position\n /// @param tierId Tier index of the position\n /// @param tickLower Lower tick boundary of the position\n /// @param tickUpper Upper tick boundary of the position\n /// @param liquidityDeltaD8 Amount of liquidity change, divided by 2^8\n /// @param collectAllFees True to collect all remaining accrued fees of the position\n function updateLiquidity(\n Pool storage pool,\n address owner,\n uint256 positionRefId,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper,\n int96 liquidityDeltaD8,\n bool collectAllFees\n )\n internal\n returns (\n uint256 amount0,\n uint256 amount1,\n uint256 feeAmtOut0,\n uint256 feeAmtOut1\n )\n {\n lock(pool);\n _checkTickInputs(tickLower, tickUpper);\n if (liquidityDeltaD8 > 0) {\n if (tickLower % int24(uint24(pool.tickSpacing)) != 0) revert InvalidTick();\n if (tickUpper % int24(uint24(pool.tickSpacing)) != 0) revert InvalidTick();\n }\n // -------------------- UPDATE LIQUIDITY --------------------\n {\n // update current liquidity if in-range\n Tiers.Tier storage tier = pool.tiers[tierId];\n if (tickLower <= tier.tick && tier.tick < tickUpper)\n tier.liquidity = tier.liquidity.addInt128(int128(liquidityDeltaD8) << 8);\n }\n // --------------------- UPDATE TICKS -----------------------\n {\n bool initialized;\n initialized = _updateTick(pool, tierId, tickLower, liquidityDeltaD8, true);\n initialized = _updateTick(pool, tierId, tickUpper, liquidityDeltaD8, false) || initialized;\n if (initialized) {\n Tiers.Tier storage tier = pool.tiers[tierId];\n tier.updateNextTick(tickLower);\n tier.updateNextTick(tickUpper);\n }\n }\n // -------------------- UPDATE POSITION ---------------------\n (feeAmtOut0, feeAmtOut1) = _updatePosition(\n pool,\n owner,\n positionRefId,\n tierId,\n tickLower,\n tickUpper,\n liquidityDeltaD8,\n collectAllFees\n );\n // -------------------- CLEAN UP TICKS ----------------------\n if (liquidityDeltaD8 < 0) {\n bool deleted;\n deleted = _deleteEmptyTick(pool, tierId, tickLower);\n deleted = _deleteEmptyTick(pool, tierId, tickUpper) || deleted;\n\n // reset tier's next ticks if any ticks deleted\n if (deleted) {\n Tiers.Tier storage tier = pool.tiers[tierId];\n int24 below = TickMaps.nextBelow(pool.tickMaps[tierId], tier.tick + 1);\n int24 above = pool.ticks[tierId][below].nextAbove;\n tier.nextTickBelow = below;\n tier.nextTickAbove = above;\n }\n }\n // -------------------- TOKEN AMOUNTS -----------------------\n // calculate input and output amount for the liquidity change\n if (liquidityDeltaD8 != 0)\n (amount0, amount1) = PoolMath.calcAmtsForLiquidity(\n pool.tiers[tierId].sqrtPrice,\n TickMath.tickToSqrtPrice(tickLower),\n TickMath.tickToSqrtPrice(tickUpper),\n liquidityDeltaD8\n );\n\n // BE AWARE the pool is locked. Please unlock it after token transfer is done.\n }\n\n /*===============================================================\n * TICKS (UPDATE LIQUIDITY)\n *==============================================================*/\n\n function _updateTick(\n Pool storage pool,\n uint8 tierId,\n int24 tick,\n int96 liquidityDeltaD8,\n bool isLower\n ) internal returns (bool initialized) {\n mapping(int24 => Ticks.Tick) storage ticks = pool.ticks[tierId];\n Ticks.Tick storage obj = ticks[tick];\n\n if (obj.liquidityLowerD8 == 0 && obj.liquidityUpperD8 == 0) {\n // initialize tick if adding liquidity to empty tick\n if (liquidityDeltaD8 > 0) {\n TickMaps.TickMap storage tickMap = pool.tickMaps[tierId];\n int24 below = tickMap.nextBelow(tick);\n int24 above = ticks[below].nextAbove;\n obj.nextBelow = below;\n obj.nextAbove = above;\n ticks[below].nextAbove = tick;\n ticks[above].nextBelow = tick;\n\n tickMap.set(tick);\n initialized = true;\n }\n\n // assume past fees and reward were generated _below_ the current tick\n Tiers.Tier storage tier = pool.tiers[tierId];\n if (tick <= tier.tick) {\n obj.feeGrowthOutside0 = tier.feeGrowthGlobal0;\n obj.feeGrowthOutside1 = tier.feeGrowthGlobal1;\n }\n }\n\n // update liquidity\n if (isLower) {\n obj.liquidityLowerD8 = obj.liquidityLowerD8.addInt96(liquidityDeltaD8);\n } else {\n obj.liquidityUpperD8 = obj.liquidityUpperD8.addInt96(liquidityDeltaD8);\n }\n }\n\n function _deleteEmptyTick(\n Pool storage pool,\n uint8 tierId,\n int24 tick\n ) internal returns (bool deleted) {\n mapping(int24 => Ticks.Tick) storage ticks = pool.ticks[tierId];\n Ticks.Tick storage obj = ticks[tick];\n\n if (obj.liquidityLowerD8 == 0 && obj.liquidityUpperD8 == 0) {\n assert(tick != TickMath.MIN_TICK && tick != TickMath.MAX_TICK);\n int24 below = obj.nextBelow;\n int24 above = obj.nextAbove;\n ticks[below].nextAbove = above;\n ticks[above].nextBelow = below;\n delete ticks[tick];\n pool.tickMaps[tierId].unset(tick);\n deleted = true;\n }\n }\n\n /*===============================================================\n * POSITION (UPDATE LIQUIDITY)\n *==============================================================*/\n\n function _getFeeGrowthInside(\n Pool storage pool,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper\n ) internal view returns (uint80 feeGrowthInside0, uint80 feeGrowthInside1) {\n Ticks.Tick storage upper = pool.ticks[tierId][tickUpper];\n Ticks.Tick storage lower = pool.ticks[tierId][tickLower];\n Tiers.Tier storage tier = pool.tiers[tierId];\n int24 tickCurrent = tier.tick;\n\n unchecked {\n if (tickCurrent < tickLower) {\n // current price below range\n feeGrowthInside0 = lower.feeGrowthOutside0 - upper.feeGrowthOutside0;\n feeGrowthInside1 = lower.feeGrowthOutside1 - upper.feeGrowthOutside1;\n } else if (tickCurrent >= tickUpper) {\n // current price above range\n feeGrowthInside0 = upper.feeGrowthOutside0 - lower.feeGrowthOutside0;\n feeGrowthInside1 = upper.feeGrowthOutside1 - lower.feeGrowthOutside1;\n } else {\n // current price in range\n feeGrowthInside0 = tier.feeGrowthGlobal0 - upper.feeGrowthOutside0 - lower.feeGrowthOutside0;\n feeGrowthInside1 = tier.feeGrowthGlobal1 - upper.feeGrowthOutside1 - lower.feeGrowthOutside1;\n }\n }\n }\n\n function _updatePosition(\n Pool storage pool,\n address owner,\n uint256 positionRefId,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper,\n int96 liquidityDeltaD8,\n bool collectAllFees\n ) internal returns (uint256 feeAmtOut0, uint256 feeAmtOut1) {\n Positions.Position storage position = Positions.get(\n pool.positions,\n owner,\n positionRefId,\n tierId,\n tickLower,\n tickUpper\n );\n {\n // update position liquidity and accrue fees\n (uint80 feeGrowth0, uint80 feeGrowth1) = _getFeeGrowthInside(pool, tierId, tickLower, tickUpper);\n (feeAmtOut0, feeAmtOut1) = position.update(liquidityDeltaD8, feeGrowth0, feeGrowth1, collectAllFees);\n }\n\n // update settlement if position is an unsettled limit order\n if (position.limitOrderType != Positions.NOT_LIMIT_ORDER) {\n // passing a zero default tick spacing to here since the settlement state must be already initialized as\n // this position has been a limit order\n uint32 nextSnapshotId = Settlement.update(\n pool.settlements[tierId],\n pool.ticks[tierId],\n tickLower,\n tickUpper,\n position.limitOrderType,\n liquidityDeltaD8,\n 0\n );\n\n // not allowed to update if already settled\n if (position.settlementSnapshotId != nextSnapshotId) revert PositionAlreadySettled();\n\n // reset position to normal if it is emptied\n if (position.liquidityD8 == 0) {\n position.limitOrderType = Positions.NOT_LIMIT_ORDER;\n position.settlementSnapshotId = 0;\n }\n }\n }\n\n /*===============================================================\n * LIMIT ORDER\n *==============================================================*/\n\n /// @notice Set (or unset) position to (or from) a limit order\n /// @dev It first unsets position from being a limit order (if it is), then set position to a new limit order type\n function setLimitOrderType(\n Pool storage pool,\n address owner,\n uint256 positionRefId,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper,\n uint8 limitOrderType\n ) internal {\n require(pool.unlocked);\n require(limitOrderType <= Positions.ONE_FOR_ZERO);\n _checkTickInputs(tickLower, tickUpper);\n\n Positions.Position storage position = Positions.get(\n pool.positions,\n owner,\n positionRefId,\n tierId,\n tickLower,\n tickUpper\n );\n uint16 defaultTickSpacing = uint16(pool.tickSpacing) * pool.limitOrderTickSpacingMultipliers[tierId];\n\n // unset position to normal type\n if (position.limitOrderType != Positions.NOT_LIMIT_ORDER) {\n (uint32 nextSnapshotId, ) = Settlement.update(\n pool.settlements[tierId],\n pool.ticks[tierId],\n tickLower,\n tickUpper,\n position.limitOrderType,\n position.liquidityD8,\n false,\n defaultTickSpacing\n );\n\n // not allowed to update if already settled\n if (position.settlementSnapshotId != nextSnapshotId) revert PositionAlreadySettled();\n\n // unset to normal\n position.limitOrderType = Positions.NOT_LIMIT_ORDER;\n position.settlementSnapshotId = 0;\n }\n\n // set position to limit order\n if (limitOrderType != Positions.NOT_LIMIT_ORDER) {\n if (position.liquidityD8 == 0) revert NoLiquidityForLimitOrder();\n (uint32 nextSnapshotId, uint16 tickSpacing) = Settlement.update(\n pool.settlements[tierId],\n pool.ticks[tierId],\n tickLower,\n tickUpper,\n limitOrderType,\n position.liquidityD8,\n true,\n defaultTickSpacing\n );\n\n // ensure position has a correct tick range for limit order\n if (uint24(tickUpper - tickLower) != tickSpacing) revert InvalidTickRangeForLimitOrder();\n\n // set to limit order\n position.limitOrderType = limitOrderType;\n position.settlementSnapshotId = nextSnapshotId;\n }\n }\n\n /// @notice Collect tokens from a settled position. Reset to normal position if all tokens are collected\n /// @dev We only need to update position state. No need to remove any active liquidity from tier or update upper or\n /// lower tick states as these have already been done when settling these positions during a swap\n function collectSettled(\n Pool storage pool,\n address owner,\n uint256 positionRefId,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper,\n uint96 liquidityD8,\n bool collectAllFees\n )\n internal\n returns (\n uint256 amount0,\n uint256 amount1,\n uint256 feeAmtOut0,\n uint256 feeAmtOut1\n )\n {\n lock(pool);\n _checkTickInputs(tickLower, tickUpper);\n\n Positions.Position storage position = Positions.get(\n pool.positions,\n owner,\n positionRefId,\n tierId,\n tickLower,\n tickUpper\n );\n\n {\n // ensure it's a settled limit order, and get data snapshot\n (bool settled, Settlement.Snapshot memory snapshot) = Settlement.getSnapshot(\n pool.settlements[tierId],\n position,\n tickLower,\n tickUpper\n );\n if (!settled) revert PositionNotSettled();\n\n // update position using snapshotted data\n (feeAmtOut0, feeAmtOut1) = position.update(\n -liquidityD8.toInt96(),\n snapshot.feeGrowthInside0,\n snapshot.feeGrowthInside1,\n collectAllFees\n );\n }\n\n // calculate output amounts using the price where settlement was done\n uint128 sqrtPriceLower = TickMath.tickToSqrtPrice(tickLower);\n uint128 sqrtPriceUpper = TickMath.tickToSqrtPrice(tickUpper);\n (amount0, amount1) = PoolMath.calcAmtsForLiquidity(\n position.limitOrderType == Positions.ZERO_FOR_ONE ? sqrtPriceUpper : sqrtPriceLower,\n sqrtPriceLower,\n sqrtPriceUpper,\n -liquidityD8.toInt96()\n );\n\n // reset position to normal if it is emptied\n if (position.liquidityD8 == 0) {\n position.limitOrderType = Positions.NOT_LIMIT_ORDER;\n position.settlementSnapshotId = 0;\n }\n\n // BE AWARE the pool is locked. Please unlock it after token transfer is done.\n }\n\n /*===============================================================\n * VIEW FUNCTIONS\n *==============================================================*/\n\n function getPositionFeeGrowthInside(\n Pool storage pool,\n address owner,\n uint256 positionRefId,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper\n ) internal view returns (uint80 feeGrowthInside0, uint80 feeGrowthInside1) {\n if (owner != address(0)) {\n (bool settled, Settlement.Snapshot memory snapshot) = Settlement.getSnapshot(\n pool.settlements[tierId],\n Positions.get(pool.positions, owner, positionRefId, tierId, tickLower, tickUpper),\n tickLower,\n tickUpper\n );\n if (settled) return (snapshot.feeGrowthInside0, snapshot.feeGrowthInside1);\n }\n return _getFeeGrowthInside(pool, tierId, tickLower, tickUpper);\n }\n\n /// @dev Convert fixed-sized array to dynamic-sized\n function getLimitOrderTickSpacingMultipliers(Pool storage pool) internal view returns (uint8[] memory multipliers) {\n uint8[MAX_TIERS] memory ms = pool.limitOrderTickSpacingMultipliers;\n multipliers = new uint8[](pool.tiers.length);\n unchecked {\n for (uint256 i; i < multipliers.length; i++) multipliers[i] = ms[i];\n }\n }\n}\n"
},
"contracts/MuffinHubBase.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport \"./interfaces/hub/IMuffinHubBase.sol\";\nimport \"./interfaces/common/IERC20Minimal.sol\";\nimport \"./libraries/Pools.sol\";\n\nabstract contract MuffinHubBase is IMuffinHubBase {\n error FailedBalanceOf();\n error NotEnoughTokenInput();\n\n /// @param locked 1 means locked. 0 or 2 means unlocked.\n /// @param protocolFeeAmt Amount of token accrued as the protocol fee\n struct TokenData {\n uint8 locked;\n uint248 protocolFeeAmt;\n }\n\n struct Pair {\n address token0;\n address token1;\n }\n\n /// @inheritdoc IMuffinHubBase\n address public governance;\n /// @dev Default tick spacing of new pool\n uint8 internal defaultTickSpacing = 100;\n /// @dev Default protocl fee of new pool (base 255)\n uint8 internal defaultProtocolFee = 0;\n /// @dev Whitelist of swap fees that LPs can choose to create a pool\n uint24[] internal defaultAllowedSqrtGammas = [99900, 99800, 99700, 99600, 99499]; // 20, 40, 60, 80, 100 bps\n\n /// @dev Pool-specific default tick spacing\n mapping(bytes32 => uint8) internal poolDefaultTickSpacing;\n /// @dev Pool-specific whitelist of swap fees\n mapping(bytes32 => uint24[]) internal poolAllowedSqrtGammas;\n\n /// @dev Mapping of poolId to pool state\n mapping(bytes32 => Pools.Pool) internal pools;\n /// @inheritdoc IMuffinHubBase\n mapping(address => mapping(bytes32 => uint256)) public accounts;\n /// @inheritdoc IMuffinHubBase\n mapping(address => TokenData) public tokens;\n /// @inheritdoc IMuffinHubBase\n mapping(bytes32 => Pair) public underlyings;\n\n /// @dev We blacklist TUSD legacy address on Ethereum to prevent TUSD from getting exploited here.\n /// In general, tokens with multiple addresses are not supported here and will cost losts of fund.\n address internal constant TUSD_LEGACY_ADDRESS = 0x8dd5fbCe2F6a956C3022bA3663759011Dd51e73E;\n\n /// @notice Maximum number of tiers each pool can technically have. This number might vary in different networks.\n function maxNumOfTiers() external pure returns (uint256) {\n return MAX_TIERS;\n }\n\n /// @dev Get token balance of this contract\n function getBalance(address token) private view returns (uint256) {\n (bool success, bytes memory data) = token.staticcall(\n abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this))\n );\n if (!success || data.length != 32) revert FailedBalanceOf();\n return abi.decode(data, (uint256));\n }\n\n /// @dev \"Lock\" the token so the token cannot be used as input token again until unlocked\n function getBalanceAndLock(address token) internal returns (uint256) {\n require(token != TUSD_LEGACY_ADDRESS);\n\n TokenData storage tokenData = tokens[token];\n require(tokenData.locked != 1); // 1 means locked\n tokenData.locked = 1;\n return getBalance(token);\n }\n\n /// @dev \"Unlock\" the token after ensuring the contract reaches an expected token balance\n function checkBalanceAndUnlock(address token, uint256 balanceMinimum) internal {\n if (getBalance(token) < balanceMinimum) revert NotEnoughTokenInput();\n tokens[token].locked = 2;\n }\n\n /// @dev Hash (owner, accRefId) as the key for the internal account\n function getAccHash(address owner, uint256 accRefId) internal pure returns (bytes32) {\n require(accRefId != 0);\n return keccak256(abi.encode(owner, accRefId));\n }\n\n modifier onlyGovernance() {\n require(msg.sender == governance);\n _;\n }\n}\n"
},
"contracts/interfaces/hub/IMuffinHubBase.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.0;\n\ninterface IMuffinHubBase {\n /// @notice Get the contract governance address\n function governance() external view returns (address);\n\n /// @notice Get token balance of a user's internal account\n /// @param token Token address\n /// @param accHash keccek256 hash of (owner, accRefId), where accRefId is an arbitrary reference id from account owner\n /// @return balance Token balance in the account\n function accounts(address token, bytes32 accHash) external view returns (uint256 balance);\n\n /// @notice Get token's reentrancy lock and accrued protocol fees\n /// @param token Token address\n /// @return locked 1 if token is locked, otherwise unlocked\n /// @return protocolFeeAmt Amount of token accrued as protocol fee\n function tokens(address token) external view returns (uint8 locked, uint248 protocolFeeAmt);\n\n /// @notice Get the addresses of the underlying tokens of a pool\n /// @param poolId Pool id, i.e. keccek256 hash of (token0, token1)\n /// @return token0 Address of the pool's token0\n /// @return token1 Address of the pool's token1\n function underlyings(bytes32 poolId) external view returns (address token0, address token1);\n\n /// @notice Maximum number of tiers each pool can technically have. This number might vary in different networks.\n function maxNumOfTiers() external pure returns (uint256);\n}\n"
},
"contracts/interfaces/hub/IMuffinHubEvents.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.0;\n\ninterface IMuffinHubEvents {\n /// @notice Emitted when user deposits tokens to an account\n event Deposit(\n address indexed recipient,\n uint256 indexed recipientAccRefId,\n address indexed token,\n uint256 amount,\n address sender\n );\n\n /// @notice Emitted when user withdraws tokens from an account\n event Withdraw(\n address indexed sender,\n uint256 indexed senderAccRefId,\n address indexed token,\n uint256 amount,\n address recipient\n );\n\n /// @notice Emitted when a pool is created\n event PoolCreated(address indexed token0, address indexed token1, bytes32 indexed poolId);\n\n /// @notice Emitted when a new tier is added, or when tier's parameters are updated\n event UpdateTier(\n bytes32 indexed poolId,\n uint8 indexed tierId,\n uint24 indexed sqrtGamma,\n uint128 sqrtPrice,\n uint8 limitOrderTickSpacingMultiplier\n );\n\n /// @notice Emitted when a pool's tick spacing or protocol fee is updated\n event UpdatePool(bytes32 indexed poolId, uint8 tickSpacing, uint8 protocolFee);\n\n /// @notice Emitted when protocol fee is collected\n event CollectProtocol(address indexed recipient, address indexed token, uint256 amount);\n\n /// @notice Emitted when governance address is updated\n event GovernanceUpdated(address indexed governance);\n\n /// @notice Emitted when default parameters are updated\n event UpdateDefaultParameters(uint8 tickSpacing, uint8 protocolFee);\n\n /// @notice Emitted when liquidity is minted for a given position\n event Mint(\n bytes32 indexed poolId,\n address indexed owner,\n uint256 indexed positionRefId,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper,\n address sender,\n uint256 senderAccRefId,\n uint96 liquidityD8,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted when a position's liquidity is removed and collected\n /// @param amount0 Token0 amount from the burned liquidity\n /// @param amount1 Token1 amount from the burned liquidity\n /// @param feeAmount0 Token0 fee collected from the position\n /// @param feeAmount0 Token1 fee collected from the position\n event Burn(\n bytes32 indexed poolId,\n address indexed owner,\n uint256 indexed positionRefId,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper,\n uint256 ownerAccRefId,\n uint96 liquidityD8,\n uint256 amount0,\n uint256 amount1,\n uint256 feeAmount0,\n uint256 feeAmount1\n );\n\n /// @notice Emitted when limit order settlement occurs during a swap\n /// @dev when tickEnd < tickStart, it means the tier crossed from a higher tick to a lower tick, and the settled\n /// limit orders were selling token1 for token0, vice versa.\n event Settle(\n bytes32 indexed poolId,\n uint8 indexed tierId,\n int24 indexed tickEnd,\n int24 tickStart,\n uint96 liquidityD8\n );\n\n /// @notice Emitted when a settled position's liquidity is collected\n event CollectSettled(\n bytes32 indexed poolId,\n address indexed owner,\n uint256 indexed positionRefId,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper,\n uint256 ownerAccRefId,\n uint96 liquidityD8,\n uint256 amount0,\n uint256 amount1,\n uint256 feeAmount0,\n uint256 feeAmount1\n );\n\n /// @notice Emitted when a position's limit order type is updated\n event SetLimitOrderType(\n bytes32 indexed poolId,\n address indexed owner,\n uint256 indexed positionRefId,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper,\n uint8 limitOrderType\n );\n\n /// @notice Emitted for any swap happened in any pool\n /// @param amountInDistribution Percentages of input token amount routed to each tier. Each value occupies FLOOR(256/MAX_TIERS)\n /// bits and is a binary fixed-point with 1 integer bit and FLOOR(256/MAX_TIERS)-1 fraction bits.\n /// @param amountOutDistribution Percentages of output token amount routed to each tier. Same format as \"amountInDistribution\".\n /// @param tierData Array of tier's liquidity (0-127th bits) and sqrt price (128-255th bits) after the swap\n event Swap(\n bytes32 indexed poolId,\n address indexed sender,\n address indexed recipient,\n uint256 senderAccRefId,\n uint256 recipientAccRefId,\n int256 amount0,\n int256 amount1,\n uint256 amountInDistribution,\n uint256 amountOutDistribution,\n uint256[] tierData\n );\n}\n"
},
"contracts/interfaces/hub/IMuffinHubActions.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.0;\n\ninterface IMuffinHubActions {\n /// @notice Deposit token into recipient's account\n /// @dev DO NOT deposit rebasing tokens or multiple-address tokens as it will cause loss of funds.\n /// DO NOT withdraw the token you deposit or swap the token out from the contract during the callback.\n /// @param recipient Recipient's address\n /// @param recipientAccRefId Recipient's account id\n /// @param token Address of the token to deposit\n /// @param amount Token amount to deposit\n /// @param data Arbitrary data that is passed to callback function\n function deposit(\n address recipient,\n uint256 recipientAccRefId,\n address token,\n uint256 amount,\n bytes calldata data\n ) external;\n\n /// @notice Withdraw token from sender's account and send to recipient's address\n /// @param recipient Recipient's address\n /// @param senderAccRefId Id of sender's account, i.e. the account to withdraw token from\n /// @param token Address of the token to withdraw\n /// @param amount Token amount to withdraw\n function withdraw(\n address recipient,\n uint256 senderAccRefId,\n address token,\n uint256 amount\n ) external;\n\n /// @notice Create pool\n /// @dev DO NOT create pool with rebasing tokens or multiple-address tokens as it will cause loss of funds\n /// @param token0 Address of token0 of the pool\n /// @param token1 Address of token1 of the pool\n /// @param sqrtGamma Sqrt (1 - percentage swap fee of the tier) (precision: 1e5)\n /// @param sqrtPrice Sqrt price of token0 denominated in token1 (UQ56.72)\n /// @param senderAccRefId Sender's account id, for paying the base liquidity\n /// @return poolId Pool id\n function createPool(\n address token0,\n address token1,\n uint24 sqrtGamma,\n uint128 sqrtPrice,\n uint256 senderAccRefId\n ) external returns (bytes32 poolId);\n\n /// @notice Add a new tier to a pool. Called by governanace only.\n /// @param token0 Address of token0 of the pool\n /// @param token1 Address of token1 of the pool\n /// @param sqrtGamma Sqrt (1 - percentage swap fee) (precision: 1e5)\n /// @param senderAccRefId Sender's account id, for paying the base liquidity\n /// @return tierId Id of the new tier\n function addTier(\n address token0,\n address token1,\n uint24 sqrtGamma,\n uint256 senderAccRefId\n ) external returns (uint8 tierId);\n\n /// @notice Swap one token for another\n /// @param tokenIn Input token address\n /// @param tokenOut Output token address\n /// @param tierChoices Bitmap to select which tiers are allowed to swap\n /// @param amountDesired Desired swap amount (positive: input, negative: output)\n /// @param recipient Recipient's address\n /// @param recipientAccRefId Recipient's account id\n /// @param senderAccRefId Sender's account id\n /// @param data Arbitrary data that is passed to callback function\n /// @return amountIn Input token amount\n /// @return amountOut Output token amount\n function swap(\n address tokenIn,\n address tokenOut,\n uint256 tierChoices,\n int256 amountDesired,\n address recipient,\n uint256 recipientAccRefId,\n uint256 senderAccRefId,\n bytes calldata data\n ) external returns (uint256 amountIn, uint256 amountOut);\n\n /// @notice Parameters for the multi-hop swap function\n /// @param path Multi-hop path. encodePacked(address tokenA, uint16 tierChoices, address tokenB, uint16 tierChoices ...)\n /// @param amountDesired Desired swap amount (positive: input, negative: output)\n /// @param recipient Recipient's address\n /// @param recipientAccRefId Recipient's account id\n /// @param senderAccRefId Sender's account id\n /// @param data Arbitrary data that is passed to callback function\n struct SwapMultiHopParams {\n bytes path;\n int256 amountDesired;\n address recipient;\n uint256 recipientAccRefId;\n uint256 senderAccRefId;\n bytes data;\n }\n\n /// @notice Swap one token for another along the specified path\n /// @param params SwapMultiHopParams struct\n /// @return amountIn Input token amount\n /// @return amountOut Output token amount\n function swapMultiHop(SwapMultiHopParams calldata params) external returns (uint256 amountIn, uint256 amountOut);\n}\n"
},
"contracts/interfaces/hub/IMuffinHubView.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.0;\n\nimport \"../../libraries/Tiers.sol\";\nimport \"../../libraries/Ticks.sol\";\nimport \"../../libraries/Positions.sol\";\n\ninterface IMuffinHubView {\n /// @notice Return whether the given fee rate is allowed in the given pool\n /// @param poolId Pool id\n /// @param sqrtGamma Fee rate, expressed in sqrt(1 - %fee) (precision: 1e5)\n /// @return allowed True if the % fee is allowed\n function isSqrtGammaAllowed(bytes32 poolId, uint24 sqrtGamma) external view returns (bool allowed);\n\n /// @notice Return pool's default tick spacing and protocol fee\n /// @return tickSpacing Default tick spacing applied to new pools. Note that there is also pool-specific default\n /// tick spacing which overrides the global default if set.\n /// @return protocolFee Default protocol fee applied to new pools\n function getDefaultParameters() external view returns (uint8 tickSpacing, uint8 protocolFee);\n\n /// @notice Return the pool's tick spacing and protocol fee\n /// @return tickSpacing Pool's tick spacing\n /// @return protocolFee Pool's protocol fee\n function getPoolParameters(bytes32 poolId) external view returns (uint8 tickSpacing, uint8 protocolFee);\n\n /// @notice Return a tier state\n function getTier(bytes32 poolId, uint8 tierId) external view returns (Tiers.Tier memory tier);\n\n /// @notice Return the number of existing tiers in the given pool\n function getTiersCount(bytes32 poolId) external view returns (uint256 count);\n\n /// @notice Return a tick state\n function getTick(\n bytes32 poolId,\n uint8 tierId,\n int24 tick\n ) external view returns (Ticks.Tick memory tickObj);\n\n /// @notice Return a position state.\n /// @param poolId Pool id\n /// @param owner Address of the position owner\n /// @param positionRefId Reference id for the position set by the owner\n /// @param tierId Tier index\n /// @param tickLower Lower tick boundary of the position\n /// @param tickUpper Upper tick boundary of the position\n /// @param position Position struct\n function getPosition(\n bytes32 poolId,\n address owner,\n uint256 positionRefId,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper\n ) external view returns (Positions.Position memory position);\n\n /// @notice Return the value of a slot in MuffinHub contract\n function getStorageAt(bytes32 slot) external view returns (bytes32 word);\n}\n"
},
"contracts/libraries/Tiers.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nlibrary Tiers {\n struct Tier {\n uint128 liquidity;\n uint128 sqrtPrice; // UQ56.72\n uint24 sqrtGamma; // 5 decimal places\n int24 tick;\n int24 nextTickBelow; // the next lower tick to cross (note that it can be equal to `tier.tick`)\n int24 nextTickAbove; // the next upper tick to cross\n uint80 feeGrowthGlobal0; // UQ16.64\n uint80 feeGrowthGlobal1; // UQ16.64\n }\n\n /// @dev Update tier's next tick if the given tick is more adjacent to the current tick\n function updateNextTick(Tier storage self, int24 tickNew) internal {\n if (tickNew <= self.tick) {\n if (tickNew > self.nextTickBelow) self.nextTickBelow = tickNew;\n } else {\n if (tickNew < self.nextTickAbove) self.nextTickAbove = tickNew;\n }\n }\n}\n"
},
"contracts/libraries/Ticks.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nlibrary Ticks {\n /**\n * @param liquidityLowerD8 Liquidity from positions with lower tick boundary at this tick\n * @param liquidityUpperD8 Liquidity from positions with upper tick boundary at this tick\n * @param nextBelow Next initialized tick below this tick\n * @param nextAbove Next initialized tick above this tick\n * @param needSettle0 True if needed to settle positions with lower tick boundary at this tick (i.e. 1 -> 0 limit orders)\n * @param needSettle1 True if needed to settle positions with upper tick boundary at this tick (i.e. 0 -> 1 limit orders)\n * @param feeGrowthOutside0 Fee0 growth per unit liquidity from this tick to the end in a direction away from the tier's current tick (UQ16.64)\n * @param feeGrowthOutside1 Fee1 growth per unit liquidity from this tick to the end in a direction away from the tier's current tick (UQ16.64)\n */\n struct Tick {\n uint96 liquidityLowerD8;\n uint96 liquidityUpperD8;\n int24 nextBelow;\n int24 nextAbove;\n bool needSettle0;\n bool needSettle1;\n uint80 feeGrowthOutside0;\n uint80 feeGrowthOutside1;\n }\n\n /// @dev Flip the direction of \"outside\". Called when the tick is being crossed.\n function flip(\n Tick storage self,\n uint80 feeGrowthGlobal0,\n uint80 feeGrowthGlobal1\n ) internal {\n unchecked {\n self.feeGrowthOutside0 = feeGrowthGlobal0 - self.feeGrowthOutside0;\n self.feeGrowthOutside1 = feeGrowthGlobal1 - self.feeGrowthOutside1;\n }\n }\n}\n"
},
"contracts/libraries/Positions.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport \"./math/Math.sol\";\n\nlibrary Positions {\n struct Position {\n uint96 liquidityD8;\n uint80 feeGrowthInside0Last; // UQ16.64\n uint80 feeGrowthInside1Last; // UQ16.64\n uint8 limitOrderType;\n uint32 settlementSnapshotId;\n }\n\n // Limit order types:\n uint8 internal constant NOT_LIMIT_ORDER = 0;\n uint8 internal constant ZERO_FOR_ONE = 1;\n uint8 internal constant ONE_FOR_ZERO = 2;\n\n /**\n * @param positions Mapping of positions\n * @param owner Position owner's address\n * @param refId Arbitrary identifier set by the position owner\n * @param tierId Index of the tier which the position is in\n * @param tickLower Lower tick boundary of the position\n * @param tickUpper Upper tick boundary of the position\n * @return position The position object\n */\n function get(\n mapping(bytes32 => Position) storage positions,\n address owner,\n uint256 refId,\n uint8 tierId,\n int24 tickLower,\n int24 tickUpper\n ) internal view returns (Position storage position) {\n position = positions[keccak256(abi.encodePacked(owner, tierId, tickLower, tickUpper, refId))];\n }\n\n /**\n * @notice Update position's liquidity and accrue fees\n * @dev When adding liquidity, feeGrowthInside{0,1} are updated so as to accrue fees without the need to transfer\n * them to owner's account. When removing partial liquidity, feeGrowthInside{0,1} are unchanged and partial fees are\n * transferred to owner's account proportionally to amount of liquidity removed.\n *\n * @param liquidityDeltaD8 Amount of liquidity change in the position, scaled down 2^8\n * @param feeGrowthInside0 Pool's current accumulated fee0 per unit of liquidity inside the position's price range\n * @param feeGrowthInside1 Pool's current accumulated fee1 per unit of liquidity inside the position's price range\n * @param collectAllFees True to collect the position's all accrued fees\n * @return feeAmtOut0 Amount of fee0 to transfer to owner account (≤ 2^(128+80))\n * @return feeAmtOut1 Amount of fee1 to transfer to owner account (≤ 2^(128+80))\n */\n function update(\n Position storage self,\n int96 liquidityDeltaD8,\n uint80 feeGrowthInside0,\n uint80 feeGrowthInside1,\n bool collectAllFees\n ) internal returns (uint256 feeAmtOut0, uint256 feeAmtOut1) {\n unchecked {\n uint96 liquidityD8 = self.liquidityD8;\n uint96 liquidityD8New = Math.addInt96(liquidityD8, liquidityDeltaD8);\n uint80 feeGrowthDelta0 = feeGrowthInside0 - self.feeGrowthInside0Last;\n uint80 feeGrowthDelta1 = feeGrowthInside1 - self.feeGrowthInside1Last;\n\n self.liquidityD8 = liquidityD8New;\n\n if (collectAllFees) {\n feeAmtOut0 = (uint256(liquidityD8) * feeGrowthDelta0) >> 56;\n feeAmtOut1 = (uint256(liquidityD8) * feeGrowthDelta1) >> 56;\n self.feeGrowthInside0Last = feeGrowthInside0;\n self.feeGrowthInside1Last = feeGrowthInside1;\n //\n } else if (liquidityDeltaD8 > 0) {\n self.feeGrowthInside0Last =\n feeGrowthInside0 -\n uint80((uint256(liquidityD8) * feeGrowthDelta0) / liquidityD8New);\n self.feeGrowthInside1Last =\n feeGrowthInside1 -\n uint80((uint256(liquidityD8) * feeGrowthDelta1) / liquidityD8New);\n //\n } else if (liquidityDeltaD8 < 0) {\n feeAmtOut0 = (uint256(uint96(-liquidityDeltaD8)) * feeGrowthDelta0) >> 56;\n feeAmtOut1 = (uint256(uint96(-liquidityDeltaD8)) * feeGrowthDelta1) >> 56;\n }\n }\n }\n}\n"
},
"contracts/libraries/math/TickMath.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.0;\n\nlibrary TickMath {\n uint256 private constant Q56 = 0x100000000000000;\n uint256 private constant Q128 = 0x100000000000000000000000000000000;\n\n /// @dev Minimum tick supported in this protocol\n int24 internal constant MIN_TICK = -776363;\n /// @dev Maximum tick supported in this protocol\n int24 internal constant MAX_TICK = 776363;\n /// @dev Minimum sqrt price, i.e. tickToSqrtPrice(MIN_TICK)\n uint128 internal constant MIN_SQRT_P = 65539;\n /// @dev Maximum sqrt price, i.e. tickToSqrtPrice(MAX_TICK)\n uint128 internal constant MAX_SQRT_P = 340271175397327323250730767849398346765;\n\n /**\n * @dev Find sqrtP = u^tick, where u = sqrt(1.0001)\n *\n * Let b_i = the i-th bit of x and b_i ∈ {0, 1}\n * Then x = (b0 * 2^0) + (b1 * 2^1) + (b2 * 2^2) + ...\n * Thus, r = u^x\n * = u^(b0 * 2^0) * u^(b1 * 2^1) * u^(b2 * 2^2) * ...\n * = k0^b0 * k1^b1 * k2^b2 * ... (where k_i = u^(2^i))\n * We pre-compute k_i since u is a known constant. In practice, we use u = 1/sqrt(1.0001) to\n * prevent overflow during the computation, then inverse the result at the end.\n */\n function tickToSqrtPrice(int24 tick) internal pure returns (uint128 sqrtP) {\n unchecked {\n require(MIN_TICK <= tick && tick <= MAX_TICK);\n uint256 x = uint256(uint24(tick < 0 ? -tick : tick)); // abs(tick)\n uint256 r = Q128; // UQ128.128\n\n if (x & 0x1 > 0) r = (r * 0xFFFCB933BD6FAD37AA2D162D1A594001) >> 128;\n if (x & 0x2 > 0) r = (r * 0xFFF97272373D413259A46990580E213A) >> 128;\n if (x & 0x4 > 0) r = (r * 0xFFF2E50F5F656932EF12357CF3C7FDCC) >> 128;\n if (x & 0x8 > 0) r = (r * 0xFFE5CACA7E10E4E61C3624EAA0941CD0) >> 128;\n if (x & 0x10 > 0) r = (r * 0xFFCB9843D60F6159C9DB58835C926644) >> 128;\n if (x & 0x20 > 0) r = (r * 0xFF973B41FA98C081472E6896DFB254C0) >> 128;\n if (x & 0x40 > 0) r = (r * 0xFF2EA16466C96A3843EC78B326B52861) >> 128;\n if (x & 0x80 > 0) r = (r * 0xFE5DEE046A99A2A811C461F1969C3053) >> 128;\n if (x & 0x100 > 0) r = (r * 0xFCBE86C7900A88AEDCFFC83B479AA3A4) >> 128;\n if (x & 0x200 > 0) r = (r * 0xF987A7253AC413176F2B074CF7815E54) >> 128;\n if (x & 0x400 > 0) r = (r * 0xF3392B0822B70005940C7A398E4B70F3) >> 128;\n if (x & 0x800 > 0) r = (r * 0xE7159475A2C29B7443B29C7FA6E889D9) >> 128;\n if (x & 0x1000 > 0) r = (r * 0xD097F3BDFD2022B8845AD8F792AA5825) >> 128;\n if (x & 0x2000 > 0) r = (r * 0xA9F746462D870FDF8A65DC1F90E061E5) >> 128;\n if (x & 0x4000 > 0) r = (r * 0x70D869A156D2A1B890BB3DF62BAF32F7) >> 128;\n if (x & 0x8000 > 0) r = (r * 0x31BE135F97D08FD981231505542FCFA6) >> 128;\n if (x & 0x10000 > 0) r = (r * 0x9AA508B5B7A84E1C677DE54F3E99BC9) >> 128;\n if (x & 0x20000 > 0) r = (r * 0x5D6AF8DEDB81196699C329225EE604) >> 128;\n if (x & 0x40000 > 0) r = (r * 0x2216E584F5FA1EA926041BEDFE98) >> 128;\n if (x & 0x80000 > 0) r = (r * 0x48A170391F7DC42444E8FA2) >> 128;\n // Stop computation here since abs(tick) < 2**20 (i.e. 776363 < 1048576)\n\n // Inverse r since base = 1/sqrt(1.0001)\n if (tick >= 0) r = type(uint256).max / r;\n\n // Downcast to UQ56.72 and round up\n sqrtP = uint128((r >> 56) + (r % Q56 > 0 ? 1 : 0));\n }\n }\n\n /// @dev Find tick = floor(log_u(sqrtP)), where u = sqrt(1.0001)\n function sqrtPriceToTick(uint128 sqrtP) internal pure returns (int24 tick) {\n unchecked {\n require(MIN_SQRT_P <= sqrtP && sqrtP <= MAX_SQRT_P);\n uint256 x = uint256(sqrtP);\n\n // Find msb of sqrtP (since sqrtP < 2^128, we start the check at 2**64)\n uint256 xc = x;\n uint256 msb;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) { xc >>= 1; msb += 1; }\n\n // Calculate integer part of log2(x), can be negative\n int256 r = (int256(msb) - 72) << 64; // Q64.64\n\n // Scale up x to make it 127-bit\n uint256 z = x << (127 - msb);\n\n // Do the following to find the decimal part of log2(x) (i.e. from 63th bit downwards):\n // 1. sqaure z\n // 2. if z becomes 128 bit:\n // 3. half z\n // 4. set this bit to 1\n // And stop at 46th bit since we have enough decimal places to continue to next steps\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x8000000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x4000000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x2000000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x1000000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x800000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x400000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x200000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x100000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x80000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x40000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x20000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x10000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x8000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x4000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x2000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x1000000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x800000000000; }\n z = (z * z) >> 127; if (z >= Q128) { z >>= 1; r |= 0x400000000000; }\n\n // Change the base of log2(x) to sqrt(1.0001). (i.e. log_u(x) = log2(u) * log_u(2))\n r *= 255738958999603826347141;\n\n // Add both the maximum positive and negative errors to r to see if it diverges into two different ticks.\n // If it does, calculate the upper tick's sqrtP and compare with the given sqrtP.\n int24 tickUpper = int24((r + 17996007701288367970265332090599899137) >> 128);\n int24 tickLower = int24(\n r < -230154402537746701963478439606373042805014528 ? (r - 98577143636729737466164032634120830977) >> 128 :\n r < -162097929153559009270803518120019400513814528 ? (r - 527810000259722480933883300202676225) >> 128 :\n r >> 128\n );\n tick = (tickUpper == tickLower || sqrtP >= tickToSqrtPrice(tickUpper)) ? tickUpper : tickLower;\n }\n }\n\n struct Cache {\n int24 tick;\n uint128 sqrtP;\n }\n\n /// @dev memoize last tick-to-sqrtP conversion\n function tickToSqrtPriceMemoized(Cache memory cache, int24 tick) internal pure returns (uint128 sqrtP) {\n if (tick == cache.tick) sqrtP = cache.sqrtP;\n else {\n sqrtP = tickToSqrtPrice(tick);\n cache.sqrtP = sqrtP;\n cache.tick = tick;\n }\n }\n}\n"
},
"contracts/libraries/math/SwapMath.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport \"./FullMath.sol\";\nimport \"./PoolMath.sol\";\nimport \"./UnsafeMath.sol\";\nimport \"./Math.sol\";\nimport \"../Tiers.sol\";\n\n/// @dev Technically maximum number of fee tiers per pool.\n/// @dev Declared at file level so other libraries/contracts can use it to define fixed-size array.\nuint256 constant MAX_TIERS = 6;\n\nlibrary SwapMath {\n using Math for uint256;\n using Math for int256;\n\n int256 internal constant REJECTED = type(int256).max; // represents the tier is rejected for the swap\n int256 private constant MAX_UINT_DIV_1E10 = 0x6DF37F675EF6EADF5AB9A2072D44268D97DF837E6748956E5C6C2117;\n uint256 private constant Q72 = 0x1000000000000000000;\n\n /// @notice Given a set of tiers and the desired input amount, calculate the optimized input amount for each tier\n /// @param tiers List of tiers\n /// @param isToken0 True if \"amount\" refers to token0\n /// @param amount Desired input amount of the swap (must be positive)\n /// @param tierChoices Bitmap to allow which tiers to swap\n /// @return amts Optimized input amounts for tiers\n function calcTierAmtsIn(\n Tiers.Tier[] memory tiers,\n bool isToken0,\n int256 amount,\n uint256 tierChoices\n ) internal pure returns (int256[MAX_TIERS] memory amts) {\n assert(amount > 0);\n uint256[MAX_TIERS] memory lsg; // array of liquidity divided by sqrt gamma (UQ128)\n uint256[MAX_TIERS] memory res; // array of token reserve divided by gamma (UQ200)\n uint256 num; // numerator of sqrt lambda (sum of UQ128)\n uint256 denom; // denominator of sqrt lambda (sum of UQ200 + amount)\n\n unchecked {\n for (uint256 i; i < tiers.length; i++) {\n // reject unselected tiers\n if (tierChoices & (1 << i) == 0) {\n amts[i] = REJECTED;\n continue;\n }\n // calculate numerator and denominator of sqrt lamdba (lagrange multiplier)\n Tiers.Tier memory t = tiers[i];\n uint256 liquidity = uint256(t.liquidity);\n uint24 sqrtGamma = t.sqrtGamma;\n num += (lsg[i] = UnsafeMath.ceilDiv(liquidity * 1e5, sqrtGamma));\n denom += (res[i] = isToken0\n ? UnsafeMath.ceilDiv(liquidity * Q72 * 1e10, uint256(t.sqrtPrice) * sqrtGamma * sqrtGamma)\n : UnsafeMath.ceilDiv(liquidity * t.sqrtPrice, (Q72 * sqrtGamma * sqrtGamma) / 1e10));\n }\n }\n denom += uint256(amount);\n\n unchecked {\n // calculate input amts, then reject the tiers with negative input amts.\n // repeat until all input amts are non-negative\n uint256 product = denom * num;\n bool wontOverflow = (product / denom == num) && (product <= uint256(type(int256).max));\n for (uint256 i; i < tiers.length; ) {\n if (amts[i] != REJECTED) {\n if (\n (amts[i] = (\n wontOverflow\n ? int256((denom * lsg[i]) / num)\n : FullMath.mulDiv(denom, lsg[i], num).toInt256()\n ).sub(int256(res[i]))) < 0\n ) {\n amts[i] = REJECTED;\n num -= lsg[i];\n denom -= res[i];\n i = 0;\n continue;\n }\n }\n i++;\n }\n }\n }\n\n /// @notice Given a set of tiers and the desired output amount, calculate the optimized output amount for each tier\n /// @param tiers List of tiers\n /// @param isToken0 True if \"amount\" refers to token0\n /// @param amount Desired output amount of the swap (must be negative)\n /// @param tierChoices Bitmap to allow which tiers to swap\n /// @return amts Optimized output amounts for tiers\n function calcTierAmtsOut(\n Tiers.Tier[] memory tiers,\n bool isToken0,\n int256 amount,\n uint256 tierChoices\n ) internal pure returns (int256[MAX_TIERS] memory amts) {\n assert(amount < 0);\n uint256[MAX_TIERS] memory lsg; // array of liquidity divided by sqrt fee (UQ128)\n uint256[MAX_TIERS] memory res; // array of token reserve (UQ200)\n uint256 num; // numerator of sqrt lambda (sum of UQ128)\n int256 denom; // denominator of sqrt lambda (sum of UQ200 - amount)\n\n unchecked {\n for (uint256 i; i < tiers.length; i++) {\n // reject unselected tiers\n if (tierChoices & (1 << i) == 0) {\n amts[i] = REJECTED;\n continue;\n }\n // calculate numerator and denominator of sqrt lamdba (lagrange multiplier)\n Tiers.Tier memory t = tiers[i];\n uint256 liquidity = uint256(t.liquidity);\n num += (lsg[i] = (liquidity * 1e5) / t.sqrtGamma);\n denom += int256(res[i] = isToken0 ? (liquidity << 72) / t.sqrtPrice : (liquidity * t.sqrtPrice) >> 72);\n }\n }\n denom += amount;\n\n unchecked {\n // calculate output amts, then reject the tiers with positive output amts.\n // repeat until all output amts are non-positive\n for (uint256 i; i < tiers.length; ) {\n if (amts[i] != REJECTED) {\n if ((amts[i] = _ceilMulDiv(denom, lsg[i], num).sub(int256(res[i]))) > 0) {\n amts[i] = REJECTED;\n num -= lsg[i];\n denom -= int256(res[i]);\n i = 0;\n continue;\n }\n }\n i++;\n }\n }\n }\n\n function _ceilMulDiv(\n int256 x,\n uint256 y,\n uint256 denom\n ) internal pure returns (int256 z) {\n unchecked {\n z = x < 0\n ? -FullMath.mulDiv(uint256(-x), y, denom).toInt256()\n : FullMath.mulDivRoundingUp(uint256(x), y, denom).toInt256();\n }\n }\n\n /// @dev Calculate a single swap step. We process the swap as much as possible until the tier's price hits the next tick.\n /// @param isToken0 True if \"amount\" refers to token0\n /// @param exactIn True if the swap is specified with an input token amount (instead of an output)\n /// @param amount The swap amount (positive: token in; negative token out)\n /// @param sqrtP The sqrt price currently\n /// @param sqrtPTick The sqrt price of the next crossing tick\n /// @param liquidity The current liqudity amount\n /// @param sqrtGamma The sqrt of (1 - percentage swap fee) (precision: 1e5)\n /// @return amtA The delta of the pool's tokenA balance (tokenA means token0 if `isToken0` is true, vice versa)\n /// @return amtB The delta of the pool's tokenB balance (tokenB means the opposite token of tokenA)\n /// @return sqrtPNew The new sqrt price after the swap\n /// @return feeAmt The fee amount charged for this swap\n function computeStep(\n bool isToken0,\n bool exactIn,\n int256 amount,\n uint128 sqrtP,\n uint128 sqrtPTick,\n uint128 liquidity,\n uint24 sqrtGamma\n )\n internal\n pure\n returns (\n int256 amtA,\n int256 amtB,\n uint128 sqrtPNew,\n uint256 feeAmt\n )\n {\n unchecked {\n amtA = amount;\n int256 amtInExclFee; // i.e. input amt excluding fee\n\n // calculate amt needed to reach to the tick\n int256 amtTick = isToken0\n ? PoolMath.calcAmt0FromSqrtP(sqrtP, sqrtPTick, liquidity)\n : PoolMath.calcAmt1FromSqrtP(sqrtP, sqrtPTick, liquidity);\n\n // calculate percentage fee (precision: 1e10)\n uint256 gamma = uint256(sqrtGamma) * sqrtGamma;\n\n if (exactIn) {\n // amtA: the input amt (positive)\n // amtB: the output amt (negative)\n\n // calculate input amt excluding fee\n amtInExclFee = amtA < MAX_UINT_DIV_1E10\n ? int256((uint256(amtA) * gamma) / 1e10)\n : int256((uint256(amtA) / 1e10) * gamma);\n\n // check if crossing tick\n if (amtInExclFee < amtTick) {\n // no cross tick: calculate new sqrt price after swap\n sqrtPNew = isToken0\n ? PoolMath.calcSqrtPFromAmt0(sqrtP, liquidity, amtInExclFee)\n : PoolMath.calcSqrtPFromAmt1(sqrtP, liquidity, amtInExclFee);\n } else {\n // cross tick: replace new sqrt price and input amt\n sqrtPNew = sqrtPTick;\n amtInExclFee = amtTick;\n\n // re-calculate input amt _including_ fee\n amtA = (\n amtInExclFee < MAX_UINT_DIV_1E10\n ? UnsafeMath.ceilDiv(uint256(amtInExclFee) * 1e10, gamma)\n : UnsafeMath.ceilDiv(uint256(amtInExclFee), gamma) * 1e10\n ).toInt256();\n }\n\n // calculate output amt\n amtB = isToken0\n ? PoolMath.calcAmt1FromSqrtP(sqrtP, sqrtPNew, liquidity)\n : PoolMath.calcAmt0FromSqrtP(sqrtP, sqrtPNew, liquidity);\n\n // calculate fee amt\n feeAmt = uint256(amtA - amtInExclFee);\n } else {\n // amtA: the output amt (negative)\n // amtB: the input amt (positive)\n\n // check if crossing tick\n if (amtA > amtTick) {\n // no cross tick: calculate new sqrt price after swap\n sqrtPNew = isToken0\n ? PoolMath.calcSqrtPFromAmt0(sqrtP, liquidity, amtA)\n : PoolMath.calcSqrtPFromAmt1(sqrtP, liquidity, amtA);\n } else {\n // cross tick: replace new sqrt price and output amt\n sqrtPNew = sqrtPTick;\n amtA = amtTick;\n }\n\n // calculate input amt excluding fee\n amtInExclFee = isToken0\n ? PoolMath.calcAmt1FromSqrtP(sqrtP, sqrtPNew, liquidity)\n : PoolMath.calcAmt0FromSqrtP(sqrtP, sqrtPNew, liquidity);\n\n // calculate input amt\n amtB = (\n amtInExclFee < MAX_UINT_DIV_1E10\n ? UnsafeMath.ceilDiv(uint256(amtInExclFee) * 1e10, gamma)\n : UnsafeMath.ceilDiv(uint256(amtInExclFee), gamma) * 1e10\n ).toInt256();\n\n // calculate fee amt\n feeAmt = uint256(amtB - amtInExclFee);\n }\n\n // reject tier if zero input amt and not crossing tick\n if (amtInExclFee == 0 && sqrtPNew != sqrtPTick) {\n amtA = REJECTED;\n amtB = 0;\n sqrtPNew = sqrtP;\n feeAmt = 0;\n }\n }\n }\n}\n"
},
"contracts/libraries/math/UnsafeMath.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.0;\n\nlibrary UnsafeMath {\n /// @dev Division by 0 has unspecified behavior, and must be checked externally.\n function ceilDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n z := add(div(x, y), gt(mod(x, y), 0))\n }\n }\n}\n"
},
"contracts/libraries/TickMaps.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport \"./math/TickMath.sol\";\n\nlibrary TickMaps {\n struct TickMap {\n uint256 blockMap; // stores which blocks are initialized\n mapping(uint256 => uint256) blocks; // stores which words are initialized\n mapping(uint256 => uint256) words; // stores which ticks are initialized\n }\n\n /// @dev Compress and convert tick into an unsigned integer, then compute the indices of the block and word that the\n /// compressed tick uses. Assume tick >= TickMath.MIN_TICK\n function _indices(int24 tick)\n internal\n pure\n returns (\n uint256 blockIdx,\n uint256 wordIdx,\n uint256 compressed\n )\n {\n unchecked {\n compressed = uint256(int256((tick - TickMath.MIN_TICK)));\n blockIdx = compressed >> 16;\n wordIdx = compressed >> 8;\n assert(blockIdx < 256);\n }\n }\n\n /// @dev Convert the unsigned integer back to a tick. Assume \"compressed\" is a valid value, computed by _indices function.\n function _decompress(uint256 compressed) internal pure returns (int24 tick) {\n unchecked {\n tick = int24(int256(compressed) + TickMath.MIN_TICK);\n }\n }\n\n function set(TickMap storage self, int24 tick) internal {\n (uint256 blockIdx, uint256 wordIdx, uint256 compressed) = _indices(tick);\n\n self.words[wordIdx] |= 1 << (compressed & 0xFF);\n self.blocks[blockIdx] |= 1 << (wordIdx & 0xFF);\n self.blockMap |= 1 << blockIdx;\n }\n\n function unset(TickMap storage self, int24 tick) internal {\n (uint256 blockIdx, uint256 wordIdx, uint256 compressed) = _indices(tick);\n\n self.words[wordIdx] &= ~(1 << (compressed & 0xFF));\n if (self.words[wordIdx] == 0) {\n self.blocks[blockIdx] &= ~(1 << (wordIdx & 0xFF));\n if (self.blocks[blockIdx] == 0) {\n self.blockMap &= ~(1 << blockIdx);\n }\n }\n }\n\n /// @dev Find the next initialized tick below the given tick. Assume tick >= TickMath.MIN_TICK\n // How to find the next initialized bit below the i-th bit inside a word (e.g. i = 8)?\n // 1) Mask _off_ the word from the 8th bit to the 255th bit (zero-indexed)\n // 2) Find the most significant bit of the masked word\n // 8th bit\n // ↓\n // word: 0001 1101 0010 1100\n // mask: 0000 0000 1111 1111 i.e. (1 << i) - 1\n // masked: 0000 0000 0010 1100\n // ↑\n // msb(masked) = 5\n function nextBelow(TickMap storage self, int24 tick) internal view returns (int24 tickBelow) {\n unchecked {\n (uint256 blockIdx, uint256 wordIdx, uint256 compressed) = _indices(tick);\n\n uint256 word = self.words[wordIdx] & ((1 << (compressed & 0xFF)) - 1);\n if (word == 0) {\n uint256 block_ = self.blocks[blockIdx] & ((1 << (wordIdx & 0xFF)) - 1);\n if (block_ == 0) {\n uint256 blockMap = self.blockMap & ((1 << blockIdx) - 1);\n assert(blockMap != 0);\n\n blockIdx = _msb(blockMap);\n block_ = self.blocks[blockIdx];\n }\n wordIdx = (blockIdx << 8) | _msb(block_);\n word = self.words[wordIdx];\n }\n\n tickBelow = _decompress((wordIdx << 8) | _msb(word));\n }\n }\n\n /// @notice Returns the index of the most significant bit of the number, where the least significant bit is at index 0\n /// and the most significant bit is at index 255\n /// @dev The function satisfies the property: x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n /// @param x the value for which to compute the most significant bit, must be greater than 0\n /// @return r the index of the most significant bit\n function _msb(uint256 x) internal pure returns (uint8 r) {\n unchecked {\n assert(x > 0);\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n r += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n r += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n r += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n r += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n r += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n r += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n r += 2;\n }\n if (x >= 0x2) r += 1;\n }\n }\n}\n"
},
"contracts/libraries/Settlement.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport \"./math/TickMath.sol\";\nimport \"./Tiers.sol\";\nimport \"./Ticks.sol\";\nimport \"./TickMaps.sol\";\nimport \"./Positions.sol\";\n\nlibrary Settlement {\n using TickMaps for TickMaps.TickMap;\n\n /**\n * @notice Data for settling single-sided positions (i.e. filled limit orders)\n * @param liquidityD8 Amount of liquidity to remove\n * @param tickSpacing Tick spacing of the limit orders\n * @param nextSnapshotId Next data snapshot id\n * @param snapshots Array of data snapshots\n */\n struct Info {\n uint96 liquidityD8;\n uint16 tickSpacing;\n uint32 nextSnapshotId;\n mapping(uint32 => Snapshot) snapshots;\n }\n\n /// @notice Data snapshot when settling the positions\n struct Snapshot {\n uint80 feeGrowthInside0;\n uint80 feeGrowthInside1;\n }\n\n /**\n * @notice Update the amount of liquidity pending to be settled on a tick, given the lower and upper tick\n * boundaries of a limit-order position.\n * @param settlements Mapping of settlements of each tick\n * @param ticks Mapping of ticks of the tier which the position is in\n * @param tickLower Lower tick boundary of the position\n * @param tickUpper Upper tick boundary of the position\n * @param limitOrderType Direction of the limit order (i.e. token0 or token1)\n * @param liquidityDeltaD8 Change of the amount of liquidity to be settled\n * @param isAdd True if the liquidity change is additive. False otherwise.\n * @param defaultTickSpacing Default tick spacing of limit orders. Only needed when initializing\n * @return nextSnapshotId Settlement's next snapshot id\n * @return tickSpacing Tick spacing of the limit orders pending to be settled\n */\n function update(\n mapping(int24 => Info[2]) storage settlements,\n mapping(int24 => Ticks.Tick) storage ticks,\n int24 tickLower,\n int24 tickUpper,\n uint8 limitOrderType,\n uint96 liquidityDeltaD8,\n bool isAdd,\n uint16 defaultTickSpacing\n ) internal returns (uint32 nextSnapshotId, uint16 tickSpacing) {\n assert(limitOrderType == Positions.ZERO_FOR_ONE || limitOrderType == Positions.ONE_FOR_ZERO);\n\n Info storage settlement = limitOrderType == Positions.ZERO_FOR_ONE\n ? settlements[tickUpper][1]\n : settlements[tickLower][0];\n\n // update the amount of liquidity to settle\n settlement.liquidityD8 = isAdd\n ? settlement.liquidityD8 + liquidityDeltaD8\n : settlement.liquidityD8 - liquidityDeltaD8;\n\n // initialize settlement if it's the first limit order at this tick\n nextSnapshotId = settlement.nextSnapshotId;\n if (settlement.tickSpacing == 0) {\n settlement.tickSpacing = defaultTickSpacing;\n settlement.snapshots[nextSnapshotId] = Snapshot(0, 1); // pre-fill to reduce SSTORE gas during swap\n }\n\n // if no liqudity to settle, clear tick spacing so as to set a latest one next time\n bool isEmpty = settlement.liquidityD8 == 0;\n if (isEmpty) settlement.tickSpacing = 0;\n\n // update \"needSettle\" flag in tick state\n if (limitOrderType == Positions.ZERO_FOR_ONE) {\n ticks[tickUpper].needSettle1 = !isEmpty;\n } else {\n ticks[tickLower].needSettle0 = !isEmpty;\n }\n\n // return data for validating position's settling status\n tickSpacing = settlement.tickSpacing;\n }\n\n /// @dev Bridging function to sidestep \"stack too deep\" problem\n function update(\n mapping(int24 => Info[2]) storage settlements,\n mapping(int24 => Ticks.Tick) storage ticks,\n int24 tickLower,\n int24 tickUpper,\n uint8 limitOrderType,\n int96 liquidityDeltaD8,\n uint16 defaultTickSpacing\n ) internal returns (uint32 nextSnapshotId) {\n bool isAdd = liquidityDeltaD8 > 0;\n unchecked {\n (nextSnapshotId, ) = update(\n settlements,\n ticks,\n tickLower,\n tickUpper,\n limitOrderType,\n uint96(isAdd ? liquidityDeltaD8 : -liquidityDeltaD8),\n isAdd,\n defaultTickSpacing\n );\n }\n }\n\n /**\n * @notice Settle single-sided positions, i.e. filled limit orders, that ends at the tick `tickEnd`.\n * @dev Called during a swap right after tickEnd is crossed. It updates settlement and tick, and possibly tickmap.\n * @param settlements Mapping of settlements of each tick\n * @param ticks Mapping of ticks of a tier\n * @param tickMap Tick bitmap of a tier\n * @param tier Latest tier data (in memory) currently used in the swap\n * @param tickEnd Ending tick of the limit orders, i.e. the tick just being crossed in the swap\n * @param token0In The direction of the ongoing swap\n * @return tickStart Starting tick of the limit orders, i.e. the other tick besides \"tickEnd\" that forms the positions\n * @return liquidityD8 Amount of liquidity settled\n */\n function settle(\n mapping(int24 => Info[2]) storage settlements,\n mapping(int24 => Ticks.Tick) storage ticks,\n TickMaps.TickMap storage tickMap,\n Tiers.Tier memory tier,\n int24 tickEnd,\n bool token0In\n ) internal returns (int24 tickStart, uint96 liquidityD8) {\n Info storage settlement; // we assume settlement is intialized\n Ticks.Tick storage start;\n Ticks.Tick storage end = ticks[tickEnd];\n\n unchecked {\n if (token0In) {\n settlement = settlements[tickEnd][0];\n tickStart = tickEnd + int16(settlement.tickSpacing);\n start = ticks[tickStart];\n\n // remove liquidity changes on ticks (effect)\n liquidityD8 = settlement.liquidityD8;\n start.liquidityUpperD8 -= liquidityD8;\n end.liquidityLowerD8 -= liquidityD8;\n end.needSettle0 = false;\n } else {\n settlement = settlements[tickEnd][1];\n tickStart = tickEnd - int16(settlement.tickSpacing);\n start = ticks[tickStart];\n\n // remove liquidity changes on ticks (effect)\n liquidityD8 = settlement.liquidityD8;\n start.liquidityLowerD8 -= liquidityD8;\n end.liquidityUpperD8 -= liquidityD8;\n end.needSettle1 = false;\n }\n\n // play extra safe to ensure settlement is initialized\n assert(tickStart != tickEnd);\n\n // snapshot data inside the tick range (effect)\n settlement.snapshots[settlement.nextSnapshotId] = Snapshot(\n end.feeGrowthOutside0 - start.feeGrowthOutside0,\n end.feeGrowthOutside1 - start.feeGrowthOutside1\n );\n }\n\n // reset settlement state since it's finished (effect)\n settlement.nextSnapshotId++;\n settlement.tickSpacing = 0;\n settlement.liquidityD8 = 0;\n\n // delete the starting tick if empty (effect)\n if (start.liquidityLowerD8 == 0 && start.liquidityUpperD8 == 0) {\n assert(tickStart != TickMath.MIN_TICK && tickStart != TickMath.MAX_TICK);\n int24 below = start.nextBelow;\n int24 above = start.nextAbove;\n ticks[below].nextAbove = above;\n ticks[above].nextBelow = below;\n delete ticks[tickStart];\n tickMap.unset(tickStart);\n }\n\n // delete the ending tick if empty (effect), and update tier's next ticks (locally)\n if (end.liquidityLowerD8 == 0 && end.liquidityUpperD8 == 0) {\n assert(tickEnd != TickMath.MIN_TICK && tickEnd != TickMath.MAX_TICK);\n int24 below = end.nextBelow;\n int24 above = end.nextAbove;\n ticks[below].nextAbove = above;\n ticks[above].nextBelow = below;\n delete ticks[tickEnd];\n tickMap.unset(tickEnd);\n\n // since the tier just crossed tickEnd, we can safely set tier's next ticks in this way\n tier.nextTickBelow = below;\n tier.nextTickAbove = above;\n }\n }\n\n /**\n * @notice Get data snapshot if the position is a settled limit order\n * @param settlements Mapping of settlements of each tick\n * @param position Position state\n * @param tickLower Position's lower tick boundary\n * @param tickUpper Position's upper tick boundary\n * @return settled True if position is settled\n * @return snapshot Data snapshot if position is settled\n */\n function getSnapshot(\n mapping(int24 => Info[2]) storage settlements,\n Positions.Position storage position,\n int24 tickLower,\n int24 tickUpper\n ) internal view returns (bool settled, Snapshot memory snapshot) {\n if (position.limitOrderType == Positions.ZERO_FOR_ONE || position.limitOrderType == Positions.ONE_FOR_ZERO) {\n Info storage settlement = position.limitOrderType == Positions.ZERO_FOR_ONE\n ? settlements[tickUpper][1]\n : settlements[tickLower][0];\n\n if (position.settlementSnapshotId < settlement.nextSnapshotId) {\n settled = true;\n snapshot = settlement.snapshots[position.settlementSnapshotId];\n }\n }\n }\n}\n"
},
"contracts/libraries/math/FullMath.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @dev https://github.com/Uniswap/uniswap-v3-core/blob/v1.0.0/contracts/libraries/FullMath.sol\n * Added `unchecked` and changed line 76 for being compatible in solidity 0.8\n */\n\n// solhint-disable max-line-length\n\n/// @title Contains 512-bit math functions\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\nlibrary FullMath {\n /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n /// @param a The multiplicand\n /// @param b The multiplier\n /// @param denominator The divisor\n /// @return result The 256-bit result\n /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\n function mulDiv(\n uint256 a,\n uint256 b,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = a * b\n // Compute the product mod 2**256 and mod 2**256 - 1\n // then use the Chinese Remainder Theorem to reconstruct\n // the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2**256 + prod0\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(a, b, not(0))\n prod0 := mul(a, b)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division\n if (prod1 == 0) {\n require(denominator > 0);\n assembly {\n result := div(prod0, denominator)\n }\n return result;\n }\n\n // Make sure the result is less than 2**256.\n // Also prevents denominator == 0\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0]\n // Compute remainder using mulmod\n uint256 remainder;\n assembly {\n remainder := mulmod(a, b, denominator)\n }\n // Subtract 256 bit number from 512 bit number\n assembly {\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator\n // Compute largest power of two divisor of denominator.\n // Always >= 1.\n\n // [*] The next line is edited to be compatible with solidity 0.8\n // ref: https://ethereum.stackexchange.com/a/96646\n // original: uint256 twos = -denominator & denominator;\n uint256 twos = denominator & (~denominator + 1);\n\n // Divide denominator by power of two\n assembly {\n denominator := div(denominator, twos)\n }\n\n // Divide [prod1 prod0] by the factors of two\n assembly {\n prod0 := div(prod0, twos)\n }\n // Shift in bits from prod1 into prod0. For this we need\n // to flip `twos` such that it is 2**256 / twos.\n // If twos is zero, then it becomes one\n assembly {\n twos := add(div(sub(0, twos), twos), 1)\n }\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2**256\n // Now that denominator is an odd number, it has an inverse\n // modulo 2**256 such that denominator * inv = 1 mod 2**256.\n // Compute the inverse by starting with a seed that is correct\n // correct for four bits. That is, denominator * inv = 1 mod 2**4\n uint256 inv = (3 * denominator) ^ 2;\n // Now use Newton-Raphson iteration to improve the precision.\n // Thanks to Hensel's lifting lemma, this also works in modular\n // arithmetic, doubling the correct bits in each step.\n inv *= 2 - denominator * inv; // inverse mod 2**8\n inv *= 2 - denominator * inv; // inverse mod 2**16\n inv *= 2 - denominator * inv; // inverse mod 2**32\n inv *= 2 - denominator * inv; // inverse mod 2**64\n inv *= 2 - denominator * inv; // inverse mod 2**128\n inv *= 2 - denominator * inv; // inverse mod 2**256\n\n // Because the division is now exact we can divide by multiplying\n // with the modular inverse of denominator. This will give us the\n // correct result modulo 2**256. Since the precoditions guarantee\n // that the outcome is less than 2**256, this is the final result.\n // We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inv;\n return result;\n }\n }\n\n /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n /// @param a The multiplicand\n /// @param b The multiplier\n /// @param denominator The divisor\n /// @return result The 256-bit result\n function mulDivRoundingUp(\n uint256 a,\n uint256 b,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n result = mulDiv(a, b, denominator);\n if (mulmod(a, b, denominator) > 0) {\n result++;\n }\n }\n}\n"
},
"contracts/libraries/math/PoolMath.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport \"./Math.sol\";\nimport \"./UnsafeMath.sol\";\nimport \"./FullMath.sol\";\n\nlibrary PoolMath {\n using Math for uint256;\n\n uint256 private constant Q72 = 0x1000000000000000000;\n uint256 private constant Q184 = 0x10000000000000000000000000000000000000000000000;\n\n // ----- sqrt price <> token amounts -----\n\n /// @dev Calculate amount0 delta when price moves from sqrtP0 to sqrtP1.\n /// i.e. Δx = L (√P0 - √P1) / (√P0 √P1)\n ///\n /// @dev Rounding rules:\n /// if sqrtP0 > sqrtP1 (price goes down): => amt0 is input => round away from zero\n /// if sqrtP0 < sqrtP1 (price goes up): => amt0 is output => round towards zero\n function calcAmt0FromSqrtP(\n uint128 sqrtP0,\n uint128 sqrtP1,\n uint128 liquidity\n ) internal pure returns (int256 amt0) {\n unchecked {\n bool priceUp = sqrtP1 > sqrtP0;\n if (priceUp) (sqrtP0, sqrtP1) = (sqrtP1, sqrtP0);\n\n uint256 num = uint256(liquidity) * (sqrtP0 - sqrtP1);\n uint256 denom = uint256(sqrtP0) * sqrtP1;\n amt0 = Math.toInt256(\n num < Q184\n ? (priceUp ? (num << 72) / denom : UnsafeMath.ceilDiv(num << 72, denom))\n : (priceUp ? FullMath.mulDiv(num, Q72, denom) : FullMath.mulDivRoundingUp(num, Q72, denom))\n );\n if (priceUp) amt0 *= -1;\n }\n }\n\n /// @dev Calculate amount1 delta when price moves from sqrtP0 to sqrtP1.\n /// i.e. Δy = L (√P0 - √P1)\n ///\n /// @dev Rounding rules:\n /// if sqrtP0 > sqrtP1 (price goes down): => amt1 is output => round towards zero\n /// if sqrtP0 < sqrtP1 (price goes up): => amt1 is input => round away from zero\n function calcAmt1FromSqrtP(\n uint128 sqrtP0,\n uint128 sqrtP1,\n uint128 liquidity\n ) internal pure returns (int256 amt1) {\n unchecked {\n bool priceDown = sqrtP1 < sqrtP0;\n if (priceDown) (sqrtP0, sqrtP1) = (sqrtP1, sqrtP0);\n\n uint256 num = uint256(liquidity) * (sqrtP1 - sqrtP0);\n amt1 = (priceDown ? num >> 72 : UnsafeMath.ceilDiv(num, Q72)).toInt256();\n if (priceDown) amt1 *= -1;\n }\n }\n\n /// @dev Calculate the new sqrt price after an amount0 delta.\n /// i.e. √P1 = L √P0 / (L + Δx * √P0) if no overflow\n /// = L / (L/√P0 + Δx) otherwise\n ///\n /// @dev Rounding rules:\n /// if amt0 in: price goes down => sqrtP1 rounded up for less price change for less amt1 out\n /// if amt0 out: price goes up => sqrtP1 rounded up for more price change for more amt1 in\n /// therefore: sqrtP1 always rounded up\n function calcSqrtPFromAmt0(\n uint128 sqrtP0,\n uint128 liquidity,\n int256 amt0\n ) internal pure returns (uint128 sqrtP1) {\n unchecked {\n if (amt0 == 0) return sqrtP0;\n uint256 absAmt0 = uint256(amt0 < 0 ? -amt0 : amt0);\n uint256 product = absAmt0 * sqrtP0;\n uint256 liquidityX72 = uint256(liquidity) << 72;\n uint256 denom;\n\n if (amt0 > 0) {\n if ((product / absAmt0 == sqrtP0) && ((denom = liquidityX72 + product) >= liquidityX72)) {\n // if product and denom don't overflow:\n uint256 num = uint256(liquidity) * sqrtP0;\n sqrtP1 = num < Q184\n ? uint128(UnsafeMath.ceilDiv(num << 72, denom)) // denom > 0\n : uint128(FullMath.mulDivRoundingUp(num, Q72, denom));\n } else {\n // if either one overflows:\n sqrtP1 = uint128(UnsafeMath.ceilDiv(liquidityX72, (liquidityX72 / sqrtP0).add(absAmt0))); // absAmt0 > 0\n }\n } else {\n // ensure product doesn't overflow and denom doesn't underflow\n require(product / absAmt0 == sqrtP0);\n require((denom = liquidityX72 - product) <= liquidityX72);\n require(denom != 0);\n uint256 num = uint256(liquidity) * sqrtP0;\n sqrtP1 = num < Q184\n ? UnsafeMath.ceilDiv(num << 72, denom).toUint128()\n : FullMath.mulDivRoundingUp(num, Q72, denom).toUint128();\n }\n }\n }\n\n /// @dev Calculate the new sqrt price after an amount1 delta.\n /// i.e. √P1 = √P0 + (Δy / L)\n ///\n /// @dev Rounding rules:\n /// if amt1 in: price goes up => sqrtP1 rounded down for less price delta for less amt0 out\n /// if amt1 out: price goes down => sqrtP1 rounded down for more price delta for more amt0 in\n /// therefore: sqrtP1 always rounded down\n function calcSqrtPFromAmt1(\n uint128 sqrtP0,\n uint128 liquidity,\n int256 amt1\n ) internal pure returns (uint128 sqrtP1) {\n unchecked {\n if (amt1 < 0) {\n // price moves down\n require(liquidity != 0);\n uint256 absAmt1 = uint256(-amt1);\n uint256 absAmt1DivL = absAmt1 < Q184\n ? UnsafeMath.ceilDiv(absAmt1 * Q72, liquidity)\n : FullMath.mulDivRoundingUp(absAmt1, Q72, liquidity);\n\n sqrtP1 = uint256(sqrtP0).sub(absAmt1DivL).toUint128();\n } else {\n // price moves up\n uint256 amt1DivL = uint256(amt1) < Q184\n ? (uint256(amt1) * Q72) / liquidity\n : FullMath.mulDiv(uint256(amt1), Q72, liquidity);\n\n sqrtP1 = uint256(sqrtP0).add(amt1DivL).toUint128();\n }\n }\n }\n\n // ----- liquidity <> token amounts -----\n\n /// @dev Calculate the amount{0,1} needed for the given liquidity change\n function calcAmtsForLiquidity(\n uint128 sqrtP,\n uint128 sqrtPLower,\n uint128 sqrtPUpper,\n int96 liquidityDeltaD8\n ) internal pure returns (uint256 amt0, uint256 amt1) {\n // we assume {sqrtP, sqrtPLower, sqrtPUpper} ≠ 0 and sqrtPLower < sqrtPUpper\n unchecked {\n // find the sqrt price at which liquidity is add/removed\n sqrtP = (sqrtP < sqrtPLower) ? sqrtPLower : (sqrtP > sqrtPUpper) ? sqrtPUpper : sqrtP;\n\n // calc amt{0,1} for the change of liquidity\n uint128 absL = uint128(uint96(liquidityDeltaD8 >= 0 ? liquidityDeltaD8 : -liquidityDeltaD8)) << 8;\n if (liquidityDeltaD8 >= 0) {\n // round up\n amt0 = uint256(calcAmt0FromSqrtP(sqrtPUpper, sqrtP, absL));\n amt1 = uint256(calcAmt1FromSqrtP(sqrtPLower, sqrtP, absL));\n } else {\n // round down\n amt0 = uint256(-calcAmt0FromSqrtP(sqrtP, sqrtPUpper, absL));\n amt1 = uint256(-calcAmt1FromSqrtP(sqrtP, sqrtPLower, absL));\n }\n }\n }\n\n /// @dev Calculate the max liquidity received if adding given token amounts to the tier.\n function calcLiquidityForAmts(\n uint128 sqrtP,\n uint128 sqrtPLower,\n uint128 sqrtPUpper,\n uint256 amt0,\n uint256 amt1\n ) internal pure returns (uint96 liquidityD8) {\n // we assume {sqrtP, sqrtPLower, sqrtPUpper} ≠ 0 and sqrtPLower < sqrtPUpper\n unchecked {\n uint256 liquidity;\n if (sqrtP <= sqrtPLower) {\n // L = Δx (√P0 √P1) / (√P0 - √P1)\n liquidity = FullMath.mulDiv(amt0, uint256(sqrtPLower) * sqrtPUpper, (sqrtPUpper - sqrtPLower) * Q72);\n } else if (sqrtP >= sqrtPUpper) {\n // L = Δy / (√P0 - √P1)\n liquidity = FullMath.mulDiv(amt1, Q72, sqrtPUpper - sqrtPLower);\n } else {\n uint256 liquidity0 = FullMath.mulDiv(amt0, uint256(sqrtP) * sqrtPUpper, (sqrtPUpper - sqrtP) * Q72);\n uint256 liquidity1 = FullMath.mulDiv(amt1, Q72, sqrtP - sqrtPLower);\n liquidity = (liquidity0 < liquidity1 ? liquidity0 : liquidity1);\n }\n liquidityD8 = (liquidity >> 8).toUint96();\n }\n }\n}\n"
},
"contracts/interfaces/common/IERC20Minimal.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.8.0;\n\ninterface IERC20Minimal {\n function approve(address spender, uint256 amount) external returns (bool);\n function balanceOf(address account) external view returns (uint256);\n function transfer(address recipient, uint256 amount) external returns (bool);\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 99999
},
"metadata": {
"bytecodeHash": "none"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}
}