Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Cross-Chain Transactions
Loading...
Loading
Contract Name:
CompounderUniswapV4
Compiler Version
v0.8.30+commit.73712a01
Optimization Enabled:
Yes with 200 runs
Other Settings:
prague EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
/**
* Created by Pragma Labs
* SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.30;
import { Compounder } from "./Compounder.sol";
import { ERC20, SafeTransferLib } from "../../../lib/accounts-v2/lib/solmate/src/utils/SafeTransferLib.sol";
import { IWETH } from "../interfaces/IWETH.sol";
import { PositionState } from "../state/PositionState.sol";
import { UniswapV4 } from "../base/UniswapV4.sol";
/**
* @title Compounder for Uniswap V4 Liquidity Positions.
* @author Pragma Labs
* @notice The Compounder will act as an Asset Manager for Arcadia Accounts.
* It will allow third parties (initiators) to trigger the compounding functionality for a Liquidity Position in the Account.
* The Arcadia Account owner must set a specific initiator that will be permissioned to compound the positions in their Account.
* Compounding can only be triggered if certain conditions are met and the initiator will get a small fee for the service provided.
* The compounding will collect the fees earned by a position and increase the liquidity of the position by those fees.
* Depending on current tick of the pool and the position range, fees will be deposited in appropriate ratio.
* @dev The initiator will provide a trusted sqrtPrice input at the time of compounding to mitigate frontrunning risks.
* This input serves as a reference point for calculating the maximum allowed deviation during the compounding process,
* ensuring that the execution remains within a controlled price range.
*/
contract CompounderUniswapV4 is Compounder, UniswapV4 {
using SafeTransferLib for ERC20;
/* //////////////////////////////////////////////////////////////
CONSTRUCTOR
////////////////////////////////////////////////////////////// */
/**
* @param owner_ The address of the Owner.
* @param arcadiaFactory The contract address of the Arcadia Factory.
* @param routerTrampoline The contract address of the Router Trampoline.
* @param positionManager The contract address of the Uniswap v4 Position Manager.
* @param permit2 The contract address of Permit2.
* @param poolManager The contract address of the Uniswap v4 Pool Manager.
* @param weth The contract address of WETH.
*/
constructor(
address owner_,
address arcadiaFactory,
address routerTrampoline,
address positionManager,
address permit2,
address poolManager,
address weth
) Compounder(owner_, arcadiaFactory, routerTrampoline) UniswapV4(positionManager, permit2, poolManager, weth) { }
/* ///////////////////////////////////////////////////////////////
SWAP LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Swaps one token for another, via a router with custom swap data.
* @param balances The balances of the underlying tokens.
* @param position A struct with position and pool related variables.
* @param zeroToOne Bool indicating if token0 has to be swapped to token1 or opposite.
* @param swapData Arbitrary calldata provided by an initiator for the swap.
* @dev Initiator has to route swap in such a way that at least minLiquidity of liquidity is added to the position after the swap.
* And leftovers must be in tokenIn, otherwise the total tokenIn balance will be added as liquidity,
* and the initiator fee will be 0 (but the transaction will not revert).
*/
function _swapViaRouter(
uint256[] memory balances,
PositionState memory position,
bool zeroToOne,
bytes memory swapData
) internal override {
// Decode the swap data.
(address router, uint256 amountIn, bytes memory data) = abi.decode(swapData, (address, uint256, bytes));
(address tokenIn, address tokenOut) =
zeroToOne ? (position.tokens[0], position.tokens[1]) : (position.tokens[1], position.tokens[0]);
// Handle pools with native ETH.
bool isNative = position.tokens[0] == address(0);
if (isNative) {
if (zeroToOne) {
tokenIn = WETH;
IWETH(WETH).deposit{ value: amountIn }();
} else {
tokenOut = WETH;
}
}
// Send tokens to the Router Trampoline.
ERC20(tokenIn).safeTransfer(address(ROUTER_TRAMPOLINE), amountIn);
// Execute swap.
(uint256 balanceIn, uint256 balanceOut) = ROUTER_TRAMPOLINE.execute(router, data, tokenIn, tokenOut, amountIn);
// Handle pools with native ETH.
if (isNative) {
uint256 wethBalance = zeroToOne ? balanceIn : balanceOut;
if (wethBalance > 0) IWETH(WETH).withdraw(wethBalance);
}
// Update the balances.
(balances[0], balances[1]) = zeroToOne
? (balances[0] - amountIn + balanceIn, balances[1] + balanceOut)
: (balances[0] + balanceOut, balances[1] - amountIn + balanceIn);
}
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.0;
import { AbstractBase } from "../base/AbstractBase.sol";
import { ActionData, IActionBase } from "../../../lib/accounts-v2/src/interfaces/IActionBase.sol";
import { ArcadiaLogic } from "../libraries/ArcadiaLogic.sol";
import { ERC20, SafeTransferLib } from "../../../lib/accounts-v2/lib/solmate/src/utils/SafeTransferLib.sol";
import { ERC721 } from "../../../lib/accounts-v2/lib/solmate/src/tokens/ERC721.sol";
import { FixedPointMathLib } from "../../../lib/accounts-v2/lib/solmate/src/utils/FixedPointMathLib.sol";
import { Guardian } from "../../guardian/Guardian.sol";
import { IAccount } from "../../interfaces/IAccount.sol";
import { IArcadiaFactory } from "../../interfaces/IArcadiaFactory.sol";
import { IRouterTrampoline } from "../interfaces/IRouterTrampoline.sol";
import { PositionState } from "../state/PositionState.sol";
import { RebalanceLogic, RebalanceParams } from "../libraries/RebalanceLogic.sol";
import { RebalanceOptimizationMath } from "../libraries/RebalanceOptimizationMath.sol";
import { SafeApprove } from "../../libraries/SafeApprove.sol";
import { TickMath } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/libraries/TickMath.sol";
/**
* @title Abstract Compounder for Concentrated Liquidity Positions.
* @author Pragma Labs
* @notice The Compounder will act as an Asset Manager for Arcadia Accounts.
* It will allow third parties (initiators) to trigger the compounding functionality for a Liquidity Position in the Account.
* The Arcadia Account owner must set a specific initiator that will be permissioned to compound the positions in their Account.
* Compounding can only be triggered if certain conditions are met and the initiator will get a small fee for the service provided.
* The compounding will collect the fees earned by a position and increase the liquidity of the position by those fees.
* Depending on current tick of the pool and the position range, fees will be deposited in appropriate ratio.
* @dev The initiator will provide a trusted sqrtPrice input at the time of compounding to mitigate frontrunning risks.
* This input serves as a reference point for calculating the maximum allowed deviation during the compounding process,
* ensuring that the execution remains within a controlled price range.
*/
abstract contract Compounder is IActionBase, AbstractBase, Guardian {
using FixedPointMathLib for uint256;
using SafeApprove for ERC20;
using SafeTransferLib for ERC20;
/* //////////////////////////////////////////////////////////////
CONSTANTS
////////////////////////////////////////////////////////////// */
// The contract address of the Arcadia Factory.
IArcadiaFactory public immutable ARCADIA_FACTORY;
// The contract address of the Router Trampoline.
IRouterTrampoline public immutable ROUTER_TRAMPOLINE;
/* //////////////////////////////////////////////////////////////
STORAGE
////////////////////////////////////////////////////////////// */
// The Account to rebalance the fees for, used as transient storage.
address internal account;
// A mapping from account to account specific information.
mapping(address account => AccountInfo) public accountInfo;
// A mapping from account to custom metadata.
mapping(address account => bytes data) public metaData;
// A mapping that sets the approved initiator per owner per account.
mapping(address accountOwner => mapping(address account => address initiator)) public accountToInitiator;
// A struct with the account specific parameters.
struct AccountInfo {
// The maximum fee charged on the claimed fees of the liquidity position, with 18 decimals precision.
uint64 maxClaimFee;
// The maximum fee charged on the ideal (without slippage) amountIn by the initiator, with 18 decimals precision.
uint64 maxSwapFee;
// The maximum relative deviation the pool can have from the trustedSqrtPrice, with 18 decimals precision.
uint64 upperSqrtPriceDeviation;
// The minimum relative deviation the pool can have from the trustedSqrtPrice, with 18 decimals precision.
uint64 lowerSqrtPriceDeviation;
// The ratio that limits the amount of slippage of the swap, with 18 decimals precision.
uint64 minLiquidityRatio;
}
// A struct with the initiator parameters.
struct InitiatorParams {
// The contract address of the position manager.
address positionManager;
// The id of the position.
uint96 id;
// The amount of token0 withdrawn from the account.
uint128 amount0;
// The amount of token1 withdrawn from the account.
uint128 amount1;
// The sqrtPrice the pool should have, given by the initiator.
uint256 trustedSqrtPrice;
// The fee charged on the claimed fees of the liquidity position, with 18 decimals precision.
uint64 claimFee;
// The fee charged on the ideal (without slippage) amountIn by the initiator, with 18 decimals precision.
uint64 swapFee;
// Calldata provided by the initiator to execute the swap.
bytes swapData;
}
// A struct with cached variables.
struct Cache {
// The lower bound the sqrtPrice can have for the pool to be balanced.
uint256 lowerBoundSqrtPrice;
// The lower bound the sqrtPrice can have for the pool to be balanced.
uint256 upperBoundSqrtPrice;
// The sqrtRatio of the lower tick.
uint160 sqrtRatioLower;
// The sqrtRatio of the upper tick.
uint160 sqrtRatioUpper;
}
/* //////////////////////////////////////////////////////////////
ERRORS
////////////////////////////////////////////////////////////// */
error InsufficientLiquidity();
error InvalidAccountVersion();
error InvalidInitiator();
error InvalidPositionManager();
error InvalidValue();
error NotAnAccount();
error OnlyAccount();
error OnlyAccountOwner();
error Reentered();
error UnbalancedPool();
/* //////////////////////////////////////////////////////////////
EVENTS
////////////////////////////////////////////////////////////// */
event AccountInfoSet(address indexed account, address indexed initiator);
event Compound(address indexed account, address indexed positionManager, uint256 id);
/* //////////////////////////////////////////////////////////////
CONSTRUCTOR
////////////////////////////////////////////////////////////// */
/**
* @param owner_ The address of the Owner.
* @param arcadiaFactory The contract address of the Arcadia Factory.
* @param routerTrampoline The contract address of the Router Trampoline.
*/
constructor(address owner_, address arcadiaFactory, address routerTrampoline) Guardian(owner_) {
ARCADIA_FACTORY = IArcadiaFactory(arcadiaFactory);
ROUTER_TRAMPOLINE = IRouterTrampoline(routerTrampoline);
}
/* ///////////////////////////////////////////////////////////////
ACCOUNT LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Optional hook called by the Arcadia Account when calling "setAssetManager()".
* @param accountOwner The current owner of the Arcadia Account.
* param status Bool indicating if the Asset Manager is enabled or disabled.
* @param data Operator specific data, passed by the Account owner.
* @dev No need to check that the Account version is 3 or greater (versions with cross account reentrancy guard),
* since version 1 and 2 don't support the onSetAssetManager hook.
*/
function onSetAssetManager(address accountOwner, bool, bytes calldata data) external {
if (account != address(0)) revert Reentered();
if (!ARCADIA_FACTORY.isAccount(msg.sender)) revert NotAnAccount();
(
address initiator,
uint256 maxClaimFee,
uint256 maxSwapFee,
uint256 maxTolerance,
uint256 minLiquidityRatio,
bytes memory metaData_
) = abi.decode(data, (address, uint256, uint256, uint256, uint256, bytes));
_setAccountInfo(
msg.sender, accountOwner, initiator, maxClaimFee, maxSwapFee, maxTolerance, minLiquidityRatio, metaData_
);
}
/**
* @notice Sets the required information for an Account.
* @param account_ The contract address of the Arcadia Account to set the information for.
* @param initiator The address of the initiator.
* @param maxClaimFee The maximum fee charged on claimed fees/rewards by the initiator, with 18 decimals precision.
* @param maxSwapFee The maximum fee charged on the ideal (without slippage) amountIn by the initiator, with 18 decimals precision.
* @param maxTolerance The maximum allowed deviation of the actual pool price for any initiator,
* relative to the price calculated with trusted external prices of both assets, with 18 decimals precision.
* @param minLiquidityRatio The ratio of the minimum amount of liquidity that must be minted,
* relative to the hypothetical amount of liquidity when we rebalance without slippage, with 18 decimals precision.
* @param metaData_ Custom metadata to be stored with the account.
*/
function setAccountInfo(
address account_,
address initiator,
uint256 maxClaimFee,
uint256 maxSwapFee,
uint256 maxTolerance,
uint256 minLiquidityRatio,
bytes calldata metaData_
) external {
if (account != address(0)) revert Reentered();
if (!ARCADIA_FACTORY.isAccount(account_)) revert NotAnAccount();
address accountOwner = IAccount(account_).owner();
if (msg.sender != accountOwner) revert OnlyAccountOwner();
// Block Account versions without cross account reentrancy guard.
if (IAccount(account_).ACCOUNT_VERSION() < 3) revert InvalidAccountVersion();
_setAccountInfo(
account_, accountOwner, initiator, maxClaimFee, maxSwapFee, maxTolerance, minLiquidityRatio, metaData_
);
}
/**
* @notice Sets the required information for an Account.
* @param account_ The contract address of the Arcadia Account to set the information for.
* @param accountOwner The current owner of the Arcadia Account.
* @param initiator The address of the initiator.
* @param maxClaimFee The maximum fee charged on claimed fees/rewards by the initiator, with 18 decimals precision.
* @param maxSwapFee The maximum fee charged on the ideal (without slippage) amountIn by the initiator, with 18 decimals precision.
* @param maxTolerance The maximum allowed deviation of the actual pool price for any initiator,
* relative to the price calculated with trusted external prices of both assets, with 18 decimals precision.
* @param minLiquidityRatio The ratio of the minimum amount of liquidity that must be minted,
* relative to the hypothetical amount of liquidity when we rebalance without slippage, with 18 decimals precision.
* @param metaData_ Custom metadata to be stored with the account.
*/
function _setAccountInfo(
address account_,
address accountOwner,
address initiator,
uint256 maxClaimFee,
uint256 maxSwapFee,
uint256 maxTolerance,
uint256 minLiquidityRatio,
bytes memory metaData_
) internal {
if (maxClaimFee > 1e18 || maxSwapFee > 1e18 || maxTolerance > 1e18 || minLiquidityRatio > 1e18) {
revert InvalidValue();
}
accountToInitiator[accountOwner][account_] = initiator;
// unsafe cast: fees <= 1e18 < type(uint64).max.
// unsafe cast: upperSqrtPriceDeviation <= √2 * 1e18 < type(uint64).max.
// forge-lint: disable-next-item(unsafe-typecast)
accountInfo[account_] = AccountInfo({
maxClaimFee: uint64(maxClaimFee),
maxSwapFee: uint64(maxSwapFee),
upperSqrtPriceDeviation: uint64(FixedPointMathLib.sqrt((1e18 + maxTolerance) * 1e18)),
lowerSqrtPriceDeviation: uint64(FixedPointMathLib.sqrt((1e18 - maxTolerance) * 1e18)),
minLiquidityRatio: uint64(minLiquidityRatio)
});
metaData[account_] = metaData_;
emit AccountInfoSet(account_, initiator);
}
/* ///////////////////////////////////////////////////////////////
COMPOUND LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Compounds a Concentrated Liquidity Positions, owned by an Arcadia Account.
* @param account_ The contract address of the account.
* @param initiatorParams A struct with the initiator parameters.
*/
function compound(address account_, InitiatorParams calldata initiatorParams) external whenNotPaused {
// Store Account address, used to validate the caller of the executeAction() callback and serves as a reentrancy guard.
if (account != address(0)) revert Reentered();
account = account_;
// If the initiator is set, account_ is an actual Arcadia Account.
if (accountToInitiator[IAccount(account_).owner()][account_] != msg.sender) revert InvalidInitiator();
if (!isPositionManager(initiatorParams.positionManager)) revert InvalidPositionManager();
// If leftovers have to be withdrawn from account, get token0 and token1.
address token0;
address token1;
if (initiatorParams.amount0 > 0 || initiatorParams.amount1 > 0) {
(token0, token1) = _getUnderlyingTokens(initiatorParams.positionManager, initiatorParams.id);
}
// Encode data for the flash-action.
bytes memory actionData = ArcadiaLogic._encodeAction(
initiatorParams.positionManager,
initiatorParams.id,
token0,
token1,
initiatorParams.amount0,
initiatorParams.amount1,
abi.encode(msg.sender, initiatorParams)
);
// Call flashAction() with this contract as actionTarget.
IAccount(account_).flashAction(address(this), actionData);
// Reset account.
account = address(0);
}
/**
* @notice Callback function called by the Arcadia Account during the flashAction.
* @param actionTargetData A bytes object containing the initiator and initiatorParams.
* @return depositData A struct with the asset data of the Liquidity Position and with the leftovers after mint, if any.
* @dev The Liquidity Position is already transferred to this contract before executeAction() is called.
* @dev When rebalancing we will burn the current Liquidity Position and mint a new one with a new tokenId.
*/
function executeAction(bytes calldata actionTargetData) external override returns (ActionData memory depositData) {
// Caller should be the Account, provided as input in rebalance().
if (msg.sender != account) revert OnlyAccount();
// Cache accountInfo.
AccountInfo memory accountInfo_ = accountInfo[msg.sender];
// Decode actionTargetData.
(address initiator, InitiatorParams memory initiatorParams) =
abi.decode(actionTargetData, (address, InitiatorParams));
address positionManager = initiatorParams.positionManager;
// Validate initiatorParams.
if (initiatorParams.claimFee > accountInfo_.maxClaimFee || initiatorParams.swapFee > accountInfo_.maxSwapFee) {
revert InvalidValue();
}
// Get all pool and position related state.
PositionState memory position = _getPositionState(positionManager, initiatorParams.id);
// Compounder has withdrawn the underlying tokens from the Account.
uint256[] memory balances = new uint256[](position.tokens.length);
balances[0] = initiatorParams.amount0;
balances[1] = initiatorParams.amount1;
uint256[] memory fees = new uint256[](balances.length);
// Cache variables that are gas expensive to calculate and used multiple times.
Cache memory cache = _getCache(accountInfo_, position, initiatorParams.trustedSqrtPrice);
// Check that pool is initially balanced.
// Prevents sandwiching attacks when swapping and/or adding liquidity.
if (!isPoolBalanced(position.sqrtPrice, cache)) revert UnbalancedPool();
// Claim pending yields and update balances.
_claim(balances, fees, positionManager, position, initiatorParams.claimFee);
// If the position is staked, unstake it.
_unstake(balances, positionManager, position);
// Get the rebalance parameters, based on a hypothetical swap through the pool itself without slippage.
RebalanceParams memory rebalanceParams = RebalanceLogic._getRebalanceParams(
accountInfo_.minLiquidityRatio,
position.fee,
initiatorParams.swapFee,
position.sqrtPrice,
cache.sqrtRatioLower,
cache.sqrtRatioUpper,
balances[0] - fees[0],
balances[1] - fees[1]
);
if (rebalanceParams.zeroToOne) fees[0] += rebalanceParams.amountInitiatorFee;
else fees[1] += rebalanceParams.amountInitiatorFee;
// Do the swap to rebalance the position.
// This can be done either directly through the pool, or via a router with custom swap data.
// For swaps directly through the pool, if slippage is bigger than calculated, the transaction will not immediately revert,
// but excess slippage will be subtracted from the initiatorFee.
// For swaps via a router, tokenOut should be the limiting factor when increasing liquidity.
// Update balances after the swap.
_swap(balances, fees, initiatorParams, position, rebalanceParams, cache);
// Check that the pool is still balanced after the swap.
// Since the swap went potentially through the pool itself (but does not have to),
// the sqrtPrice might have moved and brought the pool out of balance.
position.sqrtPrice = _getSqrtPrice(position);
if (!isPoolBalanced(position.sqrtPrice, cache)) revert UnbalancedPool();
// As explained before _swap(), tokenOut should be the limiting factor when increasing liquidity
// therefore we only subtract the initiator fee from the amountOut, not from the amountIn.
// Increase liquidity, update balances and delta liquidity.
(uint256 amount0Desired, uint256 amount1Desired) =
rebalanceParams.zeroToOne ? (balances[0], balances[1] - fees[1]) : (balances[0] - fees[0], balances[1]);
// Increase liquidity, update balances and liquidity
_increaseLiquidity(balances, positionManager, position, amount0Desired, amount1Desired);
// Check that the actual liquidity of the position is above the minimum threshold.
// This prevents loss of principal of the liquidity position due to slippage,
// or malicious initiators who remove liquidity during a custom swap.
if (position.liquidity < rebalanceParams.minLiquidity) revert InsufficientLiquidity();
// If the position was staked, stake it.
_stake(balances, positionManager, position);
// Approve the liquidity position and leftovers to be deposited back into the Account.
// And transfer the initiator fees to the initiator.
uint256 count = _approveAndTransfer(initiator, balances, fees, positionManager, position);
// Encode deposit data for the flash-action.
depositData = ArcadiaLogic._encodeDeposit(positionManager, position.id, position.tokens, balances, count);
emit Compound(msg.sender, positionManager, position.id);
}
/* ///////////////////////////////////////////////////////////////
POSITION VALIDATION
/////////////////////////////////////////////////////////////// */
/**
* @notice Returns if the pool of a Liquidity Position is balanced.
* @param sqrtPrice The sqrtPrice of the pool.
* @param cache A struct with cached variables.
* @return isBalanced Bool indicating if the pool is balanced.
*/
function isPoolBalanced(uint256 sqrtPrice, Cache memory cache) public pure returns (bool isBalanced) {
// Check if current price of the Pool is within accepted tolerance of the calculated trusted price.
isBalanced = sqrtPrice > cache.lowerBoundSqrtPrice && sqrtPrice < cache.upperBoundSqrtPrice;
}
/* ///////////////////////////////////////////////////////////////
GETTERS
/////////////////////////////////////////////////////////////// */
/**
* @notice Returns the cached variables.
* @param accountInfo_ A struct with the account specific parameters.
* @param position A struct with position and pool related variables.
* @param trustedSqrtPrice The sqrtPrice the pool should have, given by the initiator.
* @return cache A struct with cached variables.
*/
function _getCache(AccountInfo memory accountInfo_, PositionState memory position, uint256 trustedSqrtPrice)
internal
view
virtual
returns (Cache memory cache)
{
// We do not handle the edge cases where the bounds of the sqrtPrice exceed MIN_SQRT_RATIO or MAX_SQRT_RATIO.
// This will result in a revert during swapViaPool, if ever needed a different Compounder has to be deployed.
cache = Cache({
lowerBoundSqrtPrice: trustedSqrtPrice.mulDivDown(accountInfo_.lowerSqrtPriceDeviation, 1e18),
upperBoundSqrtPrice: trustedSqrtPrice.mulDivDown(accountInfo_.upperSqrtPriceDeviation, 1e18),
sqrtRatioLower: TickMath.getSqrtPriceAtTick(position.tickLower),
sqrtRatioUpper: TickMath.getSqrtPriceAtTick(position.tickUpper)
});
}
/* ///////////////////////////////////////////////////////////////
SWAP LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Swaps one token for another to rebalance the Liquidity Position.
* @param balances The balances of the underlying tokens held by the Compounder.
* @param fees The fees of the underlying tokens to be paid to the initiator.
* @param initiatorParams A struct with the initiator parameters.
* @param position A struct with position and pool related variables.
* @param rebalanceParams A struct with the rebalance parameters.
* @param cache A struct with cached variables.
* @dev Must update the balances and sqrtPrice after the swap.
*/
function _swap(
uint256[] memory balances,
uint256[] memory fees,
InitiatorParams memory initiatorParams,
PositionState memory position,
RebalanceParams memory rebalanceParams,
Cache memory cache
) internal virtual {
// Don't do swaps with zero amount.
if (rebalanceParams.amountIn == 0) return;
// Do the actual swap to rebalance the position.
// This can be done either directly through the pool, or via a router with custom swap data.
if (initiatorParams.swapData.length == 0) {
// Calculate a more accurate amountOut, with slippage.
uint256 amountOut = RebalanceOptimizationMath._getAmountOutWithSlippage(
rebalanceParams.zeroToOne,
position.fee,
_getPoolLiquidity(position),
uint160(position.sqrtPrice),
cache.sqrtRatioLower,
cache.sqrtRatioUpper,
balances[0] - fees[0],
balances[1] - fees[1],
rebalanceParams.amountIn,
rebalanceParams.amountOut
);
// Don't do swaps with zero amount.
if (amountOut == 0) return;
_swapViaPool(balances, position, rebalanceParams.zeroToOne, amountOut);
} else {
_swapViaRouter(balances, position, rebalanceParams.zeroToOne, initiatorParams.swapData);
}
}
/**
* @notice Swaps one token for another, via a router with custom swap data.
* @param balances The balances of the underlying tokens held by the Compounder.
* @param position A struct with position and pool related variables.
* @param zeroToOne Bool indicating if token0 has to be swapped to token1 or opposite.
* @param swapData Arbitrary calldata provided by an initiator for the swap.
* @dev Initiator has to route swap in such a way that at least minLiquidity of liquidity is added to the position after the swap.
* And leftovers must be in tokenIn, otherwise the total tokenIn balance will be added as liquidity,
* and the initiator fee will be 0 (but the transaction will not revert).
*/
function _swapViaRouter(
uint256[] memory balances,
PositionState memory position,
bool zeroToOne,
bytes memory swapData
) internal virtual {
// Decode the swap data.
(address router, uint256 amountIn, bytes memory data) = abi.decode(swapData, (address, uint256, bytes));
(address tokenIn, address tokenOut) =
zeroToOne ? (position.tokens[0], position.tokens[1]) : (position.tokens[1], position.tokens[0]);
// Send tokens to the Router Trampoline.
ERC20(tokenIn).safeTransfer(address(ROUTER_TRAMPOLINE), amountIn);
// Execute swap.
(uint256 balanceIn, uint256 balanceOut) = ROUTER_TRAMPOLINE.execute(router, data, tokenIn, tokenOut, amountIn);
// Update the balances.
(balances[0], balances[1]) = zeroToOne
? (balances[0] - amountIn + balanceIn, balances[1] + balanceOut)
: (balances[0] + balanceOut, balances[1] - amountIn + balanceIn);
}
/* ///////////////////////////////////////////////////////////////
APPROVE AND TRANSFER LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Approves the liquidity position and leftovers to be deposited back into the Account
* and transfers the initiator fees to the initiator.
* @param initiator The address of the initiator.
* @param balances The balances of the underlying tokens held by the Compounder.
* @param fees The fees of the underlying tokens to be paid to the initiator.
* @param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
* @return count The number of assets approved.
*/
function _approveAndTransfer(
address initiator,
uint256[] memory balances,
uint256[] memory fees,
address positionManager,
PositionState memory position
) internal returns (uint256 count) {
// Approve the Liquidity Position.
ERC721(positionManager).approve(msg.sender, position.id);
// Transfer Initiator fees and approve the leftovers.
address token;
count = 1;
for (uint256 i; i < balances.length; i++) {
token = position.tokens[i];
// If there are leftovers, deposit them back into the Account.
if (balances[i] > fees[i]) {
balances[i] = balances[i] - fees[i];
ERC20(token).safeApproveWithRetry(msg.sender, balances[i]);
count++;
} else {
fees[i] = balances[i];
balances[i] = 0;
}
// Transfer Initiator fees to the initiator.
if (fees[i] > 0) ERC20(token).safeTransfer(initiator, fees[i]);
emit FeePaid(msg.sender, initiator, token, fees[i]);
}
}
/* ///////////////////////////////////////////////////////////////
SKIM LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Recovers any native or ERC20 tokens left on the contract.
* @param token The contract address of the token, or address(0) for native tokens.
*/
function skim(address token) external onlyOwner whenNotPaused {
if (account != address(0)) revert Reentered();
if (token == address(0)) {
(bool success, bytes memory result) = payable(msg.sender).call{ value: address(this).balance }("");
require(success, string(result));
} else {
ERC20(token).safeTransfer(msg.sender, ERC20(token).balanceOf(address(this)));
}
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {ERC20} from "../tokens/ERC20.sol";
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
library SafeTransferLib {
/*//////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and store if it succeeded or not.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
require(success, "ETH_TRANSFER_FAILED");
}
/*//////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
success := call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
success := iszero(or(iszero(extcodesize(token)), returndatasize()))
}
}
require(success, "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
success := call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
success := iszero(or(iszero(extcodesize(token)), returndatasize()))
}
}
require(success, "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
success := call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
success := iszero(or(iszero(extcodesize(token)), returndatasize()))
}
}
require(success, "APPROVE_FAILED");
}
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.8.0;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external payable;
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.0;
// A struct with the position and pool state.
struct PositionState {
// The contract address of the pool.
address pool;
// The id of the position.
uint256 id;
// The fee of the pool
uint24 fee;
// The tick spacing of the pool.
int24 tickSpacing;
// The current tick of the pool.
int24 tickCurrent;
// The lower tick of the position.
int24 tickUpper;
// The upper tick of the position.
int24 tickLower;
// The liquidity of the position.
uint128 liquidity;
// The sqrtPrice of the pool.
uint256 sqrtPrice;
// The underlying tokens of the pool.
address[] tokens;
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.0;
import { AbstractBase } from "./AbstractBase.sol";
import { Actions } from "../../../lib/accounts-v2/lib/v4-periphery/src/libraries/Actions.sol";
import { BalanceDelta } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/types/BalanceDelta.sol";
import { CLMath } from "../libraries/CLMath.sol";
import { Currency } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/types/Currency.sol";
import { ERC20, SafeTransferLib } from "../../../lib/accounts-v2/lib/solmate/src/utils/SafeTransferLib.sol";
import { FixedPointMathLib } from "../../../lib/accounts-v2/lib/solmate/src/utils/FixedPointMathLib.sol";
import { IHooks } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/interfaces/IHooks.sol";
import { IPermit2 } from "../interfaces/IPermit2.sol";
import { IPoolManager } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/interfaces/IPoolManager.sol";
import { IPositionManagerV4 } from "../interfaces/IPositionManagerV4.sol";
import { IWETH } from "../interfaces/IWETH.sol";
import { LiquidityAmounts } from "../libraries/LiquidityAmounts.sol";
import { PoolKey } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/types/PoolKey.sol";
import { PositionInfo } from "../../../lib/accounts-v2/lib/v4-periphery/src/libraries/PositionInfoLibrary.sol";
import { PositionState } from "../state/PositionState.sol";
import { SafeApprove } from "../../libraries/SafeApprove.sol";
import { StateLibrary } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/libraries/StateLibrary.sol";
import { SwapParams } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/types/PoolOperation.sol";
import { TickMath } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/libraries/TickMath.sol";
/**
* @title Base implementation for managing Uniswap V4 Liquidity Positions.
*/
abstract contract UniswapV4 is AbstractBase {
using FixedPointMathLib for uint256;
using SafeApprove for ERC20;
using SafeTransferLib for ERC20;
using StateLibrary for IPoolManager;
/* //////////////////////////////////////////////////////////////
CONSTANTS
////////////////////////////////////////////////////////////// */
// The contract address of the Uniswap v4 Position Manager.
IPositionManagerV4 internal immutable POSITION_MANAGER;
// The Permit2 contract.
IPermit2 internal immutable PERMIT_2;
// The Uniswap V4 PoolManager contract.
IPoolManager internal immutable POOL_MANAGER;
// The contract address of WETH.
address internal immutable WETH;
/* //////////////////////////////////////////////////////////////
STORAGE
////////////////////////////////////////////////////////////// */
// A mapping if permit2 has been approved for a certain token.
mapping(address token => bool approved) internal approved;
/* //////////////////////////////////////////////////////////////
ERRORS
////////////////////////////////////////////////////////////// */
error InvalidPool();
error OnlyPoolManager();
/* //////////////////////////////////////////////////////////////
CONSTRUCTOR
////////////////////////////////////////////////////////////// */
/**
* @param positionManager The contract address of the Uniswap v4 Position Manager.
* @param permit2 The contract address of Permit2.
* @param poolManager The contract address of the Uniswap v4 Pool Manager.
* @param weth The contract address of WETH.
*/
constructor(address positionManager, address permit2, address poolManager, address weth) {
POSITION_MANAGER = IPositionManagerV4(positionManager);
PERMIT_2 = IPermit2(permit2);
POOL_MANAGER = IPoolManager(poolManager);
WETH = weth;
}
/* ///////////////////////////////////////////////////////////////
POSITION VALIDATION
/////////////////////////////////////////////////////////////// */
/**
* @notice Returns if a position manager matches the position manager(s) of Uniswap v4.
* @param positionManager the contract address of the position manager to check.
*/
function isPositionManager(address positionManager) public view virtual override returns (bool) {
return positionManager == address(POSITION_MANAGER);
}
/* ///////////////////////////////////////////////////////////////
GETTERS
/////////////////////////////////////////////////////////////// */
/**
* @notice Returns the underlying assets of the pool.
* param positionManager The contract address of the Position Manager.
* @param id The id of the Liquidity Position.
* @return token0 The contract address of token0.
* @return token1 The contract address of token1.
*/
function _getUnderlyingTokens(address, uint256 id)
internal
view
virtual
override
returns (address token0, address token1)
{
(PoolKey memory poolKey,) = POSITION_MANAGER.getPoolAndPositionInfo(id);
token0 = Currency.unwrap(poolKey.currency0);
token1 = Currency.unwrap(poolKey.currency1);
// If token0 is in native ETH, we need to withdraw wrapped eth from the Account.
if (token0 == address(0)) {
// Implementation cannot be used for pools of native eth and weth.
if (token1 == WETH) revert InvalidPool();
token0 = WETH;
}
}
/**
* @notice Returns the position and pool related state.
* param positionManager The contract address of the Position Manager.
* @param id The id of the Liquidity Position.
* @return position A struct with position and pool related variables.
*/
function _getPositionState(address, uint256 id)
internal
view
virtual
override
returns (PositionState memory position)
{
// Positions have two underlying tokens.
position.tokens = new address[](2);
// Get data of the Liquidity Position.
position.id = id;
(PoolKey memory poolKey, PositionInfo info) = POSITION_MANAGER.getPoolAndPositionInfo(id);
position.tickLower = info.tickLower();
position.tickUpper = info.tickUpper();
bytes32 positionId =
keccak256(abi.encodePacked(address(POSITION_MANAGER), info.tickLower(), info.tickUpper(), bytes32(id)));
position.liquidity = POOL_MANAGER.getPositionLiquidity(poolKey.toId(), positionId);
// Get data of the Liquidity Pool.
position.pool = address(poolKey.hooks);
position.tokens[0] = Currency.unwrap(poolKey.currency0);
position.tokens[1] = Currency.unwrap(poolKey.currency1);
position.fee = poolKey.fee;
position.tickSpacing = poolKey.tickSpacing;
(position.sqrtPrice, position.tickCurrent,,) = POOL_MANAGER.getSlot0(poolKey.toId());
}
/**
* @notice Returns the liquidity of the Pool.
* @param position A struct with position and pool related variables.
* @return liquidity The liquidity of the Pool.
*/
function _getPoolLiquidity(PositionState memory position)
internal
view
virtual
override
returns (uint128 liquidity)
{
PoolKey memory poolKey = PoolKey({
currency0: Currency.wrap(position.tokens[0]),
currency1: Currency.wrap(position.tokens[1]),
fee: position.fee,
tickSpacing: position.tickSpacing,
hooks: IHooks(position.pool)
});
liquidity = POOL_MANAGER.getLiquidity(poolKey.toId());
}
/**
* @notice Returns the sqrtPrice of the Pool.
* @param position A struct with position and pool related variables.
* @return sqrtPrice The sqrtPrice of the Pool.
*/
function _getSqrtPrice(PositionState memory position) internal view virtual override returns (uint160 sqrtPrice) {
PoolKey memory poolKey = PoolKey({
currency0: Currency.wrap(position.tokens[0]),
currency1: Currency.wrap(position.tokens[1]),
fee: position.fee,
tickSpacing: position.tickSpacing,
hooks: IHooks(position.pool)
});
(sqrtPrice,,,) = POOL_MANAGER.getSlot0(poolKey.toId());
}
/* ///////////////////////////////////////////////////////////////
CLAIM LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Claims fees/rewards from a Liquidity Position.
* @param balances The balances of the underlying tokens.
* @param fees The fees of the underlying tokens to be paid to the initiator.
* param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
*/
function _claim(
uint256[] memory balances,
uint256[] memory fees,
address,
PositionState memory position,
uint256 claimFee
) internal virtual override {
// Cache the currencies.
Currency currency0 = Currency.wrap(position.tokens[0]);
Currency currency1 = Currency.wrap(position.tokens[1]);
// If token0 is native ETH, we need to set the balance to 0,
// since the assets withdrawn from the account are in wet and not in native ETH.
if (position.tokens[0] == address(0)) balances[0] = 0;
// Generate calldata to collect fees (decrease liquidity with liquidityDelta = 0).
bytes memory actions = new bytes(2);
actions[0] = bytes1(uint8(Actions.DECREASE_LIQUIDITY));
actions[1] = bytes1(uint8(Actions.TAKE_PAIR));
bytes[] memory params = new bytes[](2);
params[0] = abi.encode(position.id, 0, 0, 0, "");
params[1] = abi.encode(currency0, currency1, address(this));
bytes memory decreaseLiquidityParams = abi.encode(actions, params);
POSITION_MANAGER.modifyLiquidities(decreaseLiquidityParams, block.timestamp);
// Get the balances, token0 might be native ETH.
uint256 balance0 = currency0.balanceOfSelf();
uint256 balance1 = ERC20(position.tokens[1]).balanceOf(address(this));
// Calculate claim fees.
fees[0] += (balance0 - balances[0]).mulDivDown(claimFee, 1e18);
fees[1] += (balance1 - balances[1]).mulDivDown(claimFee, 1e18);
emit YieldClaimed(msg.sender, position.tokens[0], balance0 - balances[0]);
emit YieldClaimed(msg.sender, position.tokens[1], balance1 - balances[1]);
// Update the balances.
balances[0] = balance0;
balances[1] = balance1;
}
/* ///////////////////////////////////////////////////////////////
STAKING LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Stakes a Liquidity Position.
* @param balances The balances of the underlying tokens.
* param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
*/
function _stake(uint256[] memory balances, address, PositionState memory position) internal virtual override {
// If token0 is in native ETH, wrap it.
if (position.tokens[0] == address(0)) {
position.tokens[0] = WETH;
IWETH(payable(WETH)).deposit{ value: balances[0] }();
}
}
/**
* @notice Unstakes a Liquidity Position.
* @param balances The balances of the underlying tokens.
* param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
*/
function _unstake(uint256[] memory balances, address, PositionState memory position) internal virtual override {
// If token0 is in native ETH, and weth was withdrawn from the account, unwrap it.
if (position.tokens[0] == address(0)) {
uint256 wethBalance = ERC20(WETH).balanceOf(address(this));
if (wethBalance > 0) {
IWETH(WETH).withdraw(wethBalance);
balances[0] += wethBalance;
}
}
}
/* ///////////////////////////////////////////////////////////////
BURN LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Burns the Liquidity Position.
* @param balances The balances of the underlying tokens.
* param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
* @dev Does not emit YieldClaimed event, if necessary first call _claim() to emit the event before unstaking.
*/
function _burn(uint256[] memory balances, address, PositionState memory position) internal virtual override {
// Cache the currencies.
Currency currency0 = Currency.wrap(position.tokens[0]);
Currency currency1 = Currency.wrap(position.tokens[1]);
// Generate calldata to burn the position and collect the underlying assets.
bytes memory actions = new bytes(2);
actions[0] = bytes1(uint8(Actions.BURN_POSITION));
actions[1] = bytes1(uint8(Actions.TAKE_PAIR));
bytes[] memory params = new bytes[](2);
params[0] = abi.encode(position.id, 0, 0, "");
params[1] = abi.encode(currency0, currency1, address(this));
bytes memory burnParams = abi.encode(actions, params);
POSITION_MANAGER.modifyLiquidities(burnParams, block.timestamp);
// Update the balances, token0 might be native ETH.
balances[0] = currency0.balanceOfSelf();
balances[1] = ERC20(position.tokens[1]).balanceOf(address(this));
}
/* ///////////////////////////////////////////////////////////////
SWAP LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Swaps one token for another, directly through the pool itself.
* @param balances The balances of the underlying tokens.
* @param position A struct with position and pool related variables.
* @param zeroToOne Bool indicating if token0 has to be swapped to token1 or opposite.
* @param amountOut The amount of tokenOut that must be swapped to.
*/
// forge-lint: disable-next-item(unsafe-typecast)
function _swapViaPool(uint256[] memory balances, PositionState memory position, bool zeroToOne, uint256 amountOut)
internal
virtual
override
{
// Do the swap.
bytes memory swapData = abi.encode(
SwapParams({
zeroForOne: zeroToOne,
amountSpecified: int256(amountOut),
sqrtPriceLimitX96: zeroToOne ? CLMath.MIN_SQRT_PRICE_LIMIT : CLMath.MAX_SQRT_PRICE_LIMIT
}),
PoolKey({
currency0: Currency.wrap(position.tokens[0]),
currency1: Currency.wrap(position.tokens[1]),
fee: position.fee,
tickSpacing: position.tickSpacing,
hooks: IHooks(position.pool)
})
);
bytes memory results = POOL_MANAGER.unlock(swapData);
// Update the balances.
BalanceDelta swapDelta = abi.decode(results, (BalanceDelta));
balances[0] = zeroToOne
? balances[0] - uint256(-int256(swapDelta.amount0()))
: balances[0] + uint256(int256(swapDelta.amount0()));
balances[1] = zeroToOne
? balances[1] + uint256(int256(swapDelta.amount1()))
: balances[1] - uint256(-int256(swapDelta.amount1()));
}
/**
* @notice Callback function executed during the unlock phase of a Uniswap V4 pool operation.
* @param data The encoded swap parameters and pool key.
* @return results The encoded BalanceDelta result from the swap operation.
*/
function unlockCallback(bytes calldata data) external payable virtual returns (bytes memory results) {
if (msg.sender != address(POOL_MANAGER)) revert OnlyPoolManager();
(SwapParams memory params, PoolKey memory poolKey) = abi.decode(data, (SwapParams, PoolKey));
// Do the swap.
BalanceDelta delta = POOL_MANAGER.swap(poolKey, params, "");
results = abi.encode(delta);
// Processes token balance changes.
_processSwapDelta(delta, poolKey.currency0, poolKey.currency1);
}
/**
* @notice Processes token balance changes resulting from a swap operation.
* @param delta The BalanceDelta containing the positive/negative changes in token amounts.
* @param currency0 The address of the first token in the pair.
* @param currency1 The address of the second token in the pair.
* @dev Handles token transfers between the contract and the Pool Manager based on delta values:
* - For tokens owed to the Pool Manager: transfers tokens and calls settle().
* - For tokens owed from the Pool Manager: calls take() to receive tokens.
*/
function _processSwapDelta(BalanceDelta delta, Currency currency0, Currency currency1) internal {
// Transfer tokens owed to the Pool Manager.
if (delta.amount0() < 0) {
POOL_MANAGER.sync(currency0);
if (currency0.isAddressZero()) {
POOL_MANAGER.settle{ value: uint128(-delta.amount0()) }();
} else {
// Transfer is properly handled by Currency library.
// forge-lint: disable-next-line(erc20-unchecked-transfer)
currency0.transfer(address(POOL_MANAGER), uint128(-delta.amount0()));
POOL_MANAGER.settle();
}
}
if (delta.amount1() < 0) {
POOL_MANAGER.sync(currency1);
// Transfer is properly handled by Currency library.
// forge-lint: disable-next-line(erc20-unchecked-transfer)
currency1.transfer(address(POOL_MANAGER), uint128(-delta.amount1()));
POOL_MANAGER.settle();
}
// Withdraw tokens that the Pool Manager owes.
if (delta.amount0() > 0) {
POOL_MANAGER.take(currency0, (address(this)), uint128(delta.amount0()));
}
if (delta.amount1() > 0) {
POOL_MANAGER.take(currency1, address(this), uint128(delta.amount1()));
}
}
/* ///////////////////////////////////////////////////////////////
MINT LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Mints a new Liquidity Position.
* @param balances The balances of the underlying tokens.
* param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
* @param amount0Desired The desired amount of token0 to mint as liquidity.
* @param amount1Desired The desired amount of token1 to mint as liquidity.
*/
function _mint(
uint256[] memory balances,
address,
PositionState memory position,
uint256 amount0Desired,
uint256 amount1Desired
) internal virtual override {
// Check if token0 is native ETH.
bool isNative = position.tokens[0] == address(0);
// Handle approvals.
if (!isNative) _checkAndApprovePermit2(position.tokens[0]);
_checkAndApprovePermit2(position.tokens[1]);
// Get new token id.
position.id = POSITION_MANAGER.nextTokenId();
// Calculate liquidity to be added.
position.liquidity = LiquidityAmounts.getLiquidityForAmounts(
uint160(position.sqrtPrice),
TickMath.getSqrtPriceAtTick(position.tickLower),
TickMath.getSqrtPriceAtTick(position.tickUpper),
amount0Desired,
amount1Desired
);
// Cache the pool key.
PoolKey memory poolKey = PoolKey({
currency0: Currency.wrap(position.tokens[0]),
currency1: Currency.wrap(position.tokens[1]),
fee: position.fee,
tickSpacing: position.tickSpacing,
hooks: IHooks(position.pool)
});
// Generate calldata to mint new position.
bytes memory actions = new bytes(3);
actions[0] = bytes1(uint8(Actions.MINT_POSITION));
actions[1] = bytes1(uint8(Actions.SETTLE_PAIR));
actions[2] = bytes1(uint8(Actions.SWEEP));
bytes[] memory params = new bytes[](3);
params[0] = abi.encode(
poolKey,
position.tickLower,
position.tickUpper,
position.liquidity,
type(uint128).max,
type(uint128).max,
address(this),
""
);
params[1] = abi.encode(poolKey.currency0, poolKey.currency1);
params[2] = abi.encode(poolKey.currency0, address(this));
// Mint the new position.
uint256 ethValue = isNative ? amount0Desired : 0;
bytes memory mintParams = abi.encode(actions, params);
POSITION_MANAGER.modifyLiquidities{ value: ethValue }(mintParams, block.timestamp);
// Update the balances, token0 might be native ETH.
balances[0] = poolKey.currency0.balanceOfSelf();
balances[1] = ERC20(position.tokens[1]).balanceOf(address(this));
}
/* ///////////////////////////////////////////////////////////////
INCREASE LIQUIDITY LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Swaps one token for another to rebalance the Liquidity Position.
* @param balances The balances of the underlying tokens.
* param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
* @param amount0Desired The desired amount of token0 to add as liquidity.
* @param amount1Desired The desired amount of token1 to add as liquidity.
*/
function _increaseLiquidity(
uint256[] memory balances,
address,
PositionState memory position,
uint256 amount0Desired,
uint256 amount1Desired
) internal virtual override {
// Check if token0 is native ETH.
bool isNative = position.tokens[0] == address(0);
// Handle approvals.
if (!isNative) _checkAndApprovePermit2(position.tokens[0]);
_checkAndApprovePermit2(position.tokens[1]);
// Calculate liquidity to be added.
position.liquidity = LiquidityAmounts.getLiquidityForAmounts(
uint160(position.sqrtPrice),
TickMath.getSqrtPriceAtTick(position.tickLower),
TickMath.getSqrtPriceAtTick(position.tickUpper),
amount0Desired,
amount1Desired
);
// Cache the currencies.
Currency currency0 = Currency.wrap(position.tokens[0]);
Currency currency1 = Currency.wrap(position.tokens[1]);
// Generate calldata to mint new position.
bytes memory actions = new bytes(3);
actions[0] = bytes1(uint8(Actions.INCREASE_LIQUIDITY));
actions[1] = bytes1(uint8(Actions.SETTLE_PAIR));
actions[2] = bytes1(uint8(Actions.SWEEP));
bytes[] memory params = new bytes[](3);
params[0] = abi.encode(position.id, position.liquidity, type(uint128).max, type(uint128).max, "");
params[1] = abi.encode(currency0, currency1);
params[2] = abi.encode(currency0, address(this));
// Mint the new position.
uint256 ethValue = isNative ? amount0Desired : 0;
bytes memory increaseLiquidityParams = abi.encode(actions, params);
POSITION_MANAGER.modifyLiquidities{ value: ethValue }(increaseLiquidityParams, block.timestamp);
// Update the balances, token0 might be native ETH.
balances[0] = currency0.balanceOfSelf();
balances[1] = ERC20(position.tokens[1]).balanceOf(address(this));
}
/* ///////////////////////////////////////////////////////////////
HELPERS
/////////////////////////////////////////////////////////////// */
/**
* @notice Ensures that the Permit2 contract has sufficient approval to spend a given token.
* @param token The contract address of the token.
*/
function _checkAndApprovePermit2(address token) internal {
if (!approved[token]) {
approved[token] = true;
ERC20(token).safeApproveWithRetry(address(PERMIT_2), type(uint256).max);
PERMIT_2.approve(token, address(POSITION_MANAGER), type(uint160).max, type(uint48).max);
}
}
/* ///////////////////////////////////////////////////////////////
NATIVE ETH HANDLER
/////////////////////////////////////////////////////////////// */
/**
* @notice Receives native ether.
*/
receive() external payable { }
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.0;
import { PositionState } from "../state/PositionState.sol";
/**
* @title Abstract base implementation for managing Liquidity Positions.
*/
abstract contract AbstractBase {
/* //////////////////////////////////////////////////////////////
EVENTS
////////////////////////////////////////////////////////////// */
event FeePaid(address indexed account, address indexed receiver, address indexed asset, uint256 amount);
event YieldClaimed(address indexed account, address indexed asset, uint256 amount);
/* ///////////////////////////////////////////////////////////////
POSITION VALIDATION
/////////////////////////////////////////////////////////////// */
/**
* @notice Returns if a position manager matches the position manager(s) of the protocol.
* @param positionManager The contract address of the position manager to check.
* @return isPositionManager_ Bool indicating if the position manager matches.
*/
function isPositionManager(address positionManager) public view virtual returns (bool isPositionManager_);
/* ///////////////////////////////////////////////////////////////
GETTERS
/////////////////////////////////////////////////////////////// */
/**
* @notice Returns the underlying assets of the pool.
* @param positionManager The contract address of the Position Manager.
* @param id The id of the Liquidity Position.
* @return token0 The contract address of token0.
* @return token1 The contract address of token1.
*/
function _getUnderlyingTokens(address positionManager, uint256 id)
internal
view
virtual
returns (address token0, address token1);
/**
* @notice Returns the position and pool related state.
* @param positionManager The contract address of the Position Manager.
* @param id The id of the Liquidity Position.
* @return position A struct with position and pool related variables.
*/
function _getPositionState(address positionManager, uint256 id)
internal
view
virtual
returns (PositionState memory position);
/**
* @notice Returns the liquidity of the Pool.
* @param position A struct with position and pool related variables.
* @return liquidity The liquidity of the Pool.
*/
function _getPoolLiquidity(PositionState memory position) internal view virtual returns (uint128 liquidity);
/**
* @notice Returns the sqrtPrice of the Pool.
* @param position A struct with position and pool related variables.
* @return sqrtPrice The sqrtPrice of the Pool.
*/
function _getSqrtPrice(PositionState memory position) internal view virtual returns (uint160 sqrtPrice);
/* ///////////////////////////////////////////////////////////////
CLAIM LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Claims fees/rewards from a Liquidity Position.
* @param balances The balances of the underlying tokens.
* @param fees The fees of the underlying tokens to be paid to the initiator.
* @param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
* @dev Must update the balances after the claim.
*/
function _claim(
uint256[] memory balances,
uint256[] memory fees,
address positionManager,
PositionState memory position,
uint256 claimFee
) internal virtual;
/* ///////////////////////////////////////////////////////////////
STAKING LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Stakes a Liquidity Position.
* @param balances The balances of the underlying tokens.
* @param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
*/
function _stake(uint256[] memory balances, address positionManager, PositionState memory position) internal virtual;
/**
* @notice Unstakes a Liquidity Position.
* @param balances The balances of the underlying tokens.
* @param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
*/
function _unstake(uint256[] memory balances, address positionManager, PositionState memory position)
internal
virtual;
/* ///////////////////////////////////////////////////////////////
BURN LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Burns the Liquidity Position.
* @param balances The balances of the underlying tokens.
* @param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
* @dev Must update the balances after the burn.
*/
function _burn(uint256[] memory balances, address positionManager, PositionState memory position) internal virtual;
/* ///////////////////////////////////////////////////////////////
SWAP LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Swaps one token for another, directly through the pool itself.
* @param balances The balances of the underlying tokens.
* @param position A struct with position and pool related variables.
* @param zeroToOne Bool indicating if token0 has to be swapped to token1 or opposite.
* @param amountOut The amount of tokenOut that must be swapped to.
* @dev Must update the balances and sqrtPrice after the swap.
*/
function _swapViaPool(uint256[] memory balances, PositionState memory position, bool zeroToOne, uint256 amountOut)
internal
virtual;
/* ///////////////////////////////////////////////////////////////
MINT LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Mints a new Liquidity Position.
* @param balances The balances of the underlying tokens.
* @param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
* @param amount0Desired The desired amount of token0 to mint as liquidity.
* @param amount1Desired The desired amount of token1 to mint as liquidity.
* @dev Must update the balances and liquidity and id after the mint.
*/
function _mint(
uint256[] memory balances,
address positionManager,
PositionState memory position,
uint256 amount0Desired,
uint256 amount1Desired
) internal virtual;
/* ///////////////////////////////////////////////////////////////
INCREASE LIQUIDITY LOGIC
/////////////////////////////////////////////////////////////// */
/**
* @notice Swaps one token for another to rebalance the Liquidity Position.
* @param balances The balances of the underlying tokens.
* @param positionManager The contract address of the Position Manager.
* @param position A struct with position and pool related variables.
* @param amount0Desired The desired amount of token0 to add as liquidity.
* @param amount1Desired The desired amount of token1 to add as liquidity.
* @dev Must update the balances and delta liquidity after the increase.
*/
function _increaseLiquidity(
uint256[] memory balances,
address positionManager,
PositionState memory position,
uint256 amount0Desired,
uint256 amount1Desired
) internal virtual;
/* ///////////////////////////////////////////////////////////////
ERC721 HANDLER FUNCTION
/////////////////////////////////////////////////////////////// */
/**
* @notice Returns the onERC721Received selector.
* @dev Required to receive ERC721 tokens via safeTransferFrom.
*/
// forge-lint: disable-next-item(mixed-case-function)
function onERC721Received(address, address, uint256, bytes calldata) public pure returns (bytes4) {
return this.onERC721Received.selector;
}
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.0;
// Struct with information to pass to and from the actionTarget.
struct ActionData {
// Array of the contract addresses of the assets.
address[] assets;
// Array of the IDs of the assets.
uint256[] assetIds;
// Array with the amounts of the assets.
uint256[] assetAmounts;
// Array with the types of the assets.
uint256[] assetTypes;
}
interface IActionBase {
/**
* @notice Calls an external target contract with arbitrary calldata.
* @param actionTargetData A bytes object containing the encoded input for the actionTarget.
* @return resultData An actionAssetData struct with the final balances of this actionTarget contract.
*/
function executeAction(bytes calldata actionTargetData) external returns (ActionData memory);
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.0;
import { ActionData } from "../../../lib/accounts-v2/src/interfaces/IActionBase.sol";
import { IPermit2 } from "../../../lib/accounts-v2/src/interfaces/IPermit2.sol";
library ArcadiaLogic {
/**
* @notice Encodes the action data for the flash-action used to manage a Liquidity Position.
* @param positionManager The address of the position manager.
* @param id The id of the Liquidity Position.
* @param token0 The contract address of token0.
* @param token1 The contract address of token1.
* @param amount0 The amount of token0 to transfer.
* @param amount1 The amount of token1 to transfer.
* @param actionTargetData The data to be passed to the action target.
* @return actionData Bytes string with the encoded data.
*/
function _encodeAction(
address positionManager,
uint256 id,
address token0,
address token1,
uint256 amount0,
uint256 amount1,
bytes memory actionTargetData
) internal pure returns (bytes memory actionData) {
// Calculate the number of assets to encode.
uint256 count = 1;
if (amount0 > 0) count++;
if (amount1 > 0) count++;
address[] memory assets = new address[](count);
uint256[] memory ids = new uint256[](count);
uint256[] memory amounts = new uint256[](count);
uint256[] memory types = new uint256[](count);
// Encode liquidity position.
assets[0] = positionManager;
ids[0] = id;
amounts[0] = 1;
types[0] = 2;
// Encode underlying assets of the liquidity position.
uint256 index = 1;
if (amount0 > 0) {
assets[1] = token0;
amounts[1] = amount0;
types[1] = 1;
index = 2;
}
if (amount1 > 0) {
assets[index] = token1;
amounts[index] = amount1;
types[index] = 1;
}
ActionData memory assetData =
ActionData({ assets: assets, assetIds: ids, assetAmounts: amounts, assetTypes: types });
// Empty data objects that have to be encoded when calling flashAction(), but that are not used for this specific flash-action.
bytes memory signature;
ActionData memory transferFromOwner;
IPermit2.PermitBatchTransferFrom memory permit;
// Encode the actionData.
actionData = abi.encode(assetData, transferFromOwner, permit, signature, actionTargetData);
}
/**
* @notice Encodes the deposit data after the flash-action is executed.
* @param positionManager The address of the position manager.
* @param id The id of the Liquidity Position.
* @param tokens The contract addresses of the tokens to deposit.
* @param balances The balances of the tokens to deposit.
* @param count The number of tokens to deposit.
* @return depositData Bytes string with the encoded data.
*/
function _encodeDeposit(
address positionManager,
uint256 id,
address[] memory tokens,
uint256[] memory balances,
uint256 count
) internal pure returns (ActionData memory depositData) {
address[] memory assets = new address[](count);
uint256[] memory ids = new uint256[](count);
uint256[] memory amounts = new uint256[](count);
uint256[] memory types = new uint256[](count);
// Encode liquidity position.
assets[0] = positionManager;
ids[0] = id;
amounts[0] = 1;
types[0] = 2;
// Encode underlying assets of the liquidity position.
if (count > 1) {
uint256 i = 1;
for (uint256 j; j < balances.length; j++) {
if (balances[j] > 0) {
assets[i] = tokens[j];
amounts[i] = balances[j];
types[i] = 1;
i++;
}
}
}
depositData = ActionData({ assets: assets, assetIds: ids, assetAmounts: amounts, assetTypes: types });
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Modern, minimalist, and gas efficient ERC-721 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
abstract contract ERC721 {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 indexed id);
event Approval(address indexed owner, address indexed spender, uint256 indexed id);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE/LOGIC
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
function tokenURI(uint256 id) public view virtual returns (string memory);
/*//////////////////////////////////////////////////////////////
ERC721 BALANCE/OWNER STORAGE
//////////////////////////////////////////////////////////////*/
mapping(uint256 => address) internal _ownerOf;
mapping(address => uint256) internal _balanceOf;
function ownerOf(uint256 id) public view virtual returns (address owner) {
require((owner = _ownerOf[id]) != address(0), "NOT_MINTED");
}
function balanceOf(address owner) public view virtual returns (uint256) {
require(owner != address(0), "ZERO_ADDRESS");
return _balanceOf[owner];
}
/*//////////////////////////////////////////////////////////////
ERC721 APPROVAL STORAGE
//////////////////////////////////////////////////////////////*/
mapping(uint256 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(string memory _name, string memory _symbol) {
name = _name;
symbol = _symbol;
}
/*//////////////////////////////////////////////////////////////
ERC721 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 id) public virtual {
address owner = _ownerOf[id];
require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED");
getApproved[id] = spender;
emit Approval(owner, spender, id);
}
function setApprovalForAll(address operator, bool approved) public virtual {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function transferFrom(
address from,
address to,
uint256 id
) public virtual {
require(from == _ownerOf[id], "WRONG_FROM");
require(to != address(0), "INVALID_RECIPIENT");
require(
msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id],
"NOT_AUTHORIZED"
);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
unchecked {
_balanceOf[from]--;
_balanceOf[to]++;
}
_ownerOf[id] = to;
delete getApproved[id];
emit Transfer(from, to, id);
}
function safeTransferFrom(
address from,
address to,
uint256 id
) public virtual {
transferFrom(from, to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
function safeTransferFrom(
address from,
address to,
uint256 id,
bytes calldata data
) public virtual {
transferFrom(from, to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
/*//////////////////////////////////////////////////////////////
ERC165 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return
interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721
interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 id) internal virtual {
require(to != address(0), "INVALID_RECIPIENT");
require(_ownerOf[id] == address(0), "ALREADY_MINTED");
// Counter overflow is incredibly unrealistic.
unchecked {
_balanceOf[to]++;
}
_ownerOf[id] = to;
emit Transfer(address(0), to, id);
}
function _burn(uint256 id) internal virtual {
address owner = _ownerOf[id];
require(owner != address(0), "NOT_MINTED");
// Ownership check above ensures no underflow.
unchecked {
_balanceOf[owner]--;
}
delete _ownerOf[id];
delete getApproved[id];
emit Transfer(owner, address(0), id);
}
/*//////////////////////////////////////////////////////////////
INTERNAL SAFE MINT LOGIC
//////////////////////////////////////////////////////////////*/
function _safeMint(address to, uint256 id) internal virtual {
_mint(to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
function _safeMint(
address to,
uint256 id,
bytes memory data
) internal virtual {
_mint(to, id);
require(
to.code.length == 0 ||
ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) ==
ERC721TokenReceiver.onERC721Received.selector,
"UNSAFE_RECIPIENT"
);
}
}
/// @notice A generic interface for a contract which properly accepts ERC721 tokens.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
abstract contract ERC721TokenReceiver {
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external virtual returns (bytes4) {
return ERC721TokenReceiver.onERC721Received.selector;
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
/*//////////////////////////////////////////////////////////////
SIMPLIFIED FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
uint256 internal constant MAX_UINT256 = 2**256 - 1;
uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
}
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
}
function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
}
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
}
/*//////////////////////////////////////////////////////////////
LOW LEVEL FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function mulDivDown(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
revert(0, 0)
}
// Divide x * y by the denominator.
z := div(mul(x, y), denominator)
}
}
function mulDivUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
revert(0, 0)
}
// If x * y modulo the denominator is strictly greater than 0,
// 1 is added to round up the division of x * y by the denominator.
z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
}
}
function rpow(
uint256 x,
uint256 n,
uint256 scalar
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := scalar
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store scalar in z for now.
z := scalar
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, scalar)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, scalar)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, scalar)
}
}
}
}
}
/*//////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let y := x // We start y at x, which will help us make our initial estimate.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// We check y >= 2^(k + 8) but shift right by k bits
// each branch to ensure that if x >= 256, then y >= 256.
if iszero(lt(y, 0x10000000000000000000000000000000000)) {
y := shr(128, y)
z := shl(64, z)
}
if iszero(lt(y, 0x1000000000000000000)) {
y := shr(64, y)
z := shl(32, z)
}
if iszero(lt(y, 0x10000000000)) {
y := shr(32, y)
z := shl(16, z)
}
if iszero(lt(y, 0x1000000)) {
y := shr(16, y)
z := shl(8, z)
}
// Goal was to get z*z*y within a small factor of x. More iterations could
// get y in a tighter range. Currently, we will have y in [256, 256*2^16).
// We ensured y >= 256 so that the relative difference between y and y+1 is small.
// That's not possible if x < 256 but we can just verify those cases exhaustively.
// Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
// Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
// Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.
// For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
// (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.
// Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
// sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.
// There is no overflow risk here since y < 2^136 after the first branch above.
z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If x+1 is a perfect square, the Babylonian method cycles between
// floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
// Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
// If you don't care whether the floor or ceil square root is returned, you can remove this statement.
z := sub(z, lt(div(x, z), z))
}
}
function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Mod x by y. Note this will return
// 0 instead of reverting if y is zero.
z := mod(x, y)
}
}
function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
// Divide x by y. Note this will return
// 0 instead of reverting if y is zero.
r := div(x, y)
}
}
function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Add 1 to x * y if x % y > 0. Note this will
// return 0 instead of reverting if y is zero.
z := add(gt(mod(x, y), 0), div(x, y))
}
}
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.0;
import { Owned } from "../../lib/accounts-v2/lib/solmate/src/auth/Owned.sol";
/**
* @title Guardian
* @author Pragma Labs
* @notice Pause guardian for an Asset Manager.
*/
abstract contract Guardian is Owned {
/* //////////////////////////////////////////////////////////////
STORAGE
////////////////////////////////////////////////////////////// */
// Flag indicating if the Asset Manager is paused.
bool public paused;
// Address of the Guardian.
address public guardian;
/* //////////////////////////////////////////////////////////////
ERRORS
////////////////////////////////////////////////////////////// */
error Paused();
error OnlyGuardian();
/* //////////////////////////////////////////////////////////////
EVENTS
////////////////////////////////////////////////////////////// */
event GuardianChanged(address indexed user, address indexed newGuardian);
event PauseFlagsUpdated(bool pauseUpdate);
/* //////////////////////////////////////////////////////////////
MODIFIERS
////////////////////////////////////////////////////////////// */
/**
* @dev Only guardians can call functions with this modifier.
*/
modifier onlyGuardian() {
if (msg.sender != guardian) revert OnlyGuardian();
_;
}
/**
* @dev Throws if the Asset Manager is paused.
*/
modifier whenNotPaused() {
if (paused) revert Paused();
_;
}
/* //////////////////////////////////////////////////////////////
CONSTRUCTOR
////////////////////////////////////////////////////////////// */
/**
* @param owner_ The address of the Owner.
*/
constructor(address owner_) Owned(owner_) { }
/* //////////////////////////////////////////////////////////////
GUARDIAN LOGIC
////////////////////////////////////////////////////////////// */
/**
* @notice Sets a new guardian.
* @param guardian_ The address of the new guardian.
*/
function changeGuardian(address guardian_) external onlyOwner {
emit GuardianChanged(msg.sender, guardian = guardian_);
}
/* //////////////////////////////////////////////////////////////
PAUSING LOGIC
////////////////////////////////////////////////////////////// */
/**
* @notice Pauses the Asset Manager.
*/
function pause() external onlyGuardian whenNotPaused {
emit PauseFlagsUpdated(paused = true);
}
/**
* @notice Sets the pause flag of the Asset Manager.
* @param paused_ Flag indicating if the Asset Manager is paused.
*/
function setPauseFlag(bool paused_) external onlyOwner {
emit PauseFlagsUpdated(paused = paused_);
}
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.8.0;
interface IAccount {
// forge-lint: disable-next-line(mixed-case-function)
function ACCOUNT_VERSION() external returns (uint256 version);
function flashAction(address actionTarget, bytes calldata actionData) external;
function owner() external returns (address owner_);
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.8.0;
interface IArcadiaFactory {
/**
* @notice Checks if a contract is an Account.
* @param account The contract address of the Account.
* @return bool indicating if the address is an Account or not.
*/
function isAccount(address account) external view returns (bool);
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.8.0;
interface IRouterTrampoline {
function execute(address router, bytes calldata callData, address tokenIn, address tokenOut, uint256 amountIn)
external
returns (uint256 balanceIn, uint256 balanceOut);
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.0;
import { FixedPointMathLib } from "../../../lib/accounts-v2/lib/solmate/src/utils/FixedPointMathLib.sol";
import { LiquidityAmounts } from "./LiquidityAmounts.sol";
import { CLMath } from "./CLMath.sol";
struct RebalanceParams {
// Bool indicating if token0 has to be swapped to token1 or opposite.
bool zeroToOne;
// The amount of initiator fee, in tokenIn.
uint256 amountInitiatorFee;
// The minimum amount of liquidity that must be added to the position.
uint256 minLiquidity;
// An approximation of the amount of tokenIn, based on the optimal swap through the pool itself without slippage.
uint256 amountIn;
// An approximation of the amount of tokenOut, based on the optimal swap through the pool itself without slippage.
uint256 amountOut;
}
library RebalanceLogic {
using FixedPointMathLib for uint256;
/**
* @notice Returns the parameters and constraints to rebalance the position.
* Both parameters and constraints are calculated based on a hypothetical swap (in the pool itself with fees but without slippage),
* that maximizes the amount of liquidity that can be added to the positions (no leftovers of either token0 or token1).
* @param minLiquidityRatio The ratio of the minimum amount of liquidity that must be minted,
* relative to the hypothetical amount of liquidity when we rebalance without slippage, with 18 decimals precision.
* @param poolFee The fee of the pool, with 6 decimals precision.
* @param initiatorFee The fee of the initiator, with 18 decimals precision.
* @param sqrtPrice The square root of the price (token1/token0), with 96 binary precision.
* @param sqrtRatioLower The square root price of the lower tick of the liquidity position, with 96 binary precision.
* @param sqrtRatioUpper The square root price of the upper tick of the liquidity position, with 96 binary precision.
* @param balance0 The amount of token0 that is available for the rebalance.
* @param balance1 The amount of token1 that is available for the rebalance.
* @return rebalanceParams A struct with the rebalance parameters.
*/
function _getRebalanceParams(
uint256 minLiquidityRatio,
uint256 poolFee,
uint256 initiatorFee,
uint256 sqrtPrice,
uint256 sqrtRatioLower,
uint256 sqrtRatioUpper,
uint256 balance0,
uint256 balance1
) internal pure returns (RebalanceParams memory rebalanceParams) {
// Total fee is pool fee + initiator fee, with 18 decimals precision.
// Since Uniswap uses 6 decimals precision for the fee, we have to multiply the pool fee by 1e12.
uint256 fee;
unchecked {
fee = initiatorFee + poolFee * 1e12;
}
// Calculate the swap parameters
(bool zeroToOne, uint256 amountIn, uint256 amountOut) =
CLMath._getSwapParams(sqrtPrice, sqrtRatioLower, sqrtRatioUpper, balance0, balance1, fee);
// Calculate the maximum amount of liquidity that can be added to the position.
uint256 minLiquidity;
{
// forge-lint: disable-next-item(unsafe-typecast)
uint256 liquidity = LiquidityAmounts.getLiquidityForAmounts(
uint160(sqrtPrice),
uint160(sqrtRatioLower),
uint160(sqrtRatioUpper),
zeroToOne ? balance0 - amountIn : balance0 + amountOut,
zeroToOne ? balance1 + amountOut : balance1 - amountIn
);
minLiquidity = liquidity.mulDivDown(minLiquidityRatio, 1e18);
}
// Get initiator fee amount and the actual amountIn of the swap (without initiator fee).
uint256 amountInitiatorFee;
unchecked {
amountInitiatorFee = amountIn.mulDivDown(initiatorFee, 1e18);
amountIn = amountIn - amountInitiatorFee;
}
rebalanceParams = RebalanceParams({
zeroToOne: zeroToOne,
amountInitiatorFee: amountInitiatorFee,
minLiquidity: minLiquidity,
amountIn: amountIn,
amountOut: amountOut
});
}
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.0;
import { FixedPointMathLib } from "../../../lib/accounts-v2/lib/solmate/src/utils/FixedPointMathLib.sol";
import { LiquidityAmounts } from "./LiquidityAmounts.sol";
import { SqrtPriceMath } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/libraries/SqrtPriceMath.sol";
library RebalanceOptimizationMath {
using FixedPointMathLib for uint256;
// The minimal relative difference between liquidity0 and liquidity1, with 18 decimals precision.
uint256 internal constant CONVERGENCE_THRESHOLD = 1e6;
// The maximal number of iterations to find the optimal swap parameters.
uint256 internal constant MAX_ITERATIONS = 100;
/**
* @notice Iteratively calculates the amountOut for a swap through the pool itself, that maximizes the amount of liquidity that is added.
* The calculations take both fees and slippage into account, but assume constant liquidity.
* @param zeroToOne Bool indicating if token0 has to be swapped to token1 or opposite.
* @param fee The fee of the pool, with 6 decimals precision.
* @param usableLiquidity The amount of active liquidity in the pool, at the current tick.
* @param sqrtPriceOld The square root of the pool price (token1/token0) before the swap, with 96 binary precision.
* @param sqrtRatioLower The square root price of the lower tick of the liquidity position, with 96 binary precision.
* @param sqrtRatioUpper The square root price of the upper tick of the liquidity position, with 96 binary precision.
* @param amount0 The balance of token0 before the swap.
* @param amount1 The balance of token1 before the swap.
* @param amountIn An approximation of the amount of tokenIn, based on the optimal swap through the pool itself without slippage.
* @param amountOut An approximation of the amount of tokenOut, based on the optimal swap through the pool itself without slippage.
* @return amountOut The amount of tokenOut.
* @dev The optimal amountIn and amountOut are defined as the amounts that maximize the amount of liquidity that can be added to the position.
* This means that there are no leftovers of either token0 or token1,
* and liquidity0 (calculated via getLiquidityForAmount0) will be exactly equal to liquidity1 (calculated via getLiquidityForAmount1).
* @dev The optimal amountIn and amountOut depend on the sqrtPrice of the pool via the liquidity calculations,
* but the sqrtPrice in turn depends on the amountIn and amountOut via the swap calculations.
* Since both are highly non-linear, this problem is (according to our understanding) not analytically solvable.
* Therefore we use an iterative approach to find the optimal swap parameters.
* The stop criterion is defined when the relative difference between liquidity0 and liquidity1 is below the convergence threshold.
* @dev Convergence is not guaranteed, worst case or the transaction reverts, or a non-optimal swap is performed,
* But then minLiquidity enforces that either enough liquidity is minted or the transaction will revert.
* @dev We assume constant active liquidity when calculating the swap parameters.
* For illiquid pools, or positions that are large relatively to the pool liquidity, this might result in reverting rebalances.
* But since a minimum amount of liquidity is enforced, should not lead to loss of principal.
*/
function _getAmountOutWithSlippage(
bool zeroToOne,
uint256 fee,
uint128 usableLiquidity,
uint160 sqrtPriceOld,
uint160 sqrtRatioLower,
uint160 sqrtRatioUpper,
uint256 amount0,
uint256 amount1,
uint256 amountIn,
uint256 amountOut
) internal pure returns (uint256) {
uint160 sqrtPriceNew;
bool stopCondition;
// We iteratively solve for sqrtPrice, amountOut and amountIn, so that the maximal amount of liquidity can be added to the position.
for (uint256 i = 0; i < MAX_ITERATIONS; ++i) {
// Find a better approximation for sqrtPrice, given the best approximations for the optimal amountIn and amountOut.
sqrtPriceNew = _approximateSqrtPriceNew(zeroToOne, fee, usableLiquidity, sqrtPriceOld, amountIn, amountOut);
// If the position is out of range, we can calculate the exact solution.
if (sqrtPriceNew >= sqrtRatioUpper) {
// New position is out of range and fully in token 1.
// Rebalance to a single-sided liquidity position in token 1.
// We ignore one edge case: Swapping token0 to token1 decreases the sqrtPrice,
// hence a swap for a position that is just out of range might become in range due to slippage.
// This might lead to a suboptimal rebalance, which worst case results in too little liquidity and the rebalance reverts.
return _getAmount1OutFromAmount0In(fee, usableLiquidity, sqrtPriceOld, amount0);
} else if (sqrtPriceNew <= sqrtRatioLower) {
// New position is out of range and fully in token 0.
// Rebalance to a single-sided liquidity position in token 0.
// We ignore one edge case: Swapping token1 to token0 increases the sqrtPrice,
// hence a swap for a position that is just out of range might become in range due to slippage.
// This might lead to a suboptimal rebalance, which worst case results in too little liquidity and the rebalance reverts.
return _getAmount0OutFromAmount1In(fee, usableLiquidity, sqrtPriceOld, amount1);
}
// If the position is not out of range, calculate the amountIn and amountOut, given the new approximated sqrtPrice.
(amountIn, amountOut) = _getSwapParamsExact(zeroToOne, fee, usableLiquidity, sqrtPriceOld, sqrtPriceNew);
// Given the new approximated sqrtPriceNew and its swap amounts,
// calculate a better approximation for the optimal amountIn and amountOut, that would maximize the liquidity provided
// (no leftovers of either token0 or token1).
(stopCondition, amountIn, amountOut) = _approximateOptimalSwapAmounts(
zeroToOne, sqrtRatioLower, sqrtRatioUpper, amount0, amount1, amountIn, amountOut, sqrtPriceNew
);
// Check if stop condition of iteration is met:
// The relative difference between liquidity0 and liquidity1 is below the convergence threshold.
if (stopCondition) return amountOut;
// If not, we do an extra iteration with our better approximated amountIn and amountOut.
}
// If solution did not converge within MAX_ITERATIONS steps, we use the amountOut of the last iteration step.
return amountOut;
}
/**
* @notice Approximates the SqrtPrice after the swap, given an approximation for the amountIn and amountOut that maximize liquidity added.
* @param zeroToOne Bool indicating if token0 has to be swapped to token1 or opposite.
* @param fee The fee of the pool, with 6 decimals precision.
* @param usableLiquidity The amount of active liquidity in the pool, at the current tick.
* @param sqrtPriceOld The SqrtPrice before the swap.
* @param amountIn An approximation of the amount of tokenIn, that maximize liquidity added.
* @param amountOut An approximation of the amount of tokenOut, that maximize liquidity added.
* @return sqrtPriceNew The approximation of the SqrtPrice after the swap.
*/
function _approximateSqrtPriceNew(
bool zeroToOne,
uint256 fee,
uint128 usableLiquidity,
uint160 sqrtPriceOld,
uint256 amountIn,
uint256 amountOut
) internal pure returns (uint160 sqrtPriceNew) {
unchecked {
// Calculate the exact sqrtPriceNew for both amountIn and amountOut.
// Both solutions will be different, but they will converge with every iteration closer to the same solution.
uint256 amountInLessFee = amountIn.mulDivDown(1e6 - fee, 1e6);
uint256 sqrtPriceNew0;
uint256 sqrtPriceNew1;
if (zeroToOne) {
sqrtPriceNew0 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(
sqrtPriceOld, usableLiquidity, amountInLessFee, true
);
sqrtPriceNew1 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(
sqrtPriceOld, usableLiquidity, amountOut, false
);
} else {
sqrtPriceNew0 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(
sqrtPriceOld, usableLiquidity, amountOut, false
);
sqrtPriceNew1 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(
sqrtPriceOld, usableLiquidity, amountInLessFee, true
);
}
// Calculate the new best approximation as the arithmetic average of both solutions (rounded towards current price).
// We could as well use the geometric average, but empirically we found no difference in conversion speed,
// and the geometric average is more expensive to calculate.
// Unchecked + unsafe cast: sqrtPriceNew0 and sqrtPriceNew1 are always smaller than type(uint160).max.
sqrtPriceNew = zeroToOne
? uint160(FixedPointMathLib.unsafeDiv(sqrtPriceNew0 + sqrtPriceNew1, 2))
: uint160(FixedPointMathLib.unsafeDivUp(sqrtPriceNew0 + sqrtPriceNew1, 2));
}
}
/**
* @notice Calculates the amountOut of token1, for a given amountIn of token0.
* @param fee The fee of the pool, with 6 decimals precision.
* @param usableLiquidity The amount of active liquidity in the pool, at the current tick.
* @param sqrtPriceOld The SqrtPrice before the swap.
* @param amount0 The balance of token0 before the swap.
* @return amountOut The amount of token1 that is swapped to.
* @dev The calculations take both fees and slippage into account, but assume constant liquidity.
*/
function _getAmount1OutFromAmount0In(uint256 fee, uint128 usableLiquidity, uint160 sqrtPriceOld, uint256 amount0)
internal
pure
returns (uint256 amountOut)
{
unchecked {
uint256 amountInLessFee = amount0.mulDivUp(1e6 - fee, 1e6);
uint160 sqrtPriceNew = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(
sqrtPriceOld, usableLiquidity, amountInLessFee, true
);
amountOut = SqrtPriceMath.getAmount1Delta(sqrtPriceNew, sqrtPriceOld, usableLiquidity, false);
}
}
/**
* @notice Calculates the amountOut of token0, for a given amountIn of token1.
* @param fee The fee of the pool, with 6 decimals precision.
* @param usableLiquidity The amount of active liquidity in the pool, at the current tick.
* @param sqrtPriceOld The SqrtPrice before the swap.
* @param amount1 The balance of token1 before the swap.
* @return amountOut The amount of token0 that is swapped to.
* @dev The calculations take both fees and slippage into account, but assume constant liquidity.
*/
function _getAmount0OutFromAmount1In(uint256 fee, uint128 usableLiquidity, uint160 sqrtPriceOld, uint256 amount1)
internal
pure
returns (uint256 amountOut)
{
unchecked {
uint256 amountInLessFee = amount1.mulDivUp(1e6 - fee, 1e6);
uint160 sqrtPriceNew = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(
sqrtPriceOld, usableLiquidity, amountInLessFee, true
);
amountOut = SqrtPriceMath.getAmount0Delta(sqrtPriceOld, sqrtPriceNew, usableLiquidity, false);
}
}
/**
* @notice Calculates the amountIn and amountOut of token0, for a given SqrtPrice after the swap.
* @param zeroToOne Bool indicating if token0 has to be swapped to token1 or opposite.
* @param fee The fee of the pool, with 6 decimals precision.
* @param usableLiquidity The amount of active liquidity in the pool, at the current tick.
* @param sqrtPriceOld The SqrtPrice before the swap.
* @param sqrtPriceNew The SqrtPrice after the swap.
* @return amountIn The amount of tokenIn.
* @return amountOut The amount of tokenOut.
* @dev The calculations take both fees and slippage into account, but assume constant liquidity.
*/
function _getSwapParamsExact(
bool zeroToOne,
uint256 fee,
uint128 usableLiquidity,
uint160 sqrtPriceOld,
uint160 sqrtPriceNew
) internal pure returns (uint256 amountIn, uint256 amountOut) {
unchecked {
if (zeroToOne) {
uint256 amountInLessFee =
SqrtPriceMath.getAmount0Delta(sqrtPriceNew, sqrtPriceOld, usableLiquidity, true);
amountIn = amountInLessFee.mulDivUp(1e6, 1e6 - fee);
amountOut = SqrtPriceMath.getAmount1Delta(sqrtPriceNew, sqrtPriceOld, usableLiquidity, false);
} else {
uint256 amountInLessFee =
SqrtPriceMath.getAmount1Delta(sqrtPriceOld, sqrtPriceNew, usableLiquidity, true);
amountIn = amountInLessFee.mulDivUp(1e6, 1e6 - fee);
amountOut = SqrtPriceMath.getAmount0Delta(sqrtPriceOld, sqrtPriceNew, usableLiquidity, false);
}
}
}
/**
* @notice Approximates the amountIn and amountOut that maximize liquidity added,
* given an approximation for the SqrtPrice after the swap and an approximation of the balances of token0 and token1 after the swap.
* @param zeroToOne Bool indicating if token0 has to be swapped to token1 or opposite.
* @param sqrtRatioLower The square root price of the lower tick of the liquidity position, with 96 binary precision.
* @param sqrtRatioUpper The square root price of the upper tick of the liquidity position, with 96 binary precision.
* @param amount0 The balance of token0 before the swap.
* @param amount1 The balance of token1 before the swap.
* @param amountIn An approximation of the amount of tokenIn, used to calculate the approximated balances after the swap.
* @param amountOut An approximation of the amount of tokenOut, used to calculate the approximated balances after the swap.
* @param sqrtPrice An approximation of the SqrtPrice after the swap.
* @return converged Bool indicating if the stop criterion of iteration is met.
* @return amountIn_ The new approximation of the amount of tokenIn that maximize liquidity added.
* @return amountOut_ The new approximation of the amount of amountOut that maximize liquidity added.
*/
function _approximateOptimalSwapAmounts(
bool zeroToOne,
uint160 sqrtRatioLower,
uint160 sqrtRatioUpper,
uint256 amount0,
uint256 amount1,
uint256 amountIn,
uint256 amountOut,
uint160 sqrtPrice
) internal pure returns (bool, uint256, uint256) {
unchecked {
// Calculate the liquidity for the given approximated sqrtPrice and the approximated balances of token0 and token1 after the swap.
uint256 liquidity0;
uint256 liquidity1;
if (zeroToOne) {
liquidity0 = LiquidityAmounts.getLiquidityForAmount0(
sqrtPrice, sqrtRatioUpper, amount0 > amountIn ? amount0 - amountIn : 0
);
liquidity1 = LiquidityAmounts.getLiquidityForAmount1(sqrtRatioLower, sqrtPrice, amount1 + amountOut);
} else {
liquidity0 = LiquidityAmounts.getLiquidityForAmount0(sqrtPrice, sqrtRatioUpper, amount0 + amountOut);
liquidity1 = LiquidityAmounts.getLiquidityForAmount1(
sqrtRatioLower, sqrtPrice, amount1 > amountIn ? amount1 - amountIn : 0
);
}
// Calculate the relative difference of liquidity0 and liquidity1.
uint256 relDiff = 1e18
- (liquidity0 < liquidity1
? liquidity0.mulDivDown(1e18, liquidity1)
: liquidity1.mulDivDown(1e18, liquidity0));
// In the optimal solution liquidity0 equals liquidity1,
// and there are no leftovers for token0 or token1 after minting the liquidity.
// Hence the relative distance between liquidity0 and liquidity1
// is a good estimator how close we are to the optimal solution.
bool converged = relDiff < CONVERGENCE_THRESHOLD;
// The new approximated liquidity is the minimum of liquidity0 and liquidity1.
// Calculate the new approximated amountIn or amountOut,
// for which this liquidity would be the optimal solution.
if (liquidity0 < liquidity1) {
uint256 amount1New = SqrtPriceMath.getAmount1Delta(
sqrtRatioLower, sqrtPrice, LiquidityAmounts.toUint128(liquidity0), true
);
zeroToOne
// Since amountOut can't be negative, we use 90% of the previous amountOut as a fallback.
? amountOut = amount1New > amount1 ? amount1New - amount1 : amountOut.mulDivDown(9, 10)
: amountIn = amount1 - amount1New;
} else {
uint256 amount0New = SqrtPriceMath.getAmount0Delta(
sqrtPrice, sqrtRatioUpper, LiquidityAmounts.toUint128(liquidity1), true
);
zeroToOne
? amountIn = amount0 - amount0New
// Since amountOut can't be negative, we use 90% of the previous amountOut as a fallback.
: amountOut = amount0New > amount0 ? amount0New - amount0 : amountOut.mulDivDown(9, 10);
}
return (converged, amountIn, amountOut);
}
}
}/**
* https://github.com/Vectorized/solady/blob/main/src/utils/SafeTransferLib.sol
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.8.0;
import { ERC20 } from "../../lib/accounts-v2/lib/solmate/src/tokens/ERC20.sol";
library SafeApprove {
/**
* @notice Approves an amount of token for a spender.
* @param token The contract address of the token being approved.
* @param to The spender.
* @param amount the amount of token being approved.
* @dev Copied from Solady safeApproveWithRetry (MIT): https://github.com/Vectorized/solady/blob/main/src/utils/SafeTransferLib.sol
* @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
* If the initial attempt to approve fails, attempts to reset the approved amount to zero,
* then retries the approval again (some tokens, e.g. USDT, requires this).
* Reverts upon failure.
*/
function safeApproveWithRetry(ERC20 token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
if iszero(
and(
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*//////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*//////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*//////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*//////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Library to define different pool actions.
/// @dev These are suggested common commands, however additional commands should be defined as required
/// Some of these actions are not supported in the Router contracts or Position Manager contracts, but are left as they may be helpful commands for other peripheral contracts.
library Actions {
// pool actions
// liquidity actions
uint256 internal constant INCREASE_LIQUIDITY = 0x00;
uint256 internal constant DECREASE_LIQUIDITY = 0x01;
uint256 internal constant MINT_POSITION = 0x02;
uint256 internal constant BURN_POSITION = 0x03;
uint256 internal constant INCREASE_LIQUIDITY_FROM_DELTAS = 0x04;
uint256 internal constant MINT_POSITION_FROM_DELTAS = 0x05;
// swapping
uint256 internal constant SWAP_EXACT_IN_SINGLE = 0x06;
uint256 internal constant SWAP_EXACT_IN = 0x07;
uint256 internal constant SWAP_EXACT_OUT_SINGLE = 0x08;
uint256 internal constant SWAP_EXACT_OUT = 0x09;
// donate
// note this is not supported in the position manager or router
uint256 internal constant DONATE = 0x0a;
// closing deltas on the pool manager
// settling
uint256 internal constant SETTLE = 0x0b;
uint256 internal constant SETTLE_ALL = 0x0c;
uint256 internal constant SETTLE_PAIR = 0x0d;
// taking
uint256 internal constant TAKE = 0x0e;
uint256 internal constant TAKE_ALL = 0x0f;
uint256 internal constant TAKE_PORTION = 0x10;
uint256 internal constant TAKE_PAIR = 0x11;
uint256 internal constant CLOSE_CURRENCY = 0x12;
uint256 internal constant CLEAR_OR_TAKE = 0x13;
uint256 internal constant SWEEP = 0x14;
uint256 internal constant WRAP = 0x15;
uint256 internal constant UNWRAP = 0x16;
// minting/burning 6909s to close deltas
// note this is not supported in the position manager or router
uint256 internal constant MINT_6909 = 0x17;
uint256 internal constant BURN_6909 = 0x18;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.0;
import { FixedPoint96 } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/libraries/FixedPoint96.sol";
import { FixedPointMathLib } from "../../../lib/accounts-v2/lib/solmate/src/utils/FixedPointMathLib.sol";
import { FullMath } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/libraries/FullMath.sol";
import { TickMath } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/libraries/TickMath.sol";
library CLMath {
using FixedPointMathLib for uint256;
/* //////////////////////////////////////////////////////////////
CONSTANTS
////////////////////////////////////////////////////////////// */
// The minimum sqrtPriceLimit for a swap.
uint160 internal constant MIN_SQRT_PRICE_LIMIT = TickMath.MIN_SQRT_PRICE + 1;
// The maximum sqrtPriceLimit for a swap.
uint160 internal constant MAX_SQRT_PRICE_LIMIT = TickMath.MAX_SQRT_PRICE - 1;
// The binary precision of sqrtPrice squared.
uint256 internal constant Q192 = FixedPoint96.Q96 ** 2;
/* //////////////////////////////////////////////////////////////
MATHS
////////////////////////////////////////////////////////////// */
/**
* @notice Calculates the swap parameters, calculated based on a hypothetical swap (in the pool itself with fees but without slippage).
* that maximizes the amount of liquidity that can be added to the positions (no leftovers of either token0 or token1).
* @param sqrtPrice The square root of the price (token1/token0), with 96 binary precision.
* @param sqrtRatioLower The square root price of the lower tick of the liquidity position, with 96 binary precision.
* @param sqrtRatioUpper The square root price of the upper tick of the liquidity position, with 96 binary precision.
* @param balance0 The amount of token0 that is available for the rebalance.
* @param balance1 The amount of token1 that is available for the rebalance.
* @param fee The swapping fees, with 18 decimals precision.
* @return zeroToOne Bool indicating if token0 has to be swapped to token1 or opposite.
* @return amountIn An approximation of the amount of tokenIn, based on the optimal swap through the pool itself without slippage.
* @return amountOut An approximation of the amount of tokenOut, based on the optimal swap through the pool itself without slippage.
* @dev The swap parameters are derived as follows:
* 1) First we check if the position is in or out of range.
* - If the current price is above the position, the solution is trivial: we swap the full position to token1.
* - If the current price is below the position, similar, we swap the full position to token0.
* - If the position is in range we proceed with step 2.
*
* 2) If the position is in range, we start with calculating the "Target Ratio" and "Current Ratio".
* Both ratio's are defined as the value of the amount of token1 compared to the total value of the position:
* R = valueToken1 / [valueToken0 + valueToken1]
* If we express all values in token1 and use the current pool price to denominate token0 in token1:
* R = amount1 / [amount0 * sqrtPrice² + amount1]
*
* a) The "Target Ratio" (R_target) is the ratio of the new liquidity position.
* It is calculated with the current price and the upper and lower prices of the liquidity position,
* see _getTargetRatio() for the derivation.
* To maximize the liquidity of the new position, the balances after the swap should approximate it as close as possible to not have any leftovers.
* b) The "Current Ratio" (R_current) is the ratio of the current token balances, it is calculated as follows:
* R_current = balance1 / [balance0 * sqrtPrice² + balance1].
*
* 3) From R_target and R_current we can finally derive the direction of the swap, amountIn and amountOut.
* If R_current is smaller than R_target, we have to swap an amount of token0 to token1, and vice versa.
* amountIn and amountOut can be found by solving the following equalities:
* a) The ratio of the token balances after the swap equal the "Target Ratio".
* b) The swap between token0 and token1 is done in the pool itself,
* taking into account fees, but ignoring slippage (-> sqrtPrice remains constant).
*
* If R_current < R_target (swap token0 to token1):
* a) R_target = [amount1 + amountOut] / [(amount0 - amountIn) * sqrtPrice² + (amount1 + amountOut)].
* b) amountOut = (1 - fee) * amountIn * sqrtPrice².
* => amountOut = [(R_target - R_current) * (amount0 * sqrtPrice² + amount1)] / [1 + R_target * fee / (1 - fee)].
*
* If R_current > R_target (swap token1 to token0):
* a) R_target = [(amount1 - amountIn)] / [(amount0 + amountOut) * sqrtPrice² + (amount1 - amountIn)].
* b) amountOut = (1 - fee) * amountIn / sqrtPrice².
* => amountIn = [(R_current - R_target) * (amount0 * sqrtPrice² + amount1)] / (1 - R_target * fee).
*/
function _getSwapParams(
uint256 sqrtPrice,
uint256 sqrtRatioLower,
uint256 sqrtRatioUpper,
uint256 balance0,
uint256 balance1,
uint256 fee
) internal pure returns (bool zeroToOne, uint256 amountIn, uint256 amountOut) {
if (sqrtPrice >= sqrtRatioUpper) {
// New position is out of range and fully in token 1.
// Rebalance to a single-sided liquidity position in token 1.
zeroToOne = true;
amountIn = balance0;
amountOut = _getAmountOut(sqrtPrice, true, balance0, fee);
} else if (sqrtPrice <= sqrtRatioLower) {
// New position is out of range and fully in token 0.
// Rebalance to a single-sided liquidity position in token 0.
amountIn = balance1;
amountOut = _getAmountOut(sqrtPrice, false, balance1, fee);
} else {
// Get target ratio in token1 terms.
uint256 targetRatio = _getTargetRatio(sqrtPrice, sqrtRatioLower, sqrtRatioUpper);
// Calculate the total position value in token1 equivalent:
uint256 token0ValueInToken1 = _getSpotValue(sqrtPrice, true, balance0);
uint256 totalValueInToken1 = balance1 + token0ValueInToken1;
unchecked {
// Calculate the current ratio of liquidity in token1 terms.
uint256 currentRatio = balance1.mulDivDown(1e18, totalValueInToken1);
if (currentRatio < targetRatio) {
// Swap token0 partially to token1.
zeroToOne = true;
{
uint256 denominator = 1e18 + targetRatio.mulDivDown(fee, 1e18 - fee);
amountOut = (targetRatio - currentRatio).mulDivDown(totalValueInToken1, denominator);
}
amountIn = _getAmountIn(sqrtPrice, true, amountOut, fee);
} else {
// Swap token1 partially to token0.
zeroToOne = false;
{
uint256 denominator = 1e18 - targetRatio.mulDivDown(fee, 1e18);
amountIn = (currentRatio - targetRatio).mulDivDown(totalValueInToken1, denominator);
}
amountOut = _getAmountOut(sqrtPrice, false, amountIn, fee);
}
}
}
}
/**
* @notice Calculates the value of one token in the other token for a given amountIn and sqrtPrice.
* Does not take into account slippage and fees.
* @param sqrtPrice The square root of the price (token1/token0), with 96 binary precision.
* @param zeroToOne Bool indicating if token0 has to be swapped to token1 or opposite.
* @param amountIn The amount that of tokenIn that must be swapped to tokenOut.
* @return amountOut The amount of tokenOut.
* @dev Function will revert for all pools where the sqrtPrice is bigger than type(uint128).max.
* type(uint128).max is currently more than enough for all supported pools.
* If ever the sqrtPrice of a pool exceeds type(uint128).max, a different contract has to be deployed,
* which does two consecutive mulDivs.
*/
function _getSpotValue(uint256 sqrtPrice, bool zeroToOne, uint256 amountIn)
internal
pure
returns (uint256 amountOut)
{
amountOut = zeroToOne
? FullMath.mulDiv(amountIn, sqrtPrice ** 2, Q192)
: FullMath.mulDiv(amountIn, Q192, sqrtPrice ** 2);
}
/**
* @notice Calculates the amountOut for a given amountIn and sqrtPrice for a hypothetical
* swap though the pool itself with fees but without slippage.
* @param sqrtPrice The square root of the price (token1/token0), with 96 binary precision.
* @param zeroToOne Bool indicating if token0 has to be swapped to token1 or opposite.
* @param amountIn The amount of tokenIn that must be swapped to tokenOut.
* @param fee The total fee on amountIn, with 18 decimals precision.
* @return amountOut The amount of tokenOut.
* @dev Function will revert for all pools where the sqrtPrice is bigger than type(uint128).max.
* type(uint128).max is currently more than enough for all supported pools.
* If ever the sqrtPrice of a pool exceeds type(uint128).max, a different contract has to be deployed,
* which does two consecutive mulDivs.
*/
function _getAmountOut(uint256 sqrtPrice, bool zeroToOne, uint256 amountIn, uint256 fee)
internal
pure
returns (uint256 amountOut)
{
require(sqrtPrice <= type(uint128).max);
unchecked {
uint256 amountInWithoutFees = (1e18 - fee).mulDivDown(amountIn, 1e18);
amountOut = zeroToOne
? FullMath.mulDiv(amountInWithoutFees, sqrtPrice ** 2, Q192)
: FullMath.mulDiv(amountInWithoutFees, Q192, sqrtPrice ** 2);
}
}
/**
* @notice Calculates the amountIn for a given amountOut and sqrtPrice for a hypothetical
* swap though the pool itself with fees but without slippage.
* @param sqrtPrice The square root of the price (token1/token0), with 96 binary precision.
* @param zeroToOne Bool indicating if token0 has to be swapped to token1 or opposite.
* @param amountOut The amount that tokenOut that must be swapped.
* @param fee The total fee on amountIn, with 18 decimals precision.
* @return amountIn The amount of tokenIn.
* @dev Function will revert for all pools where the sqrtPrice is bigger than type(uint128).max.
* type(uint128).max is currently more than enough for all supported pools.
* If ever the sqrtPrice of a pool exceeds type(uint128).max, a different contract has to be deployed,
* which does two consecutive mulDivs.
*/
function _getAmountIn(uint256 sqrtPrice, bool zeroToOne, uint256 amountOut, uint256 fee)
internal
pure
returns (uint256 amountIn)
{
require(sqrtPrice <= type(uint128).max);
unchecked {
uint256 amountInWithoutFees = zeroToOne
? FullMath.mulDiv(amountOut, Q192, sqrtPrice ** 2)
: FullMath.mulDiv(amountOut, sqrtPrice ** 2, Q192);
amountIn = amountInWithoutFees.mulDivDown(1e18, 1e18 - fee);
}
}
/**
* @notice Calculates the ratio of how much of the total value of a liquidity position has to be provided in token1.
* @param sqrtPrice The square root of the current pool price (token1/token0), with 96 binary precision.
* @param sqrtRatioLower The square root price of the lower tick of the liquidity position, with 96 binary precision.
* @param sqrtRatioUpper The square root price of the upper tick of the liquidity position, with 96 binary precision.
* @return targetRatio The ratio of the value of token1 compared to the total value of the position, with 18 decimals precision.
* @dev Function will revert for all pools where the sqrtPrice is bigger than type(uint128).max.
* type(uint128).max is currently more than enough for all supported pools.
* If ever the sqrtPrice of a pool exceeds type(uint128).max, a different contract has to be deployed,
* which does two consecutive mulDivs.
* @dev Derivation of the formula:
* 1) The ratio is defined as:
* R = valueToken1 / [valueToken0 + valueToken1]
* If we express all values in token1 and use the current pool price to denominate token0 in token1:
* R = amount1 / [amount0 * sqrtPrice² + amount1]
* 2) Amount0 for a given liquidity position of a Uniswap V3 pool is given as:
* Amount0 = liquidity * (sqrtRatioUpper - sqrtPrice) / (sqrtRatioUpper * sqrtPrice)
* 3) Amount1 for a given liquidity position of a Uniswap V3 pool is given as:
* Amount1 = liquidity * (sqrtPrice - sqrtRatioLower)
* 4) Combining 1), 2) and 3) and simplifying we get:
* R = [sqrtPrice - sqrtRatioLower] / [2 * sqrtPrice - sqrtRatioLower - sqrtPrice² / sqrtRatioUpper]
*/
function _getTargetRatio(uint256 sqrtPrice, uint256 sqrtRatioLower, uint256 sqrtRatioUpper)
internal
pure
returns (uint256 targetRatio)
{
require(sqrtPrice <= type(uint128).max);
// Unchecked: sqrtPrice is always bigger than sqrtRatioLower.
// Unchecked: sqrtPrice is always smaller than sqrtRatioUpper -> sqrtPrice > sqrtPrice ** 2 / sqrtRatioUpper.
unchecked {
uint256 numerator = sqrtPrice - sqrtRatioLower;
uint256 denominator = 2 * sqrtPrice - sqrtRatioLower - sqrtPrice ** 2 / sqrtRatioUpper;
targetRatio = numerator.mulDivDown(1e18, denominator);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: BUSL-1.1
*/
pragma solidity ^0.8.0;
interface IPermit2 {
/// @notice The saved permissions
/// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
/// @dev Setting amount to type(uint160).max sets an unlimited approval
struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice Approves the spender to use up to amount of the specified token up until the expiration
/// @param token The token to approve
/// @param spender The spender address to approve
/// @param amount The approved amount of the token
/// @param expiration The timestamp at which the approval is no longer valid
/// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
/// @dev Setting amount to type(uint160).max sets an unlimited approval
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
/// @notice Maps users to tokens to spender addresses and information about the approval on the token
/// @dev Indexed in the order of token owner address, token address, spender address
/// @dev The stored word saves the allowed amount, expiration on the allowance, and nonce
function allowance(address user, address token, address spender) external returns (PackedAllowance memory);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
/// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
/// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
/// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import { PoolKey } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/types/PoolKey.sol";
import { PositionInfo } from "../../../lib/accounts-v2/lib/v4-periphery/src/libraries/PositionInfoLibrary.sol";
interface IPositionManagerV4 {
/// @notice Unlocks Uniswap v4 PoolManager and batches actions for modifying liquidity
/// @dev This is the standard entrypoint for the PositionManager
/// @param unlockData is an encoding of actions, and parameters for those actions
/// @param deadline is the deadline for the batched actions to be executed
function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;
/// @notice Used to get the ID that will be used for the next minted liquidity position
/// @return uint256 The next token ID
function nextTokenId() external view returns (uint256);
/// @notice Returns the pool key and position info of a position
/// @param tokenId the ERC721 tokenId
/// @return poolKey the pool key of the position
/// @return PositionInfo a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
function getPoolAndPositionInfo(uint256 tokenId) external view returns (PoolKey memory, PositionInfo);
function approve(address spender, uint256 tokenId) external;
}/**
* https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/LiquidityAmounts.sol
* SPDX-License-Identifier: GPL-2.0-or-later
*/
pragma solidity ^0.8.0;
import { FixedPoint96 } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/libraries/FixedPoint96.sol";
import { FullMath } from "../../../lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/libraries/FullMath.sol";
/**
* @title Liquidity amount functions
* @notice Provides functions for computing liquidity amounts from token amounts and prices
*/
// forge-lint: disable-next-item(mixed-case-variable,unsafe-typecast)
library LiquidityAmounts {
/**
* @notice Downcasts uint256 to uint128
* @param x The uint258 to be downcasted
* @return y The passed value, downcasted to uint128
*/
function toUint128(uint256 x) internal pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/**
* @notice Computes the amount of liquidity received for a given amount of token0 and price range
* @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
* @param sqrtRatioAX96 A sqrt price representing the first tick boundary
* @param sqrtRatioBX96 A sqrt price representing the second tick boundary
* @param amount0 The amount0 being sent in
* @return liquidity The amount of returned liquidity
*/
function getLiquidityForAmount0(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0)
internal
pure
returns (uint256 liquidity)
{
unchecked {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96);
}
}
/**
* @notice Computes the amount of liquidity received for a given amount of token1 and price range
* @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
* @param sqrtRatioAX96 A sqrt price representing the first tick boundary
* @param sqrtRatioBX96 A sqrt price representing the second tick boundary
* @param amount1 The amount1 being sent in
* @return liquidity The amount of returned liquidity
*/
function getLiquidityForAmount1(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1)
internal
pure
returns (uint256 liquidity)
{
unchecked {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96);
}
}
/**
* @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
* pool prices and the prices at the tick boundaries
* @param sqrtRatioX96 A sqrt price representing the current pool prices
* @param sqrtRatioAX96 A sqrt price representing the first tick boundary
* @param sqrtRatioBX96 A sqrt price representing the second tick boundary
* @param amount0 The amount of token0 being sent in
* @param amount1 The amount of token1 being sent in
* @return liquidity The maximum amount of liquidity received
*/
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) {
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
}
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = toUint128(getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0));
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint256 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint256 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = toUint128(liquidity0 < liquidity1 ? liquidity0 : liquidity1);
} else {
liquidity = toUint128(getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1));
}
}
/**
* @notice Computes the amount of token0 for a given amount of liquidity and a price range
* @param sqrtRatioAX96 A sqrt price representing the first tick boundary
* @param sqrtRatioBX96 A sqrt price representing the second tick boundary
* @param liquidity The liquidity being valued
* @return amount0 The amount of token0
*/
function getAmount0ForLiquidity(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity)
internal
pure
returns (uint256 amount0)
{
unchecked {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96
) / sqrtRatioAX96;
}
}
/**
* @notice Computes the amount of token1 for a given amount of liquidity and a price range
* @param sqrtRatioAX96 A sqrt price representing the first tick boundary
* @param sqrtRatioBX96 A sqrt price representing the second tick boundary
* @param liquidity The liquidity being valued
* @return amount1 The amount of token1
*/
function getAmount1ForLiquidity(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity)
internal
pure
returns (uint256 amount1)
{
unchecked {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
}
/**
* @notice Computes the token0 and token1 value for a given amount of liquidity, the current
* pool prices and the prices at the tick boundaries
* @param sqrtRatioX96 A sqrt price representing the current pool prices
* @param sqrtRatioAX96 A sqrt price representing the first tick boundary
* @param sqrtRatioBX96 A sqrt price representing the second tick boundary
* @param liquidity The liquidity being valued
* @return amount0 The amount of token0
* @return amount1 The amount of token1
*/
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) {
(sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
}
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
/**
* @dev PositionInfo is a packed version of solidity structure.
* Using the packaged version saves gas and memory by not storing the structure fields in memory slots.
*
* Layout:
* 200 bits poolId | 24 bits tickUpper | 24 bits tickLower | 8 bits hasSubscriber
*
* Fields in the direction from the least significant bit:
*
* A flag to know if the tokenId is subscribed to an address
* uint8 hasSubscriber;
*
* The tickUpper of the position
* int24 tickUpper;
*
* The tickLower of the position
* int24 tickLower;
*
* The truncated poolId. Truncates a bytes32 value so the most signifcant (highest) 200 bits are used.
* bytes25 poolId;
*
* Note: If more bits are needed, hasSubscriber can be a single bit.
*
*/
type PositionInfo is uint256;
using PositionInfoLibrary for PositionInfo global;
library PositionInfoLibrary {
PositionInfo internal constant EMPTY_POSITION_INFO = PositionInfo.wrap(0);
uint256 internal constant MASK_UPPER_200_BITS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000;
uint256 internal constant MASK_8_BITS = 0xFF;
uint24 internal constant MASK_24_BITS = 0xFFFFFF;
uint256 internal constant SET_UNSUBSCRIBE = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00;
uint256 internal constant SET_SUBSCRIBE = 0x01;
uint8 internal constant TICK_LOWER_OFFSET = 8;
uint8 internal constant TICK_UPPER_OFFSET = 32;
/// @dev This poolId is NOT compatible with the poolId used in UniswapV4 core. It is truncated to 25 bytes, and just used to lookup PoolKey in the poolKeys mapping.
function poolId(PositionInfo info) internal pure returns (bytes25 _poolId) {
assembly ("memory-safe") {
_poolId := and(MASK_UPPER_200_BITS, info)
}
}
function tickLower(PositionInfo info) internal pure returns (int24 _tickLower) {
assembly ("memory-safe") {
_tickLower := signextend(2, shr(TICK_LOWER_OFFSET, info))
}
}
function tickUpper(PositionInfo info) internal pure returns (int24 _tickUpper) {
assembly ("memory-safe") {
_tickUpper := signextend(2, shr(TICK_UPPER_OFFSET, info))
}
}
function hasSubscriber(PositionInfo info) internal pure returns (bool _hasSubscriber) {
assembly ("memory-safe") {
_hasSubscriber := and(MASK_8_BITS, info)
}
}
/// @dev this does not actually set any storage
function setSubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
assembly ("memory-safe") {
_info := or(info, SET_SUBSCRIBE)
}
}
/// @dev this does not actually set any storage
function setUnsubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
assembly ("memory-safe") {
_info := and(info, SET_UNSUBSCRIBE)
}
}
/// @notice Creates the default PositionInfo struct
/// @dev Called when minting a new position
/// @param _poolKey the pool key of the position
/// @param _tickLower the lower tick of the position
/// @param _tickUpper the upper tick of the position
/// @return info packed position info, with the truncated poolId and the hasSubscriber flag set to false
function initialize(PoolKey memory _poolKey, int24 _tickLower, int24 _tickUpper)
internal
pure
returns (PositionInfo info)
{
bytes25 _poolId = bytes25(PoolId.unwrap(_poolKey.toId()));
assembly {
info :=
or(
or(and(MASK_UPPER_200_BITS, _poolId), shl(TICK_UPPER_OFFSET, and(MASK_24_BITS, _tickUpper))),
shl(TICK_LOWER_OFFSET, and(MASK_24_BITS, _tickLower))
)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";
/// @notice A helper library to provide state getters that use extsload
library StateLibrary {
/// @notice index of pools mapping in the PoolManager
bytes32 public constant POOLS_SLOT = bytes32(uint256(6));
/// @notice index of feeGrowthGlobal0X128 in Pool.State
uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;
// feeGrowthGlobal1X128 offset in Pool.State = 2
/// @notice index of liquidity in Pool.State
uint256 public constant LIQUIDITY_OFFSET = 3;
/// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;
uint256 public constant TICKS_OFFSET = 4;
/// @notice index of tickBitmap mapping in Pool.State
uint256 public constant TICK_BITMAP_OFFSET = 5;
/// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;
uint256 public constant POSITIONS_OFFSET = 6;
/**
* @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee
* @dev Corresponds to pools[poolId].slot0
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.
* @return tick The current tick of the pool.
* @return protocolFee The protocol fee of the pool.
* @return lpFee The swap fee of the pool.
*/
function getSlot0(IPoolManager manager, PoolId poolId)
internal
view
returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
bytes32 data = manager.extsload(stateSlot);
// 24 bits |24bits|24bits |24 bits|160 bits
// 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7
// ---------- | fee |protocolfee | tick | sqrtPriceX96
assembly ("memory-safe") {
// bottom 160 bits of data
sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
// next 24 bits of data
tick := signextend(2, shr(160, data))
// next 24 bits of data
protocolFee := and(shr(184, data), 0xFFFFFF)
// last 24 bits of data
lpFee := and(shr(208, data), 0xFFFFFF)
}
}
/**
* @notice Retrieves the tick information of a pool at a specific tick.
* @dev Corresponds to pools[poolId].ticks[tick]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve information for.
* @return liquidityGross The total position liquidity that references this tick
* @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
* @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
* @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
*/
function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128
)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
// read all 3 words of the TickInfo struct
bytes32[] memory data = manager.extsload(slot, 3);
assembly ("memory-safe") {
let firstWord := mload(add(data, 32))
liquidityNet := sar(128, firstWord)
liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
feeGrowthOutside0X128 := mload(add(data, 64))
feeGrowthOutside1X128 := mload(add(data, 96))
}
}
/**
* @notice Retrieves the liquidity information of a pool at a specific tick.
* @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve liquidity for.
* @return liquidityGross The total position liquidity that references this tick
* @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
*/
function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (uint128 liquidityGross, int128 liquidityNet)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
bytes32 value = manager.extsload(slot);
assembly ("memory-safe") {
liquidityNet := sar(128, value)
liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
/**
* @notice Retrieves the fee growth outside a tick range of a pool
* @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve fee growth for.
* @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
* @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
*/
function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
// offset by 1 word, since the first word is liquidityGross + liquidityNet
bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);
assembly ("memory-safe") {
feeGrowthOutside0X128 := mload(add(data, 32))
feeGrowthOutside1X128 := mload(add(data, 64))
}
}
/**
* @notice Retrieves the global fee growth of a pool.
* @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return feeGrowthGlobal0 The global fee growth for token0.
* @return feeGrowthGlobal1 The global fee growth for token1.
* @dev Note that feeGrowthGlobal can be artificially inflated
* For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal
* atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
*/
function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
internal
view
returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State, `uint256 feeGrowthGlobal0X128`
bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);
// read the 2 words of feeGrowthGlobal
bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);
assembly ("memory-safe") {
feeGrowthGlobal0 := mload(add(data, 32))
feeGrowthGlobal1 := mload(add(data, 64))
}
}
/**
* @notice Retrieves total the liquidity of a pool.
* @dev Corresponds to pools[poolId].liquidity
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return liquidity The liquidity of the pool.
*/
function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `uint128 liquidity`
bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);
liquidity = uint128(uint256(manager.extsload(slot)));
}
/**
* @notice Retrieves the tick bitmap of a pool at a specific tick.
* @dev Corresponds to pools[poolId].tickBitmap[tick]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve the bitmap for.
* @return tickBitmap The bitmap of the tick.
*/
function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)
internal
view
returns (uint256 tickBitmap)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(int16 => uint256) tickBitmap;`
bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);
// slot id of the mapping key: `pools[poolId].tickBitmap[tick]
bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));
tickBitmap = uint256(manager.extsload(slot));
}
/**
* @notice Retrieves the position information of a pool without needing to calculate the `positionId`.
* @dev Corresponds to pools[poolId].positions[positionId]
* @param poolId The ID of the pool.
* @param owner The owner of the liquidity position.
* @param tickLower The lower tick of the liquidity range.
* @param tickUpper The upper tick of the liquidity range.
* @param salt The bytes32 randomness to further distinguish position state.
* @return liquidity The liquidity of the position.
* @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
* @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
*/
function getPositionInfo(
IPoolManager manager,
PoolId poolId,
address owner,
int24 tickLower,
int24 tickUpper,
bytes32 salt
) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {
// positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);
(liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);
}
/**
* @notice Retrieves the position information of a pool at a specific position ID.
* @dev Corresponds to pools[poolId].positions[positionId]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param positionId The ID of the position.
* @return liquidity The liquidity of the position.
* @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
* @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
*/
function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)
internal
view
returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)
{
bytes32 slot = _getPositionInfoSlot(poolId, positionId);
// read all 3 words of the Position.State struct
bytes32[] memory data = manager.extsload(slot, 3);
assembly ("memory-safe") {
liquidity := mload(add(data, 32))
feeGrowthInside0LastX128 := mload(add(data, 64))
feeGrowthInside1LastX128 := mload(add(data, 96))
}
}
/**
* @notice Retrieves the liquidity of a position.
* @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param positionId The ID of the position.
* @return liquidity The liquidity of the position.
*/
function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)
internal
view
returns (uint128 liquidity)
{
bytes32 slot = _getPositionInfoSlot(poolId, positionId);
liquidity = uint128(uint256(manager.extsload(slot)));
}
/**
* @notice Calculate the fee growth inside a tick range of a pool
* @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tickLower The lower tick of the range.
* @param tickUpper The upper tick of the range.
* @return feeGrowthInside0X128 The fee growth inside the tick range for token0.
* @return feeGrowthInside1X128 The fee growth inside the tick range for token1.
*/
function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)
internal
view
returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
{
(uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);
(uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =
getTickFeeGrowthOutside(manager, poolId, tickLower);
(uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =
getTickFeeGrowthOutside(manager, poolId, tickUpper);
(, int24 tickCurrent,,) = getSlot0(manager, poolId);
unchecked {
if (tickCurrent < tickLower) {
feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
} else if (tickCurrent >= tickUpper) {
feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;
feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;
} else {
feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
}
}
}
function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
}
function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(int24 => TickInfo) ticks`
bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);
// slot key of the tick key: `pools[poolId].ticks[tick]
return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));
}
function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(bytes32 => Position.State) positions;`
bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);
// slot of the mapping key: `pools[poolId].positions[positionId]
return keccak256(abi.encodePacked(positionId, positionMapping));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}/**
* Created by Pragma Labs
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.8.0;
interface IPermit2 {
/**
* @notice The token and amount details for a transfer signed in the permit transfer signature
*/
struct TokenPermissions {
// ERC20 token address
address token;
// the maximum amount that can be spent
uint256 amount;
}
/**
* @notice Used to reconstruct the signed permit message for multiple token transfers
* @dev Do not need to pass in spender address as it is required that it is msg.sender
* @dev Note that a user still signs over a spender address
*/
struct PermitBatchTransferFrom {
// the tokens and corresponding amounts permitted for a transfer
TokenPermissions[] permitted;
// a unique value for every token owner's signature to prevent signature replays
uint256 nonce;
// deadline on the permit signature
uint256 deadline;
}
/**
* @notice Specifies the recipient address and amount for batched transfers.
* @dev Recipients and amounts correspond to the index of the signed token permissions array.
* @dev Reverts if the requested amount is greater than the permitted signed amount.
*/
struct SignatureTransferDetails {
// recipient address
address to;
// spender requested amount
uint256 requestedAmount;
}
/**
* @notice Transfers multiple tokens using a signed permit message
* @param permit The permit data signed over by the owner
* @param owner The owner of the tokens to transfer
* @param transferDetails Specifies the recipient and requested amount for the token transfer
* @param signature The signature to verify
*/
function permitTransferFrom(
PermitBatchTransferFrom memory permit,
SignatureTransferDetails[] calldata transferDetails,
address owner,
bytes calldata signature
) external;
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/// @notice Simple single owner authorization mixin.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
abstract contract Owned {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OwnershipTransferred(address indexed user, address indexed newOwner);
/*//////////////////////////////////////////////////////////////
OWNERSHIP STORAGE
//////////////////////////////////////////////////////////////*/
address public owner;
modifier onlyOwner() virtual {
require(msg.sender == owner, "UNAUTHORIZED");
_;
}
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(address _owner) {
owner = _owner;
emit OwnershipTransferred(address(0), _owner);
}
/*//////////////////////////////////////////////////////////////
OWNERSHIP LOGIC
//////////////////////////////////////////////////////////////*/
function transferOwnership(address newOwner) public virtual onlyOwner {
owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "./SafeCast.sol";
import {FullMath} from "./FullMath.sol";
import {UnsafeMath} from "./UnsafeMath.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
using SafeCast for uint256;
error InvalidPriceOrLiquidity();
error InvalidPrice();
error NotEnoughLiquidity();
error PriceOverflow();
/// @notice Gets the next sqrt price given a delta of currency0
/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
/// price less in order to not send too much output.
/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
/// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of currency0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of currency0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
internal
pure
returns (uint160)
{
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96;
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
if (add) {
unchecked {
uint256 product = amount * sqrtPX96;
if (product / amount == sqrtPX96) {
uint256 denominator = numerator1 + product;
if (denominator >= numerator1) {
// always fits in 160 bits
return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
}
}
}
// denominator is checked for overflow
return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));
} else {
unchecked {
uint256 product = amount * sqrtPX96;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
// equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow();
assembly ("memory-safe") {
if iszero(
and(
eq(div(product, amount), and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
gt(numerator1, product)
)
) {
mstore(0, 0xf5c787f1) // selector for PriceOverflow()
revert(0x1c, 0x04)
}
}
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
}
/// @notice Gets the next sqrt price given a delta of currency1
/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
/// price less in order to not send too much output.
/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
/// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of currency1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of currency1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
internal
pure
returns (uint160)
{
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (add) {
uint256 quotient = (
amount <= type(uint160).max
? (amount << FixedPoint96.RESOLUTION) / liquidity
: FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
);
return (uint256(sqrtPX96) + quotient).toUint160();
} else {
uint256 quotient = (
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
: FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
);
// equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity();
assembly ("memory-safe") {
if iszero(gt(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff), quotient)) {
mstore(0, 0x4323a555) // selector for NotEnoughLiquidity()
revert(0x1c, 0x04)
}
}
// always fits 160 bits
unchecked {
return uint160(sqrtPX96 - quotient);
}
}
}
/// @notice Gets the next sqrt price given an input amount of currency0 or currency1
/// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
/// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
/// @param liquidity The amount of usable liquidity
/// @param amountIn How much of currency0, or currency1, is being swapped in
/// @param zeroForOne Whether the amount in is currency0 or currency1
/// @return uint160 The price after adding the input amount to currency0 or currency1
function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne)
internal
pure
returns (uint160)
{
// equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
assembly ("memory-safe") {
if or(
iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
) {
mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
revert(0x1c, 0x04)
}
}
// round to make sure that we don't pass the target price
return zeroForOne
? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
: getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
}
/// @notice Gets the next sqrt price given an output amount of currency0 or currency1
/// @dev Throws if price or liquidity are 0 or the next price is out of bounds
/// @param sqrtPX96 The starting price before accounting for the output amount
/// @param liquidity The amount of usable liquidity
/// @param amountOut How much of currency0, or currency1, is being swapped out
/// @param zeroForOne Whether the amount out is currency1 or currency0
/// @return uint160 The price after removing the output amount of currency0 or currency1
function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne)
internal
pure
returns (uint160)
{
// equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
assembly ("memory-safe") {
if or(
iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
) {
mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
revert(0x1c, 0x04)
}
}
// round to make sure that we pass the target price
return zeroForOne
? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
: getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
}
/// @notice Gets the amount0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return uint256 Amount of currency0 required to cover a position of size liquidity between the two passed prices
function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
internal
pure
returns (uint256)
{
unchecked {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
// equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice();
assembly ("memory-safe") {
if iszero(and(sqrtPriceAX96, 0xffffffffffffffffffffffffffffffffffffffff)) {
mstore(0, 0x00bfc921) // selector for InvalidPrice()
revert(0x1c, 0x04)
}
}
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96;
return roundUp
? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96)
: FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96;
}
}
/// @notice Equivalent to: `a >= b ? a - b : b - a`
function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {
assembly ("memory-safe") {
let diff :=
sub(and(a, 0xffffffffffffffffffffffffffffffffffffffff), and(b, 0xffffffffffffffffffffffffffffffffffffffff))
// mask = 0 if a >= b else -1 (all 1s)
let mask := sar(255, diff)
// if a >= b, res = a - b = 0 ^ (a - b)
// if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)
// either way, res = mask ^ (a - b + mask)
res := xor(mask, add(mask, diff))
}
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices
function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
internal
pure
returns (uint256 amount1)
{
uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96);
uint256 denominator = FixedPoint96.Q96;
uint256 _liquidity = uint256(liquidity);
/**
* Equivalent to:
* amount1 = roundUp
* ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96)
* : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
* Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
*/
amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);
assembly ("memory-safe") {
amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))
}
}
/// @notice Helper that gets signed currency0 delta
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount0 delta
/// @return int256 Amount of currency0 corresponding to the passed liquidityDelta between the two prices
function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
internal
pure
returns (int256)
{
unchecked {
return liquidity < 0
? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
: -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
}
}
/// @notice Helper that gets signed currency1 delta
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount1 delta
/// @return int256 Amount of currency1 corresponding to the passed liquidityDelta between the two prices
function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
internal
pure
returns (int256)
{
unchecked {
return liquidity < 0
? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
: -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly ("memory-safe") {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly ("memory-safe") {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (0 - denominator) & denominator;
// Divide denominator by power of two
assembly ("memory-safe") {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly ("memory-safe") {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly ("memory-safe") {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the preconditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) != 0) {
require(++result > 0);
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
using CustomRevert for bytes4;
/// @notice Cannot update a position with no liquidity
error CannotUpdateEmptyPosition();
// info stored for each user's position
struct State {
// the amount of liquidity owned by this position
uint128 liquidity;
// fee growth per unit of liquidity as of the last update to liquidity or fees owed
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
}
/// @notice Returns the State struct of a position, given an owner and position boundaries
/// @param self The mapping containing all user positions
/// @param owner The address of the position owner
/// @param tickLower The lower tick boundary of the position
/// @param tickUpper The upper tick boundary of the position
/// @param salt A unique value to differentiate between multiple positions in the same range
/// @return position The position info struct of the given owners' position
function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
internal
view
returns (State storage position)
{
bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
position = self[positionKey];
}
/// @notice A helper function to calculate the position key
/// @param owner The address of the position owner
/// @param tickLower the lower tick boundary of the position
/// @param tickUpper the upper tick boundary of the position
/// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
internal
pure
returns (bytes32 positionKey)
{
// positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
mstore(fmp, owner) // [0x0c, 0x20)
positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes
// now clean the memory we used
mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
mstore(fmp, 0) // fmp held owner
}
}
/// @notice Credits accumulated fees to a user's position
/// @param self The individual position to update
/// @param liquidityDelta The change in pool liquidity as a result of the position update
/// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
/// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
/// @return feesOwed0 The amount of currency0 owed to the position owner
/// @return feesOwed1 The amount of currency1 owed to the position owner
function update(
State storage self,
int128 liquidityDelta,
uint256 feeGrowthInside0X128,
uint256 feeGrowthInside1X128
) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
uint128 liquidity = self.liquidity;
if (liquidityDelta == 0) {
// disallow pokes for 0 liquidity positions
if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
} else {
self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
}
// calculate accumulated fees. overflow in the subtraction of fee growth is expected
unchecked {
feesOwed0 =
FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
feesOwed1 =
FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
}
// update the position
self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 will return 0, and should be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly ("memory-safe") {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
/// @notice Calculates floor(a×b÷denominator)
/// @dev division by 0 will return 0, and should be checked externally
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result, floor(a×b÷denominator)
function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
assembly ("memory-safe") {
result := div(mul(a, b), denominator)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math library for liquidity
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
assembly ("memory-safe") {
z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
if shr(128, z) {
// revert SafeCastOverflow()
mstore(0, 0x93dafdf1)
revert(0x1c, 0x04)
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}{
"remappings": [
"@ensdomains/=lib/lending-v2/lib/accounts-v2/lib/slipstream/node_modules/@ensdomains/",
"@nomad-xyz/=lib/lending-v2/lib/accounts-v2/lib/slipstream/lib/ExcessivelySafeCall/",
"@openzeppelin/=lib/lending-v2/lib/accounts-v2/lib/slipstream/lib/openzeppelin-contracts/",
"@solidity-parser/=lib/lending-v2/lib/accounts-v2/lib/slipstream/node_modules/solhint/node_modules/@solidity-parser/",
"@uniswap/v2-core/contracts/=lib/lending-v2/lib/accounts-v2/./test/utils/fixtures/swap-router-02/",
"@uniswap/v3-core/contracts/=lib/lending-v2/lib/accounts-v2/lib/v3-core/contracts/",
"@uniswap/v3-periphery/contracts/=lib/lending-v2/lib/accounts-v2/lib/v3-periphery/contracts/",
"@uniswap/v4-core/=lib/lending-v2/lib/accounts-v2/lib/v4-periphery/lib/v4-core/",
"@utils/=lib/lending-v2/lib/accounts-v2/lib/merkl-contracts/node_modules/utils/src/",
"ExcessivelySafeCall/=lib/lending-v2/lib/accounts-v2/lib/slipstream/lib/ExcessivelySafeCall/src/",
"accounts-v2/=lib/lending-v2/lib/accounts-v2/src/",
"arcadia-periphery/=lib/arcadia-periphery/src/",
"asset-managers/=lib/arcadia-periphery/lib/asset-managers/src/",
"base64-sol/=lib/lending-v2/lib/accounts-v2/lib/slipstream/lib/base64/",
"base64/=lib/lending-v2/lib/accounts-v2/lib/slipstream/lib/base64/",
"contracts/=lib/lending-v2/lib/accounts-v2/lib/slipstream/contracts/",
"ds-test/=lib/lending-v2/lib/accounts-v2/lib/solmate/lib/ds-test/src/",
"erc4626-tests/=lib/lending-v2/lib/accounts-v2/lib/openzeppelin-contracts-v4.9/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/lending-v2/lib/accounts-v2/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"forge-std/=lib/lending-v2/lib/accounts-v2/lib/forge-std/src/",
"hardhat/=lib/lending-v2/lib/accounts-v2/lib/slipstream/node_modules/hardhat/",
"lending-v2/=lib/lending-v2/src/",
"merkl-contracts/=lib/lending-v2/lib/accounts-v2/lib/merkl-contracts/",
"openzeppelin-contracts-upgradeable-v4.9/=lib/lending-v2/lib/accounts-v2/lib/openzeppelin-contracts-upgradeable-v4.9/",
"openzeppelin-contracts-v3.4/=lib/lending-v2/lib/accounts-v2/lib/openzeppelin-contracts-v3.4/contracts/",
"openzeppelin-contracts-v4.9/=lib/lending-v2/lib/accounts-v2/lib/openzeppelin-contracts-v4.9/",
"openzeppelin-contracts/=lib/lending-v2/lib/accounts-v2/lib/slipstream/lib/openzeppelin-contracts/contracts/",
"openzeppelin/=lib/lending-v2/lib/accounts-v2/lib/openzeppelin-contracts-v4.9/contracts/",
"oz/=lib/lending-v2/lib/accounts-v2/lib/merkl-contracts/node_modules/@openzeppelin/contracts/",
"permit2/=lib/lending-v2/lib/accounts-v2/lib/v4-periphery/lib/permit2/",
"slipstream/=lib/lending-v2/lib/accounts-v2/lib/slipstream/",
"solady/=lib/lending-v2/lib/accounts-v2/lib/solady/src/",
"solidity-lib/=lib/lending-v2/lib/accounts-v2/lib/slipstream/lib/solidity-lib/contracts/",
"solmate/=lib/lending-v2/lib/accounts-v2/lib/solmate/",
"swap-router-contracts/=lib/lending-v2/lib/accounts-v2/lib/swap-router-contracts/contracts/",
"v3-core/=lib/lending-v2/lib/accounts-v2/lib/v3-core/",
"v3-periphery/=lib/lending-v2/lib/accounts-v2/lib/v3-periphery/contracts/",
"v4-core/=lib/lending-v2/lib/accounts-v2/lib/v4-periphery/lib/v4-core/src/",
"v4-periphery/=lib/lending-v2/lib/accounts-v2/lib/v4-periphery/",
"lib/accounts-v2/lib/merkl-contracts:@openzeppelin/contracts-upgradeable/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/openzeppelin-contracts-upgradeable-v4.9/contracts/",
"lib/accounts-v2/lib/merkl-contracts:@openzeppelin/contracts/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/openzeppelin-contracts-v4.9/contracts/",
"lib/accounts-v2/lib/openzeppelin-contracts-upgradeable-v4.9:@openzeppelin/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/openzeppelin-contracts-v4.9/",
"lib/accounts-v2/lib/slipstream:@openzeppelin/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/slipstream/lib/openzeppelin-contracts/",
"lib/accounts-v2/lib/swap-router-contracts:@openzeppelin/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/openzeppelin-contracts-v3.4/",
"lib/accounts-v2/lib/v3-periphery:@openzeppelin/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/openzeppelin-contracts-v3.4/",
"lib/accounts-v2/lib/v4-periphery:@openzeppelin/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"lib/accounts-v2/lib/v4-periphery/lib/v4-core:@openzeppelin/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"lib/asset-managers/lib/accounts-v2/lib/slipstream:@openzeppelin/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/slipstream/lib/openzeppelin-contracts/",
"lib/asset-managers/lib/accounts-v2/lib/swap-router-contracts:@openzeppelin/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/openzeppelin-contracts-v3.4/",
"lib/asset-managers/lib/accounts-v2/lib/v3-periphery:@openzeppelin/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/openzeppelin-contracts-v3.4/",
"lib/asset-managers/lib/accounts-v2/lib/v4-periphery:@openzeppelin/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"lib/asset-managers/lib/accounts-v2/lib/v4-periphery/lib/v4-core:@openzeppelin/=lib/arcadia-periphery/lib/asset-managers/lib/accounts-v2/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"lib/merkl-contracts:@openzeppelin/contracts-upgradeable/=lib/lending-v2/lib/accounts-v2/lib/openzeppelin-contracts-upgradeable-v4.9/contracts/",
"lib/merkl-contracts:@openzeppelin/contracts/=lib/lending-v2/lib/accounts-v2/lib/openzeppelin-contracts-v4.9/contracts/",
"lib/openzeppelin-contracts-upgradeable-v4.9:@openzeppelin/=lib/lending-v2/lib/accounts-v2/lib/openzeppelin-contracts-v4.9/",
"lib/slipstream:@openzeppelin/=lib/lending-v2/lib/accounts-v2/lib/slipstream/lib/openzeppelin-contracts/",
"lib/v3-periphery:@openzeppelin/=lib/lending-v2/lib/accounts-v2/lib/openzeppelin-contracts-v3.4/",
"lib/v4-periphery:@openzeppelin/=lib/lending-v2/lib/accounts-v2/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"lib/v4-periphery/lib/v4-core:@openzeppelin/=lib/lending-v2/lib/accounts-v2/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "prague",
"viaIR": true
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"owner_","type":"address"},{"internalType":"address","name":"arcadiaFactory","type":"address"},{"internalType":"address","name":"routerTrampoline","type":"address"},{"internalType":"address","name":"positionManager","type":"address"},{"internalType":"address","name":"permit2","type":"address"},{"internalType":"address","name":"poolManager","type":"address"},{"internalType":"address","name":"weth","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"InsufficientLiquidity","type":"error"},{"inputs":[],"name":"InvalidAccountVersion","type":"error"},{"inputs":[],"name":"InvalidInitiator","type":"error"},{"inputs":[],"name":"InvalidPool","type":"error"},{"inputs":[],"name":"InvalidPositionManager","type":"error"},{"inputs":[],"name":"InvalidValue","type":"error"},{"inputs":[],"name":"NotAnAccount","type":"error"},{"inputs":[],"name":"OnlyAccount","type":"error"},{"inputs":[],"name":"OnlyAccountOwner","type":"error"},{"inputs":[],"name":"OnlyGuardian","type":"error"},{"inputs":[],"name":"OnlyPoolManager","type":"error"},{"inputs":[],"name":"Paused","type":"error"},{"inputs":[],"name":"Reentered","type":"error"},{"inputs":[],"name":"UnbalancedPool","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"initiator","type":"address"}],"name":"AccountInfoSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"positionManager","type":"address"},{"indexed":false,"internalType":"uint256","name":"id","type":"uint256"}],"name":"Compound","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":true,"internalType":"address","name":"asset","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FeePaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"newGuardian","type":"address"}],"name":"GuardianChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"pauseUpdate","type":"bool"}],"name":"PauseFlagsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"asset","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"YieldClaimed","type":"event"},{"inputs":[],"name":"ARCADIA_FACTORY","outputs":[{"internalType":"contract IArcadiaFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ROUTER_TRAMPOLINE","outputs":[{"internalType":"contract IRouterTrampoline","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"accountInfo","outputs":[{"internalType":"uint64","name":"maxClaimFee","type":"uint64"},{"internalType":"uint64","name":"maxSwapFee","type":"uint64"},{"internalType":"uint64","name":"upperSqrtPriceDeviation","type":"uint64"},{"internalType":"uint64","name":"lowerSqrtPriceDeviation","type":"uint64"},{"internalType":"uint64","name":"minLiquidityRatio","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"accountOwner","type":"address"},{"internalType":"address","name":"account","type":"address"}],"name":"accountToInitiator","outputs":[{"internalType":"address","name":"initiator","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"guardian_","type":"address"}],"name":"changeGuardian","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account_","type":"address"},{"components":[{"internalType":"address","name":"positionManager","type":"address"},{"internalType":"uint96","name":"id","type":"uint96"},{"internalType":"uint128","name":"amount0","type":"uint128"},{"internalType":"uint128","name":"amount1","type":"uint128"},{"internalType":"uint256","name":"trustedSqrtPrice","type":"uint256"},{"internalType":"uint64","name":"claimFee","type":"uint64"},{"internalType":"uint64","name":"swapFee","type":"uint64"},{"internalType":"bytes","name":"swapData","type":"bytes"}],"internalType":"struct Compounder.InitiatorParams","name":"initiatorParams","type":"tuple"}],"name":"compound","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"actionTargetData","type":"bytes"}],"name":"executeAction","outputs":[{"components":[{"internalType":"address[]","name":"assets","type":"address[]"},{"internalType":"uint256[]","name":"assetIds","type":"uint256[]"},{"internalType":"uint256[]","name":"assetAmounts","type":"uint256[]"},{"internalType":"uint256[]","name":"assetTypes","type":"uint256[]"}],"internalType":"struct ActionData","name":"depositData","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"guardian","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"sqrtPrice","type":"uint256"},{"components":[{"internalType":"uint256","name":"lowerBoundSqrtPrice","type":"uint256"},{"internalType":"uint256","name":"upperBoundSqrtPrice","type":"uint256"},{"internalType":"uint160","name":"sqrtRatioLower","type":"uint160"},{"internalType":"uint160","name":"sqrtRatioUpper","type":"uint160"}],"internalType":"struct Compounder.Cache","name":"cache","type":"tuple"}],"name":"isPoolBalanced","outputs":[{"internalType":"bool","name":"isBalanced","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"positionManager","type":"address"}],"name":"isPositionManager","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"metaData","outputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"accountOwner","type":"address"},{"internalType":"bool","name":"","type":"bool"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"onSetAssetManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account_","type":"address"},{"internalType":"address","name":"initiator","type":"address"},{"internalType":"uint256","name":"maxClaimFee","type":"uint256"},{"internalType":"uint256","name":"maxSwapFee","type":"uint256"},{"internalType":"uint256","name":"maxTolerance","type":"uint256"},{"internalType":"uint256","name":"minLiquidityRatio","type":"uint256"},{"internalType":"bytes","name":"metaData_","type":"bytes"}],"name":"setAccountInfo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"paused_","type":"bool"}],"name":"setPauseFlag","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"skim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"unlockCallback","outputs":[{"internalType":"bytes","name":"results","type":"bytes"}],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}]Contract Creation Code
610140346101e857601f61595838819003918201601f19168301916001600160401b038311848410176101ec5780849260e0946040528339810103126101e85761004881610200565b61005460208301610200565b9161006160408201610200565b61006d60608301610200565b61007960808401610200565b9161009260c061008b60a08701610200565b9501610200565b5f80546001600160a01b0319166001600160a01b039097169687178155604051979196907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08180a36001600160a01b0390811660805290811660a05290811660c05290811660e052166101005261012052615743908161021582396080518181816124ca01528181612ce80152612e95015260a0518181816103260152614060015260c0518181816106df0152818161074801528181610bb501528181610c140152818161135e015281816113b40152818161266201528181612b260152818161313e0152615006015260e05181614f87015261010051818181610800015281816108b3015281816110bc01528181611f300152613c3e01526101205181818161184801528181611c7301528181611cbc01528181611d0901528181612b86015281816141710152818161424501526142d90152f35b5f80fd5b634e487b7160e01b5f52604160045260245ffd5b51906001600160a01b03821682036101e85756fe61010080604052600436101561001d575b50361561001b575f80fd5b005b5f60e0525f3560e01c9081630686ddd914613172575080630a73e3911461311e5780631204f525146130cb578063150b7a02146130755780632fcb4f04146130025780633d692da114612e11578063452a932014612de95780635c975abb14612dc55780635f4860df14612c7c5780637d5ad9cd146125865780638456cb59146124f95780638cffa277146124b35780638da5cb5b146124885780638da92e711461240557806391dd734614611f03578063a129568d1461045a578063a7310b58146103d4578063a89d6dd414610355578063b699b82b1461030f578063bc25cf77146101965763f2fde38b14610114575f610010565b346101905760203660031901126101905761012d613250565b60e0515490610146336001600160a01b03841614613457565b60018060a01b031680916001600160601b0360a01b161760e05155337f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060e05160e051a360e05180f35b60e05180fd5b34610190576020366003190112610190576101af613250565b60e0515460ff906101ca336001600160a01b03831614613457565b60a01c166102fc576002546001600160a01b03166102e9576001600160a01b031680610264575060e05180808047335af13d1561025c573d9061020c826134cd565b9161021a6040519384613319565b825260e0513d90602084013e5b1561023457505b60e05180f35b60405162461bcd60e51b81526020600482015290819061025890602483019061333a565b0390fd5b606090610227565b6040516370a0823160e01b815230600482015290602082602481845afa9081156102dc5760e051916102a2575b61029d92503390614340565b61022e565b90506020823d6020116102d4575b816102bd60209383613319565b810103126102d05761029d915190610291565b5f80fd5b3d91506102b0565b6040513d60e051823e3d90fd5b63b5dfd9e560e01b60e05152600460e051fd5b6313d0ff5960e31b60e05152600460e051fd5b346101905760e051366003190112610190576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b346101905760a03660031901126101905760803660231901126101905760405161037e816132c8565b602435815260443560208201526064356001600160a01b03811681036101905760408201526084356001600160a01b038116810361019057816103ca91606060209401526004356136e4565b6040519015158152f35b34610190576020366003190112610190576001600160a01b036103f5613250565b1660e05152600360205260a0604060e051206001600160401b036001825492015416604051916001600160401b03811683526001600160401b038160401c1660208401526001600160401b038160801c16604084015260c01c60608301526080820152f35b34610190576020366003190112610190576004356001600160401b0381116101905761048a90369060040161335e565b906104936135f4565b506002546001600160a01b03163303611ef0573360e051526003602052604060e0512090604051926104c4846132fe565b6001600160401b03600184549482861687526020870195838160401c168752838160801c16604089015260c01c60608801520154166080850152810190604081830312610190576105148161327c565b906020810135906001600160401b03821161019057019161010083820312610190576040519261010084018481106001600160401b03821117611eaa5760405261055d8161327c565b845261056b60208201613575565b916020850192835261057f60408301613589565b604086015261059060608301613589565b6060860152608082013560808601526105ab60a0830161359d565b60a08601526105bc60c0830161359d565b60c086015260e08201356001600160401b038111610190576105de920161351e565b60e084015260018060a01b03835116936001600160401b0360a0850151166001600160401b0387511610908115611ed5575b50611ec2575160405194906001600160601b031661014086016001600160401b03811187821017611eaa5760405260e051865260e051602087015260e051604087015260e051606087015260e051608087015260e05160a087015260e05160c087015260e05160e087015260e05161010087015260606101208701525f60c052606060c0526040516106a460c05182613319565b6002815260c051601f190136602083013761012087015260208601819052604051637ba03aad60e01b8152600481018290529060c0826024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa9081156102dc5760e051928392611e76575b508160081c60020b60c08901528160201c60020b60a08901526040519060208201926001600160601b03197f000000000000000000000000000000000000000000000000000000000000000060c0511b16845262ffffff60e81b8160e01b16603484015262ffffff60e81b9060c81b166037830152603a820152603a81526107a4605a82613319565b5190206107b360a083206150a8565b600681018111611e5e5760066040519160208301938452016040820152604081526107e060c05182613319565b519020604051631e2eaeaf60e01b815260048101919091526020816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa9081156102dc5760e05191611e2a575b506001600160801b031660e087015260808101516001600160a01b03908116875281516101208801516108d79360a0939092169061087790613661565b52600180831b036020820151166108926101208a0151613682565b5262ffffff604082015116604089015260c05181015160020b6060890152207f00000000000000000000000000000000000000000000000000000000000000006145d5565b505060020b60808701526001600160a01b0316610100860152610120850151516109009061362f565b60a0526001600160801b0360408401511661091c60a051613661565b526001600160801b0360608401511661093660a051613682565b5261094360a0515161362f565b92608081015191604051610956816132c8565b60e051815260e051602082015260e051604082015260e0519060c05101526001600160401b0360608201511692835f19048111840215670de0b6b3a76400000215610190576001600160401b03604083015116805f19048211810215670de0b6b3a7640000021561019057670de0b6b3a76400006109da60c08b015160020b614689565b916109eb60a08c015160020b614689565b9382604051986109fa8a6132c8565b8202048852020460208601526001600160a01b03908116604086015260c051911690840152610100870151610a309084906136e4565b156119c1576001600160401b0360a08301511660018060a01b03610a586101208a0151613661565b51169060018060a01b03610a706101208b0151613682565b511660018060a01b03610a876101208c0151613661565b511615611e16575b60406080819052805190610aa39082613319565b6002815260208101601f196080510136823781511561195f576001905380516001101561195f576011602182015360805151916060610ae28185613319565b6002845260e0515b601f1982018110611e0457505090610bb39160208d01516080515190602082015260e05160805182015260e05160c05182015260e051608082015260a08082015260e05160c082015260c08152610b4260e082613319565b610b4b85613661565b52610b5584613661565b5060805151908660208301526080518201523060c05182015260c0518152610b7e608082613319565b610b8784613682565b52610b9183613682565b50610ba56080515193849260208401613ae1565b03601f198101835282613319565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03163b1561019057608051519063dd46508f60e01b82528180610c0660e05193429060048401613b53565b038160e05160018060a01b037f0000000000000000000000000000000000000000000000000000000000000000165af1801561182a57611deb575b50610c4d6024926149b6565b90602060018060a01b03610c656101208d0151613682565b511660805151948580926370a0823160e01b82523060048301525afa92831561182a5760e05193611db7575b50610ca7610ca060a051613661565b51836136b6565b815f190490818111830215670de0b6b3a7640000021561019057670de0b6b3a764000083610ce0920204610cda8b613661565b516136d7565b610ce98a613661565b52610cff610cf860a051613682565b51856136b6565b908111820215670de0b6b3a7640000021561019057610d2d91670de0b6b3a7640000910204610cda89613682565b610d3688613682565b526101208901516001600160a01b0390610d4f90613661565b5116610d5f610ca060a051613661565b608051519081527ff3055bc8d92d9c8d2f12b45d112dd345cd2cfd17292b8d65c5642ac6f912dfd760203392a36101208901516001600160a01b0390610da490613682565b5116610dbb610db460a051613682565b51846136b6565b608051519081527ff3055bc8d92d9c8d2f12b45d112dd345cd2cfd17292b8d65c5642ac6f912dfd760203392a3610df360a051613661565b52610dff60a051613682565b526101208701516001600160a01b0390610e1890613661565b511615611c57575b60806001600160401b03910151169162ffffff6040880151166001600160401b0360c084015116926101008901519060018060a01b0360408501511660018060a01b0360c0518601511690610e8a610e7960a051613661565b51610e838c613661565b51906136b6565b91610ea3610e9960a051613682565b51610e838d613682565b9460805151610eb1816132fe565b60e08051825280516020830152805160808051840191909152815160c051840152815192019190915251828210611a1e5750600195849760e051506001600160801b0383116101905764e8d4a51000028a01670de0b6b3a76400000392855f19048411860215670de0b6b3a76400000215610190576001600160801b0394610f8e94610f5690610f3f615196565b90670de0b6b3a76400008a6002890a92020461537e565b965b8a888b15611a0d5750610f6a916136b6565b925b878b8b156119fc5750610f7e916136d7565b935b6001600160a01b0316614a27565b1691875f19048311880215670de0b6b3a7640000021561019057865f19048511870215670de0b6b3a76400000215610190576110f9966110459587958e94670de0b6b3a7640000608051519c8d98610fe58a6132fe565b8415158a52828787020460208b01520204608051880152670de0b6b3a764000084840204830360c051880152608087015215155f146119d45750506110316020840151610cda8c613661565b61103a8b613661565b525b8960a051613b6f565b6110e060a0600180821b0361105e6101208b0151613661565b5116600180831b036110746101208c0151613682565b511662ffffff60408c01511660608c015160020b90600180861b038d51169260805151946110a1866132fe565b8552602085015260805184015260c0518301526080820152207f00000000000000000000000000000000000000000000000000000000000000006145d5565b5050506001600160a01b031661010088018190526136e4565b156119c1578051156119985761111060a051613661565b5161112961111f60a051613682565b51610e8386613682565b6001600160801b036111ad60018060a01b036111496101208b0151613661565b511615928315611977575b6101208a0151611177906001600160a01b039061117090613682565b5116614f49565b8460018060a01b036101008c0151168b6111a760a061119c60c084015160020b614689565b92015160020b614689565b91614a27565b1660e08801526101208701516001600160a01b03906111cb90613661565b51169160018060a01b036111e36101208a0151613682565b5116906080515060805151926111fb60805185613319565b60038452608051601f190136602086013783511561195f5760e051602085015383516001101561195f57600d602185015383516002101561195f57601460228501536080805151939061124e8186613319565b6003855260e0515b601f198201811061193957505060208b01516001600160801b0360e08d015116608051519160208301526080518201526001600160801b0360c0518201526001600160801b03608082015260a08082015260e05160c082015260c081526112be60e082613319565b6112c785613661565b526112d184613661565b50608051519086602083015260805182015260805181526112f460c05182613319565b6112fd84613682565b5261130783613682565b506080515185602082015230608051820152608051815261132a60c05182613319565b61133384613692565b5261133d83613692565b501561192c5761135c90925b610ba56080515193849260208401613ae1565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03163b156101905760805151809263dd46508f60e01b825281806113b060e05195429060048401613b53565b03917f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af1801561182a57611913575b506113f3906149b6565b6113fe60a051613661565b526024602060018060a01b03611418610120890151613682565b511660805151928380926370a0823160e01b82523060048301525afa90811561182a5760e051916118e1575b5061145060a051613682565b526001600160801b0360e086015116906080510151116118ce576101208401516001600160a01b039061148290613661565b511615611838575b6020840151833b15610190576080515163095ea7b360e01b8152336004820152602481019190915260e0518160448183885af1801561182a57611811575b5060e0519360015b60a05151861015611691576101208201516001600160a01b03906114f59088906136a2565b5116956115048160a0516136a2565b5161150f82876136a2565b511015611660576115306115258260a0516136a2565b51610e8383886136a2565b61153c8260a0516136a2565b526115498160a0516136a2565b51336014528060345263095ea7b360601b60e05152602060e0516044601060e0518c5af13d15600160e051511417161561160b575b5061159060019260e051603452613ab3565b965b61159c82876136a2565b516115ea575b6115ac82876136a2565b5160805151908152838060a01b038616907f1b37fcc57f4b6029ca7b3a70af0104811f67c72fe73e8043575f03a01e05663160203392a401946114d0565b6116066115f783886136a2565b51848060a01b03871683614340565b6115a2565b60e08051603481905263095ea7b360601b9052513860446010838c5af150603452602060e0516044601060e0518b5af13d15600160e0515114171615611651578761157e565b633e3f8f7360e051526004601cfd5b600191966116708260a0516136a2565b5161167b83886136a2565b5260e05161168b8360a0516136a2565b52611592565b84602083015192610120810151926116a76135f4565b506116b18161362f565b936116bb8261362f565b9060016116c78461362f565b936116d18161362f565b98876116dc8a613661565b526116e685613661565b52816116f186613661565b5260026116fd8a613661565b5211611776575b50946020929161177296608051519661171c886132c8565b87528487015260805186015260c0518501520151608051519081527f6c7e7d4cb83a668aef31739dd35dc3fc3d5f31d62b69e438b7b24d35b40dcc6360203392a3608051519182916020835260208301906133cd565b0390f35b60e051919693959394600194925b60a051518110156118015761179b8160a0516136a2565b516117a9575b600101611784565b946001906117f9906001600160a01b036117c389876136a2565b51166117cf82886136a2565b526117dc8860a0516136a2565b516117e782896136a2565b52826117f3828b6136a2565b52613ab3565b9590506117a1565b5094969195935060209050611704565b60e05161181d91613319565b60e05161019057846114c8565b608051513d60e051823e3d90fd5b611846610120850151613661565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169081905260a05161188090613661565b5190803b15610190576004916080515192838092630d0e30db60e41b825260e051945af1801561182a576118b5575b5061148a565b60e0516118c191613319565b60e05161019057846118af565b63bb55fd2760e01b60e05152600460e051fd5b90506020813d60201161190b575b816118fc60209383613319565b810103126102d0575186611444565b3d91506118ef565b60e05161191f91613319565b60e05161019057866113e9565b5061135c60e05192611349565b60209060c05182828901015201611256565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b60e051526032600452602460e051fd5b6101208a0151611993906001600160a01b039061117090613661565b611154565b6119b06119a660a051613661565b51610e8385613661565b6119bb60a051613682565b51611129565b633a8bf65960e01b60e05152600460e051fd5b6119ed91670de0b6b3a7640000910204610cda8c613682565b6119f68b613682565b5261103c565b9050611a07916136b6565b93610f80565b9050611a18916136d7565b92610f6c565b959092909190808411611a5557916001600160801b039391610f8e93611a4f64e8d4a51000849b028d0184866151df565b96610f58565b919290949395506001600160801b038111610190576002810a92828203611a7c87866150ce565b848460011b0303907812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f218111670de0b6b3a7640000021582021561019057670de0b6b3a7640000020495611ae2611adc611acd856150d8565b611ad5615196565b908b61537e565b836136d7565b967812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f218311670de0b6b3a764000002158802156101905787818d99670de0b6b3a7640000860204105f14611bd657611b8991611b7a91611b5b64e8d4a51000999a9b9c9d60019d8b82028101670de0b6b3a7640000039b8c92020184614674565b670de0b6b3a7640000019181670de0b6b3a76400008802049003614674565b96611b83615196565b8861537e565b937812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f218511670de0b6b3a76400000215860215610190576001600160801b0395670de0b6b3a7640000610f8e96020499610f58565b60e05199979850955093670de0b6b3a764000064e8d4a510008b028d015f1981900487110215021561019057611a4f64e8d4a51000611c4c610f8e978f99670de0b6b3a76400008f9b856001600160801b039d0201830204670de0b6b3a7640000039181670de0b6b3a76400008a020403614674565b9b028d018b866151df565b608051516370a0823160e01b81523060048201526020816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa90811561182a5760e05191611d85575b5080611cba575b50610e20565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03163b156101905760805151632e1a7d4d60e01b81526004810182905260e05181602481837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af1801561182a57611d6c575b506001600160401b0391611d59608092610cda60a051613661565b611d6460a051613661565b529150611cb4565b60e051611d7891613319565b60e0516101905788611d3e565b90506020813d602011611daf575b81611da060209383613319565b810103126102d0575188611cad565b3d9150611d93565b9092506020813d602011611de3575b81611dd360209383613319565b810103126102d05751918a610c91565b3d9150611dc6565b60e051611df791613319565b60e0516101905789610c41565b60209060c05182828801015201610aea565b60e051611e2460a051613661565b52610a8f565b90506020813d602011611e56575b81611e4560209383613319565b810103126102d057516108d761083a565b3d9150611e38565b634e487b7160e01b60e051526011600452602460e051fd5b909250611e9b915060c03d60c011611ea3575b611e938183613319565b810190613a2a565b90918861071b565b503d611e89565b634e487b7160e01b60e051526041600452602460e051fd5b632a9ffab760e21b60e05152600460e051fd5b90506001600160401b038060c0860151169151161086610610565b63f3f6425d60e01b60e05152600460e051fd5b6020366003190112610190576004356001600160401b03811161019057611f2e90369060040161335e565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690338290036123f2578290810103610100811261019057606081126101905760405190611f84826132e3565b83359081151582036101905760a091835260208501356020840152611fab6040860161327c565b6040840152605f1901126101905760405192611fc6846132fe565b611fd26060820161327c565b8452611fe06080820161327c565b906020850191825260a081013562ffffff8116810361019057604086015260c0810135908160020b820361019057606086019190915260e001356001600160a01b0381168103610190576080850152604051633cf3645360e21b8152916120759061204e60048501876135b1565b8051151560a4850152602081015160c4850152604001516001600160a01b031660e4840152565b61012061010483015260e0516101248301526020826101448160e051875af19182156102dc5760e051926123be575b5060405193826020860152602085526120be604086613319565b51905160e0516001600160a01b0391821692608085901d600f81900b939091169183126122cf575b84600f0b9260e051841261220f575b60e05112612199575b505060e0511261211f575b604051602080825281906117729082018761333a565b823b1561019057604051630b0d9c0960e01b815260e0516001600160a01b0390921660048201523060248201526001600160801b03909216604483015290918290818060648101039160e051905af180156102dc57612180575b8080612109565b60e05161218c91613319565b60e0516101905781612179565b853b1561019057604051630b0d9c0960e01b815260e0516001600160a01b0390931660048201523060248201526001600160801b03909116604482015290818060648101038160e051895af180156102dc576121f6575b806120fe565b60e05161220291613319565b60e05161019057856121f0565b863b1561019057604051632961046560e21b81526004810186905260e05181602481838c5af180156102dc576122b6575b5061225d6001600160801b0361225586613ac1565b168887614492565b604051630476982d60e21b815260208160048160e0518c5af180156102dc57612287575b506120f5565b6122a89060203d6020116122af575b6122a08183613319565b8101906134be565b5088612281565b503d612296565b60e0516122c291613319565b60e0516101905788612240565b853b1561019057604051632961046560e21b81526004810183905260e05181602481838b5af180156102dc576123a5575b508161236057600460206001600160801b0361231b84613ac1565b1660405192838092630476982d60e21b82528b5af180156102dc57612341575b506120e6565b6123599060203d6020116122af576122a08183613319565b508761233b565b61237c6001600160801b0361237483613ac1565b168784614492565b604051630476982d60e21b815260208160048160e0518b5af180156102dc5761234157506120e6565b60e0516123b191613319565b60e0516101905787612300565b9091506020813d6020116123ea575b816123da60209383613319565b810103126102d0575190846120a4565b3d91506123cd565b63f655705d60e01b60e05152600460e051fd5b3461019057602036600319011261019057600435801515908190036101905760e051547f549bab54c75a364ce0e438a4fbf09df7e6b096bcc83a6f91065a0fc8e410b29a91602091612461336001600160a01b03831614613457565b60e05160ff60a01b1990911660a083901b60ff60a01b16179055604051908152a160e05180f35b346101905760e0513660031901126101905760e051546040516001600160a01b039091168152602090f35b346101905760e051366003190112610190576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b346101905760e051366003190112610190576001546001600160a01b031633036125735760e0515460ff8160a01c166102fc5760e05160ff60a01b19909116600160a01b179055604051600181527f549bab54c75a364ce0e438a4fbf09df7e6b096bcc83a6f91065a0fc8e410b29a90602090a160e05180f35b636570ecab60e11b60e05152600460e051fd5b346102d05760403660031901126102d05761259f613250565b602435906001600160401b0382116102d057816004018236036101006003198201126102d05760ff5f5460a01c16612c6d57600254926001600160a01b038416612c5e576001600160a01b03166001600160a01b0319939093168317600255604051638da5cb5b60e01b81526020816004815f885af1908115612a28575f91612c24575b506001600160a01b039081165f908152600560209081526040808320878452909152902054163303612c155761265882613539565b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116911603612c06575f5f60448601956001600160801b036126a28861354d565b1615801590612be9575b612ae9575b6126ba85613539565b9160248201916126c983613561565b956126d38a61354d565b9960648301906126e28261354d565b60408051336020820152808201919091529a9096906001600160a01b03906127099061327c565b1660608c015261271890613575565b6001600160601b031660808b015261272f90613589565b6001600160801b031660a08a015261274690613589565b6001600160801b031660c0890152608482013560e089015261276a60a4830161359d565b6001600160401b031661010089015261278560c4830161359d565b6001600160401b031661012089015260e482013590602219018112156102d05701602460048201359101906001600160401b0381116102d05780360382136102d0576001600160601b03996128176101808a846001600160801b039695879661010061014085015281610160850152848401375f838284010152601f801991011681010301601f1981018b528a613319565b169216916001948115159182612ae0575b8415159182612ad0575b61283b8861362f565b9b8c996128478a61362f565b9861286361285d6128578d61362f565b9c61362f565b9c613661565b6001600160a01b0390911690521661287a88613661565b52600161288689613661565b5260026128928a613661565b52600193612a96575b5050612a61575b5050509061290d959291604051936128b9856132c8565b84526020840152604083015260608201526128d26135f4565b604051906128df826132e3565b6060825260208201905f825261291f60408401915f835260405198899660a0602089015260c08801906133cd565b868103601f19016040880152906133cd565b91601f19858403016060860152606083019351936060845284518091526020608085019501905f5b818110612a33575050509160406129aa94926129b8979451602084015251910152601f19848203016080850152606051808252806080602084015e5f828201602090810191909152601f909101601f191690910184810360a0860152019061333a565b03601f198101845283613319565b803b156102d0576040805162b9252f60e41b81523060048201526024810191909152905f9082908183816129ef604482018961333a565b03925af18015612a2857612a14575b600280546001600160a01b031916905560e05180f35b5f612a1e91613319565b5f60e052806129fe565b6040513d5f823e3d90fd5b825180516001600160a01b03168852602090810151818901528b985060409097019690920191600101612947565b600192612a8d92612a72838c6136a2565b90858060a01b03169052612a8682876136a2565b52856136a2565b528680806128a2565b90919250612aa38b613682565b6001600160a01b039091169052612ab986613682565b526001612ac587613682565b526002908a8061289b565b96612ada90613ab3565b96612832565b60029650612828565b915050612af583613539565b506001600160601b03612b0a60248301613561565b604051637ba03aad60e01b81529116600482015260c0816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115612a28575f91612bc9575b5080516020909101516001600160a01b0391821691168115612b82575b90916126b1565b90507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0381168214612bbb5790612b7b565b62820f3560e61b5f5260045ffd5b612be2915060c03d60c011611ea357611e938183613319565b5086612b5e565b506001600160801b03612bfe6064830161354d565b1615156126ac565b63ed5f09f160e01b5f5260045ffd5b6317fb43e560e31b5f5260045ffd5b90506020813d602011612c56575b81612c3f60209383613319565b810103126102d057612c50906134aa565b85612623565b3d9150612c32565b63b5dfd9e560e01b5f5260045ffd5b6313d0ff5960e31b5f5260045ffd5b346102d05760603660031901126102d057612c95613250565b612c9d61338b565b506044356001600160401b0381116102d057612cbd90369060040161335e565b6002546001600160a01b0316612c5e57604051630972932760e21b81523360048201526020816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115612a28575f91612d96575b5015612d875781019160c0828403126102d057612d3c8261327c565b9060a08301356001600160401b0381116102d05761001b94612d5f91850161351e565b9260808101359260608201359260408301359260200135916001600160a01b031690336136fd565b630ea8370b60e41b5f5260045ffd5b612db8915060203d602011612dbe575b612db08183613319565b810190613492565b84612d20565b503d612da6565b346102d0575f3660031901126102d057602060ff5f5460a01c166040519015158152f35b346102d0575f3660031901126102d0576001546040516001600160a01b039091168152602090f35b346102d05760e03660031901126102d057612e2a613250565b612e32613266565b9060c4356001600160401b0381116102d057612e5290369060040161335e565b60025491939092916001600160a01b0316612c5e57604051630972932760e21b81526001600160a01b0383811660048301819052949190602090829060249082907f0000000000000000000000000000000000000000000000000000000000000000165afa908115612a28575f91612fe3575b5015612d8757604051638da5cb5b60e01b8152936020856004815f855af1948515612a28575f95612fa7575b506001600160a01b0385163303612f985760205f91600460405180948193635e34633b60e11b83525af18015612a28575f90612f65575b6003915010612f565761001b94612f409136916134e8565b9260a435926084359260643592604435926136fd565b63a93eca7960e01b5f5260045ffd5b506020813d602011612f90575b81612f7f60209383613319565b810103126102d05760039051612f28565b3d9150612f72565b6312272fd360e11b5f5260045ffd5b9094506020813d602011612fdb575b81612fc360209383613319565b810103126102d057612fd4906134aa565b9386612ef1565b3d9150612fb6565b612ffc915060203d602011612dbe57612db08183613319565b86612ec5565b346102d05760203660031901126102d05761301b613250565b61302f60018060a01b035f54163314613457565b600180546001600160a01b0319166001600160a01b03929092169182179055337fa14fc14d8620a708a896fd11392a235647d99385500a295f0d7da2a258b2e9675f80a3005b346102d05760803660031901126102d05761308e613250565b50613097613266565b506064356001600160401b0381116102d0576130b790369060040161335e565b5050604051630a85bd0160e11b8152602090f35b346102d05760403660031901126102d0576130e4613250565b6130ec613266565b6001600160a01b039182165f908152600560209081526040808320938516835292815290829020549151919092168152f35b346102d05760203660031901126102d0576020613139613250565b6040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b039081169216919091148152f35b346102d05760203660031901126102d0576001600160a01b03613193613250565b165f52600460205260405f205f908054906131ad82613290565b808552916001811690811561322957506001146131e9575b611772846131d581860382613319565b60405191829160208352602083019061333a565b5f90815260208120939250905b80821061320f575090915081016020016131d5826131c5565b9192600181602092548385880101520191019092916131f6565b60ff191660208087019190915292151560051b850190920192506131d591508390506131c5565b600435906001600160a01b03821682036102d057565b602435906001600160a01b03821682036102d057565b35906001600160a01b03821682036102d057565b90600182811c921680156132be575b60208310146132aa57565b634e487b7160e01b5f52602260045260245ffd5b91607f169161329f565b608081019081106001600160401b0382111761194b57604052565b606081019081106001600160401b0382111761194b57604052565b60a081019081106001600160401b0382111761194b57604052565b90601f801991011681019081106001600160401b0382111761194b57604052565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b9181601f840112156102d0578235916001600160401b0383116102d057602083818601950101116102d057565b6024359081151582036102d057565b90602080835192838152019201905f5b8181106133b75750505090565b82518452602093840193909201916001016133aa565b80516080808452815190840181905260a08401949391602001905f5b81811061343857505050606061342461341261343595966020860151858203602087015261339a565b6040850151848203604086015261339a565b92015190606081840391015261339a565b90565b82516001600160a01b03168752602096870196909201916001016133e9565b1561345e57565b60405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606490fd5b908160209103126102d0575180151581036102d05790565b51906001600160a01b03821682036102d057565b908160209103126102d0575190565b6001600160401b03811161194b57601f01601f191660200190565b9291926134f4826134cd565b916135026040519384613319565b8294818452818301116102d0578281602093845f960137010152565b9080601f830112156102d057816020613435933591016134e8565b356001600160a01b03811681036102d05790565b356001600160801b03811681036102d05790565b356001600160601b03811681036102d05790565b35906001600160601b03821682036102d057565b35906001600160801b03821682036102d057565b35906001600160401b03821682036102d057565b80516001600160a01b03908116835260208083015182169084015260408083015162ffffff169084015260608083015160020b9084015260809182015116910152565b60405190613601826132c8565b606080838181528160208201528160408201520152565b6001600160401b03811161194b5760051b60200190565b9061363982613618565b6136466040519182613319565b8281528092613657601f1991613618565b0190602036910137565b80511561366e5760200190565b634e487b7160e01b5f52603260045260245ffd5b80516001101561366e5760400190565b80516002101561366e5760600190565b805182101561366e5760209160051b010190565b919082039182116136c357565b634e487b7160e01b5f52601160045260245ffd5b919082018092116136c357565b8151811191826136f357505090565b6020015111919050565b9196949095929395670de0b6b3a764000085118015613a19575b8015613a08575b80156139f7575b6139e8576001600160a01b039081165f9081526005602090815260408083208685168452909152902080546001600160a01b031916989091169788179055670de0b6b3a76400008082019081106136c357670de0b6b3a7640000810290808204670de0b6b3a764000014901517156136c3576137a86001600160401b03916143d0565b169281670de0b6b3a76400000391670de0b6b3a764000083116136c357670de0b6b3a76400008302928304670de0b6b3a76400001490670de0b6b3a76400001417156136c3576001600160401b03936001938561380581956143d0565b169084604051986138158a6132fe565b16885284602089019a168a526040880192835260608801918252846080890194168452858060a01b031698895f526003602052848060405f209951161685198954161788555191846fffffffffffffffff00000000000000008954928260801b905160801b16938260c01b905160c01b169460401b16911617171785555116920191166001600160401b0319825416179055815f52600460205260405f20908051906001600160401b03821161194b5781906138d18454613290565b601f8111613998575b50602090601f8311600114613935575f9261392a575b50508160011b915f199060031b1c19161790555b7febc70f7c8d6a67b19e15e968cb908d21719e8ff9a778a71171fba931a618d0525f80a3565b015190505f806138f0565b5f8581528281209350601f198516905b8181106139805750908460019594939210613968575b505050811b019055613904565b01515f1960f88460031b161c191690555f808061395b565b92936020600181928786015181550195019301613945565b909150835f5260205f20601f840160051c810191602085106139de575b90601f859493920160051c01905b8181106139d057506138da565b5f81558493506001016139c3565b90915081906139b5565b632a9ffab760e21b5f5260045ffd5b50670de0b6b3a76400008411613725565b50670de0b6b3a7640000821161371e565b50670de0b6b3a76400008711613717565b8092910360c081126102d05760a0136102d057604051613a49816132fe565b613a52836134aa565b8152613a60602084016134aa565b6020820152604083015162ffffff811681036102d057604082015260608301518060020b81036102d05760608201526080830151906001600160a01b03821682036102d05760a091608082015292015190565b5f1981146136c35760010190565b600f0b6f7fffffffffffffffffffffffffffffff1981146136c3575f0390565b90613af49060408352604083019061333a565b906020818303910152815180825260208201916020808360051b8301019401925f915b838310613b2657505050505090565b9091929394602080613b44600193601f19868203018752895161333a565b97019301930191939290613b17565b929190613b6a60209160408652604086019061333a565b930152565b94909293919360608301928351955f96156143365760e00151805180613f975750508051151590604083019362ffffff8551169661012085019760018060a01b03613bba8a51613661565b511697613c1b60a0600180821b03613bd28d51613682565b51169a62ffffff8b51169b60608b019c8d5160020b90600180861b038d51169260405194613bff866132fe565b85526020850152604084015260608301526080820152206150a8565b9260038401809411613f8357604051631e2eaeaf60e01b815260048101949094527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316966020856024818b5afa948515613f7857908e92918e96613f3d575b506101008a01516040880151606090980151613ce8986001600160a01b0391821694908216939190921691613cd090610e83613cc9613cc36119a68a613661565b98613682565b5191613682565b9551966001600160801b0360808c0151991691614b1c565b908115613f325787968795613e0395613dce9351151598895f14613f18576401000276a45b60405196613d1a886132e3565b8b885260208801526001600160a01b039081166040880152845162ffffff9190613d4390613661565b5195519516946001600160a01b0390613d5b90613682565b5116935116905160020b9160018060a01b039051169260405194613d7e866132fe565b85526020850152604084015260608301526080820152613dc4604051936020850190604090805115158352602081015160208401528160018060a01b0391015116910152565b60808301906135b1565b6101008152613ddf61012082613319565b6040519687809481936348c8949160e01b835260206004840152602483019061333a565b03925af1928315613f0d578293613ec3575b50602083519381808201958692010103126102d057613e87925191815f14613ea457613e59613e4386613661565b51613e538560801d600f0b614f39565b906136b6565b613e6286613661565b525015613e8a57613e8190613e7684613682565b5190600f0b906136d7565b91613682565b52565b613e8190613e53613e9a85613682565b5191600f0b614f39565b613ebe613eb086613661565b518460801d600f0b906136d7565b613e59565b9092503d8083833e613ed58183613319565b810190602081830312613f09578051906001600160401b038211613f0557613efe929101614ad6565b915f613e15565b8380fd5b8280fd5b6040513d84823e3d90fd5b73fffd8963efd1fc6a506488495d951d5263988d25613d0d565b505050505050505050565b925094506020823d602011613f70575b81613f5a60209383613319565b810103126102d0579051938d9190613ce8613c82565b3d9150613f4d565b6040513d8f823e3d90fd5b634e487b7160e01b8c52601160045260248cfd5b9350969450909250511515908501936060868603126102d05760208601516001600160a01b03811695908690036102d0576040870151966060810151916001600160401b0383116102d057613ff3926020809201920101614ad6565b9482156142fe576101208401958260018060a01b036140128951613661565b5198519816976001600160a01b039061402a90613682565b5116975b979561404561012060018060a01b03920151613661565b511615978861423a575b6040936140bc936001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116949193919291166140938d8683614340565b8651998a96879586946344bc658560e01b8652600486015260a0602486015260a485019061333a565b60448401929092526001600160a01b03166064830152608482018d905203925af194851561422d57819382966141f2575b5061415b575b50156141355761411c61412691614117613e87959661411186613661565b516136b6565b6136d7565b93610cda83613682565b61412f82613682565b52613661565b6141569061411761414c613e8795610cda86613661565b9561411185613682565b614126565b81156141ec57825b8061416f575b506140f3565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690813b15613f09578291602483926040519485938492632e1a7d4d60e01b845260048401525af18015613f0d579082916141d4575b50614169565b816141de91613319565b6141e957805f6141ce565b80fd5b84614163565b935094506040833d604011614225575b8161420f60409383613319565b810103126141e95760208351930151945f6140ed565b3d9150614202565b50604051903d90823e3d90fd5b905084156142cd57507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b038116803b156102d0575f8a91600460405180948193630d0e30db60e41b83525af18015612a28576142ae575b50916140bc91846040945b91935091935061404f565b604093919450916142c25f6140bc94613319565b5f9491935091614298565b94506040916140bc91847f0000000000000000000000000000000000000000000000000000000000000000976142a3565b6101208401958260018060a01b036143168951613682565b5198519816976001600160a01b039061432e90613661565b51169761402e565b5050505050505050565b60405163a9059cbb60e01b81526001600160a01b03909216600483015260248201929092526020905f9060449082855af19081601f3d1160015f51141615166143c3575b501561438c57565b60405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606490fd5b3b153d171590505f614384565b60b581600160881b81101561447b575b8069010000000000000000006201000092101561446e575b65010000000000811015614461575b6301000000811015614454575b010260121c8082040160011c8082040160011c8082040160011c8082040160011c8082040160011c8082040160011c8082040160011c8080920410900390565b60101c9160081b91614414565b60201c9160101b91614407565b60401c9160201b916143f8565b5068b500000000000000009050608082901c6143e0565b9091906001600160a01b03811690816145205750505f80808093855af1156144b75750565b6040516390bfb86560e01b81526001600160a01b0390911660048201525f602482018190526080604483015260a03d601f01601f191690810160648401523d6084840152903d9060a484013e808201600460a482015260c4633d2cec6f60e21b91015260e40190fd5b60205f604481949682604095865198899363a9059cbb60e01b855260018060a01b0316600485015260248401525af13d15601f3d116001855114161716928281528260208201520152156145715750565b6040516390bfb86560e01b8152600481019190915263a9059cbb60e01b602482015260806044820152601f3d01601f191660a0810160648301523d60848301523d5f60a484013e808201600460a482015260c4633c9fd93960e21b91015260e40190fd5b91906145e26020916150a8565b604051631e2eaeaf60e01b8152600481019190915292839060249082906001600160a01b03165afa918215612a28575f92614640575b506001600160a01b0382169160a081901c60020b9162ffffff60b883901c81169260d01c1690565b9091506020813d60201161466c575b8161465c60209383613319565b810103126102d05751905f614618565b3d915061464f565b815f190481118202158302156102d057020490565b60020b908160ff1d82810118620d89e881116149a35763ffffffff9192600182167001fffcb933bd6fad37aa2d162d1a59400102600160801b189160028116614987575b6004811661496b575b6008811661494f575b60108116614933575b60208116614917575b604081166148fb575b608081166148df575b61010081166148c3575b61020081166148a7575b610400811661488b575b610800811661486f575b6110008116614853575b6120008116614837575b614000811661481b575b61800081166147ff575b6201000081166147e3575b6202000081166147c8575b6204000081166147ad575b6208000016614794575b5f1261478c575b0160201c90565b5f1904614785565b6b048a170391f7dc42444e8fa290910260801c9061477e565b6d2216e584f5fa1ea926041bedfe9890920260801c91614774565b916e5d6af8dedb81196699c329225ee6040260801c91614769565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c9161475e565b916f31be135f97d08fd981231505542fcfa60260801c91614753565b916f70d869a156d2a1b890bb3df62baf32f70260801c91614749565b916fa9f746462d870fdf8a65dc1f90e061e50260801c9161473f565b916fd097f3bdfd2022b8845ad8f792aa58250260801c91614735565b916fe7159475a2c29b7443b29c7fa6e889d90260801c9161472b565b916ff3392b0822b70005940c7a398e4b70f30260801c91614721565b916ff987a7253ac413176f2b074cf7815e540260801c91614717565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c9161470d565b916ffe5dee046a99a2a811c461f1969c30530260801c91614703565b916fff2ea16466c96a3843ec78b326b528610260801c916146fa565b916fff973b41fa98c081472e6896dfb254c00260801c916146f1565b916fffcb9843d60f6159c9db58835c9266440260801c916146e8565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c916146df565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c916146d6565b916ffff97272373d413259a46990580e213a0260801c916146cd565b826345c3193d60e11b5f5260045260245ffd5b6001600160a01b0316806149c957504790565b6020602491604051928380926370a0823160e01b82523060048301525afa908115612a28575f916149f8575090565b90506020813d602011614a1f575b81614a1360209383613319565b810103126102d0575190565b3d9150614a06565b936001600160a01b0383811690831611614ace575b6001600160a01b03858116959083168611614a71575050614a5d9350615264565b6001600160801b0381169081036102d05790565b919490939192906001600160a01b0382161115614ac2578291614a9891614a9e9594615264565b93615233565b80821015614abb57506001600160801b0381169081036102d05790565b9050614a5d565b915050614a5d92615233565b909190614a3c565b81601f820112156102d057805190614aed826134cd565b92614afb6040519485613319565b828452602083830101116102d057815f9260208093018386015e8301015290565b93929597949091965f945b60648610614b3c575050505050505050505090565b9091929394959697989984620f42400397885f19048111890215620f424002156102d057620f4240908902048215614f08576001600160a01b0390614b82908c8c61545d565b16906001600160a01b038111614ebc5760601b6001600160801b038b1680820615159104015b6001600160a01b038a169080821115614eaf5790036001600160a01b03165b8215614e91570160011c6001600160a01b0316945b6001600160a01b038681169085168110614c14575050505050505050614c08614c0f916134359561552d565b838361545d565b615659565b60018060a09d9c9b9a939495969798999d1b0383161015614e68578215614e4757614c4990614c448a8a8a6155f9565b615550565b99614c55898989615659565b965b87908c8c838715614e14575050808d1115614e0a57614c7a908d035b8883615264565b614c878a88018387615233565b995b8a82109a8b15614dc9577812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f218311670de0b6b3a764000002158102156102d05780670de0b6b3a76400008402049b5b15614d825750506001600160801b0381169081036102d057614cf29185615685565b908415614d785785919082821115614d3a5750035b620f4240819c98670de0b6b3a76400000310614d2b57506001019492909391614b27565b9a505050505050505050505090565b915050600a60097f1c71c71c71c71c71c71c71c71c71c71c71c71c71c71c71c71c71c71c71c71c718311021502156102d0576009600a910204614d07565b9b5084039a614d07565b90939e9291506001600160801b0381169081036102d05788614da3926155f9565b918515614db45750508a039a614d07565b8c92919d508282115f14614d3a575003614d07565b7812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f218111670de0b6b3a764000002158302156102d05782670de0b6b3a76400008202049b614cd0565b50614c7a5f614c73565b614e2091018984615264565b9080881115614e3d57614e379088035b8387615233565b99614c89565b50614e375f614e30565b614e5690614c448a898b615685565b99614e6289888a61558f565b96614c57565b9450505090506134359650614e8b93949550614e84925061552d565b83836154d7565b9061558f565b6001600160a01b039180820160011c91600291081515011694614bdc565b634323a5555f526004601cfd5b6001600160801b038b16614ed581600160601b8461537e565b918115614ef457600160601b900915614ba85760010180614ba8575f80fd5b634e487b7160e01b5f52601260045260245ffd5b906001600160a01b0390614f1d908c8c6153fe565b16906001600160a01b0390614f33908c8c6154d7565b16614bc7565b600160ff1b81146136c3575f0390565b6001600160a01b03165f8181526006602052604090205460ff1615614f6b5750565b5f8181526006602090815260408220805460ff191660011790557f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031660148190525f1960345263095ea7b360601b835292916044601082855af13d1560015f5114171615615064575b5f603452813b156102d0576040516387517c4560e01b815260048101919091526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081166024830152604482015265ffffffffffff6064820152905f908290608490829084905af18015612a28576150585750565b5f61506291613319565b565b5f603481905263095ea7b360601b8152386044601083855af1505f1960345260205f6044601082855af13d1560015f51141716614fdc57633e3f8f735f526004601cfd5b6040516020810191825260066040820152604081526150c8606082613319565b51902090565b8115614ef4570490565b5f908015615190578080600114615188576002146151815760016101338210166001600b83101617615173579060019060025b600181116151375750825f1904821161512357500290565b634e487b7160e01b81526011600452602490fd5b92805f1904811161515f5760018416615156575b80029260011c61510b565b8092029161514b565b634e487b7160e01b82526011600452602482fd5b6002900a9190806151235750565b5050600490565b505050600190565b50505f90565b600160601b600160025b600181116151b75750815f190481116136c3570290565b91805f190481116136c357600183166151d6575b80029160011c6151a0565b809102906151cb565b90916001600160801b0382116102d057670de0b6b3a76400000390825f19048211830215670de0b6b3a764000002156102d057670de0b6b3a7640000613435936002615229615196565b930a93020461537e565b6134359291906001600160a01b038083169082161161525e575b90036001600160a01b0316906152ab565b9061524d565b61343592916001600160a01b03808216908316116152a5575b6152936001600160a01b03828116908416615335565b9190036001600160a01b03169161537e565b9061527d565b90606082901b905f19600160601b8409928280851094039380850394858411156102d0571461532e578190600160601b900981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b81810291905f1982820991838084109303928084039384600160601b11156102d0571461537557600160601b910990828211900360a01b910360601c1790565b50505060601c90565b91818302915f19818509938380861095039480860395868511156102d057146153f6579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b91908115615458576001600160a01b03909216918183029160609190911b600160601b600160e01b03169082048314828211161561544b5761343592615446928203916156c1565b6156ea565b63f5c787f15f526004601cfd5b505090565b919081156154585760601b600160601b600160e01b0316916001600160a01b0316908082028261548d83836150ce565b146154b5575b506141176154a192846150ce565b80820491061515016001600160a01b031690565b8301838110615493576001600160a01b03936154d3939192506156c1565b1690565b6134359261544692906001600160a01b038111615514576001600160801b0361550492169060601b6150ce565b905b6001600160a01b03166136d7565b6001600160801b036155279216906152ab565b90615506565b815f19048111820215620f424002156102d05702620f4240808204910615150190565b7d10c6f7a0b5ed8d36b4c7f34938583621fafc8b0079a2834d26fa3fcc9ea98111620f424002158202156102d057620f42400290808204910615150190565b906001600160a01b03808216908316116155f3575b6001600160a01b0382169182156155e757613435936155e2926001600160a01b0380821693909103169060601b600160601b600160e01b031661537e565b6150ce565b62bfc9215f526004601cfd5b906155a4565b6001600160a01b0382811690821611615653575b6001600160a01b0381169283156155e757615647926001600160a01b0380821693909103169060601b600160601b600160e01b03166156c1565b90808206151591040190565b9061560d565b613435926001600160a01b03928316919092160360ff81901d90810118906001600160801b0316615335565b6001600160a01b0391821691160360ff81901d90810118906001906001600160801b03166156b38382615335565b928260601b91091515160190565b9291906156cf82828661537e565b938215614ef457096156dd57565b906001019081156102d057565b6001600160a01b038116919082036156fe57565b6393dafdf160e01b5f5260045ffdfea2646970667358221220ce3236855debde6b4e6818f671f25f9ab778cb4a74be3cb3331e8c6ccc85914764736f6c634300081e0033000000000000000000000000b4d72b1c91e640e4ed7d7397f3244de4d8acc50b000000000000000000000000da14fdd72345c4d2511357214c5b89a919768e59000000000000000000000000354dbba1348985cc952c467b8ddaf5dd075906670000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba30000000000000000000000001f984000000000000000000000000000000000040000000000000000000000004200000000000000000000000000000000000006
Deployed Bytecode
0x61010080604052600436101561001d575b50361561001b575f80fd5b005b5f60e0525f3560e01c9081630686ddd914613172575080630a73e3911461311e5780631204f525146130cb578063150b7a02146130755780632fcb4f04146130025780633d692da114612e11578063452a932014612de95780635c975abb14612dc55780635f4860df14612c7c5780637d5ad9cd146125865780638456cb59146124f95780638cffa277146124b35780638da5cb5b146124885780638da92e711461240557806391dd734614611f03578063a129568d1461045a578063a7310b58146103d4578063a89d6dd414610355578063b699b82b1461030f578063bc25cf77146101965763f2fde38b14610114575f610010565b346101905760203660031901126101905761012d613250565b60e0515490610146336001600160a01b03841614613457565b60018060a01b031680916001600160601b0360a01b161760e05155337f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060e05160e051a360e05180f35b60e05180fd5b34610190576020366003190112610190576101af613250565b60e0515460ff906101ca336001600160a01b03831614613457565b60a01c166102fc576002546001600160a01b03166102e9576001600160a01b031680610264575060e05180808047335af13d1561025c573d9061020c826134cd565b9161021a6040519384613319565b825260e0513d90602084013e5b1561023457505b60e05180f35b60405162461bcd60e51b81526020600482015290819061025890602483019061333a565b0390fd5b606090610227565b6040516370a0823160e01b815230600482015290602082602481845afa9081156102dc5760e051916102a2575b61029d92503390614340565b61022e565b90506020823d6020116102d4575b816102bd60209383613319565b810103126102d05761029d915190610291565b5f80fd5b3d91506102b0565b6040513d60e051823e3d90fd5b63b5dfd9e560e01b60e05152600460e051fd5b6313d0ff5960e31b60e05152600460e051fd5b346101905760e051366003190112610190576040517f000000000000000000000000354dbba1348985cc952c467b8ddaf5dd075906676001600160a01b03168152602090f35b346101905760a03660031901126101905760803660231901126101905760405161037e816132c8565b602435815260443560208201526064356001600160a01b03811681036101905760408201526084356001600160a01b038116810361019057816103ca91606060209401526004356136e4565b6040519015158152f35b34610190576020366003190112610190576001600160a01b036103f5613250565b1660e05152600360205260a0604060e051206001600160401b036001825492015416604051916001600160401b03811683526001600160401b038160401c1660208401526001600160401b038160801c16604084015260c01c60608301526080820152f35b34610190576020366003190112610190576004356001600160401b0381116101905761048a90369060040161335e565b906104936135f4565b506002546001600160a01b03163303611ef0573360e051526003602052604060e0512090604051926104c4846132fe565b6001600160401b03600184549482861687526020870195838160401c168752838160801c16604089015260c01c60608801520154166080850152810190604081830312610190576105148161327c565b906020810135906001600160401b03821161019057019161010083820312610190576040519261010084018481106001600160401b03821117611eaa5760405261055d8161327c565b845261056b60208201613575565b916020850192835261057f60408301613589565b604086015261059060608301613589565b6060860152608082013560808601526105ab60a0830161359d565b60a08601526105bc60c0830161359d565b60c086015260e08201356001600160401b038111610190576105de920161351e565b60e084015260018060a01b03835116936001600160401b0360a0850151166001600160401b0387511610908115611ed5575b50611ec2575160405194906001600160601b031661014086016001600160401b03811187821017611eaa5760405260e051865260e051602087015260e051604087015260e051606087015260e051608087015260e05160a087015260e05160c087015260e05160e087015260e05161010087015260606101208701525f60c052606060c0526040516106a460c05182613319565b6002815260c051601f190136602083013761012087015260208601819052604051637ba03aad60e01b8152600481018290529060c0826024817f0000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf6001600160a01b03165afa9081156102dc5760e051928392611e76575b508160081c60020b60c08901528160201c60020b60a08901526040519060208201926001600160601b03197f0000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf60c0511b16845262ffffff60e81b8160e01b16603484015262ffffff60e81b9060c81b166037830152603a820152603a81526107a4605a82613319565b5190206107b360a083206150a8565b600681018111611e5e5760066040519160208301938452016040820152604081526107e060c05182613319565b519020604051631e2eaeaf60e01b815260048101919091526020816024817f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b03165afa9081156102dc5760e05191611e2a575b506001600160801b031660e087015260808101516001600160a01b03908116875281516101208801516108d79360a0939092169061087790613661565b52600180831b036020820151166108926101208a0151613682565b5262ffffff604082015116604089015260c05181015160020b6060890152207f0000000000000000000000001f984000000000000000000000000000000000046145d5565b505060020b60808701526001600160a01b0316610100860152610120850151516109009061362f565b60a0526001600160801b0360408401511661091c60a051613661565b526001600160801b0360608401511661093660a051613682565b5261094360a0515161362f565b92608081015191604051610956816132c8565b60e051815260e051602082015260e051604082015260e0519060c05101526001600160401b0360608201511692835f19048111840215670de0b6b3a76400000215610190576001600160401b03604083015116805f19048211810215670de0b6b3a7640000021561019057670de0b6b3a76400006109da60c08b015160020b614689565b916109eb60a08c015160020b614689565b9382604051986109fa8a6132c8565b8202048852020460208601526001600160a01b03908116604086015260c051911690840152610100870151610a309084906136e4565b156119c1576001600160401b0360a08301511660018060a01b03610a586101208a0151613661565b51169060018060a01b03610a706101208b0151613682565b511660018060a01b03610a876101208c0151613661565b511615611e16575b60406080819052805190610aa39082613319565b6002815260208101601f196080510136823781511561195f576001905380516001101561195f576011602182015360805151916060610ae28185613319565b6002845260e0515b601f1982018110611e0457505090610bb39160208d01516080515190602082015260e05160805182015260e05160c05182015260e051608082015260a08082015260e05160c082015260c08152610b4260e082613319565b610b4b85613661565b52610b5584613661565b5060805151908660208301526080518201523060c05182015260c0518152610b7e608082613319565b610b8784613682565b52610b9183613682565b50610ba56080515193849260208401613ae1565b03601f198101835282613319565b7f0000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf6001600160a01b03163b1561019057608051519063dd46508f60e01b82528180610c0660e05193429060048401613b53565b038160e05160018060a01b037f0000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf165af1801561182a57611deb575b50610c4d6024926149b6565b90602060018060a01b03610c656101208d0151613682565b511660805151948580926370a0823160e01b82523060048301525afa92831561182a5760e05193611db7575b50610ca7610ca060a051613661565b51836136b6565b815f190490818111830215670de0b6b3a7640000021561019057670de0b6b3a764000083610ce0920204610cda8b613661565b516136d7565b610ce98a613661565b52610cff610cf860a051613682565b51856136b6565b908111820215670de0b6b3a7640000021561019057610d2d91670de0b6b3a7640000910204610cda89613682565b610d3688613682565b526101208901516001600160a01b0390610d4f90613661565b5116610d5f610ca060a051613661565b608051519081527ff3055bc8d92d9c8d2f12b45d112dd345cd2cfd17292b8d65c5642ac6f912dfd760203392a36101208901516001600160a01b0390610da490613682565b5116610dbb610db460a051613682565b51846136b6565b608051519081527ff3055bc8d92d9c8d2f12b45d112dd345cd2cfd17292b8d65c5642ac6f912dfd760203392a3610df360a051613661565b52610dff60a051613682565b526101208701516001600160a01b0390610e1890613661565b511615611c57575b60806001600160401b03910151169162ffffff6040880151166001600160401b0360c084015116926101008901519060018060a01b0360408501511660018060a01b0360c0518601511690610e8a610e7960a051613661565b51610e838c613661565b51906136b6565b91610ea3610e9960a051613682565b51610e838d613682565b9460805151610eb1816132fe565b60e08051825280516020830152805160808051840191909152815160c051840152815192019190915251828210611a1e5750600195849760e051506001600160801b0383116101905764e8d4a51000028a01670de0b6b3a76400000392855f19048411860215670de0b6b3a76400000215610190576001600160801b0394610f8e94610f5690610f3f615196565b90670de0b6b3a76400008a6002890a92020461537e565b965b8a888b15611a0d5750610f6a916136b6565b925b878b8b156119fc5750610f7e916136d7565b935b6001600160a01b0316614a27565b1691875f19048311880215670de0b6b3a7640000021561019057865f19048511870215670de0b6b3a76400000215610190576110f9966110459587958e94670de0b6b3a7640000608051519c8d98610fe58a6132fe565b8415158a52828787020460208b01520204608051880152670de0b6b3a764000084840204830360c051880152608087015215155f146119d45750506110316020840151610cda8c613661565b61103a8b613661565b525b8960a051613b6f565b6110e060a0600180821b0361105e6101208b0151613661565b5116600180831b036110746101208c0151613682565b511662ffffff60408c01511660608c015160020b90600180861b038d51169260805151946110a1866132fe565b8552602085015260805184015260c0518301526080820152207f0000000000000000000000001f984000000000000000000000000000000000046145d5565b5050506001600160a01b031661010088018190526136e4565b156119c1578051156119985761111060a051613661565b5161112961111f60a051613682565b51610e8386613682565b6001600160801b036111ad60018060a01b036111496101208b0151613661565b511615928315611977575b6101208a0151611177906001600160a01b039061117090613682565b5116614f49565b8460018060a01b036101008c0151168b6111a760a061119c60c084015160020b614689565b92015160020b614689565b91614a27565b1660e08801526101208701516001600160a01b03906111cb90613661565b51169160018060a01b036111e36101208a0151613682565b5116906080515060805151926111fb60805185613319565b60038452608051601f190136602086013783511561195f5760e051602085015383516001101561195f57600d602185015383516002101561195f57601460228501536080805151939061124e8186613319565b6003855260e0515b601f198201811061193957505060208b01516001600160801b0360e08d015116608051519160208301526080518201526001600160801b0360c0518201526001600160801b03608082015260a08082015260e05160c082015260c081526112be60e082613319565b6112c785613661565b526112d184613661565b50608051519086602083015260805182015260805181526112f460c05182613319565b6112fd84613682565b5261130783613682565b506080515185602082015230608051820152608051815261132a60c05182613319565b61133384613692565b5261133d83613692565b501561192c5761135c90925b610ba56080515193849260208401613ae1565b7f0000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf6001600160a01b03163b156101905760805151809263dd46508f60e01b825281806113b060e05195429060048401613b53565b03917f0000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf6001600160a01b03165af1801561182a57611913575b506113f3906149b6565b6113fe60a051613661565b526024602060018060a01b03611418610120890151613682565b511660805151928380926370a0823160e01b82523060048301525afa90811561182a5760e051916118e1575b5061145060a051613682565b526001600160801b0360e086015116906080510151116118ce576101208401516001600160a01b039061148290613661565b511615611838575b6020840151833b15610190576080515163095ea7b360e01b8152336004820152602481019190915260e0518160448183885af1801561182a57611811575b5060e0519360015b60a05151861015611691576101208201516001600160a01b03906114f59088906136a2565b5116956115048160a0516136a2565b5161150f82876136a2565b511015611660576115306115258260a0516136a2565b51610e8383886136a2565b61153c8260a0516136a2565b526115498160a0516136a2565b51336014528060345263095ea7b360601b60e05152602060e0516044601060e0518c5af13d15600160e051511417161561160b575b5061159060019260e051603452613ab3565b965b61159c82876136a2565b516115ea575b6115ac82876136a2565b5160805151908152838060a01b038616907f1b37fcc57f4b6029ca7b3a70af0104811f67c72fe73e8043575f03a01e05663160203392a401946114d0565b6116066115f783886136a2565b51848060a01b03871683614340565b6115a2565b60e08051603481905263095ea7b360601b9052513860446010838c5af150603452602060e0516044601060e0518b5af13d15600160e0515114171615611651578761157e565b633e3f8f7360e051526004601cfd5b600191966116708260a0516136a2565b5161167b83886136a2565b5260e05161168b8360a0516136a2565b52611592565b84602083015192610120810151926116a76135f4565b506116b18161362f565b936116bb8261362f565b9060016116c78461362f565b936116d18161362f565b98876116dc8a613661565b526116e685613661565b52816116f186613661565b5260026116fd8a613661565b5211611776575b50946020929161177296608051519661171c886132c8565b87528487015260805186015260c0518501520151608051519081527f6c7e7d4cb83a668aef31739dd35dc3fc3d5f31d62b69e438b7b24d35b40dcc6360203392a3608051519182916020835260208301906133cd565b0390f35b60e051919693959394600194925b60a051518110156118015761179b8160a0516136a2565b516117a9575b600101611784565b946001906117f9906001600160a01b036117c389876136a2565b51166117cf82886136a2565b526117dc8860a0516136a2565b516117e782896136a2565b52826117f3828b6136a2565b52613ab3565b9590506117a1565b5094969195935060209050611704565b60e05161181d91613319565b60e05161019057846114c8565b608051513d60e051823e3d90fd5b611846610120850151613661565b7f00000000000000000000000042000000000000000000000000000000000000066001600160a01b03169081905260a05161188090613661565b5190803b15610190576004916080515192838092630d0e30db60e41b825260e051945af1801561182a576118b5575b5061148a565b60e0516118c191613319565b60e05161019057846118af565b63bb55fd2760e01b60e05152600460e051fd5b90506020813d60201161190b575b816118fc60209383613319565b810103126102d0575186611444565b3d91506118ef565b60e05161191f91613319565b60e05161019057866113e9565b5061135c60e05192611349565b60209060c05182828901015201611256565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b60e051526032600452602460e051fd5b6101208a0151611993906001600160a01b039061117090613661565b611154565b6119b06119a660a051613661565b51610e8385613661565b6119bb60a051613682565b51611129565b633a8bf65960e01b60e05152600460e051fd5b6119ed91670de0b6b3a7640000910204610cda8c613682565b6119f68b613682565b5261103c565b9050611a07916136b6565b93610f80565b9050611a18916136d7565b92610f6c565b959092909190808411611a5557916001600160801b039391610f8e93611a4f64e8d4a51000849b028d0184866151df565b96610f58565b919290949395506001600160801b038111610190576002810a92828203611a7c87866150ce565b848460011b0303907812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f218111670de0b6b3a7640000021582021561019057670de0b6b3a7640000020495611ae2611adc611acd856150d8565b611ad5615196565b908b61537e565b836136d7565b967812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f218311670de0b6b3a764000002158802156101905787818d99670de0b6b3a7640000860204105f14611bd657611b8991611b7a91611b5b64e8d4a51000999a9b9c9d60019d8b82028101670de0b6b3a7640000039b8c92020184614674565b670de0b6b3a7640000019181670de0b6b3a76400008802049003614674565b96611b83615196565b8861537e565b937812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f218511670de0b6b3a76400000215860215610190576001600160801b0395670de0b6b3a7640000610f8e96020499610f58565b60e05199979850955093670de0b6b3a764000064e8d4a510008b028d015f1981900487110215021561019057611a4f64e8d4a51000611c4c610f8e978f99670de0b6b3a76400008f9b856001600160801b039d0201830204670de0b6b3a7640000039181670de0b6b3a76400008a020403614674565b9b028d018b866151df565b608051516370a0823160e01b81523060048201526020816024817f00000000000000000000000042000000000000000000000000000000000000066001600160a01b03165afa90811561182a5760e05191611d85575b5080611cba575b50610e20565b7f00000000000000000000000042000000000000000000000000000000000000066001600160a01b03163b156101905760805151632e1a7d4d60e01b81526004810182905260e05181602481837f00000000000000000000000042000000000000000000000000000000000000066001600160a01b03165af1801561182a57611d6c575b506001600160401b0391611d59608092610cda60a051613661565b611d6460a051613661565b529150611cb4565b60e051611d7891613319565b60e0516101905788611d3e565b90506020813d602011611daf575b81611da060209383613319565b810103126102d0575188611cad565b3d9150611d93565b9092506020813d602011611de3575b81611dd360209383613319565b810103126102d05751918a610c91565b3d9150611dc6565b60e051611df791613319565b60e0516101905789610c41565b60209060c05182828801015201610aea565b60e051611e2460a051613661565b52610a8f565b90506020813d602011611e56575b81611e4560209383613319565b810103126102d057516108d761083a565b3d9150611e38565b634e487b7160e01b60e051526011600452602460e051fd5b909250611e9b915060c03d60c011611ea3575b611e938183613319565b810190613a2a565b90918861071b565b503d611e89565b634e487b7160e01b60e051526041600452602460e051fd5b632a9ffab760e21b60e05152600460e051fd5b90506001600160401b038060c0860151169151161086610610565b63f3f6425d60e01b60e05152600460e051fd5b6020366003190112610190576004356001600160401b03811161019057611f2e90369060040161335e565b7f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b031690338290036123f2578290810103610100811261019057606081126101905760405190611f84826132e3565b83359081151582036101905760a091835260208501356020840152611fab6040860161327c565b6040840152605f1901126101905760405192611fc6846132fe565b611fd26060820161327c565b8452611fe06080820161327c565b906020850191825260a081013562ffffff8116810361019057604086015260c0810135908160020b820361019057606086019190915260e001356001600160a01b0381168103610190576080850152604051633cf3645360e21b8152916120759061204e60048501876135b1565b8051151560a4850152602081015160c4850152604001516001600160a01b031660e4840152565b61012061010483015260e0516101248301526020826101448160e051875af19182156102dc5760e051926123be575b5060405193826020860152602085526120be604086613319565b51905160e0516001600160a01b0391821692608085901d600f81900b939091169183126122cf575b84600f0b9260e051841261220f575b60e05112612199575b505060e0511261211f575b604051602080825281906117729082018761333a565b823b1561019057604051630b0d9c0960e01b815260e0516001600160a01b0390921660048201523060248201526001600160801b03909216604483015290918290818060648101039160e051905af180156102dc57612180575b8080612109565b60e05161218c91613319565b60e0516101905781612179565b853b1561019057604051630b0d9c0960e01b815260e0516001600160a01b0390931660048201523060248201526001600160801b03909116604482015290818060648101038160e051895af180156102dc576121f6575b806120fe565b60e05161220291613319565b60e05161019057856121f0565b863b1561019057604051632961046560e21b81526004810186905260e05181602481838c5af180156102dc576122b6575b5061225d6001600160801b0361225586613ac1565b168887614492565b604051630476982d60e21b815260208160048160e0518c5af180156102dc57612287575b506120f5565b6122a89060203d6020116122af575b6122a08183613319565b8101906134be565b5088612281565b503d612296565b60e0516122c291613319565b60e0516101905788612240565b853b1561019057604051632961046560e21b81526004810183905260e05181602481838b5af180156102dc576123a5575b508161236057600460206001600160801b0361231b84613ac1565b1660405192838092630476982d60e21b82528b5af180156102dc57612341575b506120e6565b6123599060203d6020116122af576122a08183613319565b508761233b565b61237c6001600160801b0361237483613ac1565b168784614492565b604051630476982d60e21b815260208160048160e0518b5af180156102dc5761234157506120e6565b60e0516123b191613319565b60e0516101905787612300565b9091506020813d6020116123ea575b816123da60209383613319565b810103126102d0575190846120a4565b3d91506123cd565b63f655705d60e01b60e05152600460e051fd5b3461019057602036600319011261019057600435801515908190036101905760e051547f549bab54c75a364ce0e438a4fbf09df7e6b096bcc83a6f91065a0fc8e410b29a91602091612461336001600160a01b03831614613457565b60e05160ff60a01b1990911660a083901b60ff60a01b16179055604051908152a160e05180f35b346101905760e0513660031901126101905760e051546040516001600160a01b039091168152602090f35b346101905760e051366003190112610190576040517f000000000000000000000000da14fdd72345c4d2511357214c5b89a919768e596001600160a01b03168152602090f35b346101905760e051366003190112610190576001546001600160a01b031633036125735760e0515460ff8160a01c166102fc5760e05160ff60a01b19909116600160a01b179055604051600181527f549bab54c75a364ce0e438a4fbf09df7e6b096bcc83a6f91065a0fc8e410b29a90602090a160e05180f35b636570ecab60e11b60e05152600460e051fd5b346102d05760403660031901126102d05761259f613250565b602435906001600160401b0382116102d057816004018236036101006003198201126102d05760ff5f5460a01c16612c6d57600254926001600160a01b038416612c5e576001600160a01b03166001600160a01b0319939093168317600255604051638da5cb5b60e01b81526020816004815f885af1908115612a28575f91612c24575b506001600160a01b039081165f908152600560209081526040808320878452909152902054163303612c155761265882613539565b6001600160a01b037f0000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf8116911603612c06575f5f60448601956001600160801b036126a28861354d565b1615801590612be9575b612ae9575b6126ba85613539565b9160248201916126c983613561565b956126d38a61354d565b9960648301906126e28261354d565b60408051336020820152808201919091529a9096906001600160a01b03906127099061327c565b1660608c015261271890613575565b6001600160601b031660808b015261272f90613589565b6001600160801b031660a08a015261274690613589565b6001600160801b031660c0890152608482013560e089015261276a60a4830161359d565b6001600160401b031661010089015261278560c4830161359d565b6001600160401b031661012089015260e482013590602219018112156102d05701602460048201359101906001600160401b0381116102d05780360382136102d0576001600160601b03996128176101808a846001600160801b039695879661010061014085015281610160850152848401375f838284010152601f801991011681010301601f1981018b528a613319565b169216916001948115159182612ae0575b8415159182612ad0575b61283b8861362f565b9b8c996128478a61362f565b9861286361285d6128578d61362f565b9c61362f565b9c613661565b6001600160a01b0390911690521661287a88613661565b52600161288689613661565b5260026128928a613661565b52600193612a96575b5050612a61575b5050509061290d959291604051936128b9856132c8565b84526020840152604083015260608201526128d26135f4565b604051906128df826132e3565b6060825260208201905f825261291f60408401915f835260405198899660a0602089015260c08801906133cd565b868103601f19016040880152906133cd565b91601f19858403016060860152606083019351936060845284518091526020608085019501905f5b818110612a33575050509160406129aa94926129b8979451602084015251910152601f19848203016080850152606051808252806080602084015e5f828201602090810191909152601f909101601f191690910184810360a0860152019061333a565b03601f198101845283613319565b803b156102d0576040805162b9252f60e41b81523060048201526024810191909152905f9082908183816129ef604482018961333a565b03925af18015612a2857612a14575b600280546001600160a01b031916905560e05180f35b5f612a1e91613319565b5f60e052806129fe565b6040513d5f823e3d90fd5b825180516001600160a01b03168852602090810151818901528b985060409097019690920191600101612947565b600192612a8d92612a72838c6136a2565b90858060a01b03169052612a8682876136a2565b52856136a2565b528680806128a2565b90919250612aa38b613682565b6001600160a01b039091169052612ab986613682565b526001612ac587613682565b526002908a8061289b565b96612ada90613ab3565b96612832565b60029650612828565b915050612af583613539565b506001600160601b03612b0a60248301613561565b604051637ba03aad60e01b81529116600482015260c0816024817f0000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf6001600160a01b03165afa908115612a28575f91612bc9575b5080516020909101516001600160a01b0391821691168115612b82575b90916126b1565b90507f00000000000000000000000042000000000000000000000000000000000000066001600160a01b0381168214612bbb5790612b7b565b62820f3560e61b5f5260045ffd5b612be2915060c03d60c011611ea357611e938183613319565b5086612b5e565b506001600160801b03612bfe6064830161354d565b1615156126ac565b63ed5f09f160e01b5f5260045ffd5b6317fb43e560e31b5f5260045ffd5b90506020813d602011612c56575b81612c3f60209383613319565b810103126102d057612c50906134aa565b85612623565b3d9150612c32565b63b5dfd9e560e01b5f5260045ffd5b6313d0ff5960e31b5f5260045ffd5b346102d05760603660031901126102d057612c95613250565b612c9d61338b565b506044356001600160401b0381116102d057612cbd90369060040161335e565b6002546001600160a01b0316612c5e57604051630972932760e21b81523360048201526020816024817f000000000000000000000000da14fdd72345c4d2511357214c5b89a919768e596001600160a01b03165afa908115612a28575f91612d96575b5015612d875781019160c0828403126102d057612d3c8261327c565b9060a08301356001600160401b0381116102d05761001b94612d5f91850161351e565b9260808101359260608201359260408301359260200135916001600160a01b031690336136fd565b630ea8370b60e41b5f5260045ffd5b612db8915060203d602011612dbe575b612db08183613319565b810190613492565b84612d20565b503d612da6565b346102d0575f3660031901126102d057602060ff5f5460a01c166040519015158152f35b346102d0575f3660031901126102d0576001546040516001600160a01b039091168152602090f35b346102d05760e03660031901126102d057612e2a613250565b612e32613266565b9060c4356001600160401b0381116102d057612e5290369060040161335e565b60025491939092916001600160a01b0316612c5e57604051630972932760e21b81526001600160a01b0383811660048301819052949190602090829060249082907f000000000000000000000000da14fdd72345c4d2511357214c5b89a919768e59165afa908115612a28575f91612fe3575b5015612d8757604051638da5cb5b60e01b8152936020856004815f855af1948515612a28575f95612fa7575b506001600160a01b0385163303612f985760205f91600460405180948193635e34633b60e11b83525af18015612a28575f90612f65575b6003915010612f565761001b94612f409136916134e8565b9260a435926084359260643592604435926136fd565b63a93eca7960e01b5f5260045ffd5b506020813d602011612f90575b81612f7f60209383613319565b810103126102d05760039051612f28565b3d9150612f72565b6312272fd360e11b5f5260045ffd5b9094506020813d602011612fdb575b81612fc360209383613319565b810103126102d057612fd4906134aa565b9386612ef1565b3d9150612fb6565b612ffc915060203d602011612dbe57612db08183613319565b86612ec5565b346102d05760203660031901126102d05761301b613250565b61302f60018060a01b035f54163314613457565b600180546001600160a01b0319166001600160a01b03929092169182179055337fa14fc14d8620a708a896fd11392a235647d99385500a295f0d7da2a258b2e9675f80a3005b346102d05760803660031901126102d05761308e613250565b50613097613266565b506064356001600160401b0381116102d0576130b790369060040161335e565b5050604051630a85bd0160e11b8152602090f35b346102d05760403660031901126102d0576130e4613250565b6130ec613266565b6001600160a01b039182165f908152600560209081526040808320938516835292815290829020549151919092168152f35b346102d05760203660031901126102d0576020613139613250565b6040517f0000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf6001600160a01b039081169216919091148152f35b346102d05760203660031901126102d0576001600160a01b03613193613250565b165f52600460205260405f205f908054906131ad82613290565b808552916001811690811561322957506001146131e9575b611772846131d581860382613319565b60405191829160208352602083019061333a565b5f90815260208120939250905b80821061320f575090915081016020016131d5826131c5565b9192600181602092548385880101520191019092916131f6565b60ff191660208087019190915292151560051b850190920192506131d591508390506131c5565b600435906001600160a01b03821682036102d057565b602435906001600160a01b03821682036102d057565b35906001600160a01b03821682036102d057565b90600182811c921680156132be575b60208310146132aa57565b634e487b7160e01b5f52602260045260245ffd5b91607f169161329f565b608081019081106001600160401b0382111761194b57604052565b606081019081106001600160401b0382111761194b57604052565b60a081019081106001600160401b0382111761194b57604052565b90601f801991011681019081106001600160401b0382111761194b57604052565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b9181601f840112156102d0578235916001600160401b0383116102d057602083818601950101116102d057565b6024359081151582036102d057565b90602080835192838152019201905f5b8181106133b75750505090565b82518452602093840193909201916001016133aa565b80516080808452815190840181905260a08401949391602001905f5b81811061343857505050606061342461341261343595966020860151858203602087015261339a565b6040850151848203604086015261339a565b92015190606081840391015261339a565b90565b82516001600160a01b03168752602096870196909201916001016133e9565b1561345e57565b60405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606490fd5b908160209103126102d0575180151581036102d05790565b51906001600160a01b03821682036102d057565b908160209103126102d0575190565b6001600160401b03811161194b57601f01601f191660200190565b9291926134f4826134cd565b916135026040519384613319565b8294818452818301116102d0578281602093845f960137010152565b9080601f830112156102d057816020613435933591016134e8565b356001600160a01b03811681036102d05790565b356001600160801b03811681036102d05790565b356001600160601b03811681036102d05790565b35906001600160601b03821682036102d057565b35906001600160801b03821682036102d057565b35906001600160401b03821682036102d057565b80516001600160a01b03908116835260208083015182169084015260408083015162ffffff169084015260608083015160020b9084015260809182015116910152565b60405190613601826132c8565b606080838181528160208201528160408201520152565b6001600160401b03811161194b5760051b60200190565b9061363982613618565b6136466040519182613319565b8281528092613657601f1991613618565b0190602036910137565b80511561366e5760200190565b634e487b7160e01b5f52603260045260245ffd5b80516001101561366e5760400190565b80516002101561366e5760600190565b805182101561366e5760209160051b010190565b919082039182116136c357565b634e487b7160e01b5f52601160045260245ffd5b919082018092116136c357565b8151811191826136f357505090565b6020015111919050565b9196949095929395670de0b6b3a764000085118015613a19575b8015613a08575b80156139f7575b6139e8576001600160a01b039081165f9081526005602090815260408083208685168452909152902080546001600160a01b031916989091169788179055670de0b6b3a76400008082019081106136c357670de0b6b3a7640000810290808204670de0b6b3a764000014901517156136c3576137a86001600160401b03916143d0565b169281670de0b6b3a76400000391670de0b6b3a764000083116136c357670de0b6b3a76400008302928304670de0b6b3a76400001490670de0b6b3a76400001417156136c3576001600160401b03936001938561380581956143d0565b169084604051986138158a6132fe565b16885284602089019a168a526040880192835260608801918252846080890194168452858060a01b031698895f526003602052848060405f209951161685198954161788555191846fffffffffffffffff00000000000000008954928260801b905160801b16938260c01b905160c01b169460401b16911617171785555116920191166001600160401b0319825416179055815f52600460205260405f20908051906001600160401b03821161194b5781906138d18454613290565b601f8111613998575b50602090601f8311600114613935575f9261392a575b50508160011b915f199060031b1c19161790555b7febc70f7c8d6a67b19e15e968cb908d21719e8ff9a778a71171fba931a618d0525f80a3565b015190505f806138f0565b5f8581528281209350601f198516905b8181106139805750908460019594939210613968575b505050811b019055613904565b01515f1960f88460031b161c191690555f808061395b565b92936020600181928786015181550195019301613945565b909150835f5260205f20601f840160051c810191602085106139de575b90601f859493920160051c01905b8181106139d057506138da565b5f81558493506001016139c3565b90915081906139b5565b632a9ffab760e21b5f5260045ffd5b50670de0b6b3a76400008411613725565b50670de0b6b3a7640000821161371e565b50670de0b6b3a76400008711613717565b8092910360c081126102d05760a0136102d057604051613a49816132fe565b613a52836134aa565b8152613a60602084016134aa565b6020820152604083015162ffffff811681036102d057604082015260608301518060020b81036102d05760608201526080830151906001600160a01b03821682036102d05760a091608082015292015190565b5f1981146136c35760010190565b600f0b6f7fffffffffffffffffffffffffffffff1981146136c3575f0390565b90613af49060408352604083019061333a565b906020818303910152815180825260208201916020808360051b8301019401925f915b838310613b2657505050505090565b9091929394602080613b44600193601f19868203018752895161333a565b97019301930191939290613b17565b929190613b6a60209160408652604086019061333a565b930152565b94909293919360608301928351955f96156143365760e00151805180613f975750508051151590604083019362ffffff8551169661012085019760018060a01b03613bba8a51613661565b511697613c1b60a0600180821b03613bd28d51613682565b51169a62ffffff8b51169b60608b019c8d5160020b90600180861b038d51169260405194613bff866132fe565b85526020850152604084015260608301526080820152206150a8565b9260038401809411613f8357604051631e2eaeaf60e01b815260048101949094527f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b0316966020856024818b5afa948515613f7857908e92918e96613f3d575b506101008a01516040880151606090980151613ce8986001600160a01b0391821694908216939190921691613cd090610e83613cc9613cc36119a68a613661565b98613682565b5191613682565b9551966001600160801b0360808c0151991691614b1c565b908115613f325787968795613e0395613dce9351151598895f14613f18576401000276a45b60405196613d1a886132e3565b8b885260208801526001600160a01b039081166040880152845162ffffff9190613d4390613661565b5195519516946001600160a01b0390613d5b90613682565b5116935116905160020b9160018060a01b039051169260405194613d7e866132fe565b85526020850152604084015260608301526080820152613dc4604051936020850190604090805115158352602081015160208401528160018060a01b0391015116910152565b60808301906135b1565b6101008152613ddf61012082613319565b6040519687809481936348c8949160e01b835260206004840152602483019061333a565b03925af1928315613f0d578293613ec3575b50602083519381808201958692010103126102d057613e87925191815f14613ea457613e59613e4386613661565b51613e538560801d600f0b614f39565b906136b6565b613e6286613661565b525015613e8a57613e8190613e7684613682565b5190600f0b906136d7565b91613682565b52565b613e8190613e53613e9a85613682565b5191600f0b614f39565b613ebe613eb086613661565b518460801d600f0b906136d7565b613e59565b9092503d8083833e613ed58183613319565b810190602081830312613f09578051906001600160401b038211613f0557613efe929101614ad6565b915f613e15565b8380fd5b8280fd5b6040513d84823e3d90fd5b73fffd8963efd1fc6a506488495d951d5263988d25613d0d565b505050505050505050565b925094506020823d602011613f70575b81613f5a60209383613319565b810103126102d0579051938d9190613ce8613c82565b3d9150613f4d565b6040513d8f823e3d90fd5b634e487b7160e01b8c52601160045260248cfd5b9350969450909250511515908501936060868603126102d05760208601516001600160a01b03811695908690036102d0576040870151966060810151916001600160401b0383116102d057613ff3926020809201920101614ad6565b9482156142fe576101208401958260018060a01b036140128951613661565b5198519816976001600160a01b039061402a90613682565b5116975b979561404561012060018060a01b03920151613661565b511615978861423a575b6040936140bc936001600160a01b037f000000000000000000000000354dbba1348985cc952c467b8ddaf5dd075906678116949193919291166140938d8683614340565b8651998a96879586946344bc658560e01b8652600486015260a0602486015260a485019061333a565b60448401929092526001600160a01b03166064830152608482018d905203925af194851561422d57819382966141f2575b5061415b575b50156141355761411c61412691614117613e87959661411186613661565b516136b6565b6136d7565b93610cda83613682565b61412f82613682565b52613661565b6141569061411761414c613e8795610cda86613661565b9561411185613682565b614126565b81156141ec57825b8061416f575b506140f3565b7f00000000000000000000000042000000000000000000000000000000000000066001600160a01b031690813b15613f09578291602483926040519485938492632e1a7d4d60e01b845260048401525af18015613f0d579082916141d4575b50614169565b816141de91613319565b6141e957805f6141ce565b80fd5b84614163565b935094506040833d604011614225575b8161420f60409383613319565b810103126141e95760208351930151945f6140ed565b3d9150614202565b50604051903d90823e3d90fd5b905084156142cd57507f00000000000000000000000042000000000000000000000000000000000000066001600160a01b038116803b156102d0575f8a91600460405180948193630d0e30db60e41b83525af18015612a28576142ae575b50916140bc91846040945b91935091935061404f565b604093919450916142c25f6140bc94613319565b5f9491935091614298565b94506040916140bc91847f0000000000000000000000004200000000000000000000000000000000000006976142a3565b6101208401958260018060a01b036143168951613682565b5198519816976001600160a01b039061432e90613661565b51169761402e565b5050505050505050565b60405163a9059cbb60e01b81526001600160a01b03909216600483015260248201929092526020905f9060449082855af19081601f3d1160015f51141615166143c3575b501561438c57565b60405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606490fd5b3b153d171590505f614384565b60b581600160881b81101561447b575b8069010000000000000000006201000092101561446e575b65010000000000811015614461575b6301000000811015614454575b010260121c8082040160011c8082040160011c8082040160011c8082040160011c8082040160011c8082040160011c8082040160011c8080920410900390565b60101c9160081b91614414565b60201c9160101b91614407565b60401c9160201b916143f8565b5068b500000000000000009050608082901c6143e0565b9091906001600160a01b03811690816145205750505f80808093855af1156144b75750565b6040516390bfb86560e01b81526001600160a01b0390911660048201525f602482018190526080604483015260a03d601f01601f191690810160648401523d6084840152903d9060a484013e808201600460a482015260c4633d2cec6f60e21b91015260e40190fd5b60205f604481949682604095865198899363a9059cbb60e01b855260018060a01b0316600485015260248401525af13d15601f3d116001855114161716928281528260208201520152156145715750565b6040516390bfb86560e01b8152600481019190915263a9059cbb60e01b602482015260806044820152601f3d01601f191660a0810160648301523d60848301523d5f60a484013e808201600460a482015260c4633c9fd93960e21b91015260e40190fd5b91906145e26020916150a8565b604051631e2eaeaf60e01b8152600481019190915292839060249082906001600160a01b03165afa918215612a28575f92614640575b506001600160a01b0382169160a081901c60020b9162ffffff60b883901c81169260d01c1690565b9091506020813d60201161466c575b8161465c60209383613319565b810103126102d05751905f614618565b3d915061464f565b815f190481118202158302156102d057020490565b60020b908160ff1d82810118620d89e881116149a35763ffffffff9192600182167001fffcb933bd6fad37aa2d162d1a59400102600160801b189160028116614987575b6004811661496b575b6008811661494f575b60108116614933575b60208116614917575b604081166148fb575b608081166148df575b61010081166148c3575b61020081166148a7575b610400811661488b575b610800811661486f575b6110008116614853575b6120008116614837575b614000811661481b575b61800081166147ff575b6201000081166147e3575b6202000081166147c8575b6204000081166147ad575b6208000016614794575b5f1261478c575b0160201c90565b5f1904614785565b6b048a170391f7dc42444e8fa290910260801c9061477e565b6d2216e584f5fa1ea926041bedfe9890920260801c91614774565b916e5d6af8dedb81196699c329225ee6040260801c91614769565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c9161475e565b916f31be135f97d08fd981231505542fcfa60260801c91614753565b916f70d869a156d2a1b890bb3df62baf32f70260801c91614749565b916fa9f746462d870fdf8a65dc1f90e061e50260801c9161473f565b916fd097f3bdfd2022b8845ad8f792aa58250260801c91614735565b916fe7159475a2c29b7443b29c7fa6e889d90260801c9161472b565b916ff3392b0822b70005940c7a398e4b70f30260801c91614721565b916ff987a7253ac413176f2b074cf7815e540260801c91614717565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c9161470d565b916ffe5dee046a99a2a811c461f1969c30530260801c91614703565b916fff2ea16466c96a3843ec78b326b528610260801c916146fa565b916fff973b41fa98c081472e6896dfb254c00260801c916146f1565b916fffcb9843d60f6159c9db58835c9266440260801c916146e8565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c916146df565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c916146d6565b916ffff97272373d413259a46990580e213a0260801c916146cd565b826345c3193d60e11b5f5260045260245ffd5b6001600160a01b0316806149c957504790565b6020602491604051928380926370a0823160e01b82523060048301525afa908115612a28575f916149f8575090565b90506020813d602011614a1f575b81614a1360209383613319565b810103126102d0575190565b3d9150614a06565b936001600160a01b0383811690831611614ace575b6001600160a01b03858116959083168611614a71575050614a5d9350615264565b6001600160801b0381169081036102d05790565b919490939192906001600160a01b0382161115614ac2578291614a9891614a9e9594615264565b93615233565b80821015614abb57506001600160801b0381169081036102d05790565b9050614a5d565b915050614a5d92615233565b909190614a3c565b81601f820112156102d057805190614aed826134cd565b92614afb6040519485613319565b828452602083830101116102d057815f9260208093018386015e8301015290565b93929597949091965f945b60648610614b3c575050505050505050505090565b9091929394959697989984620f42400397885f19048111890215620f424002156102d057620f4240908902048215614f08576001600160a01b0390614b82908c8c61545d565b16906001600160a01b038111614ebc5760601b6001600160801b038b1680820615159104015b6001600160a01b038a169080821115614eaf5790036001600160a01b03165b8215614e91570160011c6001600160a01b0316945b6001600160a01b038681169085168110614c14575050505050505050614c08614c0f916134359561552d565b838361545d565b615659565b60018060a09d9c9b9a939495969798999d1b0383161015614e68578215614e4757614c4990614c448a8a8a6155f9565b615550565b99614c55898989615659565b965b87908c8c838715614e14575050808d1115614e0a57614c7a908d035b8883615264565b614c878a88018387615233565b995b8a82109a8b15614dc9577812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f218311670de0b6b3a764000002158102156102d05780670de0b6b3a76400008402049b5b15614d825750506001600160801b0381169081036102d057614cf29185615685565b908415614d785785919082821115614d3a5750035b620f4240819c98670de0b6b3a76400000310614d2b57506001019492909391614b27565b9a505050505050505050505090565b915050600a60097f1c71c71c71c71c71c71c71c71c71c71c71c71c71c71c71c71c71c71c71c71c718311021502156102d0576009600a910204614d07565b9b5084039a614d07565b90939e9291506001600160801b0381169081036102d05788614da3926155f9565b918515614db45750508a039a614d07565b8c92919d508282115f14614d3a575003614d07565b7812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f218111670de0b6b3a764000002158302156102d05782670de0b6b3a76400008202049b614cd0565b50614c7a5f614c73565b614e2091018984615264565b9080881115614e3d57614e379088035b8387615233565b99614c89565b50614e375f614e30565b614e5690614c448a898b615685565b99614e6289888a61558f565b96614c57565b9450505090506134359650614e8b93949550614e84925061552d565b83836154d7565b9061558f565b6001600160a01b039180820160011c91600291081515011694614bdc565b634323a5555f526004601cfd5b6001600160801b038b16614ed581600160601b8461537e565b918115614ef457600160601b900915614ba85760010180614ba8575f80fd5b634e487b7160e01b5f52601260045260245ffd5b906001600160a01b0390614f1d908c8c6153fe565b16906001600160a01b0390614f33908c8c6154d7565b16614bc7565b600160ff1b81146136c3575f0390565b6001600160a01b03165f8181526006602052604090205460ff1615614f6b5750565b5f8181526006602090815260408220805460ff191660011790557f000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba36001600160a01b031660148190525f1960345263095ea7b360601b835292916044601082855af13d1560015f5114171615615064575b5f603452813b156102d0576040516387517c4560e01b815260048101919091526001600160a01b037f0000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf81166024830152604482015265ffffffffffff6064820152905f908290608490829084905af18015612a28576150585750565b5f61506291613319565b565b5f603481905263095ea7b360601b8152386044601083855af1505f1960345260205f6044601082855af13d1560015f51141716614fdc57633e3f8f735f526004601cfd5b6040516020810191825260066040820152604081526150c8606082613319565b51902090565b8115614ef4570490565b5f908015615190578080600114615188576002146151815760016101338210166001600b83101617615173579060019060025b600181116151375750825f1904821161512357500290565b634e487b7160e01b81526011600452602490fd5b92805f1904811161515f5760018416615156575b80029260011c61510b565b8092029161514b565b634e487b7160e01b82526011600452602482fd5b6002900a9190806151235750565b5050600490565b505050600190565b50505f90565b600160601b600160025b600181116151b75750815f190481116136c3570290565b91805f190481116136c357600183166151d6575b80029160011c6151a0565b809102906151cb565b90916001600160801b0382116102d057670de0b6b3a76400000390825f19048211830215670de0b6b3a764000002156102d057670de0b6b3a7640000613435936002615229615196565b930a93020461537e565b6134359291906001600160a01b038083169082161161525e575b90036001600160a01b0316906152ab565b9061524d565b61343592916001600160a01b03808216908316116152a5575b6152936001600160a01b03828116908416615335565b9190036001600160a01b03169161537e565b9061527d565b90606082901b905f19600160601b8409928280851094039380850394858411156102d0571461532e578190600160601b900981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b81810291905f1982820991838084109303928084039384600160601b11156102d0571461537557600160601b910990828211900360a01b910360601c1790565b50505060601c90565b91818302915f19818509938380861095039480860395868511156102d057146153f6579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b91908115615458576001600160a01b03909216918183029160609190911b600160601b600160e01b03169082048314828211161561544b5761343592615446928203916156c1565b6156ea565b63f5c787f15f526004601cfd5b505090565b919081156154585760601b600160601b600160e01b0316916001600160a01b0316908082028261548d83836150ce565b146154b5575b506141176154a192846150ce565b80820491061515016001600160a01b031690565b8301838110615493576001600160a01b03936154d3939192506156c1565b1690565b6134359261544692906001600160a01b038111615514576001600160801b0361550492169060601b6150ce565b905b6001600160a01b03166136d7565b6001600160801b036155279216906152ab565b90615506565b815f19048111820215620f424002156102d05702620f4240808204910615150190565b7d10c6f7a0b5ed8d36b4c7f34938583621fafc8b0079a2834d26fa3fcc9ea98111620f424002158202156102d057620f42400290808204910615150190565b906001600160a01b03808216908316116155f3575b6001600160a01b0382169182156155e757613435936155e2926001600160a01b0380821693909103169060601b600160601b600160e01b031661537e565b6150ce565b62bfc9215f526004601cfd5b906155a4565b6001600160a01b0382811690821611615653575b6001600160a01b0381169283156155e757615647926001600160a01b0380821693909103169060601b600160601b600160e01b03166156c1565b90808206151591040190565b9061560d565b613435926001600160a01b03928316919092160360ff81901d90810118906001600160801b0316615335565b6001600160a01b0391821691160360ff81901d90810118906001906001600160801b03166156b38382615335565b928260601b91091515160190565b9291906156cf82828661537e565b938215614ef457096156dd57565b906001019081156102d057565b6001600160a01b038116919082036156fe57565b6393dafdf160e01b5f5260045ffdfea2646970667358221220ce3236855debde6b4e6818f671f25f9ab778cb4a74be3cb3331e8c6ccc85914764736f6c634300081e0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000b4d72b1c91e640e4ed7d7397f3244de4d8acc50b000000000000000000000000da14fdd72345c4d2511357214c5b89a919768e59000000000000000000000000354dbba1348985cc952c467b8ddaf5dd075906670000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba30000000000000000000000001f984000000000000000000000000000000000040000000000000000000000004200000000000000000000000000000000000006
-----Decoded View---------------
Arg [0] : owner_ (address): 0xb4d72B1c91e640e4ED7d7397F3244De4D8ACc50B
Arg [1] : arcadiaFactory (address): 0xDa14Fdd72345c4d2511357214c5B89A919768e59
Arg [2] : routerTrampoline (address): 0x354dBBa1348985CC952c467b8ddaF5dD07590667
Arg [3] : positionManager (address): 0x4529A01c7A0410167c5740C487A8DE60232617bf
Arg [4] : permit2 (address): 0x000000000022D473030F116dDEE9F6B43aC78BA3
Arg [5] : poolManager (address): 0x1F98400000000000000000000000000000000004
Arg [6] : weth (address): 0x4200000000000000000000000000000000000006
-----Encoded View---------------
7 Constructor Arguments found :
Arg [0] : 000000000000000000000000b4d72b1c91e640e4ed7d7397f3244de4d8acc50b
Arg [1] : 000000000000000000000000da14fdd72345c4d2511357214c5b89a919768e59
Arg [2] : 000000000000000000000000354dbba1348985cc952c467b8ddaf5dd07590667
Arg [3] : 0000000000000000000000004529a01c7a0410167c5740c487a8de60232617bf
Arg [4] : 000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba3
Arg [5] : 0000000000000000000000001f98400000000000000000000000000000000004
Arg [6] : 0000000000000000000000004200000000000000000000000000000000000006
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.