Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00| Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
Latest 1 internal transaction
| Parent Transaction Hash | Block | From | To | |||
|---|---|---|---|---|---|---|
| 32645327 | 127 days ago | Contract Creation | 0 ETH |
Cross-Chain Transactions
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
CreatorCoinHook
Compiler Version
v0.8.28+commit.7893614a
Optimization Enabled:
Yes with 200 runs
Other Settings:
prague EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {CreatorCoinConstants} from "../libs/CreatorCoinConstants.sol";
import {CreatorCoinRewards} from "../libs/CreatorCoinRewards.sol";
import {IPoolManager, IDeployedCoinVersionLookup, IHasRewardsRecipients, Currency, BaseZoraV4CoinHook} from "./BaseZoraV4CoinHook.sol";
import {IHooksUpgradeGate} from "../interfaces/IHooksUpgradeGate.sol";
contract CreatorCoinHook is BaseZoraV4CoinHook {
constructor(
IPoolManager poolManager_,
IDeployedCoinVersionLookup coinVersionLookup_,
address[] memory trustedMessageSenders_,
IHooksUpgradeGate upgradeGate
) BaseZoraV4CoinHook(poolManager_, coinVersionLookup_, trustedMessageSenders_, upgradeGate, CreatorCoinConstants.MARKET_SUPPLY) {}
/// @dev Override for distributing market rewards and vested coins to the creator
function _distributeMarketRewards(Currency currency, uint128 fees, IHasRewardsRecipients coin, address) internal override {
CreatorCoinRewards.distributeMarketRewards(currency, fees, coin);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
library CreatorCoinConstants {
uint256 internal constant TOTAL_SUPPLY = 1_000_000_000e18; // 1b coins
uint256 internal constant MARKET_SUPPLY = 500_000_000e18; // 500m coins
uint256 internal constant CREATOR_VESTING_SUPPLY = 500_000_000e18; // 500m coins
uint256 internal constant CREATOR_VESTING_DURATION = 5 * 365 days; // 5 years
address internal constant CURRENCY = 0x1111111111166b7FE7bd91427724B487980aFc69;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {ICreatorCoinHook} from "../interfaces/ICreatorCoinHook.sol";
import {CoinRewardsV4, IPoolManager, Currency, IHasRewardsRecipients} from "./CoinRewardsV4.sol";
library CreatorCoinRewards {
function distributeMarketRewards(Currency currency, uint128 fees, IHasRewardsRecipients coin) internal {
address payoutRecipient = coin.payoutRecipient();
address protocolRewardRecipient = coin.protocolRewardRecipient();
uint256 totalAmount = uint256(fees);
uint256 creatorAmount = CoinRewardsV4.calculateReward(totalAmount, CoinRewardsV4.CREATOR_REWARD_BPS);
uint256 protocolAmount = totalAmount - creatorAmount;
CoinRewardsV4._transferCurrency(currency, creatorAmount, payoutRecipient);
CoinRewardsV4._transferCurrency(currency, protocolAmount, protocolRewardRecipient);
emit ICreatorCoinHook.CreatorCoinRewards(
address(coin),
Currency.unwrap(currency),
payoutRecipient,
protocolRewardRecipient,
creatorAmount,
protocolAmount
);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {BaseHook} from "@uniswap/v4-periphery/src/utils/BaseHook.sol";
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {BalanceDelta, BalanceDeltaLibrary} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {IZoraV4CoinHook} from "../interfaces/IZoraV4CoinHook.sol";
import {IMsgSender} from "../interfaces/IMsgSender.sol";
import {IHasSwapPath} from "../interfaces/ICoinV4.sol";
import {LpPosition} from "../types/LpPosition.sol";
import {V4Liquidity} from "../libs/V4Liquidity.sol";
import {CoinRewardsV4} from "../libs/CoinRewardsV4.sol";
import {ICoinV4} from "../interfaces/ICoinV4.sol";
import {IDeployedCoinVersionLookup} from "../interfaces/IDeployedCoinVersionLookup.sol";
import {CoinCommon} from "../libs/CoinCommon.sol";
import {CoinDopplerMultiCurve} from "../libs/CoinDopplerMultiCurve.sol";
import {PoolStateReader} from "../libs/PoolStateReader.sol";
import {IHasRewardsRecipients} from "../interfaces/ICoin.sol";
import {CoinConfigurationVersions} from "../libs/CoinConfigurationVersions.sol";
import {IUpgradeableV4Hook} from "../interfaces/IUpgradeableV4Hook.sol";
import {IHooksUpgradeGate} from "../interfaces/IHooksUpgradeGate.sol";
import {MultiOwnable} from "../utils/MultiOwnable.sol";
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IUpgradeableDestinationV4Hook} from "../interfaces/IUpgradeableV4Hook.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {BurnedPosition} from "../interfaces/IUpgradeableV4Hook.sol";
import {LiquidityAmounts} from "../utils/uniswap/LiquidityAmounts.sol";
import {TickMath} from "../utils/uniswap/TickMath.sol";
import {ContractVersionBase, IVersionedContract} from "../version/ContractVersionBase.sol";
/// @title ZoraV4CoinHook
/// @notice Uniswap V4 hook that automatically handles fee collection and reward distributions on every swap,
/// paying out all rewards in a backing currency.
/// @dev This hook executes on afterSwap withdraw fees, swap for a backing currency, and distribute rewards.
/// On pool initialization, it creates multiple liquidity positions based on the coin's pool configuration.
/// On every swap, it automatically:
/// 1. Collects accrued LP fees from all positions
/// 2. Swaps collected fees to the backing currency through multi-hop paths
/// 3. Distributes converted fees as rewards
/// @author oveddan
abstract contract BaseZoraV4CoinHook is BaseHook, ContractVersionBase, IZoraV4CoinHook, ERC165, IUpgradeableDestinationV4Hook {
using BalanceDeltaLibrary for BalanceDelta;
/// @notice Mapping of trusted message senders - these are addresses that are trusted to provide a
/// an original msg.sender
mapping(address => bool) internal trustedMessageSender;
/// @notice Mapping of pool keys to coins.
mapping(bytes32 => IZoraV4CoinHook.PoolCoin) internal poolCoins;
/// @notice The coin version lookup contract - used to determine if an address is a coin and what version it is.
IDeployedCoinVersionLookup internal immutable coinVersionLookup;
/// @notice The upgrade gate contract - used to verify allowed upgrade paths
IHooksUpgradeGate internal immutable upgradeGate;
uint256 internal immutable totalSupplyForPositions;
/// @notice The constructor for the ZoraV4CoinHook.
/// @param poolManager_ The Uniswap V4 pool manager
/// @param coinVersionLookup_ The coin version lookup contract - used to determine if an address is a coin and what version it is.
/// @param trustedMessageSenders_ The addresses of the trusted message senders - these are addresses that are trusted to provide a
/// @param upgradeGate_ The upgrade gate contract for managing hook upgrades
constructor(
IPoolManager poolManager_,
IDeployedCoinVersionLookup coinVersionLookup_,
address[] memory trustedMessageSenders_,
IHooksUpgradeGate upgradeGate_,
uint256 totalSupplyForPositions_
) BaseHook(poolManager_) {
require(address(coinVersionLookup_) != address(0), CoinVersionLookupCannotBeZeroAddress());
require(address(upgradeGate_) != address(0), UpgradeGateCannotBeZeroAddress());
coinVersionLookup = coinVersionLookup_;
upgradeGate = upgradeGate_;
totalSupplyForPositions = totalSupplyForPositions_;
for (uint256 i = 0; i < trustedMessageSenders_.length; i++) {
trustedMessageSender[trustedMessageSenders_[i]] = true;
}
}
/// @notice Returns the uniswap v4 hook settings / permissions.
/// @dev The permissions currently requested are: afterInitialize and afterSwap.
function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
return
Hooks.Permissions({
beforeInitialize: false,
afterInitialize: true,
beforeAddLiquidity: false,
afterAddLiquidity: false,
beforeRemoveLiquidity: false,
afterRemoveLiquidity: false,
beforeSwap: false,
afterSwap: true,
beforeDonate: false,
afterDonate: false,
beforeSwapReturnDelta: false,
afterSwapReturnDelta: false,
afterAddLiquidityReturnDelta: false,
afterRemoveLiquidityReturnDelta: false
});
}
/// @inheritdoc IZoraV4CoinHook
function isTrustedMessageSender(address sender) external view returns (bool) {
return trustedMessageSender[sender];
}
/// @inheritdoc IZoraV4CoinHook
function getPoolCoinByHash(bytes23 poolKeyHash) external view returns (IZoraV4CoinHook.PoolCoin memory) {
return poolCoins[poolKeyHash];
}
/// @inheritdoc IZoraV4CoinHook
function getPoolCoin(PoolKey memory key) external view returns (IZoraV4CoinHook.PoolCoin memory) {
return poolCoins[CoinCommon.hashPoolKey(key)];
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
super.supportsInterface(interfaceId) ||
interfaceId == type(IUpgradeableDestinationV4Hook).interfaceId ||
interfaceId == type(IVersionedContract).interfaceId;
}
/// @notice Internal fn generating the positions for a given pool key.
/// @param coin The coin address.
/// @param key The pool key for the coin.
/// @return positions The contract-created liquidity positions the positions for the coin's pool.
function _generatePositions(ICoinV4 coin, PoolKey memory key) internal view returns (LpPosition[] memory positions) {
bool isCoinToken0 = Currency.unwrap(key.currency0) == address(coin);
positions = CoinDopplerMultiCurve.calculatePositions(isCoinToken0, coin.getPoolConfiguration(), totalSupplyForPositions);
}
/// @notice Internal fn called when a pool is initialized.
/// @dev This hook is called from BaseHook library from uniswap v4.
/// @param sender The address of the sender.
/// @param key The pool key.
/// @return selector The selector of the afterInitialize hook to confirm the action.
function _afterInitialize(address sender, PoolKey calldata key, uint160, int24) internal override returns (bytes4) {
// If the sender is the hook itself, we assume this is a migration and we return early.
if (sender == address(this)) {
return BaseHook.afterInitialize.selector;
}
// Otherwise, we initialize the hook positions.
address coin = sender;
if (!CoinConfigurationVersions.isV4(coinVersionLookup.getVersionForDeployedCoin(coin))) {
revert NotACoin(coin);
}
LpPosition[] memory positions = _generatePositions(ICoinV4(coin), key);
_initializeForPositions(key, coin, positions);
return BaseHook.afterInitialize.selector;
}
/// @inheritdoc IUpgradeableDestinationV4Hook
function initializeFromMigration(
PoolKey calldata poolKey,
address coin,
uint160 sqrtPriceX96,
BurnedPosition[] calldata migratedLiquidity,
bytes calldata
) external {
address oldHook = msg.sender;
address newHook = address(this);
// Verify that the caller (new hook) is authorized to perform this migration
// Only registered upgrade paths in the upgrade gate are allowed to migrate liquidity
if (!upgradeGate.isRegisteredUpgradePath(oldHook, newHook)) {
revert IUpgradeableV4Hook.UpgradePathNotRegistered(oldHook, newHook);
}
// Create a new pool key with the same parameters but pointing to this hook
// This ensures the migrated pool uses the new hook implementation
PoolKey memory newKey = PoolKey({
currency0: poolKey.currency0,
currency1: poolKey.currency1,
fee: poolKey.fee,
tickSpacing: poolKey.tickSpacing,
hooks: IHooks(newHook)
});
// Initialize the new pool with the migrated price
// This creates the actual Uniswap V4 pool with the current market price
// A side effect is that the _afterInitialize hook is called here, so we find self-referential calls there and return early.
// This preserves the previous sqrtPriceX96 in the new pools.
poolManager.initialize(newKey, sqrtPriceX96);
// Convert the burned/migrated liquidity positions into new LP positions
// This recreates the liquidity structure from the old hook in the new hook
LpPosition[] memory positions = V4Liquidity.generatePositionsFromMigratedLiquidity(sqrtPriceX96, migratedLiquidity);
// Store the positions and mint the initial liquidity into the new pool
_initializeForPositions(newKey, coin, positions);
// Handle any remaining token balances by adding them to the last position
// This ensures no tokens are left unminted during the migration process
_mintExtraLiquidityAtLastPosition(sqrtPriceX96, newKey);
}
/// @notice Internal fn to add any remaining token balances to the last liquidity position.
/// @param sqrtPriceX96 The sqrt price x96.
/// @param poolKey The pool key.
function _mintExtraLiquidityAtLastPosition(uint160 sqrtPriceX96, PoolKey memory poolKey) internal {
// Check if there are any leftover token balances in the hook after migration
// These could result from rounding or partial liquidity transfers
uint256 currency0Balance = poolKey.currency0.balanceOfSelf();
uint256 currency1Balance = poolKey.currency1.balanceOfSelf();
// Get the stored positions for this pool to access the last position
LpPosition[] storage positions = poolCoins[CoinCommon.hashPoolKey(poolKey)].positions;
// Only proceed if there are actually leftover tokens to mint
if (currency0Balance > 0 || currency1Balance > 0) {
// Get reference to the last position where we'll add the extra liquidity
LpPosition storage lastPosition = positions[positions.length - 1];
// Calculate how much liquidity we can create with the remaining token balances
// This uses the current pool price and the last position's tick range
uint128 newLiquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtPriceX96,
TickMath.getSqrtPriceAtTick(lastPosition.tickLower),
TickMath.getSqrtPriceAtTick(lastPosition.tickUpper),
currency0Balance,
currency1Balance
);
// Create a temporary array with just the last position to mint the extra liquidity
LpPosition[] memory newPositions = new LpPosition[](1);
newPositions[0] = lastPosition;
newPositions[0].liquidity = newLiquidity; // Set the calculated liquidity amount
// Mint the extra liquidity into the pool using the V4 liquidity manager
V4Liquidity.lockAndMint(poolManager, poolKey, newPositions);
// Update our internal tracking of the last position's liquidity
// This keeps our records in sync with the actual pool state
positions[positions.length - 1].liquidity += newPositions[0].liquidity;
}
}
/// @notice Saves the positions for the coin and mints them into the pool
/// @param key The pool key.
/// @param coin The coin address.
/// @param positions The positions.
function _initializeForPositions(PoolKey memory key, address coin, LpPosition[] memory positions) internal {
// Store the association between this pool and its coin + positions
// This creates the internal mapping that tracks which coin owns which positions
poolCoins[CoinCommon.hashPoolKey(key)] = PoolCoin({coin: coin, positions: positions});
// Mint all the calculated liquidity positions into the Uniswap V4 pool
// This actually provides the liquidity that users can trade against
V4Liquidity.lockAndMint(poolManager, key, positions);
}
/// @notice Internal fn called when a swap is executed.
/// @dev This hook is called from BaseHook library from uniswap v4.
/// This hook:
/// 1. Collects accrued LP fees from all positions
/// 2. Mints a new LP position back into the pool
/// 3. Swaps remaining collected fees to the backing currency through multi-hop paths
/// 4. Distributes converted fees as rewards
/// @param sender The address of the sender.
/// @param key The pool key.
/// @param params The swap parameters.
/// @param delta The balance delta.
/// @param hookData The hook data.
/// @return selector The selector of the afterSwap hook to confirm the action.
function _afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) internal virtual override returns (bytes4, int128) {
bytes32 poolKeyHash = CoinCommon.hashPoolKey(key);
// get the coin address and positions for the pool key; they must have been set in the afterInitialize callback
address coin = poolCoins[poolKeyHash].coin;
require(coin != address(0), NoCoinForHook(key));
// get path for swapping the payout to a single currency
IHasSwapPath.PayoutSwapPath memory payoutSwapPath = IHasSwapPath(coin).getPayoutSwapPath(coinVersionLookup);
// collect lp fees
(int128 fees0, int128 fees1) = V4Liquidity.collectFees(poolManager, key, poolCoins[poolKeyHash].positions);
(uint128 marketRewardsAmount0, uint128 marketRewardsAmount1) = CoinRewardsV4.mintLpReward(poolManager, key, fees0, fees1);
// convert remaining fees to payout currency for market rewards
(Currency payoutCurrency, uint128 payoutAmount) = CoinRewardsV4.convertToPayoutCurrency(
poolManager,
marketRewardsAmount0,
marketRewardsAmount1,
payoutSwapPath
);
_distributeMarketRewards(payoutCurrency, payoutAmount, ICoinV4(coin), CoinRewardsV4.getTradeReferral(hookData));
{
(address swapper, bool isTrustedSwapSenderAddress) = _getOriginalMsgSender(sender);
bool isCoinBuy = params.zeroForOne ? Currency.unwrap(key.currency1) == address(coin) : Currency.unwrap(key.currency0) == address(coin);
emit Swapped(
sender,
swapper,
isTrustedSwapSenderAddress,
key,
poolKeyHash,
params,
delta.amount0(),
delta.amount1(),
isCoinBuy,
hookData,
PoolStateReader.getSqrtPriceX96(key, poolManager)
);
}
return (BaseHook.afterSwap.selector, 0);
}
/// @dev Internal fn to allow for overriding market reward distribution logic
function _distributeMarketRewards(Currency currency, uint128 fees, IHasRewardsRecipients coin, address tradeReferrer) internal virtual;
/// @notice Internal fn called when the PoolManager is unlocked. Used to mint initial liquidity positions.
function unlockCallback(bytes calldata data) external onlyPoolManager returns (bytes memory) {
return V4Liquidity.handleCallback(poolManager, data);
}
/// @notice Internal fn to get the original message sender.
/// @param sender The address of the sender.
/// @return swapper The original message sender.
/// @return senderIsTrusted Whether the sender is a trusted message sender.
function _getOriginalMsgSender(address sender) internal view returns (address swapper, bool senderIsTrusted) {
senderIsTrusted = trustedMessageSender[sender];
// If getter function reverts, we return a 0 address by default and continue execution.
try IMsgSender(sender).msgSender() returns (address _swapper) {
swapper = _swapper;
} catch {
swapper = address(0);
}
}
/// @inheritdoc IUpgradeableV4Hook
function migrateLiquidity(address newHook, PoolKey memory poolKey, bytes calldata additionalData) external returns (PoolKey memory newPoolKey) {
bytes32 poolKeyHash = CoinCommon.hashPoolKey(poolKey);
PoolCoin storage poolCoin = poolCoins[poolKeyHash];
// check that the coin associated with the poolkey is the caller
require(poolCoin.coin == msg.sender, OnlyCoin(msg.sender, poolCoin.coin));
// Verify upgrade path is allowed
if (!upgradeGate.isRegisteredUpgradePath(address(this), newHook)) {
revert IUpgradeableV4Hook.UpgradePathNotRegistered(address(this), newHook);
}
newPoolKey = V4Liquidity.lockAndMigrate(poolManager, poolKey, poolCoin.positions, poolCoin.coin, newHook, additionalData);
}
receive() external payable onlyPoolManager {}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
interface IHooksUpgradeGate {
function isRegisteredUpgradePath(address baseImpl, address upgradeImpl) external view returns (bool);
function registerUpgradePath(address[] memory baseImpls, address upgradeImpl) external;
function removeUpgradePath(address baseImpl, address upgradeImpl) external;
event UpgradeRegistered(address fromImpl, address toImpl);
event UpgradeRemoved(address fromImpl, address toImpl);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
interface ICreatorCoinHook {
/// @notice Emitted when creator coin rewards are distributed
/// @param coin The address of the creator coin associated with rewards
/// @param currency The address of the currency in which rewards are paid
/// @param creator The address of the creator receiving rewards
/// @param protocol The address of the protocol receiving rewards
/// @param creatorAmount The amount of `currency` distributed to the creator
/// @param protocolAmount The amount of `currency` distributed to the protocol
event CreatorCoinRewards(address indexed coin, address currency, address creator, address protocol, uint256 creatorAmount, uint256 protocolAmount);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {PathKey} from "@uniswap/v4-periphery/src/libraries/PathKey.sol";
import {ModifyLiquidityParams} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {SafeCast} from "@uniswap/v4-core/src/libraries/SafeCast.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {TransientStateLibrary} from "@uniswap/v4-core/src/libraries/TransientStateLibrary.sol";
import {LpPosition} from "../types/LpPosition.sol";
import {V4Liquidity} from "./V4Liquidity.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DopplerMath} from "../libs/DopplerMath.sol";
import {LiquidityAmounts} from "../utils/uniswap/LiquidityAmounts.sol";
import {IHasRewardsRecipients} from "../interfaces/IHasRewardsRecipients.sol";
import {ICoin} from "../interfaces/ICoin.sol";
import {IZoraV4CoinHook} from "../interfaces/IZoraV4CoinHook.sol";
import {IHasSwapPath} from "../interfaces/ICoinV4.sol";
import {V4Liquidity} from "./V4Liquidity.sol";
import {UniV4SwapToCurrency} from "./UniV4SwapToCurrency.sol";
library CoinRewardsV4 {
using SafeERC20 for IERC20;
// creator gets 50% of the market rewards
// market rewards are 2/3 of the total fee
uint256 public constant CREATOR_REWARD_BPS = 5000;
// create referrer gets 15% of the market rewards
// market rewards are 2/3 of the total fee
uint256 public constant CREATE_REFERRAL_REWARD_BPS = 1500;
// trade referrer gets 10% of the market rewards
// market rewards are 2/3 of the total fee
uint256 public constant TRADE_REFERRAL_REWARD_BPS = 1500;
// doppler gets 5% of the market rewards
// market rewards are 2/3 of the total fee
uint256 public constant DOPPLER_REWARD_BPS = 500;
// LPs get 1/3 of the total fee
uint256 public constant LP_REWARD_BPS = 3333;
function getTradeReferral(bytes calldata hookData) internal pure returns (address) {
return hookData.length > 0 ? abi.decode(hookData, (address)) : address(0);
}
/// @dev Converts collected fees from LP positions into target payout currency, and transfers to hook contract, so
/// that they can later be distributed as rewards.
/// @param poolManager The pool manager instance
/// @param fees0 The amount of fees collected in currency0
/// @param fees1 The amount of fees collected in currency1
/// @param payoutSwapPath The swap path to convert fees to target currency
/// @return receivedCurrency The final currency after swapping
/// @return receivedAmount The final amount after swapping
function convertToPayoutCurrency(
IPoolManager poolManager,
uint128 fees0,
uint128 fees1,
IHasSwapPath.PayoutSwapPath memory payoutSwapPath
) internal returns (Currency receivedCurrency, uint128 receivedAmount) {
// This handles multi-hop swaps if needed (e.g. coin -> backingCoin -> backingCoin's currency)
(receivedCurrency, receivedAmount) = UniV4SwapToCurrency.swapToPath(poolManager, fees0, fees1, payoutSwapPath.currencyIn, payoutSwapPath.path);
// Transfer the final converted currency amount to this contract for distribution
// This makes the tokens available for the subsequent reward distribution
if (receivedAmount > 0) {
poolManager.take(receivedCurrency, address(this), receivedAmount);
}
}
/// @dev Computes the LP reward and remaining amount for market rewards from the total amount
function computeLpReward(uint128 totalBackingAmount) internal pure returns (uint128 lpRewardAmount) {
lpRewardAmount = uint128(calculateReward(uint256(totalBackingAmount), LP_REWARD_BPS));
}
function convertDeltaToPositiveUint128(int256 delta) internal pure returns (uint128) {
if (delta < 0) {
revert SafeCast.SafeCastOverflow();
}
return uint128(uint256(delta));
}
function getCurrencyZeroBalance(IPoolManager poolManager, PoolKey calldata key) internal view returns (uint128) {
return convertDeltaToPositiveUint128(TransientStateLibrary.currencyDelta(poolManager, address(this), key.currency0));
}
function getCurrencyOneBalance(IPoolManager poolManager, PoolKey calldata key) internal view returns (uint128) {
return convertDeltaToPositiveUint128(TransientStateLibrary.currencyDelta(poolManager, address(this), key.currency1));
}
/// @notice Mints LP rewards by creating new liquidity positions from collected fees
/// @dev Splits collected fees between LP rewards and market rewards, then mints new LP positions
/// with the LP reward portion. The remaining amount becomes market rewards for distribution.
/// @param poolManager The pool manager instance
/// @param key The pool key identifying the specific pool
/// @param fees0 The amount of fees collected in currency0
/// @param fees1 The amount of fees collected in currency1
/// @return marketRewardsAmount0 The amount of currency0 remaining for market rewards
/// @return marketRewardsAmount1 The amount of currency1 remaining for market rewards
function mintLpReward(
IPoolManager poolManager,
PoolKey calldata key,
int128 fees0,
int128 fees1
) internal returns (uint128 marketRewardsAmount0, uint128 marketRewardsAmount1) {
if (fees0 > 0) {
uint128 lpRewardAmount0 = computeLpReward(uint128(fees0));
if (lpRewardAmount0 > 0) {
_modifyLiquidity(poolManager, key, lpRewardAmount0, true);
}
}
if (fees1 > 0) {
uint128 lpRewardAmount1 = computeLpReward(uint128(fees1));
if (lpRewardAmount1 > 0) {
_modifyLiquidity(poolManager, key, lpRewardAmount1, false);
}
}
marketRewardsAmount0 = getCurrencyZeroBalance(poolManager, key);
marketRewardsAmount1 = getCurrencyOneBalance(poolManager, key);
}
/// @notice Mints a single-sided LP position
/// @dev The position is created for a single tick spacing range, either entirely above or below the current tick, to ensure only one currency is required
function _modifyLiquidity(IPoolManager poolManager, PoolKey calldata key, uint128 lpRewardAmount, bool isFeesToken0) private {
// Get the current tick to determine where to place the new position.
(, int24 currentTick, , ) = StateLibrary.getSlot0(poolManager, key.toId());
int24 tickLower;
int24 tickUpper;
if (isFeesToken0) {
// For token0 fees, the position must be entirely above the current tick
// We set the lower tick to be at least two tick spacings away to ensure it's not in the active range
int24 minTickLower = currentTick + (key.tickSpacing * 2);
tickLower = DopplerMath.alignTickToTickSpacing(true, minTickLower, key.tickSpacing);
tickUpper = tickLower + key.tickSpacing;
} else {
// For token1 fees, the position must be entirely below the current tick
// We set the upper tick to be at least two tick spacings away
int24 maxTickUpper = currentTick - (key.tickSpacing * 2);
tickUpper = DopplerMath.alignTickToTickSpacing(false, maxTickUpper, key.tickSpacing);
tickLower = tickUpper - key.tickSpacing;
}
uint160 sqrtPriceA = TickMath.getSqrtPriceAtTick(tickLower);
uint160 sqrtPriceB = TickMath.getSqrtPriceAtTick(tickUpper);
uint128 liquidity = isFeesToken0
? LiquidityAmounts.getLiquidityForAmount0(sqrtPriceA, sqrtPriceB, lpRewardAmount)
: LiquidityAmounts.getLiquidityForAmount1(sqrtPriceA, sqrtPriceB, lpRewardAmount);
if (liquidity > 0) {
ModifyLiquidityParams memory params = ModifyLiquidityParams({
tickLower: tickLower,
tickUpper: tickUpper,
liquidityDelta: SafeCast.toInt256(liquidity),
salt: 0
});
poolManager.modifyLiquidity(key, params, "");
}
}
/// @notice Distributes collected market fees as rewards to various recipients including creator, referrers, protocol, and doppler
/// @dev Calculates reward amounts based on predefined basis points and transfers the specified currency to each recipient
/// @param currency The currency token to distribute as rewards (can be native ETH if address is zero)
/// @param fees The total amount of fees collected to be distributed
/// @param coin The coin contract instance that implements IHasRewardsRecipients to get recipient addresses
/// @param tradeReferrer The address of the trade referrer who should receive trade referral rewards (can be zero address)
function distributeMarketRewards(Currency currency, uint128 fees, IHasRewardsRecipients coin, address tradeReferrer) internal {
address payoutRecipient = coin.payoutRecipient();
address platformReferrer = coin.platformReferrer();
address protocolRewardRecipient = coin.protocolRewardRecipient();
address doppler = coin.dopplerFeeRecipient();
MarketRewards memory rewards = _distributeCurrencyRewards(
currency,
fees,
payoutRecipient,
platformReferrer,
protocolRewardRecipient,
doppler,
tradeReferrer
);
IZoraV4CoinHook.MarketRewardsV4 memory marketRewards = IZoraV4CoinHook.MarketRewardsV4({
creatorPayoutAmountCurrency: rewards.creatorAmount,
creatorPayoutAmountCoin: 0,
platformReferrerAmountCurrency: rewards.platformReferrerAmount,
platformReferrerAmountCoin: 0,
tradeReferrerAmountCurrency: rewards.tradeReferrerAmount,
tradeReferrerAmountCoin: 0,
protocolAmountCurrency: rewards.protocolAmount,
protocolAmountCoin: 0,
dopplerAmountCurrency: rewards.dopplerAmount,
dopplerAmountCoin: 0
});
emit IZoraV4CoinHook.CoinMarketRewardsV4(
address(coin),
Currency.unwrap(currency),
payoutRecipient,
platformReferrer,
tradeReferrer,
protocolRewardRecipient,
doppler,
marketRewards
);
}
struct MarketRewards {
uint256 platformReferrerAmount;
uint256 tradeReferrerAmount;
uint256 protocolAmount;
uint256 creatorAmount;
uint256 dopplerAmount;
}
function _distributeCurrencyRewards(
Currency currency,
uint128 fee,
address payoutRecipient,
address platformReferrer,
address protocolRewardRecipient,
address doppler,
address tradeReferral
) internal returns (MarketRewards memory rewards) {
rewards = _computeMarketRewards(fee, tradeReferral != address(0), platformReferrer != address(0));
if (platformReferrer != address(0)) {
_transferCurrency(currency, rewards.platformReferrerAmount, platformReferrer);
}
if (tradeReferral != address(0)) {
_transferCurrency(currency, rewards.tradeReferrerAmount, tradeReferral);
}
_transferCurrency(currency, rewards.creatorAmount, payoutRecipient);
_transferCurrency(currency, rewards.dopplerAmount, doppler);
_transferCurrency(currency, rewards.protocolAmount, protocolRewardRecipient);
}
function _transferCurrency(Currency currency, uint256 amount, address to) internal {
if (amount == 0) {
return;
}
if (currency.isAddressZero()) {
(bool success, ) = payable(to).call{value: amount}("");
if (!success) {
revert ICoin.EthTransferFailed();
}
} else {
IERC20(Currency.unwrap(currency)).safeTransfer(to, amount);
}
}
function _computeMarketRewards(uint128 fee, bool hasTradeReferral, bool hasCreateReferral) internal pure returns (MarketRewards memory rewards) {
if (fee == 0) {
return rewards;
}
uint256 totalAmount = uint256(fee);
rewards.platformReferrerAmount = hasCreateReferral ? calculateReward(totalAmount, CREATE_REFERRAL_REWARD_BPS) : 0;
rewards.tradeReferrerAmount = hasTradeReferral ? calculateReward(totalAmount, TRADE_REFERRAL_REWARD_BPS) : 0;
rewards.creatorAmount = calculateReward(totalAmount, CREATOR_REWARD_BPS);
rewards.dopplerAmount = calculateReward(totalAmount, DOPPLER_REWARD_BPS);
rewards.protocolAmount = totalAmount - rewards.platformReferrerAmount - rewards.tradeReferrerAmount - rewards.creatorAmount - rewards.dopplerAmount;
}
function calculateReward(uint256 amount, uint256 bps) internal pure returns (uint256) {
return (amount * bps) / 10_000;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {BeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {ImmutableState} from "../base/ImmutableState.sol";
import {ModifyLiquidityParams, SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
/// @title Base Hook
/// @notice abstract contract for hook implementations
abstract contract BaseHook is IHooks, ImmutableState {
error HookNotImplemented();
constructor(IPoolManager _manager) ImmutableState(_manager) {
validateHookAddress(this);
}
/// @notice Returns a struct of permissions to signal which hook functions are to be implemented
/// @dev Used at deployment to validate the address correctly represents the expected permissions
/// @return Permissions struct
function getHookPermissions() public pure virtual returns (Hooks.Permissions memory);
/// @notice Validates the deployed hook address agrees with the expected permissions of the hook
/// @dev this function is virtual so that we can override it during testing,
/// which allows us to deploy an implementation to any address
/// and then etch the bytecode into the correct address
function validateHookAddress(BaseHook _this) internal pure virtual {
Hooks.validateHookPermissions(_this, getHookPermissions());
}
/// @inheritdoc IHooks
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96)
external
onlyPoolManager
returns (bytes4)
{
return _beforeInitialize(sender, key, sqrtPriceX96);
}
function _beforeInitialize(address, PoolKey calldata, uint160) internal virtual returns (bytes4) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
onlyPoolManager
returns (bytes4)
{
return _afterInitialize(sender, key, sqrtPriceX96, tick);
}
function _afterInitialize(address, PoolKey calldata, uint160, int24) internal virtual returns (bytes4) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _beforeAddLiquidity(sender, key, params, hookData);
}
function _beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _beforeRemoveLiquidity(sender, key, params, hookData);
}
function _beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external onlyPoolManager returns (bytes4, BalanceDelta) {
return _afterAddLiquidity(sender, key, params, delta, feesAccrued, hookData);
}
function _afterAddLiquidity(
address,
PoolKey calldata,
ModifyLiquidityParams calldata,
BalanceDelta,
BalanceDelta,
bytes calldata
) internal virtual returns (bytes4, BalanceDelta) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external onlyPoolManager returns (bytes4, BalanceDelta) {
return _afterRemoveLiquidity(sender, key, params, delta, feesAccrued, hookData);
}
function _afterRemoveLiquidity(
address,
PoolKey calldata,
ModifyLiquidityParams calldata,
BalanceDelta,
BalanceDelta,
bytes calldata
) internal virtual returns (bytes4, BalanceDelta) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
onlyPoolManager
returns (bytes4, BeforeSwapDelta, uint24)
{
return _beforeSwap(sender, key, params, hookData);
}
function _beforeSwap(address, PoolKey calldata, SwapParams calldata, bytes calldata)
internal
virtual
returns (bytes4, BeforeSwapDelta, uint24)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external onlyPoolManager returns (bytes4, int128) {
return _afterSwap(sender, key, params, delta, hookData);
}
function _afterSwap(address, PoolKey calldata, SwapParams calldata, BalanceDelta, bytes calldata)
internal
virtual
returns (bytes4, int128)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _beforeDonate(sender, key, amount0, amount1, hookData);
}
function _beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _afterDonate(sender, key, amount0, amount1, hookData);
}
function _afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.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.
library Hooks {
using LPFeeLibrary for uint24;
using Hooks for IHooks;
using SafeCast for int256;
using BeforeSwapDeltaLibrary for BeforeSwapDelta;
using ParseBytes for bytes;
using CustomRevert for bytes4;
uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);
uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;
uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;
uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;
uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;
uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;
uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;
struct Permissions {
bool beforeInitialize;
bool afterInitialize;
bool beforeAddLiquidity;
bool afterAddLiquidity;
bool beforeRemoveLiquidity;
bool afterRemoveLiquidity;
bool beforeSwap;
bool afterSwap;
bool beforeDonate;
bool afterDonate;
bool beforeSwapReturnDelta;
bool afterSwapReturnDelta;
bool afterAddLiquidityReturnDelta;
bool afterRemoveLiquidityReturnDelta;
}
/// @notice Thrown if the address will not lead to the specified hook calls being called
/// @param hooks The address of the hooks contract
error HookAddressNotValid(address hooks);
/// @notice Hook did not return its selector
error InvalidHookResponse();
/// @notice Additional context for ERC-7751 wrapped error when a hook call fails
error HookCallFailed();
/// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
error HookDeltaExceedsSwapAmount();
/// @notice Utility function intended to be used in hook constructors to ensure
/// the deployed hooks address causes the intended hooks to be called
/// @param permissions The hooks that are intended to be called
/// @dev permissions param is memory as the function will be called from constructors
function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
if (
permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
|| permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
|| permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
|| permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
|| permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
|| permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
|| permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
|| permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
|| permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
|| permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
|| permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
|| permissions.afterRemoveLiquidityReturnDelta
!= self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) {
HookAddressNotValid.selector.revertWith(address(self));
}
}
/// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
/// @param self The hook to verify
/// @param fee The fee of the pool the hook is used with
/// @return bool True if the hook address is valid
function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
// The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
{
return false;
}
if (
!self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
&& self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) return false;
// If there is no hook contract set, then fee cannot be dynamic
// If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
return address(self) == address(0)
? !fee.isDynamicFee()
: (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
}
/// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
/// @return result The complete data returned by the hook
function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
bool success;
assembly ("memory-safe") {
success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
}
// Revert with FailedHookCall, containing any error message to bubble up
if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);
// The call was successful, fetch the returned data
assembly ("memory-safe") {
// allocate result byte array from the free memory pointer
result := mload(0x40)
// store new free memory pointer at the end of the array padded to 32 bytes
mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
// store length in memory
mstore(result, returndatasize())
// copy return data to result
returndatacopy(add(result, 0x20), 0, returndatasize())
}
// Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
InvalidHookResponse.selector.revertWith();
}
}
/// @notice performs a hook call using the given calldata on the given hook
/// @return int256 The delta returned by the hook
function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
bytes memory result = callHook(self, data);
// If this hook wasn't meant to return something, default to 0 delta
if (!parseReturn) return 0;
// A length of 64 bytes is required to return a bytes4, and a 32 byte delta
if (result.length != 64) InvalidHookResponse.selector.revertWith();
return result.parseReturnDelta();
}
/// @notice modifier to prevent calling a hook if they initiated the action
modifier noSelfCall(IHooks self) {
if (msg.sender != address(self)) {
_;
}
}
/// @notice calls beforeInitialize hook if permissioned and validates return value
function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
}
}
/// @notice calls afterInitialize hook if permissioned and validates return value
function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
}
}
/// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
function beforeModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
bytes calldata hookData
) internal noSelfCall(self) {
if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
} else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
}
}
/// @notice calls afterModifyLiquidity hook if permissioned and validates return value
function afterModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);
callerDelta = delta;
if (params.liquidityDelta > 0) {
if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
} else {
if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
}
}
/// @notice calls beforeSwap hook if permissioned and validates return value
function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)
internal
returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
{
amountToSwap = params.amountSpecified;
if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);
if (self.hasPermission(BEFORE_SWAP_FLAG)) {
bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));
// A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
if (result.length != 96) InvalidHookResponse.selector.revertWith();
// dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
// is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();
// skip this logic for the case where the hook return is 0
if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());
// any return in unspecified is passed to the afterSwap hook for handling
int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();
// Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
if (hookDeltaSpecified != 0) {
bool exactInput = amountToSwap < 0;
amountToSwap += hookDeltaSpecified;
if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
HookDeltaExceedsSwapAmount.selector.revertWith();
}
}
}
}
}
/// @notice calls afterSwap hook if permissioned and validates return value
function afterSwap(
IHooks self,
PoolKey memory key,
SwapParams memory params,
BalanceDelta swapDelta,
bytes calldata hookData,
BeforeSwapDelta beforeSwapHookReturn
) internal returns (BalanceDelta, BalanceDelta) {
if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);
int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();
if (self.hasPermission(AFTER_SWAP_FLAG)) {
hookDeltaUnspecified += self.callHookWithReturnDelta(
abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
).toInt128();
}
BalanceDelta hookDelta;
if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
: toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);
// the caller has to pay for (or receive) the hook's delta
swapDelta = swapDelta - hookDelta;
}
return (swapDelta, hookDelta);
}
/// @notice calls beforeDonate hook if permissioned and validates return value
function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(BEFORE_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
/// @notice calls afterDonate hook if permissioned and validates return value
function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
return uint160(address(self)) & flag != 0;
}
}// 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: 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 {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.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.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.23;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {LpPosition} from "../types/LpPosition.sol";
import {ICoin} from "./ICoin.sol";
import {IUpgradeableV4Hook} from "./IUpgradeableV4Hook.sol";
interface IZoraV4CoinHook is IUpgradeableV4Hook {
/// @notice Emitted when a swap is executed.
/// @param sender The address of the sender.
/// @param swapSender The address of the swap sender.
/// @param isTrustedSwapSenderAddress Whether the swap sender is a trusted address. (Based on a registry of trusted addresses)
/// @param key The pool key struct to identify the pool.
/// @param poolKeyHash The hash of the pool key for indexing.
/// @param params The swap parameters.
/// @param amount0 The amount of token0.
/// @param amount1 The amount of token1.
/// @param isCoinBuy Whether the swap is a coin buy.
/// @param hookData The data passed into the hook for the swap.
event Swapped(
address indexed sender,
address indexed swapSender,
bool isTrustedSwapSenderAddress,
PoolKey key,
bytes32 indexed poolKeyHash,
SwapParams params,
int128 amount0,
int128 amount1,
bool isCoinBuy,
bytes hookData,
uint160 sqrtPriceX96
);
/// @notice Thrown when a non-coin is used to initialize a pool with this hook.
/// @param coin The address of the coin.
error NotACoin(address coin);
/// @notice Coin version lookup cannot be the zero address.
error CoinVersionLookupCannotBeZeroAddress();
/// @notice Upgrade gate cannot be the zero address.
error UpgradeGateCannotBeZeroAddress();
/// @notice Thrown when a pool is not initialized for the hook.
/// @param key The pool key struct to identify the pool.
error NoCoinForHook(PoolKey key);
/// @notice Thrown when a attempting to swap with a path that has no steps.
error PathMustHaveAtLeastOneStep();
/// @notice Thrown when a non-coin is used to access the functionality of a coin.
error OnlyCoin(address caller, address expectedCoin);
/// @notice The pool coin struct. Lists all the contract-created positions for the coin.
struct PoolCoin {
/// @notice The address of the coin.
address coin;
/// @notice The positions of the pool coin.
LpPosition[] positions;
}
/// @notice The rewards accrued from the market's liquidity position
/// @param creatorPayoutAmountCurrency The amount of currency payed out to the creator
/// @param creatorPayoutAmountCoin The amount of coin payed out to the creator
/// @param platformReferrerAmountCurrency The amount of currency payed out to the platform referrer
/// @param platformReferrerAmountCoin The amount of coin payed out to the platform referrer
/// @param tradeReferrerAmountCurrency The amount of currency payed out to the trade referrer
/// @param tradeReferrerAmountCoin The amount of coin to pay to the trade referrer
/// @param protocolAmountCurrency The amount of currency to pay to the protocol
/// @param protocolAmountCoin The amount of coin to pay to the protocol
/// @param dopplerAmountCurrency The amount of currency to pay to doppler
/// @param dopplerAmountCoin The amount of coin to pay to doppler
struct MarketRewardsV4 {
uint256 creatorPayoutAmountCurrency;
uint256 creatorPayoutAmountCoin;
uint256 platformReferrerAmountCurrency;
uint256 platformReferrerAmountCoin;
uint256 tradeReferrerAmountCurrency;
uint256 tradeReferrerAmountCoin;
uint256 protocolAmountCurrency;
uint256 protocolAmountCoin;
uint256 dopplerAmountCurrency;
uint256 dopplerAmountCoin;
}
/// @notice Emitted when market rewards are distributed
/// @param coin The address of the coin
/// @param currency The address of the currency
/// @param payoutRecipient The address of the creator rewards payout recipient
/// @param platformReferrer The address of the platform referrer
/// @param protocolRewardRecipient The address of the protocol reward recipient
/// @param dopplerRecipient The address of the doppler recipient
/// @param tradeReferrer The address of the trade referrer
/// @param marketRewards The rewards accrued from the market's liquidity position
event CoinMarketRewardsV4(
address coin,
address currency,
address payoutRecipient,
address platformReferrer,
address tradeReferrer,
address protocolRewardRecipient,
address dopplerRecipient,
MarketRewardsV4 marketRewards
);
/// @notice Emitted when LP rewards are distributed
/// @param coin The address of the coin
/// @param currency The address of the currency
/// @param amountCurrency The amount paid out
/// @param tick The current tick
/// @param liquidity The current liquidity
event LpReward(address indexed coin, address indexed currency, uint256 amountCurrency, int24 tick, uint128 liquidity);
/// @notice Returns the pool coin for a given pool key hash.
/// @param poolKeyHash The hash of the pool key for indexing.
/// @return poolCoin The pool coin confirmation data.
function getPoolCoinByHash(bytes23 poolKeyHash) external view returns (IZoraV4CoinHook.PoolCoin memory);
/// @notice Returns the pool coin for a given pool key.
/// @param key The pool key.
/// @return poolCoin The pool coin confirmation data.
function getPoolCoin(PoolKey memory key) external view returns (IZoraV4CoinHook.PoolCoin memory);
/// @notice Returns whether the sender is a trusted message sender.
/// @param sender The address of the sender.
/// @return isTrusted Whether the sender is a trusted message sender.
function isTrustedMessageSender(address sender) external view returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
/// @notice Interface for getting the correct message sender.
interface IMsgSender {
/// @notice Returns the address of the message sender.
/// @return The address of the message sender.
function msgSender() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {ICoin} from "./ICoin.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolConfiguration} from "../types/PoolConfiguration.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {PathKey} from "@uniswap/v4-periphery/src/libraries/PathKey.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {IDeployedCoinVersionLookup} from "./IDeployedCoinVersionLookup.sol";
/// @notice Returns the pool key for the coin
interface IHasPoolKey {
/// @notice Returns the Uniswap V4 pool key associated with this coin
/// @return The PoolKey struct containing pool identification parameters
function getPoolKey() external view returns (PoolKey memory);
}
/// @notice Returns the pool configuration for the coin
interface IHasSwapPath {
/// @notice Struct containing the swap path configuration for converting fees to payout currency
/// @param path Array of PathKey structs defining the multi-hop swap route
/// @param currencyIn The input currency to start the swap path from
struct PayoutSwapPath {
PathKey[] path;
Currency currencyIn;
}
/// @notice Returns the swap path configuration for converting this coin to its final payout currency
/// @dev This enables multi-hop swaps through intermediate currencies to reach the target payout token
/// @param coinVersionLookup Contract for looking up deployed coin versions to build recursive paths
/// @return PayoutSwapPath struct containing the complete swap route configuration
function getPayoutSwapPath(IDeployedCoinVersionLookup coinVersionLookup) external view returns (PayoutSwapPath memory);
}
interface ICoinV4 is ICoin, IHasPoolKey, IHasSwapPath {
/// @notice Returns the pool configuration settings for this coin's Uniswap V4 pool
/// @return PoolConfiguration struct containing pool-specific settings and parameters
function getPoolConfiguration() external view returns (PoolConfiguration memory);
/// @notice Emitted when a hook is upgraded
/// @param fromPoolKey The pool key being upgraded
/// @param toPoolKey The new pool key returned from the destination hook
event LiquidityMigrated(PoolKey fromPoolKey, bytes32 fromPoolKeyHash, PoolKey toPoolKey, bytes32 toPoolKeyHash);
/// @notice Returns the hooks contract used by this coin's Uniswap V4 pool
/// @return The IHooks contract interface that handles pool lifecycle events
function hooks() external view returns (IHooks);
/// @notice Initializes the coin
/// @dev Called by the factory contract when the contract is deployed.
/// @param payoutRecipient_ The address of the payout recipient. Can be updated by the owner. Cannot be 0 address.
/// @param owners_ The addresses of the owners. All owners have the same full admin access. Cannot be 0 address.
/// @param tokenURI_ The URI of the token. Can be updated by the owner.
/// @param name_ The name of the token. Cannot be updated.
/// @param symbol_ The symbol of the token. Cannot be updated.
/// @param platformReferrer_ The address of the platform referrer. Cannot be updated.
/// @param currency_ The currency of the coin. Cannot be updated. Can be the zero address for ETH.
/// @param poolKey_ The pool key for the coin. Derived in the factory.
/// @param sqrtPriceX96 The initial sqrt price for the pool
/// @param poolConfiguration_ The configuration for the pool
function initialize(
address payoutRecipient_,
address[] memory owners_,
string memory tokenURI_,
string memory name_,
string memory symbol_,
address platformReferrer_,
address currency_,
PoolKey memory poolKey_,
uint160 sqrtPriceX96,
PoolConfiguration memory poolConfiguration_
) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
struct LpPosition {
int24 tickLower;
int24 tickUpper;
uint128 liquidity;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {SqrtPriceMath} from "@uniswap/v4-core/src/libraries/SqrtPriceMath.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {IPoolManager, PoolKey, IHooks, ModifyLiquidityParams, BalanceDelta} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {BalanceDeltaLibrary} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {TransientStateLibrary} from "@uniswap/v4-core/src/libraries/TransientStateLibrary.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {LpPosition} from "../types/LpPosition.sol";
import {SafeCast} from "@uniswap/v4-core/src/libraries/SafeCast.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {IHasRewardsRecipients} from "../interfaces/ICoin.sol";
import {IHasSwapPath} from "../interfaces/ICoinV4.sol";
import {UniV4SwapToCurrency} from "./UniV4SwapToCurrency.sol";
import {PathKey} from "@uniswap/v4-periphery/src/libraries/PathKey.sol";
import {Position} from "@uniswap/v4-core/src/libraries/Position.sol";
import {BurnedPosition, Delta, MigratedLiquidityResult, IUpgradeableV4Hook} from "../interfaces/IUpgradeableV4Hook.sol";
import {PoolStateReader} from "../libs/PoolStateReader.sol";
import {IUpgradeableDestinationV4Hook} from "../interfaces/IUpgradeableV4Hook.sol";
import {LiquidityAmounts} from "../utils/uniswap/LiquidityAmounts.sol";
// command = 1; mint
struct MintCallbackData {
PoolKey poolKey;
LpPosition[] positions;
}
struct BurnAllPositionsCallbackData {
PoolKey poolKey;
LpPosition[] positions;
address coin;
address newHook;
}
library V4Liquidity {
using BalanceDeltaLibrary for BalanceDelta;
using CurrencyLibrary for Currency;
uint8 constant MINT_CALLBACK_ID = 1;
uint8 constant BURN_ALL_POSITIONS_CALLBACK_ID = 2;
error InvalidCallbackId(uint8 callbackId);
/// @notice Locks the pool, and mint initial positions to the hook
/// @param poolManager The pool manager.
/// @param poolKey The pool key.
/// @param positions The positions.
function lockAndMint(IPoolManager poolManager, PoolKey memory poolKey, LpPosition[] memory positions) internal {
bytes memory data = abi.encode(MINT_CALLBACK_ID, abi.encode(MintCallbackData({poolKey: poolKey, positions: positions})));
IPoolManager(poolManager).unlock(data);
}
/// @notice Locks the pool, burns positions, and transfers deltas to the new hook
function lockAndMigrate(
IPoolManager poolManager,
PoolKey memory poolKey,
LpPosition[] memory positions,
address coin,
address newHook,
bytes calldata additionalData
) internal returns (PoolKey memory) {
bytes memory data = abi.encode(
BURN_ALL_POSITIONS_CALLBACK_ID,
abi.encode(BurnAllPositionsCallbackData({poolKey: poolKey, positions: positions, coin: coin, newHook: newHook}))
);
// lock the pool and burn positions - this hook will then have a balance of the deltas
bytes memory result = IPoolManager(poolManager).unlock(data);
MigratedLiquidityResult memory migratedLiquidityResult = abi.decode(result, (MigratedLiquidityResult));
// Check if new hook supports the upgradeable destination interface
require(IERC165(newHook).supportsInterface(type(IUpgradeableDestinationV4Hook).interfaceId), IUpgradeableV4Hook.InvalidNewHook(newHook));
// Initialize new hook with migration data
IUpgradeableDestinationV4Hook(address(newHook)).initializeFromMigration(
poolKey,
coin,
migratedLiquidityResult.sqrtPriceX96,
migratedLiquidityResult.burnedPositions,
additionalData
);
return
PoolKey({currency0: poolKey.currency0, currency1: poolKey.currency1, fee: poolKey.fee, tickSpacing: poolKey.tickSpacing, hooks: IHooks(newHook)});
}
/// @notice Handles the callback from the pool manager. Called by the hook upon unlock.
function handleCallback(IPoolManager poolManager, bytes memory data) internal returns (bytes memory) {
(uint8 callbackId, bytes memory contents) = abi.decode(data, (uint8, bytes));
if (callbackId == MINT_CALLBACK_ID) {
_handleMintPositionsCallback(poolManager, abi.decode(contents, (MintCallbackData)));
return bytes("");
}
if (callbackId == BURN_ALL_POSITIONS_CALLBACK_ID) {
return _handleBurnAllPositionsCallback(poolManager, abi.decode(contents, (BurnAllPositionsCallbackData)));
}
revert InvalidCallbackId(callbackId);
}
function _handleMintPositionsCallback(IPoolManager poolManager, MintCallbackData memory callbackData) private {
mintPositions(poolManager, callbackData.poolKey, callbackData.positions);
_settleUp(poolManager, callbackData.poolKey);
}
function _handleBurnAllPositionsCallback(IPoolManager poolManager, BurnAllPositionsCallbackData memory callbackData) private returns (bytes memory) {
uint160 sqrtPriceX96 = PoolStateReader.getSqrtPriceX96(callbackData.poolKey, poolManager);
BurnedPosition[] memory burnedPositions = burnPositions(poolManager, callbackData.poolKey, callbackData.positions);
int256 deltas0 = TransientStateLibrary.currencyDelta(poolManager, address(this), callbackData.poolKey.currency0);
int256 deltas1 = TransientStateLibrary.currencyDelta(poolManager, address(this), callbackData.poolKey.currency1);
// settle deltas, transferring the balance to destination hook contract
_settleDeltas(poolManager, callbackData.poolKey, deltas0, deltas1, callbackData.newHook);
// transfer deltas to the new hook
MigratedLiquidityResult memory result = MigratedLiquidityResult({
sqrtPriceX96: sqrtPriceX96,
burnedPositions: burnedPositions,
totalAmount0: uint256(deltas0),
totalAmount1: uint256(deltas1)
});
return abi.encode(result);
}
function generatePositionsFromMigratedLiquidity(
uint160 sqrtPriceX96,
BurnedPosition[] calldata migratedLiquidity
) internal pure returns (LpPosition[] memory positions) {
positions = new LpPosition[](migratedLiquidity.length);
for (uint256 i = 0; i < migratedLiquidity.length; i++) {
uint128 liquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtPriceX96,
TickMath.getSqrtPriceAtTick(migratedLiquidity[i].tickLower),
TickMath.getSqrtPriceAtTick(migratedLiquidity[i].tickUpper),
migratedLiquidity[i].amount0Received,
migratedLiquidity[i].amount1Received
);
positions[i] = LpPosition({liquidity: liquidity, tickLower: migratedLiquidity[i].tickLower, tickUpper: migratedLiquidity[i].tickUpper});
}
}
function collectFees(IPoolManager poolManager, PoolKey memory poolKey, LpPosition[] storage positions) internal returns (int128 balance0, int128 balance1) {
ModifyLiquidityParams memory params;
uint256 numPositions = positions.length;
for (uint256 i; i < numPositions; i++) {
// if there is no liquidity, skip
uint128 liquidity = getLiquidity(poolManager, address(this), poolKey, positions[i].tickLower, positions[i].tickUpper);
if (liquidity == 0) {
continue;
}
params = ModifyLiquidityParams({
tickLower: positions[i].tickLower,
tickUpper: positions[i].tickUpper,
liquidityDelta: 0, // only collect
salt: 0
});
(, BalanceDelta feesDelta) = poolManager.modifyLiquidity(poolKey, params, "");
// check if there is enough erc20 balance for each token to take the fees
balance0 += feesDelta.amount0();
balance1 += feesDelta.amount1();
}
}
function burnPositions(
IPoolManager poolManager,
PoolKey memory poolKey,
LpPosition[] memory positions
) internal returns (BurnedPosition[] memory burnedPositions) {
burnedPositions = new BurnedPosition[](positions.length);
for (uint256 i; i < positions.length; i++) {
uint128 liquidity = getLiquidity(poolManager, address(this), poolKey, positions[i].tickLower, positions[i].tickUpper);
ModifyLiquidityParams memory params = ModifyLiquidityParams({
tickLower: positions[i].tickLower,
tickUpper: positions[i].tickUpper,
liquidityDelta: -SafeCast.toInt256(liquidity),
salt: 0
});
(BalanceDelta liquidityDelta, BalanceDelta feesAccrued) = poolManager.modifyLiquidity(poolKey, params, "");
burnedPositions[i] = BurnedPosition({
tickLower: positions[i].tickLower,
tickUpper: positions[i].tickUpper,
amount0Received: uint128(liquidityDelta.amount0() + feesAccrued.amount0()),
amount1Received: uint128(liquidityDelta.amount1() + feesAccrued.amount1())
});
}
}
function getLiquidity(
IPoolManager poolManager,
address owner,
PoolKey memory poolKey,
int24 tickLower,
int24 tickUpper
) internal view returns (uint128 liquidity) {
bytes32 positionId = Position.calculatePositionKey(owner, tickLower, tickUpper, bytes32(0));
liquidity = StateLibrary.getPositionLiquidity(poolManager, poolKey.toId(), positionId);
}
function mintPositions(IPoolManager poolManager, PoolKey memory poolKey, LpPosition[] memory positions) internal returns (int128 amount0, int128 amount1) {
ModifyLiquidityParams memory params;
uint256 numPositions = positions.length;
for (uint256 i; i < numPositions; i++) {
params = ModifyLiquidityParams({
tickLower: positions[i].tickLower,
tickUpper: positions[i].tickUpper,
liquidityDelta: SafeCast.toInt256(positions[i].liquidity),
salt: 0
});
(BalanceDelta delta, ) = poolManager.modifyLiquidity(poolKey, params, "");
amount0 += delta.amount0();
amount1 += delta.amount1();
}
}
function _settleUp(IPoolManager poolManager, PoolKey memory poolKey) private returns (int256 currency0Delta, int256 currency1Delta) {
// calculate the current deltas
currency0Delta = TransientStateLibrary.currencyDelta(poolManager, address(this), poolKey.currency0);
currency1Delta = TransientStateLibrary.currencyDelta(poolManager, address(this), poolKey.currency1);
_settleDeltas(poolManager, poolKey, currency0Delta, currency1Delta, address(this));
}
function _settleDeltas(IPoolManager poolManager, PoolKey memory poolKey, int256 currency0Delta, int256 currency1Delta, address to) private {
if (currency0Delta > 0) {
poolManager.take(poolKey.currency0, to, uint256(currency0Delta));
}
if (currency1Delta > 0) {
poolManager.take(poolKey.currency1, to, uint256(currency1Delta));
}
if (currency0Delta < 0) {
poolManager.sync(poolKey.currency0);
poolKey.currency0.transfer(address(poolManager), uint256(-currency0Delta));
poolManager.settle();
}
if (currency1Delta < 0) {
poolManager.sync(poolKey.currency1);
poolKey.currency1.transfer(address(poolManager), uint256(-currency1Delta));
poolManager.settle();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
/// @title IDeployedCoinVersionLookup
/// @notice Interface for querying the version of a deployed coin
interface IDeployedCoinVersionLookup {
/// @notice Gets the version for a deployed coin
/// @param coin The address of the coin
/// @return version The version of the coin (0 if not found)
function getVersionForDeployedCoin(address coin) external view returns (uint8);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
library CoinCommon {
// Helper function to sort tokens and determine if coin is token0
function sortTokens(address coin, address currency) internal pure returns (bool isCoinToken0) {
return coin < currency;
}
function hashPoolKey(PoolKey memory key) internal pure returns (bytes32) {
return keccak256(abi.encode(key));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {PoolConfiguration} from "../interfaces/ICoin.sol";
import {CoinConfigurationVersions} from "./CoinConfigurationVersions.sol";
import {LpPosition} from "../types/LpPosition.sol";
import {MarketConstants} from "./MarketConstants.sol";
import {FullMath} from "../utils/uniswap/FullMath.sol";
import {TickMath} from "../utils/uniswap/TickMath.sol";
import {IDopplerErrors} from "../interfaces/IDopplerErrors.sol";
import {DopplerMath} from "./DopplerMath.sol";
library CoinDopplerMultiCurve {
error ArrayLengthMismatch();
error ZeroDiscoveryPositions();
error ZeroDiscoverySupplyShare();
error InvalidTickRangeMisordered(int24 tickLower, int24 tickUpper);
error ConfigTickLowerMustBeLessThanTickUpper();
/**
* @notice Configures multi-curve liquidity based on the provided parameters.
* @param isCoinToken0 A boolean indicating if the coin is token0 (true) or token1 (false) in the pair.
* This affects tick ordering and price calculations.
* @param poolConfig_ ABI encoded data containing the pool configuration parameters.
* It is expected to be encoded in the following order:
* - version (uint8): The version of the pool configuration.
* (e.g., 2 for UniswapV3, 4 for Doppler/Uniswap V4).
* - currency (address): The address of the currency token (e.g., WETH) paired with the coin.
* - tickLower (int24[]): An array of lower tick boundaries for each liquidity curve.
* - tickUpper (int24[]): An array of upper tick boundaries for each liquidity curve.
* - numDiscoveryPositions (uint16[]): An array specifying the number of discrete liquidity
* positions within each curve's discovery phase.
* - maxDiscoverySupplyShare (uint256[]): An array of WAD-scaled values (1e18) representing
* the maximum share of the coin's total supply
* allocated to each curve's discovery phase.
* @return sqrtPriceX96 The initial square root price of the pool, scaled to X96 format.
* @return poolConfiguration A struct containing the configured pool parameters,
* including version, number of positions, fee, tick spacing,
* and arrays for discovery positions, tick boundaries, and supply shares.
*/
function setupPool(bool isCoinToken0, bytes memory poolConfig_) internal pure returns (uint160 sqrtPriceX96, PoolConfiguration memory poolConfiguration) {
(, , int24[] memory tickLower_, int24[] memory tickUpper_, uint16[] memory numDiscoveryPositions_, uint256[] memory maxDiscoverySupplyShare_) = abi
.decode(poolConfig_, (uint8, address, int24[], int24[], uint16[], uint256[]));
uint256 numCurves = tickLower_.length;
if (numCurves != tickUpper_.length || numCurves != numDiscoveryPositions_.length || numCurves != maxDiscoverySupplyShare_.length) {
revert ArrayLengthMismatch();
}
uint256 totalDiscoverySupplyShare;
uint256 totalDiscoveryPositions;
int24 boundryTickLower = DopplerMath.alignTickToTickSpacing(isCoinToken0, TickMath.MAX_TICK, MarketConstants.TICK_SPACING);
int24 boundryTickUpper = DopplerMath.alignTickToTickSpacing(isCoinToken0, TickMath.MIN_TICK, MarketConstants.TICK_SPACING);
// For each curve:
for (uint256 i; i < numCurves; i++) {
// Ensure a value is specified
require(numDiscoveryPositions_[i] > 0, ZeroDiscoveryPositions());
require(maxDiscoverySupplyShare_[i] > 0, ZeroDiscoverySupplyShare());
// Aggregate the total discovery positions and supply across curves
totalDiscoveryPositions += numDiscoveryPositions_[i];
totalDiscoverySupplyShare += maxDiscoverySupplyShare_[i];
int24 currentTickLower = DopplerMath.alignTickToTickSpacing(isCoinToken0, tickLower_[i], MarketConstants.TICK_SPACING);
int24 currentTickUpper = DopplerMath.alignTickToTickSpacing(isCoinToken0, tickUpper_[i], MarketConstants.TICK_SPACING);
require(currentTickLower < currentTickUpper, ConfigTickLowerMustBeLessThanTickUpper());
// Sort the tick values based on token order
tickLower_[i] = isCoinToken0 ? currentTickLower : -currentTickUpper;
tickUpper_[i] = isCoinToken0 ? currentTickUpper : -currentTickLower;
boundryTickLower = boundryTickLower < tickLower_[i] ? boundryTickLower : tickLower_[i];
boundryTickUpper = boundryTickUpper > tickUpper_[i] ? boundryTickUpper : tickUpper_[i];
}
require(boundryTickLower < boundryTickUpper, InvalidTickRangeMisordered(boundryTickLower, boundryTickUpper));
require(totalDiscoveryPositions > 1 && totalDiscoveryPositions <= 200, IDopplerErrors.NumDiscoveryPositionsOutOfRange());
require(totalDiscoverySupplyShare < MarketConstants.WAD, IDopplerErrors.MaxShareToBeSoldExceeded(totalDiscoverySupplyShare, MarketConstants.WAD));
sqrtPriceX96 = TickMath.getSqrtPriceAtTick(isCoinToken0 ? boundryTickLower : boundryTickUpper);
poolConfiguration = PoolConfiguration({
version: CoinConfigurationVersions.DOPPLER_MULTICURVE_UNI_V4_POOL_VERSION,
numPositions: uint16(totalDiscoveryPositions + 1), // Add one for the final tail position
fee: MarketConstants.LP_FEE_V4,
tickSpacing: MarketConstants.TICK_SPACING,
numDiscoveryPositions: numDiscoveryPositions_,
tickLower: tickLower_,
tickUpper: tickUpper_,
maxDiscoverySupplyShare: maxDiscoverySupplyShare_
});
}
/// @notice Calculates the LP positions for a given multi-curve configuration
function calculatePositions(
bool isCoinToken0,
PoolConfiguration memory poolConfiguration,
uint256 totalSupply
) internal pure returns (LpPosition[] memory positions) {
positions = new LpPosition[](poolConfiguration.numPositions);
uint256 discoverySupply;
uint256 currentPositionOffset;
uint256 numCurves = poolConfiguration.tickLower.length;
for (uint256 i; i < numCurves; i++) {
uint256 curveSupply = FullMath.mulDiv(totalSupply, poolConfiguration.maxDiscoverySupplyShare[i], MarketConstants.WAD);
(positions, curveSupply) = DopplerMath.calculateLogNormalDistribution(
poolConfiguration.tickLower[i],
poolConfiguration.tickUpper[i],
MarketConstants.TICK_SPACING,
isCoinToken0,
curveSupply,
poolConfiguration.numDiscoveryPositions[i],
positions,
currentPositionOffset
);
discoverySupply += curveSupply;
currentPositionOffset += poolConfiguration.numDiscoveryPositions[i];
}
uint256 tailSupply = totalSupply - discoverySupply;
// Calculate the tail position (the last position in the array)
positions[poolConfiguration.numPositions - 1] = DopplerMath.calculateLpTail(
poolConfiguration.tickLower[numCurves - 1],
poolConfiguration.tickUpper[numCurves - 1],
isCoinToken0,
tailSupply,
MarketConstants.TICK_SPACING
);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
/// @title PoolStateReader
/// @notice Library for reading state information from Uniswap V4 pools
/// @dev Provides utility functions to extract specific pool state data without requiring full slot0 information
library PoolStateReader {
/// @notice Retrieves the current square root price from a Uniswap V4 pool
/// @dev Gets the sqrtPriceX96 value from slot0 of the specified pool, discarding other slot0 data
/// @param key The PoolKey struct identifying the specific pool to query
/// @param poolManager The IPoolManager contract instance to query pool state from
/// @return sqrtPriceX96 The current square root price of the pool in X96 fixed-point format
function getSqrtPriceX96(PoolKey memory key, IPoolManager poolManager) internal view returns (uint160 sqrtPriceX96) {
PoolId poolId = key.toId();
(sqrtPriceX96, , , ) = StateLibrary.getSlot0(poolManager, poolId);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IERC7572} from "./IERC7572.sol";
import {IDopplerErrors} from "./IDopplerErrors.sol";
import {PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {PoolConfiguration} from "../types/PoolConfiguration.sol";
import {IHasRewardsRecipients} from "./IHasRewardsRecipients.sol";
struct PoolConfigurationV4 {
uint8 version;
PoolKey poolKey;
int24 tick;
}
struct PoolKeyStruct {
address currency0;
address currency1;
uint24 fee;
int24 tickSpacing;
address hooks;
}
interface ICoin is IERC165, IERC7572, IDopplerErrors, IHasRewardsRecipients {
/// @notice Thrown when the name is required for the coin
error NameIsRequired();
/// @notice Thrown when an operation is attempted with a zero address
error AddressZero();
/// @notice Thrown when an invalid market type is specified
error InvalidMarketType();
/// @notice Thrown when there are insufficient funds for an operation
error InsufficientFunds();
/// @notice Thrown when there is insufficient liquidity for a transaction
error InsufficientLiquidity();
/// @notice Thrown when the slippage bounds are exceeded during a transaction
error SlippageBoundsExceeded();
/// @notice Thrown when the initial order size is too large
error InitialOrderSizeTooLarge();
/// @notice Thrown when the msg.value amount does not match the amount of currency sent
error EthAmountMismatch();
/// @notice Thrown when the ETH amount is too small for a transaction
error EthAmountTooSmall();
/// @notice Thrown when the expected amount of ERC20s transferred does not match the amount received
error ERC20TransferAmountMismatch();
/// @notice Thrown when ETH is sent with a buy or sell but the currency is not WETH
error EthTransferInvalid();
/// @notice Thrown when an ETH transfer fails
error EthTransferFailed();
/// @notice Thrown when an operation is attempted by an entity other than the pool
error OnlyPool(address sender, address pool);
/// @notice Thrown when an operation is attempted by an entity other than WETH
error OnlyWeth();
/// @notice Thrown when a market is not yet graduated
error MarketNotGraduated();
/// @notice Thrown when a market is already graduated
error MarketAlreadyGraduated();
/// @notice Thrown when the lower tick is not less than the maximum tick or not a multiple of 200
error InvalidCurrencyLowerTick();
/// @notice Thrown when the lower tick is not set to the default value
error InvalidWethLowerTick();
/// @notice Thrown when a legacy pool does not have one discovery position
error LegacyPoolMustHaveOneDiscoveryPosition();
/// @notice Thrown when a Doppler pool does not have more than 2 discovery positions
error DopplerPoolMustHaveMoreThan2DiscoveryPositions();
/// @notice Thrown when an invalid pool version is specified
error InvalidPoolVersion();
/// @notice The rewards accrued from the market's liquidity position
struct MarketRewards {
uint256 totalAmountCurrency;
uint256 totalAmountCoin;
uint256 creatorPayoutAmountCurrency;
uint256 creatorPayoutAmountCoin;
uint256 platformReferrerAmountCurrency;
uint256 platformReferrerAmountCoin;
uint256 protocolAmountCurrency;
uint256 protocolAmountCoin;
}
/// @notice Emitted when market rewards are distributed
/// @param payoutRecipient The address of the creator rewards payout recipient
/// @param platformReferrer The address of the platform referrer
/// @param protocolRewardRecipient The address of the protocol reward recipient
/// @param currency The address of the currency
/// @param marketRewards The rewards accrued from the market's liquidity position
event CoinMarketRewards(
address indexed payoutRecipient,
address indexed platformReferrer,
address protocolRewardRecipient,
address currency,
MarketRewards marketRewards
);
/// @notice Emitted when coins are bought
/// @param buyer The address of the buyer
/// @param recipient The address of the recipient
/// @param tradeReferrer The address of the trade referrer
/// @param coinsPurchased The number of coins purchased
/// @param currency The address of the currency
/// @param amountFee The fee for the purchase
/// @param amountSold The amount of the currency sold
event CoinBuy(
address indexed buyer,
address indexed recipient,
address indexed tradeReferrer,
uint256 coinsPurchased,
address currency,
uint256 amountFee,
uint256 amountSold
);
/// @notice Emitted when coins are sold
/// @param seller The address of the seller
/// @param recipient The address of the recipient
/// @param tradeReferrer The address of the trade referrer
/// @param coinsSold The number of coins sold
/// @param currency The address of the currency
/// @param amountFee The fee for the sale
/// @param amountPurchased The amount of the currency purchased
event CoinSell(
address indexed seller,
address indexed recipient,
address indexed tradeReferrer,
uint256 coinsSold,
address currency,
uint256 amountFee,
uint256 amountPurchased
);
/// @notice Emitted when a coin is transferred
/// @param sender The address of the sender
/// @param recipient The address of the recipient
/// @param amount The amount of coins
/// @param senderBalance The balance of the sender after the transfer
/// @param recipientBalance The balance of the recipient after the transfer
event CoinTransfer(address indexed sender, address indexed recipient, uint256 amount, uint256 senderBalance, uint256 recipientBalance);
/// @notice Emitted when trade rewards are distributed
/// @param payoutRecipient The address of the creator rewards payout recipient
/// @param platformReferrer The address of the platform referrer
/// @param tradeReferrer The address of the trade referrer
/// @param protocolRewardRecipient The address of the protocol reward recipient
/// @param creatorReward The reward for the creator
/// @param platformReferrerReward The reward for the platform referrer
/// @param traderReferrerReward The reward for the trade referrer
/// @param protocolReward The reward for the protocol
/// @param currency The address of the currency
event CoinTradeRewards(
address indexed payoutRecipient,
address indexed platformReferrer,
address indexed tradeReferrer,
address protocolRewardRecipient,
uint256 creatorReward,
uint256 platformReferrerReward,
uint256 traderReferrerReward,
uint256 protocolReward,
address currency
);
/// @notice Emitted when the coin name is updated
/// @param caller The msg.sender address
/// @param newName The new coin name
/// @param newSymbol The new coin symbol
event NameAndSymbolUpdated(address indexed caller, string newName, string newSymbol);
/// @notice Emitted when the creator's payout address is updated
/// @param caller The msg.sender address
/// @param prevRecipient The previous payout recipient address
/// @param newRecipient The new payout recipient address
event CoinPayoutRecipientUpdated(address indexed caller, address indexed prevRecipient, address indexed newRecipient);
/// @notice Emitted when the contract URI is updated
/// @param caller The msg.sender address
/// @param newURI The new contract URI
/// @param name The coin name
event ContractMetadataUpdated(address indexed caller, string newURI, string name);
/// @notice Enables a user to burn their tokens
/// @param amount The amount of tokens to burn
function burn(uint256 amount) external;
/// @notice Returns the URI of the token
/// @return The token URI
function tokenURI() external view returns (string memory);
/// @notice Returns the address of the currency
/// @return The currency's address
function currency() external view returns (address);
/// @notice Returns the address of the Airlock
/// @return The Airlock's address
function airlock() external view returns (address);
/// @notice Updates the name and symbol of the coin
/// @param newName The new coin name
/// @param newSymbol The new coin symbol
function setNameAndSymbol(string memory newName, string memory newSymbol) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {CoinConstants} from "./CoinConstants.sol";
library CoinConfigurationVersions {
uint8 constant LEGACY_POOL_VERSION = 1;
uint8 constant DOPPLER_UNI_V3_POOL_VERSION = 2;
uint8 constant DOPPLER_MULTICURVE_UNI_V4_POOL_VERSION = 4;
function getVersion(bytes memory poolConfig) internal pure returns (uint8 version) {
return (version) = abi.decode(poolConfig, (uint8));
}
function isV3(uint8 version) internal pure returns (bool) {
return version == DOPPLER_UNI_V3_POOL_VERSION || version == LEGACY_POOL_VERSION;
}
function isV4(uint8 version) internal pure returns (bool) {
return version == DOPPLER_MULTICURVE_UNI_V4_POOL_VERSION;
}
function decodeVersionAndCurrency(bytes memory poolConfig) internal pure returns (uint8 version, address currency) {
(version, currency) = abi.decode(poolConfig, (uint8, address));
}
function decodeDopplerUniV3(
bytes memory poolConfig
)
internal
pure
returns (uint8 version, address currency, int24 tickLower_, int24 tickUpper_, uint16 numDiscoveryPositions_, uint256 maxDiscoverySupplyShare_)
{
(version, currency, tickLower_, tickUpper_, numDiscoveryPositions_, maxDiscoverySupplyShare_) = abi.decode(
poolConfig,
(uint8, address, int24, int24, uint16, uint256)
);
}
function encodeDopplerUniV3(
address currency,
int24 tickLower_,
int24 tickUpper_,
uint16 numDiscoveryPositions_,
uint256 maxDiscoverySupplyShare_
) internal pure returns (bytes memory) {
return abi.encode(DOPPLER_UNI_V3_POOL_VERSION, currency, tickLower_, tickUpper_, numDiscoveryPositions_, maxDiscoverySupplyShare_);
}
function decodeLegacy(bytes memory poolConfig) internal pure returns (uint8 version, address currency, int24 tickLower_) {
(version, currency, tickLower_) = abi.decode(poolConfig, (uint8, address, int24));
}
function decodeVanillaUniV4(bytes memory poolConfig) internal pure returns (uint8 version, address currency, int24 tickLower_) {
(version, currency, tickLower_) = abi.decode(poolConfig, (uint8, address, int24));
}
function encodeDopplerMultiCurveUniV4(
address currency,
int24[] memory tickLower_,
int24[] memory tickUpper_,
uint16[] memory numDiscoveryPositions_,
uint256[] memory maxDiscoverySupplyShare_
) internal pure returns (bytes memory) {
return abi.encode(DOPPLER_MULTICURVE_UNI_V4_POOL_VERSION, currency, tickLower_, tickUpper_, numDiscoveryPositions_, maxDiscoverySupplyShare_);
}
function decodeDopplerMultiCurveUniV4(
bytes memory poolConfig
)
internal
pure
returns (
uint8 version,
address currency,
int24[] memory tickLower_,
int24[] memory tickUpper_,
uint16[] memory numDiscoveryPositions_,
uint256[] memory maxDiscoverySupplyShare_
)
{
(version, currency, tickLower_, tickUpper_, numDiscoveryPositions_, maxDiscoverySupplyShare_) = abi.decode(
poolConfig,
(uint8, address, int24[], int24[], uint16[], uint256[])
);
}
function defaultDopplerUniV3(address currency) internal pure returns (bytes memory) {
return
encodeDopplerUniV3(
currency,
CoinConstants.DEFAULT_DISCOVERY_TICK_LOWER,
CoinConstants.DEFAULT_DISCOVERY_TICK_UPPER,
CoinConstants.DEFAULT_NUM_DISCOVERY_POSITIONS,
CoinConstants.DEFAULT_DISCOVERY_SUPPLY_SHARE
);
}
function defaultDopplerMultiCurveUniV4(address currency) internal pure returns (bytes memory) {
int24[] memory tickLower = new int24[](2);
int24[] memory tickUpper = new int24[](2);
uint16[] memory numDiscoveryPositions = new uint16[](2);
uint256[] memory maxDiscoverySupplyShare = new uint256[](2);
// todo: configure defaults
// Curve 1
tickLower[0] = -328_000;
tickUpper[0] = -300_000;
numDiscoveryPositions[0] = 2;
maxDiscoverySupplyShare[0] = 0.1e18;
// Curve 2
tickLower[1] = -200_000;
tickUpper[1] = -100_000;
numDiscoveryPositions[1] = 2;
maxDiscoverySupplyShare[1] = 0.1e18;
return encodeDopplerMultiCurveUniV4(currency, tickLower, tickUpper, numDiscoveryPositions, maxDiscoverySupplyShare);
}
function defaultConfig(address currency) internal pure returns (bytes memory) {
return defaultDopplerUniV3(currency);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {LpPosition} from "../types/LpPosition.sol";
struct Delta {
int128 token0;
int128 token1;
}
struct MigratedLiquidityResult {
uint160 sqrtPriceX96;
BurnedPosition[] burnedPositions;
uint256 totalAmount0;
uint256 totalAmount1;
}
struct BurnedPosition {
int24 tickLower;
int24 tickUpper;
uint128 amount0Received;
uint128 amount1Received;
}
interface IUpgradeableV4Hook {
/// @notice Migrate liquidity from this hook to a new hook
/// @param newHook Address of the new hook implementation
/// @param poolKey The pool key to migrate
/// @param additionalData Additional data to pass to the new hook during initialization
/// @return newPoolKey The new pool key returned from the destination hook
function migrateLiquidity(address newHook, PoolKey memory poolKey, bytes calldata additionalData) external returns (PoolKey memory newPoolKey);
error InvalidNewHook(address newHook);
error UpgradePathNotRegistered(address oldHook, address newHook);
}
interface IUpgradeableDestinationV4Hook {
/// @notice Initialize after migration from old hook
/// @param poolKey The pool key being migrated
/// @param coin The coin address
/// @param sqrtPriceX96 The current sqrt price
/// @param migratedLiquidity The migrated liquidity
/// @param additionalData Additional data for initialization
function initializeFromMigration(
PoolKey calldata poolKey,
address coin,
uint160 sqrtPriceX96,
BurnedPosition[] calldata migratedLiquidity,
bytes calldata additionalData
) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/// @title MultiOwnable
/// @notice Allows multiple addresses to have owner privileges
contract MultiOwnable is Initializable {
using EnumerableSet for EnumerableSet.AddressSet;
event OwnerUpdated(address indexed caller, address indexed prevOwner, address indexed newOwner);
error AlreadyOwner();
error NotOwner();
error OneOwnerRequired();
error OwnerCannotBeAddressZero();
error OnlyOwner();
error UseRevokeOwnershipToRemoveSelf();
EnumerableSet.AddressSet internal _owners;
/// @notice Restricts function access to current owners
modifier onlyOwner() {
if (!isOwner(msg.sender)) {
revert OnlyOwner();
}
_;
}
/// @dev Initializes the contract with a set of owners
/// @param initialOwners An list of initial owner addresses
function __MultiOwnable_init(address[] memory initialOwners) internal onlyInitializing {
uint256 numOwners = initialOwners.length;
if (numOwners == 0) {
revert OneOwnerRequired();
}
for (uint256 i; i < numOwners; ++i) {
if (initialOwners[i] == address(0)) {
revert OwnerCannotBeAddressZero();
}
if (isOwner(initialOwners[i])) {
revert AlreadyOwner();
}
_owners.add(initialOwners[i]);
emit OwnerUpdated(msg.sender, address(0), initialOwners[i]);
}
}
/// @notice Checks if an address is an owner
/// @param account The address to check
function isOwner(address account) public view returns (bool) {
return _owners.contains(account);
}
/// @notice The current owner addresses
function owners() public view returns (address[] memory) {
return _owners.values();
}
/// @notice Adds multiple owners
/// @param accounts The addresses to add as owners
function addOwners(address[] memory accounts) public onlyOwner {
for (uint256 i; i < accounts.length; ++i) {
addOwner(accounts[i]);
}
}
/// @notice Adds a new owner
/// @dev Only callable by existing owners
/// @param account The address to add as an owner
function addOwner(address account) public onlyOwner {
if (account == address(0)) {
revert OwnerCannotBeAddressZero();
}
if (isOwner(account)) {
revert AlreadyOwner();
}
_owners.add(account);
emit OwnerUpdated(msg.sender, address(0), account);
}
/// @notice Removes multiple owners
/// @param accounts The addresses to remove as owners
function removeOwners(address[] memory accounts) public onlyOwner {
for (uint256 i; i < accounts.length; ++i) {
removeOwner(accounts[i]);
}
}
/// @notice Removes an existing owner
/// @dev Only callable by existing owners
/// @param account The address to remove as an owner
function removeOwner(address account) public onlyOwner {
if (account == address(0)) {
revert OwnerCannotBeAddressZero();
}
if (account == msg.sender) {
revert UseRevokeOwnershipToRemoveSelf();
}
if (!isOwner(account)) {
revert NotOwner();
}
_owners.remove(account);
emit OwnerUpdated(msg.sender, account, address(0));
}
/// @notice Revokes ownership for the caller
function revokeOwnership() public onlyOwner {
_owners.remove(msg.sender);
emit OwnerUpdated(msg.sender, msg.sender, address(0));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// 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: UNLICENSED
pragma solidity ^0.8.20;
import "./FullMath.sol";
import "./FixedPoint96.sol";
/// @dev https://github.com/Uniswap/v4-core/blob/80311e34080fee64b6fc6c916e9a51a437d0e482/test/utils/LiquidityAmounts.sol
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
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) private pure returns (uint128 y) {
require((y = uint128(x)) == x, "liquidity overflow");
}
/// @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 sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 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 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0) internal pure returns (uint128 liquidity) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
uint256 intermediate = FullMath.mulDiv(sqrtPriceAX96, sqrtPriceBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtPriceBX96 - sqrtPriceAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 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 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1) internal pure returns (uint128 liquidity) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtPriceBX96 - sqrtPriceAX96));
}
/// @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 sqrtPriceX96 A sqrt price representing the current pool prices
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 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 sqrtPriceX96,
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
if (sqrtPriceX96 <= sqrtPriceAX96) {
liquidity = getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0);
} else if (sqrtPriceX96 < sqrtPriceBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, sqrtPriceBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity) internal pure returns (uint256 amount0) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return FullMath.mulDiv(uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtPriceBX96 - sqrtPriceAX96, sqrtPriceBX96) / sqrtPriceAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity) internal pure returns (uint256 amount1) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, 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 sqrtPriceX96 A sqrt price representing the current pool prices
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 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 sqrtPriceX96,
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
if (sqrtPriceX96 <= sqrtPriceAX96) {
amount0 = getAmount0ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
} else if (sqrtPriceX96 < sqrtPriceBX96) {
amount0 = getAmount0ForLiquidity(sqrtPriceX96, sqrtPriceBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @dev https://github.com/Uniswap/v4-core/blob/80311e34080fee64b6fc6c916e9a51a437d0e482/src/libraries/TickMath.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;
}
}
}// This file is automatically generated by code; do not manually update
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {IVersionedContract} from "@zoralabs/shared-contracts/interfaces/IVersionedContract.sol";
/// @title ContractVersionBase
/// @notice Base contract for versioning contracts
contract ContractVersionBase is IVersionedContract {
/// @notice The version of the contract
function contractVersion() external pure override returns (string memory) {
return "1.1.2";
}
}//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
struct PathKey {
Currency intermediateCurrency;
uint24 fee;
int24 tickSpacing;
IHooks hooks;
bytes hookData;
}
using PathKeyLibrary for PathKey global;
/// @title PathKey Library
/// @notice Functions for working with PathKeys
library PathKeyLibrary {
/// @notice Get the pool and swap direction for a given PathKey
/// @param params the given PathKey
/// @param currencyIn the input currency
/// @return poolKey the pool key of the swap
/// @return zeroForOne the direction of the swap, true if currency0 is being swapped for currency1
function getPoolAndSwapDirection(PathKey calldata params, Currency currencyIn)
internal
pure
returns (PoolKey memory poolKey, bool zeroForOne)
{
Currency currencyOut = params.intermediateCurrency;
(Currency currency0, Currency currency1) =
currencyIn < currencyOut ? (currencyIn, currencyOut) : (currencyOut, currencyIn);
zeroForOne = currencyIn == currency0;
poolKey = PoolKey(currency0, currency1, params.fee, params.tickSpacing, params.hooks);
}
}// 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;
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: MIT
pragma solidity ^0.8.24;
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Currency} from "../types/Currency.sol";
import {CurrencyReserves} from "./CurrencyReserves.sol";
import {NonzeroDeltaCount} from "./NonzeroDeltaCount.sol";
import {Lock} from "./Lock.sol";
/// @notice A helper library to provide state getters that use exttload
library TransientStateLibrary {
/// @notice returns the reserves for the synced currency
/// @param manager The pool manager contract.
/// @return uint256 The reserves of the currency.
/// @dev returns 0 if the reserves are not synced or value is 0.
/// Checks the synced currency to only return valid reserve values (after a sync and before a settle).
function getSyncedReserves(IPoolManager manager) internal view returns (uint256) {
if (getSyncedCurrency(manager).isAddressZero()) return 0;
return uint256(manager.exttload(CurrencyReserves.RESERVES_OF_SLOT));
}
function getSyncedCurrency(IPoolManager manager) internal view returns (Currency) {
return Currency.wrap(address(uint160(uint256(manager.exttload(CurrencyReserves.CURRENCY_SLOT)))));
}
/// @notice Returns the number of nonzero deltas open on the PoolManager that must be zeroed out before the contract is locked
function getNonzeroDeltaCount(IPoolManager manager) internal view returns (uint256) {
return uint256(manager.exttload(NonzeroDeltaCount.NONZERO_DELTA_COUNT_SLOT));
}
/// @notice Get the current delta for a caller in the given currency
/// @param target The credited account address
/// @param currency The currency for which to lookup the delta
function currencyDelta(IPoolManager manager, address target, Currency currency) internal view returns (int256) {
bytes32 key;
assembly ("memory-safe") {
mstore(0, and(target, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(32, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
key := keccak256(0, 64)
}
return int256(uint256(manager.exttload(key)));
}
/// @notice Returns whether the contract is unlocked or not
function isUnlocked(IPoolManager manager) internal view returns (bool) {
return manager.exttload(Lock.IS_UNLOCKED_SLOT) != 0x0;
}
}// 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
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {IDopplerErrors} from "../interfaces/IDopplerErrors.sol";
import {TickMath} from "../utils/uniswap/TickMath.sol";
import {FullMath} from "../utils/uniswap/FullMath.sol";
import {SqrtPriceMath} from "../utils/uniswap/SqrtPriceMath.sol";
import {LiquidityAmounts} from "../utils/uniswap/LiquidityAmounts.sol";
import {LpPosition} from "../types/LpPosition.sol";
import {MarketConstants} from "./MarketConstants.sol";
/// @author Whetstone Research
/// @notice Calculates liquidity provisioning with Uniswap v3
library DopplerMath {
/// @notice Calculates the distribution of liquidity positions across tick ranges.
/// @dev For example, with 1000 tokens and 10 bins starting at tick 0:
/// - Creates positions: [0,10], [1,10], [2,10], ..., [9,10]
/// - Each position gets an equal share of tokens (100 tokens each)
/// This creates a linear distribution of liquidity across the tick range
/// @dev Changed from UniswapV3Initializer:
/// - Added `LpPosition[] memory newPositions` as an input parameter, removing the internal allocation (`new LpPosition[](totalPositions + 1)`).
/// - Added `uint256 positionOffset` as an input parameter to specify the starting write index within the `newPositions` array.
/// - Removed the calculation and accumulation of the `reserves` variable entirely.
/// - Return value changed from `(LpPosition[] memory, uint256)` (positions, reserves) to `(LpPosition[] memory, uint256)` (positions, totalAssetsSold).
/// @param tickLower The lower tick of the LP range set
/// @param tickUpper The upper tick of the LP range set
/// @param tickSpacing The tick spacing of the LP range set
/// @param isToken0 Whether the base asset is the token0 of the pair
/// @param discoverySupply The total supply of the base asset to be sold
/// @param totalPositions The total number of positions in the LP range set
/// @param newPositions The array of new positions to be created
/// @param positionOffset The starting index to update `newPositions`
/// @return newPositions The array of new positions to be created
/// @return totalAssetsSold The total assets used in the LP range set
function calculateLogNormalDistribution(
int24 tickLower,
int24 tickUpper,
int24 tickSpacing,
bool isToken0,
uint256 discoverySupply,
uint16 totalPositions,
LpPosition[] memory newPositions,
uint256 positionOffset
) internal pure returns (LpPosition[] memory, uint256) {
int24 farTick = isToken0 ? tickUpper : tickLower;
int24 closeTick = isToken0 ? tickLower : tickUpper;
int24 spread = tickUpper - tickLower;
uint160 farSqrtPriceX96 = TickMath.getSqrtPriceAtTick(farTick);
uint256 amountPerPosition = FullMath.mulDiv(discoverySupply, MarketConstants.WAD, totalPositions * MarketConstants.WAD);
uint256 totalAssetsSold;
for (uint256 i; i < totalPositions; i++) {
// calculate the ticks position * 1/n to optimize the division
int24 startingTick = isToken0
? closeTick + int24(uint24(FullMath.mulDiv(i, uint256(uint24(spread)), totalPositions)))
: closeTick - int24(uint24(FullMath.mulDiv(i, uint256(uint24(spread)), totalPositions)));
// round the tick to the nearest bin
startingTick = alignTickToTickSpacing(isToken0, startingTick, tickSpacing);
if (startingTick != farTick) {
uint160 startingSqrtPriceX96 = TickMath.getSqrtPriceAtTick(startingTick);
// if discoverySupply is 0, we skip the liquidity calculation as we are burning max liquidity
// in each position
uint128 liquidity;
if (discoverySupply != 0) {
liquidity = isToken0
? LiquidityAmounts.getLiquidityForAmount0(startingSqrtPriceX96, farSqrtPriceX96, amountPerPosition)
: LiquidityAmounts.getLiquidityForAmount1(farSqrtPriceX96, startingSqrtPriceX96, amountPerPosition);
totalAssetsSold += (
isToken0
? SqrtPriceMath.getAmount0Delta(startingSqrtPriceX96, farSqrtPriceX96, liquidity, true)
: SqrtPriceMath.getAmount1Delta(farSqrtPriceX96, startingSqrtPriceX96, liquidity, true)
);
}
int24 posFinalTickLower;
int24 posFinalTickUpper;
if (farSqrtPriceX96 < startingSqrtPriceX96) {
posFinalTickLower = farTick;
posFinalTickUpper = startingTick;
} else {
posFinalTickLower = startingTick;
posFinalTickUpper = farTick;
}
newPositions[positionOffset + i] = LpPosition({tickLower: posFinalTickLower, tickUpper: posFinalTickUpper, liquidity: liquidity});
}
}
require(totalAssetsSold <= discoverySupply, IDopplerErrors.CannotMintZeroLiquidity());
return (newPositions, totalAssetsSold);
}
/// @notice Calculates the final LP position that extends from the far tick to the pool's min/max tick
/// @dev This position ensures price equivalence between Uniswap v2 and v3 pools beyond the LBP range
/// @dev Changed from UniswapV3Initializer:
/// - Removed parameters: `id`, `reserves`
/// - Liquidity calculation is based *solely* on the provided `tailSupply` within the calculated tail tick range using `LiquidityAmounts.getLiquidityForAmount0` or `getLiquidityForAmount1`.
function calculateLpTail(
int24 tickLower,
int24 tickUpper,
bool isToken0,
uint256 tailSupply,
int24 tickSpacing
) internal pure returns (LpPosition memory lpTail) {
int24 posTickLower = isToken0 ? tickUpper : alignTickToTickSpacing(false, TickMath.MIN_TICK, tickSpacing);
int24 posTickUpper = isToken0 ? alignTickToTickSpacing(true, TickMath.MAX_TICK, tickSpacing) : tickLower;
require(posTickLower < posTickUpper, IDopplerErrors.InvalidTickRangeMisordered(posTickLower, posTickUpper));
// Calculate the sqrtPrices for the tail range boundaries
uint160 sqrtPriceA = TickMath.getSqrtPriceAtTick(posTickLower);
uint160 sqrtPriceB = TickMath.getSqrtPriceAtTick(posTickUpper);
// Calculate liquidity only based on the tail range supply
uint128 lpTailLiquidity = isToken0
? LiquidityAmounts.getLiquidityForAmount0(sqrtPriceA, sqrtPriceB, tailSupply)
: LiquidityAmounts.getLiquidityForAmount1(sqrtPriceA, sqrtPriceB, tailSupply);
lpTail = LpPosition({tickLower: posTickLower, tickUpper: posTickUpper, liquidity: lpTailLiquidity});
}
/// @notice Aligns a tick to the nearest tick spacing
/// @dev The tickSpacing parameter cannot be zero
/// @param isToken0 Whether the base asset is the token0 of the pair
/// @param tick The tick to align
/// @param tickSpacing The tick spacing of the pair
/// @return alignedTick The aligned tick
function alignTickToTickSpacing(bool isToken0, int24 tick, int24 tickSpacing) internal pure returns (int24) {
if (isToken0) {
// Round down if isToken0
if (tick < 0) {
// If the tick is negative, we round up (negatively) the negative result to round down
return ((tick - tickSpacing + 1) / tickSpacing) * tickSpacing;
} else {
// Else if positive, we simply round down
return (tick / tickSpacing) * tickSpacing;
}
} else {
// Round up if isToken1
if (tick < 0) {
// If the tick is negative, we round down the negative result to round up
return (tick / tickSpacing) * tickSpacing;
} else {
// Else if positive, we simply round up
return ((tick + tickSpacing - 1) / tickSpacing) * tickSpacing;
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
interface IHasRewardsRecipients {
function payoutRecipient() external view returns (address);
function platformReferrer() external view returns (address);
function protocolRewardRecipient() external view returns (address);
function dopplerFeeRecipient() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {ISwapPathRouter} from "../interfaces/ISwapPathRouter.sol";
import {IHasPoolKey} from "../interfaces/ICoinV4.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IPoolManager, PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {BalanceDelta, BalanceDeltaLibrary} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {IHasSwapPath} from "../interfaces/ICoinV4.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {PathKey} from "@uniswap/v4-periphery/src/libraries/PathKey.sol";
import {IDeployedCoinVersionLookup} from "../interfaces/IDeployedCoinVersionLookup.sol";
import {IZoraV4CoinHook} from "../interfaces/IZoraV4CoinHook.sol";
import {CoinConfigurationVersions} from "./CoinConfigurationVersions.sol";
library UniV4SwapToCurrency {
using BalanceDeltaLibrary for BalanceDelta;
function swapToPath(
IPoolManager poolManager,
uint128 amount0,
uint128 amount1,
Currency currencyIn,
PathKey[] memory path
) internal returns (Currency lastCurrency, uint128 lastCurrencyBalance) {
require(path.length > 0, IZoraV4CoinHook.PathMustHaveAtLeastOneStep());
// do first swap - the first swap updates output the balance with the initial balance that existed before the swap
(lastCurrency, lastCurrencyBalance) = doFirstSwapFromCoinToCurrency(poolManager, path[0], currencyIn, amount0, amount1);
// for each path, swap the currency to the next currency
for (uint256 i = 1; i < path.length; i++) {
(PoolKey memory poolKey, bool zeroForOne) = _getPoolAndSwapDirection(path[i], lastCurrency);
lastCurrencyBalance = uint128(_swap(poolManager, poolKey, zeroForOne, -int128(lastCurrencyBalance), ""));
lastCurrency = zeroForOne ? poolKey.currency1 : poolKey.currency0;
}
}
function doFirstSwapFromCoinToCurrency(
IPoolManager poolManager,
PathKey memory pathKey,
Currency coin,
uint128 amount0,
uint128 amount1
) internal returns (Currency outputCurrency, uint128 outputAmount) {
(PoolKey memory poolKey, bool zeroForOne) = _getPoolAndSwapDirection(pathKey, coin);
uint128 inputAmount = zeroForOne ? amount0 : amount1;
outputCurrency = zeroForOne ? poolKey.currency1 : poolKey.currency0;
uint128 initialAmountCurrency = zeroForOne ? amount1 : amount0;
// if not swapping any coin for currency, output amount is amount of currency
if (inputAmount == 0) {
outputAmount = initialAmountCurrency;
} else {
outputAmount = initialAmountCurrency + uint128(_swap(poolManager, poolKey, zeroForOne, -int128(inputAmount), bytes("")));
}
}
function _swap(
IPoolManager poolManager,
PoolKey memory poolKey,
bool zeroForOne,
int256 amountSpecified,
bytes memory hookData
) private returns (int128 reciprocalAmount) {
// for protection of exactOut swaps, sqrtPriceLimit is not exposed as a feature in this contract
unchecked {
BalanceDelta delta = poolManager.swap(
poolKey,
SwapParams(zeroForOne, amountSpecified, zeroForOne ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1),
hookData
);
reciprocalAmount = (zeroForOne == amountSpecified < 0) ? delta.amount1() : delta.amount0();
}
}
/// @notice Get the pool and swap direction for a given PathKey
/// @param params the given PathKey
/// @param currencyIn the input currency
/// @return poolKey the pool key of the swap
/// @return zeroForOne the direction of the swap, true if currency0 is being swapped for currency1
function _getPoolAndSwapDirection(PathKey memory params, Currency currencyIn) internal pure returns (PoolKey memory poolKey, bool zeroForOne) {
Currency currencyOut = params.intermediateCurrency;
(Currency currency0, Currency currency1) = currencyIn < currencyOut ? (currencyIn, currencyOut) : (currencyOut, currencyIn);
zeroForOne = currencyIn == currency0;
poolKey = PoolKey(currency0, currency1, params.fee, params.tickSpacing, params.hooks);
}
function getSubSwapPath(address currency, IDeployedCoinVersionLookup coinVersionLookup) internal view returns (PathKey[] memory) {
if (!_hasSwapPath(currency, coinVersionLookup)) {
return new PathKey[](0);
}
return IHasSwapPath(currency).getPayoutSwapPath(coinVersionLookup).path;
}
function _hasSwapPath(address currency, IDeployedCoinVersionLookup coinVersionLookup) private view returns (bool) {
if (CoinConfigurationVersions.isV4(coinVersionLookup.getVersionForDeployedCoin(currency))) {
return IERC165(currency).supportsInterface(type(IHasSwapPath).interfaceId);
}
return false;
}
}// 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 {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IImmutableState} from "../interfaces/IImmutableState.sol";
/// @title Immutable State
/// @notice A collection of immutable state variables, commonly used across multiple contracts
contract ImmutableState is IImmutableState {
/// @inheritdoc IImmutableState
IPoolManager public immutable poolManager;
/// @notice Thrown when the caller is not PoolManager
error NotPoolManager();
/// @notice Only allow calls from the PoolManager contract
modifier onlyPoolManager() {
if (msg.sender != address(poolManager)) revert NotPoolManager();
_;
}
constructor(IPoolManager _poolManager) {
poolManager = _poolManager;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
using LPFeeLibrary for uint24;
using CustomRevert for bytes4;
/// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
error LPFeeTooLarge(uint24 fee);
/// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;
/// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
// only dynamic-fee pools can return a fee via the beforeSwap hook
uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;
/// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;
/// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
uint24 public constant MAX_LP_FEE = 1000000;
/// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
/// @param self The fee to check
/// @return bool True of the fee is dynamic
function isDynamicFee(uint24 self) internal pure returns (bool) {
return self == DYNAMIC_FEE_FLAG;
}
/// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
/// @param self The fee to check
/// @return bool True of the fee is valid
function isValid(uint24 self) internal pure returns (bool) {
return self <= MAX_LP_FEE;
}
/// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
/// @param self The fee to validate
function validate(uint24 self) internal pure {
if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
}
/// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
/// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
/// @param self The fee to get the initial LP from
/// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
function getInitialLPFee(uint24 self) internal pure returns (uint24) {
// the initial fee for a dynamic fee pool is 0
if (self.isDynamicFee()) return 0;
self.validate();
return self;
}
/// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
/// @param self The fee to check
/// @return bool True of the fee has the override flag set
function isOverride(uint24 self) internal pure returns (bool) {
return self & OVERRIDE_FEE_FLAG != 0;
}
/// @notice returns a fee with the override flag removed
/// @param self The fee to remove the override flag from
/// @return fee The fee without the override flag set
function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
return self & REMOVE_OVERRIDE_MASK;
}
/// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
/// @param self The fee to remove the override flag from, and then validate
/// @return fee The fee without the override flag set (if valid)
function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
fee = self.removeOverrideFlag();
fee.validate();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
// equivalent: (selector,) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
selector := mload(add(result, 0x20))
}
}
function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
// equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
assembly ("memory-safe") {
lpFee := mload(add(result, 0x60))
}
}
function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
// equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
hookReturn := mload(add(result, 0x40))
}
}
}// 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;
/// @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;
/// @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.23;
/// @notice The configuration of the pool
/// @dev This is used to configure the pool's liquidity positions
struct PoolConfiguration {
uint8 version;
uint16 numPositions;
uint24 fee;
int24 tickSpacing;
uint16[] numDiscoveryPositions;
int24[] tickLower;
int24[] tickUpper;
uint256[] maxDiscoverySupplyShare;
}// 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 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;
/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
/// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
/// @param data The data that was passed to the call to unlock
/// @return Any data that you want to be returned from the unlock call
function unlockCallback(bytes calldata data) external returns (bytes memory);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// 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.23;
library MarketConstants {
/// @notice The number of coins allocated to the liquidity pool
/// @dev 990 million coins
uint256 internal constant POOL_LAUNCH_SUPPLY = 990_000_000e18;
/// @dev Constant used to increase precision during calculations
uint256 constant WAD = 1e18;
/// @notice The LP fee
/// @dev 10000 basis points = 1%
uint24 internal constant LP_FEE = 10000;
/// @notice The LP fee
/// @dev 30000 basis points = 3%
uint24 internal constant LP_FEE_V4 = 30000;
/// @notice The spacing for 1% pools
/// @dev 200 ticks
int24 internal constant TICK_SPACING = 200;
/// @notice The minimum lower tick for legacy single LP WETH pools
int24 internal constant LP_TICK_LOWER_WETH = -208200;
/// @notice The upper tick for legacy single LP WETH pools
int24 internal constant LP_TICK_UPPER = 887200;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @dev https://github.com/Uniswap/v4-core/blob/80311e34080fee64b6fc6c916e9a51a437d0e482/src/libraries/FullMath.sol
/// @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.23;
interface IDopplerErrors {
error NumDiscoveryPositionsOutOfRange();
error CannotMintZeroLiquidity();
/// @notice Thrown when the tick range is misordered
error InvalidTickRangeMisordered(int24 tickLower, int24 tickUpper);
/// @notice Thrown when the max share to be sold exceeds the maximum unit
error MaxShareToBeSoldExceeded(uint256 value, uint256 limit);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice For compatibility with ERC7572 - the interface for contract-level metadata
/// @dev https://eips.ethereum.org/EIPS/eip-7572
interface IERC7572 {
/// @notice Emitted when the contract URI is updated
event ContractURIUpdated();
/// @notice Returns the contract-level metadata
function contractURI() external view returns (string memory);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
library CoinConstants {
/// @notice The maximum total supply
/// @dev Set to 1 billion coins with 18 decimals
uint256 public constant MAX_TOTAL_SUPPLY = 1_000_000_000e18;
/// @notice The number of coins allocated to the liquidity pool
/// @dev 990 million coins
uint256 public constant POOL_LAUNCH_SUPPLY = 990_000_000e18;
/// @notice The number of coins rewarded to the creator
/// @dev 10 million coins
uint256 public constant CREATOR_LAUNCH_REWARD = 10_000_000e18;
/// @notice The minimum order size allowed for trades
/// @dev Set to 0.0000001 ETH to prevent dust transactions
uint256 public constant MIN_ORDER_SIZE = 0.0000001 ether;
/// @notice The total fee percentage in basis points
/// @dev 100 basis points = 1%
uint256 public constant TOTAL_FEE_BPS = 100;
/// @notice The percentage of the total fee allocated to creators
/// @dev 5000 basis points = 50% of TOTAL_FEE_BPS
uint256 public constant TOKEN_CREATOR_FEE_BPS = 5000;
/// @notice The percentage of the total fee allocated to the protocol
/// @dev 2000 basis points = 20% of TOTAL_FEE_BPS
uint256 public constant PROTOCOL_FEE_BPS = 2000;
/// @notice The percentage of the total fee allocated to platform referrers
/// @dev 1500 basis points = 15% of TOTAL_FEE_BPS
uint256 public constant PLATFORM_REFERRER_FEE_BPS = 1500;
/// @notice The percentage of the total fee allocated to trade referrers
/// @dev 1500 basis points = 15% of TOTAL_FEE_BPS
uint256 public constant TRADE_REFERRER_FEE_BPS = 1500;
/// @notice The percentage of the LP fee allocated to creators
/// @dev 5000 basis points = 50% of the 1% LP FEE
uint256 public constant CREATOR_MARKET_REWARD_BPS = 5000;
/// @notice The percentage of the LP fee allocated to platform referrers
/// @dev 2500 basis points = 25% of the 1% LP FEE
uint256 public constant PLATFORM_REFERRER_MARKET_REWARD_BPS = 2500;
/// @notice The percentage of the LP fee allocated to the Doppler protocol
/// @dev 500 basis points = 5% of the 1% LP FEE
uint256 public constant DOPPLER_MARKET_REWARD_BPS = 500;
int24 internal constant DEFAULT_DISCOVERY_TICK_LOWER = -777000;
int24 internal constant DEFAULT_DISCOVERY_TICK_UPPER = 222000;
uint16 internal constant DEFAULT_NUM_DISCOVERY_POSITIONS = 10; // will be 11 total with tail position
uint256 internal constant DEFAULT_DISCOVERY_SUPPLY_SHARE = 0.495e18; // half of the 990m total pool supply
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @dev https://github.com/Uniswap/v4-core/blob/80311e34080fee64b6fc6c916e9a51a437d0e482/src/libraries/FixedPoint96.sol
/// @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;
/// @dev https://github.com/Uniswap/v4-core/blob/80311e34080fee64b6fc6c916e9a51a437d0e482/src/libraries/BitMath.sol
/// @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;
/// @dev https://github.com/Uniswap/v4-core/blob/80311e34080fee64b6fc6c916e9a51a437d0e482/src/libraries/CustomRevert.sol
/// @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.17;
interface IVersionedContract {
function contractVersion() external pure returns (string memory);
}// 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: BUSL-1.1
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {CustomRevert} from "./CustomRevert.sol";
library CurrencyReserves {
using CustomRevert for bytes4;
/// bytes32(uint256(keccak256("ReservesOf")) - 1)
bytes32 constant RESERVES_OF_SLOT = 0x1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd95;
/// bytes32(uint256(keccak256("Currency")) - 1)
bytes32 constant CURRENCY_SLOT = 0x27e098c505d44ec3574004bca052aabf76bd35004c182099d8c575fb238593b9;
function getSyncedCurrency() internal view returns (Currency currency) {
assembly ("memory-safe") {
currency := tload(CURRENCY_SLOT)
}
}
function resetCurrency() internal {
assembly ("memory-safe") {
tstore(CURRENCY_SLOT, 0)
}
}
function syncCurrencyAndReserves(Currency currency, uint256 value) internal {
assembly ("memory-safe") {
tstore(CURRENCY_SLOT, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
tstore(RESERVES_OF_SLOT, value)
}
}
function getSyncedReserves() internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(RESERVES_OF_SLOT)
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// for the nonzero delta count.
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library NonzeroDeltaCount {
// The slot holding the number of nonzero deltas. bytes32(uint256(keccak256("NonzeroDeltaCount")) - 1)
bytes32 internal constant NONZERO_DELTA_COUNT_SLOT =
0x7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b;
function read() internal view returns (uint256 count) {
assembly ("memory-safe") {
count := tload(NONZERO_DELTA_COUNT_SLOT)
}
}
function increment() internal {
assembly ("memory-safe") {
let count := tload(NONZERO_DELTA_COUNT_SLOT)
count := add(count, 1)
tstore(NONZERO_DELTA_COUNT_SLOT, count)
}
}
/// @notice Potential to underflow. Ensure checks are performed by integrating contracts to ensure this does not happen.
/// Current usage ensures this will not happen because we call decrement with known boundaries (only up to the number of times we call increment).
function decrement() internal {
assembly ("memory-safe") {
let count := tload(NONZERO_DELTA_COUNT_SLOT)
count := sub(count, 1)
tstore(NONZERO_DELTA_COUNT_SLOT, count)
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library Lock {
// The slot holding the unlocked state, transiently. bytes32(uint256(keccak256("Unlocked")) - 1)
bytes32 internal constant IS_UNLOCKED_SLOT = 0xc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab23;
function unlock() internal {
assembly ("memory-safe") {
// unlock
tstore(IS_UNLOCKED_SLOT, true)
}
}
function lock() internal {
assembly ("memory-safe") {
tstore(IS_UNLOCKED_SLOT, false)
}
}
function isUnlocked() internal view returns (bool unlocked) {
assembly ("memory-safe") {
unlocked := tload(IS_UNLOCKED_SLOT)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}// 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";
/// @dev https://github.com/Uniswap/v4-core/blob/80311e34080fee64b6fc6c916e9a51a437d0e482/src/libraries/SqrtPriceMath.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.25;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
interface ISwapPathRouter {
struct Path {
PoolKey key;
Currency currencyIn;
}
function getSwapPath(PoolKey memory key, Currency toSwapOut) external view returns (Path[] memory path);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
/// @title IImmutableState
/// @notice Interface for the ImmutableState contract
interface IImmutableState {
/// @notice The Uniswap v4 PoolManager contract
function poolManager() external view returns (IPoolManager);
}// 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;
/// @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 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;
import {CustomRevert} from "./CustomRevert.sol";
/// @dev https://github.com/Uniswap/v4-core/blob/80311e34080fee64b6fc6c916e9a51a437d0e482/src/libraries/SafeCast.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;
/// @dev https://github.com/Uniswap/v4-core/blob/80311e34080fee64b6fc6c916e9a51a437d0e482/src/libraries/UnsafeMath.sol
/// @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)
}
}
}{
"remappings": [
"ds-test/=node_modules/ds-test/src/",
"forge-std/=node_modules/forge-std/src/",
"@openzeppelin/=node_modules/@openzeppelin/",
"@zoralabs/shared-contracts/=node_modules/@zoralabs/shared-contracts/src/",
"solady/=node_modules/solady/src/",
"@uniswap/v4-core/=node_modules/@uniswap/v4-core/",
"@uniswap/v4-periphery/=node_modules/@uniswap/v4-periphery/",
"permit2/src/=node_modules/@uniswap/permit2/src/",
"@uniswap/universal-router/contracts/=node_modules/@uniswap/universal-router/contracts/",
"solmate/=node_modules/solmate/src/",
"hookmate/=node_modules/hookmate/"
],
"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,
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"contract IPoolManager","name":"poolManager_","type":"address"},{"internalType":"contract IDeployedCoinVersionLookup","name":"coinVersionLookup_","type":"address"},{"internalType":"address[]","name":"trustedMessageSenders_","type":"address[]"},{"internalType":"contract IHooksUpgradeGate","name":"upgradeGate","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"CannotMintZeroLiquidity","type":"error"},{"inputs":[],"name":"CoinVersionLookupCannotBeZeroAddress","type":"error"},{"inputs":[],"name":"EthTransferFailed","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"HookNotImplemented","type":"error"},{"inputs":[{"internalType":"uint8","name":"callbackId","type":"uint8"}],"name":"InvalidCallbackId","type":"error"},{"inputs":[{"internalType":"address","name":"newHook","type":"address"}],"name":"InvalidNewHook","type":"error"},{"inputs":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"}],"name":"InvalidTickRangeMisordered","type":"error"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"NoCoinForHook","type":"error"},{"inputs":[{"internalType":"address","name":"coin","type":"address"}],"name":"NotACoin","type":"error"},{"inputs":[],"name":"NotPoolManager","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"expectedCoin","type":"address"}],"name":"OnlyCoin","type":"error"},{"inputs":[],"name":"PathMustHaveAtLeastOneStep","type":"error"},{"inputs":[],"name":"SafeCastOverflow","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"UpgradeGateCannotBeZeroAddress","type":"error"},{"inputs":[{"internalType":"address","name":"oldHook","type":"address"},{"internalType":"address","name":"newHook","type":"address"}],"name":"UpgradePathNotRegistered","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"coin","type":"address"},{"indexed":false,"internalType":"address","name":"currency","type":"address"},{"indexed":false,"internalType":"address","name":"payoutRecipient","type":"address"},{"indexed":false,"internalType":"address","name":"platformReferrer","type":"address"},{"indexed":false,"internalType":"address","name":"tradeReferrer","type":"address"},{"indexed":false,"internalType":"address","name":"protocolRewardRecipient","type":"address"},{"indexed":false,"internalType":"address","name":"dopplerRecipient","type":"address"},{"components":[{"internalType":"uint256","name":"creatorPayoutAmountCurrency","type":"uint256"},{"internalType":"uint256","name":"creatorPayoutAmountCoin","type":"uint256"},{"internalType":"uint256","name":"platformReferrerAmountCurrency","type":"uint256"},{"internalType":"uint256","name":"platformReferrerAmountCoin","type":"uint256"},{"internalType":"uint256","name":"tradeReferrerAmountCurrency","type":"uint256"},{"internalType":"uint256","name":"tradeReferrerAmountCoin","type":"uint256"},{"internalType":"uint256","name":"protocolAmountCurrency","type":"uint256"},{"internalType":"uint256","name":"protocolAmountCoin","type":"uint256"},{"internalType":"uint256","name":"dopplerAmountCurrency","type":"uint256"},{"internalType":"uint256","name":"dopplerAmountCoin","type":"uint256"}],"indexed":false,"internalType":"struct IZoraV4CoinHook.MarketRewardsV4","name":"marketRewards","type":"tuple"}],"name":"CoinMarketRewardsV4","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"coin","type":"address"},{"indexed":false,"internalType":"address","name":"currency","type":"address"},{"indexed":false,"internalType":"address","name":"creator","type":"address"},{"indexed":false,"internalType":"address","name":"protocol","type":"address"},{"indexed":false,"internalType":"uint256","name":"creatorAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"protocolAmount","type":"uint256"}],"name":"CreatorCoinRewards","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"coin","type":"address"},{"indexed":true,"internalType":"address","name":"currency","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountCurrency","type":"uint256"},{"indexed":false,"internalType":"int24","name":"tick","type":"int24"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"}],"name":"LpReward","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"swapSender","type":"address"},{"indexed":false,"internalType":"bool","name":"isTrustedSwapSenderAddress","type":"bool"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"indexed":false,"internalType":"struct PoolKey","name":"key","type":"tuple"},{"indexed":true,"internalType":"bytes32","name":"poolKeyHash","type":"bytes32"},{"components":[{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"indexed":false,"internalType":"struct SwapParams","name":"params","type":"tuple"},{"indexed":false,"internalType":"int128","name":"amount0","type":"int128"},{"indexed":false,"internalType":"int128","name":"amount1","type":"int128"},{"indexed":false,"internalType":"bool","name":"isCoinBuy","type":"bool"},{"indexed":false,"internalType":"bytes","name":"hookData","type":"bytes"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"}],"name":"Swapped","type":"event"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct ModifyLiquidityParams","name":"params","type":"tuple"},{"internalType":"BalanceDelta","name":"delta","type":"int256"},{"internalType":"BalanceDelta","name":"feesAccrued","type":"int256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"afterAddLiquidity","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"},{"internalType":"BalanceDelta","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"afterDonate","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"int24","name":"tick","type":"int24"}],"name":"afterInitialize","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct ModifyLiquidityParams","name":"params","type":"tuple"},{"internalType":"BalanceDelta","name":"delta","type":"int256"},{"internalType":"BalanceDelta","name":"feesAccrued","type":"int256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"afterRemoveLiquidity","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"},{"internalType":"BalanceDelta","name":"","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct SwapParams","name":"params","type":"tuple"},{"internalType":"BalanceDelta","name":"delta","type":"int256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"afterSwap","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"},{"internalType":"int128","name":"","type":"int128"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct ModifyLiquidityParams","name":"params","type":"tuple"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"beforeAddLiquidity","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"beforeDonate","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"}],"name":"beforeInitialize","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int256","name":"liquidityDelta","type":"int256"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"internalType":"struct ModifyLiquidityParams","name":"params","type":"tuple"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"beforeRemoveLiquidity","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"components":[{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"}],"internalType":"struct SwapParams","name":"params","type":"tuple"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"name":"beforeSwap","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"},{"internalType":"BeforeSwapDelta","name":"","type":"int256"},{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"contractVersion","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getHookPermissions","outputs":[{"components":[{"internalType":"bool","name":"beforeInitialize","type":"bool"},{"internalType":"bool","name":"afterInitialize","type":"bool"},{"internalType":"bool","name":"beforeAddLiquidity","type":"bool"},{"internalType":"bool","name":"afterAddLiquidity","type":"bool"},{"internalType":"bool","name":"beforeRemoveLiquidity","type":"bool"},{"internalType":"bool","name":"afterRemoveLiquidity","type":"bool"},{"internalType":"bool","name":"beforeSwap","type":"bool"},{"internalType":"bool","name":"afterSwap","type":"bool"},{"internalType":"bool","name":"beforeDonate","type":"bool"},{"internalType":"bool","name":"afterDonate","type":"bool"},{"internalType":"bool","name":"beforeSwapReturnDelta","type":"bool"},{"internalType":"bool","name":"afterSwapReturnDelta","type":"bool"},{"internalType":"bool","name":"afterAddLiquidityReturnDelta","type":"bool"},{"internalType":"bool","name":"afterRemoveLiquidityReturnDelta","type":"bool"}],"internalType":"struct Hooks.Permissions","name":"","type":"tuple"}],"stateMutability":"pure","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"getPoolCoin","outputs":[{"components":[{"internalType":"address","name":"coin","type":"address"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"liquidity","type":"uint128"}],"internalType":"struct LpPosition[]","name":"positions","type":"tuple[]"}],"internalType":"struct IZoraV4CoinHook.PoolCoin","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes23","name":"poolKeyHash","type":"bytes23"}],"name":"getPoolCoinByHash","outputs":[{"components":[{"internalType":"address","name":"coin","type":"address"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"liquidity","type":"uint128"}],"internalType":"struct LpPosition[]","name":"positions","type":"tuple[]"}],"internalType":"struct IZoraV4CoinHook.PoolCoin","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"address","name":"coin","type":"address"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"amount0Received","type":"uint128"},{"internalType":"uint128","name":"amount1Received","type":"uint128"}],"internalType":"struct BurnedPosition[]","name":"migratedLiquidity","type":"tuple[]"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"initializeFromMigration","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"isTrustedMessageSender","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newHook","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"bytes","name":"additionalData","type":"bytes"}],"name":"migrateLiquidity","outputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"newPoolKey","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"unlockCallback","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]Contract Creation Code
610100604052346103c5576152be8038038061001a8161041d565b9283398101906080818303126103c55780516001600160a01b03811681036103c55760208201516001600160a01b038116929091908383036103c55760408101516001600160401b0381116103c557810185601f820112156103c5578051956001600160401b0387116103e9578660051b9160208061009a81860161041d565b809a815201938201019182116103c557602001915b8183106103c95750505060600151926001600160a01b038416918285036103c5576080525f6101a06100df6103fd565b8281528260208201528260408201528260608201528260808201528260a08201528260c08201528260e0820152826101008201528261012082015282610140820152826101608201528261018082015201525f6101a061013d6103fd565b828152600160208201528260408201528260608201528260808201528260a08201528260c0820152600160e0820152826101008201528261012082015282610140820152826101608201528261018082015201526120003016158015906103b4575b80156103a7575b801561039a575b801561038d575b8015610380575b8015610374575b8015610364575b8015610358575b801561034c575b8015610340575b8015610334575b8015610328575b801561031c575b61030957156102fa57156102eb5760a05260c0526b019d971e4fe8401e7400000060e0525f5b815181101561025057600190818060a01b0360208260051b85010151165f525f60205260405f208260ff1982541617905501610219565b604051614e7b90816104438239608051818181601d015281816102ab015281816106c00152818161074001528181610790015281816109c101528181611636015281816116a901528181611776015281816118a001528181611ab901528181611f4f0152613869015260a051818181610a3001526126a1015260c051818181610204015261197b015260e05181818161276801526129000152f35b631decd2b160e31b5f5260045ffd5b637a01d33160e11b5f5260045ffd5b630732d7b560e51b5f523060045260245ffd5b506001301615156101f3565b506002301615156101ec565b506004301615156101e5565b506008301615156101de565b506010301615156101d7565b506020301615156101d0565b50604030161515600114156101c9565b506080301615156101c2565b50610100301615156101bb565b50610200301615156101b4565b50610400301615156101ad565b50610800301615156101a6565b50611000301615156001141561019f565b5f80fd5b82516001600160a01b03811681036103c5578152602092830192016100af565b634e487b7160e01b5f52604160045260245ffd5b604051906101c082016001600160401b038111838210176103e957604052565b6040519190601f01601f191682016001600160401b038111838210176103e95760405256fe61010080604052600436101561005c575b50361561001b575f80fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316330361004d57005b63570c108560e11b5f5260045ffd5b5f905f3560e01c90816301ffc9a714611f905750806321d0ee7014611f3c578063259982e514611f3c5780632c5fe5a914611e815780634a862f63146118da578063575e24b4146118465780635859e6d0146117d15780636c2bbe7e1461161f5780636fe7e6eb1461173a57806391dd7346146116765780639f063efc1461161f578063a0a8e460146115d2578063b47b2fb114610966578063b6a8b0fa146106a9578063bc9113b314610928578063c4e833ce146107bf578063dc4c90d31461077a578063dc98354e1461070b578063e1b4af69146106a95763fee56dd90361001057346106a657366003190161012081126106a45760a0136106a65760a4356001600160a01b03811681036106a4576101756123b1565b60e4356001600160401b0381116106a057366023820112156106a0578060040135906001600160401b03821161069c576024810190602436918460071b01011161069c57610104356001600160401b038111610698576101d9903690600401612025565b50506040516321f7434760e01b81523360048201523060248201526020816044816001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165afa90811561068d57869161065e575b5015610647576004356001600160a01b03811692908381036106435750610259612559565b9460443562ffffff811680910361063f57606435908160020b9182810361063b575060405195610288876120eb565b8652602086019760018060a01b03168852604086015260608501523060808501527f00000000000000000000000000000000000000000000000000000000000000009260405163313b65df60e11b81526102e56004820187612305565b6001600160a01b0387811660a4830152602090829060c49082908d908a165af18015610630576105f5575b5061031a83613726565b92885b8181106104f9575050509061033291846137ce565b815161035a9061034a906001600160a01b0316613f31565b94516001600160a01b0316613f31565b610363836125a1565b86526001602052600160408720019480158015906104f0575b610384578680f35b85545f1981019081116104dc57906103a06103c5939288613934565b509586546103bf6103b38260020b613a91565b9160181c60020b613a91565b91613dbe565b6040805194906103d5818761213d565b60018652601f1901875b8181106104b157505084604094610435946001600160801b03979461040661043095612472565b61040f856137ad565b52610419846137ad565b508888610425866137ad565b510191169052613e59565b6137ad565b51015182549116915f19820191821161049d57610459610493939261046e92613934565b50916001600160801b03835460301c16613949565b600160301b600160b01b0382549160301b1690600160301b600160b01b031916179055565b5f80808080808680f35b634e487b7160e01b84526011600452602484fd5b6020906104bc613708565b82828a010152016103df565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b88526011600452602488fd5b5081151561037c565b610504818385613775565b61050d90612585565b61051690613a91565b610521828486613775565b60200161052d90612585565b61053690613a91565b610541838587613775565b60400161054d90613799565b90610559848688613775565b60600161056590613799565b6001600160801b0316916001600160801b031690610583938c613dbe565b61058e828486613775565b61059790612585565b906105a3838587613775565b6020016105af90612585565b604051926105bc84612122565b60020b835260020b60208301526001600160801b031660408201526105e182876137ba565b526105ec81866137ba565b5060010161031d565b6020813d602011610628575b8161060e6020938361213d565b810103126106245761061f90612593565b610310565b8880fd5b3d9150610601565b6040513d8b823e3d90fd5b8980fd5b8780fd5b8680fd5b63abeba34560e01b85523360045230602452604485fd5b610680915060203d602011610686575b610678818361213d565b810190612526565b5f610234565b503d61066e565b6040513d88823e3d90fd5b8580fd5b8480fd5b8380fd5b505b80fd5b50346106a6576004906106bb366123eb565b5050507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316330392506106ff91505057630a85dc2960e01b8152fd5b63570c108560e11b8152fd5b50346106a65760e03660031901126106a657610725611ffb565b5060a03660231901126106a65760049061073d6123b1565b507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031633036106ff57630a85dc2960e01b8152fd5b50346106a657806003193601126106a6576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346106a657806003193601126106a657806101c0916101a06040516107e481612106565b8281528260208201528260408201528260608201528260808201528260a08201528260c08201528260e0820152826101008201528261012082015282610140820152826101608201528261018082015201526040519061084382612106565b80825260208201916001835260408101828152606082018381526080830184815260a0840185815260c0850186815260e0860190600182526101008701928884526101208801948986526101408901968a88526101608a01988b8a526101a06101808c019b8d8d52019b808d5260206040519e8f92835251151591015251151560408d015251151560608c015251151560808b015251151560a08a015251151560c089015251151560e08801525115156101008701525115156101208601525115156101408501525115156101608401525115156101808301525115156101a0820152f35b50346106a65760203660031901126106a65760209060ff906040906001600160a01b03610953611ffb565b1681528084522054166040519015158152f35b50346106a6576101603660031901126106a657610981611ffb565b60a03660231901126106a45760603660c31901126106a45761012435610144356001600160401b0381116106a0576109bd903690600401612025565b90917f00000000000000000000000000000000000000000000000000000000000000009060018060a01b038216928333036115c357610a036109fe3661218c565b6125a1565b808852600160205260408820546001600160a01b0316919082156115a55760405163f3ffe14b60e01b81527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166004820152928984602481845afa93841561159a578a9461141f575b50818a526001602052600160408b2001610a8d3661218c565b8b908c8093610a9a6139dd565b5080549082935b8d8d8487106112f6575050505050905081600f0b136111e1575b508a81600f0b1361104a575b50610ae2610add610ad6612559565b3089613fbf565b614ab1565b97610af8610add610af161256f565b308a613fbf565b60208601519551805190966001600160a01b0316901561103b57610b268d91610b20896137ad565b51614ac4565b801561102d576001600160801b038d945b821561101c5760208401516001600160a01b03169e5b83156110145750945b1680610fc957505050509a999597989a5b9a976001966020995b8751891015610c00576001600160801b03610bb28e9f8f9e9f8e908e610bca938f8f98610b20610ba29260019b6137ba565b9681988894929316600f0b61449b565b600f0b93610bc3604051968761213d565b8552614b4c565b6001600160801b03169d5015610bf2578b828060a01b03910151165b9801979c9b9a9c610b70565b818060a01b03905116610be6565b8c94928b9694928f928e6001600160801b038e95168015918215610f62575b508b15610f5d578a878d8101031261063b5786356001600160a01b03811690819003610e8057505b604051633fb80b1560e01b8152918b836004818c5afa928315610f52578b93610f1b575b50604051637a9f55c760e11b8152908c826004818d5afa918215610f10578c92610ed5575b50611388830290838204611388141715610ec1579260a0928a95928e610cdc6127107fea92473287be4e55f8279d0b8395a45960a217ae2f1a76ac9cae84af58a751ed98048094613927565b93610ce8818588614c96565b610cf3838688614c96565b60405195600180891b03168652600180881b031690850152600180861b0316604084015260608301526080820152a260018060a01b03169283875286885260ff6040882054169260405163d737d0c760e01b81528981600481895afa899181610e8a575b50610e84575087925b60c4359687151597888103610e8057610d9f919015610e68576001600160a01b03610d8961256f565b1614925b60a0610d983661218c565b20906144bb565b505050966040519515158652610db68b870161361e565b60c086015260e43560e0860152610104356001600160a01b0381169081900361063b579260409b869593610e3f9387966101007fd0565428a2140862827b5b6126002556c70acb52db537fae9cf41a18a470ec4a9a01528060801d600f0b610120880152600f0b61014087015215156101608601526101c06101808601526101c0850191612646565b6001600160a01b039687166101a08401529516940390a4825163b47b2fb160e01b815291820152f35b6001600160a01b03610e78612559565b161492610d8d565b8a80fd5b92610d60565b9091508a81813d8311610eba575b610ea2818361213d565b8101031261063b57610eb390612ec3565b908c610d57565b503d610e98565b634e487b7160e01b8c52601160045260248cfd5b9091508c81813d8311610f09575b610eed818361213d565b81010312610f0557610efe90612ec3565b908e610c90565b8b80fd5b503d610ee3565b6040513d8e823e3d90fd5b9092508b81813d8311610f4b575b610f33818361213d565b81010312610e8057610f4490612ec3565b918d610c6b565b503d610f29565b6040513d8d823e3d90fd5b610c47565b803b15610e8057604051630b0d9c0960e01b81526001600160a01b038516600482015230602482015260448101839052908b908290606490829084905af18015610f5257908b91610fb4575b50610c1f565b81610fbe9161213d565b61063b57898d610fae565b91611009949391610fdf610ffa94600f0b61449b565b60405193610fee60208661213d565b8452600f0b918d614b4c565b6001600160801b031690613949565b9a999597989a610b67565b905094610b56565b83516001600160a01b03169e610b4d565b6001600160801b0384610b37565b6319dcad4d60e31b8d5260048dfd5b61105d6001600160801b039182166143d0565b168015610ac75761107b60a0611074366024612213565b20886144bb565b50509050608435908c8260020b83036106a6576110bc6110b5846110b06001600160801b03956110aa836143ff565b90614445565b614a55565b9384614445565b936110c685613a91565b916110d085613a91565b90156111d3576110df926145b6565b1690816110ee575b5050610ac7565b8c82126111c4576101648d936040936111719385519261110d846120d0565b60020b835260020b60208301528482015284606082015283519485938492632d35e7ed60e11b8452611143600485016024613693565b8051600290810b60a48601526020820151900b60c4850152604081015160e485015260600151610104840152565b610140610124830152806101448301528c5af18015610f5257611196575b80806110e7565b6111b79060403d6040116111bd575b6111af818361213d565b810190613a01565b5061118f565b503d6111a5565b6393dafdf160e01b8d5260048dfd5b6111dc92614573565b6110df565b6111f46001600160801b039182166143d0565b168015610abb578b61121360a061120c366024612213565b208a6144bb565b5050929050608435928360020b84036112f2576001600160801b03916112586112518661124c61127295611246836143ff565b9061447d565b614a83565b958661447d565b9361126286613a91565b61126b86613a91565b91506145b6565b169081611281575b5050610abb565b8d82126112e3576101648e936040936112a09385519261110d846120d0565b610140610124830152806101448301528d5af18015610f10576112c5575b808061127a565b6112dd9060403d6040116111bd576111af818361213d565b506112be565b6393dafdf160e01b8e5260048efd5b8280fd5b6113336001600160801b03916113138987999b96989a9c97613934565b505460020b876113238d8b613934565b505460181c60020b9230906142e8565b161561141357604061139b889261134a8b89613934565b505460020b6113598c8a613934565b505460181c60020b84519161136d836120d0565b8252602082015284848201528460608201528351948580948193632d35e7ed60e11b83528b60048401613a17565b03925af196871561140757966113d8575b506001916113c16113cb928860801d90613a6b565b96600f0b90613a6b565b955b019290918f92610aa1565b6113cb919650916113c16113fb60019460403d81116111bd576111af818361213d565b905097925050916113ac565b604051903d90823e3d90fd5b509450946001906113cd565b9093503d808b833e611431818361213d565b810190602081830312610e80578051906001600160401b038211610f055701604081830312610e805760405191611467836120b5565b81516001600160401b03811161159657820181601f82011215611596578051906114908261245b565b9261149e604051948561213d565b82845260208085019360051b830101918183116115925760208101935b8385106114e25750505050506114d691602091845201612ec3565b6020820152925f610a74565b84516001600160401b03811161158f5782019060a0828503601f19011261158f5760405190611510826120eb565b61151c60208401612ec3565b825261152a60408401612ed7565b602083015261153b60608401612593565b604083015261154c60808401612ec3565b606083015260a0830151916001600160401b03831161158757611577866020809695819601016125c7565b60808201528152019401936114bb565b505050508f80fd5b50505b8f80fd5b8c80fd5b6040513d8c823e3d90fd5b604051632653ac6960e21b815260a4906115c16004820161361e565bfd5b63570c108560e11b8752600487fd5b50346106a657806003193601126106a6575061161b6040516115f560408261213d565b6005815264189718971960d91b60208201526040519182916020835260208301906123c7565b0390f35b50346106a65760049061163136612348565b5050507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316330393506106ff9250505057630a85dc2960e01b8152fd5b50346106a65760203660031901126106a6576004356001600160401b0381116106a4576116a7903690600401612025565b7f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b038216330361172b576116e28161253e565b926116f0604051948561213d565b818452368282011161069c579360208285949361161b978361171798013784010152612feb565b6040519182916020835260208301906123c7565b63570c108560e11b8452600484fd5b50346106a6576101003660031901126106a657611755611ffb565b9060a03660231901126106a65761176a6123b1565b5061177361216e565b507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031633036117c25760206117af83612674565b6040516001600160e01b03199091168152f35b63570c108560e11b8152600490fd5b50346106a65760203660031901126106a65760043568ffffffffffffffffff1981168091036106a45761161b91604091611809612442565b508152600160205220611835600160405192611824846120b5565b818060a01b038154168452016124a7565b6020820152604051918291826122d6565b50346106a6576101403660031901126106a657611861611ffb565b5060a03660231901126106a65760603660c31901126106a657610124356001600160401b0381116106a4579061189c60049236908401612025565b50507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031633036106ff57630a85dc2960e01b8152fd5b34611d6a5760e0366003190112611d6a576118f3611ffb565b6118fc3661218c565b60c4356001600160401b038111611d6a5761191b903690600401612025565b92906119256124fc565b5061192f836125a1565b5f52600160205260405f209360018060a01b0385541691338303611e6a576040516321f7434760e01b81523060048201526001600160a01b0385166024820152602081806044810103817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115611d06575f91611e4b575b5015611e29575f611a84611a92611a29611a676119d56001611ab49c016124a7565b986119de6124fc565b50604051906119ec826120d0565b8b8252602082019a8b5260408201908a8252611a3d606084019160018060a01b03169c8d8352604051968795602080880152604087019051612305565b5161010060e086015261014085019061227c565b91516001600160a01b0390811661010085015290511661012083015203601f19810183528261213d565b6040519283916002602084015260408084015260608301906123c7565b03601f19810183528261213d565b604051809881926348c8949160e01b83526020600484015260248301906123c7565b0381837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af1958615611d06575f96611e05575b50855186016020810196602081830312611d6a576020810151906001600160401b038211611d6a5701608081830312611d6a5760405191611b31836120d0565b60208201516001600160a01b0381168103611d6a57835260408201516001600160401b038111611d6a576020908301019880601f8b011215611d6a57895191611b798361245b565b9a611b876040519c8d61213d565b838c526020808d019460071b820101928311611d6a57602001925b828410611da057505050506080906020830198895260608101516040840152015160608201526040516301ffc9a760e01b815263fee56dd960e01b6004820152602081602481895afa908115611d06575f91611d81575b5015611d6e575195516001600160a01b039096169592843b15611d6a579591929060405196879363fee56dd960e01b8552610124850191611c3d600487018a612305565b60a486015260c485015261012060e48501528251809152602061014485019301905f5b818110611d115750505082915f94611c849260031985840301610104860152612646565b038183855af1928315611d065760a093611cf6575b50600180841b0382511691600180851b0360208201511690606062ffffff60408301511691015160020b9160405194611cd1866120eb565b85526020850152604084015260608301526080820152611cf46040518092612305565bf35b5f611d009161213d565b5f611c99565b6040513d5f823e3d90fd5b9195945091926020611d5b6001928851906001600160801b036060608093805160020b8452602081015160020b602085015282604082015116604085015201511660608201520190565b96019101918894959392611c60565b5f80fd5b84630f83548360e41b5f5260045260245ffd5b611d9a915060203d60201161068657610678818361213d565b88611bf9565b608060208584030112611d6a576020608091604051611dbe816120d0565b611dc787612593565b8152611dd4838801612593565b83820152611de460408801612632565b6040820152611df560608801612632565b6060820152815201930192611ba2565b611e229196503d805f833e611e1a818361213d565b81019061260d565b9486611af1565b63abeba34560e01b5f908152306004526001600160a01b038516602452604490fd5b611e64915060203d60201161068657610678818361213d565b876119b3565b82631f798e2b60e31b5f523360045260245260445ffd5b34611d6a5760a0366003190112611d6a57604051611e9e816120eb565b6004356001600160a01b0381168103611d6a5781526024356001600160a01b0381168103611d6a57602082015260443562ffffff81168103611d6a5760408201526064358060020b8103611d6a576060820152608435906001600160a01b0382168203611d6a57611f1c916080820152611f16612442565b506125a1565b5f52600160205261161b60405f20611835600160405192611824846120b5565b34611d6a57611f4a36612052565b5050507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03163303915061004d905057630a85dc2960e01b5f5260045ffd5b34611d6a576020366003190112611d6a576004359063ffffffff60e01b8216809203611d6a576020916301ffc9a760e01b8114908115611fea575b8115611fd9575b5015158152f35b630505472360e51b14905083611fd2565b63fee56dd960e01b81149150611fcb565b600435906001600160a01b0382168203611d6a57565b35906001600160a01b0382168203611d6a57565b9181601f84011215611d6a578235916001600160401b038311611d6a5760208381860195010111611d6a57565b90610160600319830112611d6a576004356001600160a01b0381168103611d6a579160a0602319820112611d6a57602491608060c319830112611d6a5760c49161014435906001600160401b038211611d6a576120b191600401612025565b9091565b604081019081106001600160401b038211176104c857604052565b608081019081106001600160401b038211176104c857604052565b60a081019081106001600160401b038211176104c857604052565b6101c081019081106001600160401b038211176104c857604052565b606081019081106001600160401b038211176104c857604052565b90601f801991011681019081106001600160401b038211176104c857604052565b359062ffffff82168203611d6a57565b60e435908160020b8203611d6a57565b35908160020b8203611d6a57565b60a0906023190112611d6a57604051906121a5826120eb565b816024356001600160a01b0381168103611d6a5781526044356001600160a01b0381168103611d6a57602082015260643562ffffff81168103611d6a5760408201526084358060020b8103611d6a57606082015260a435906001600160a01b0382168203611d6a5760800152565b91908260a0910312611d6a5760405161222b816120eb565b608061227781839561223c81612011565b855261224a60208201612011565b602086015261225b6040820161215e565b604086015261226c6060820161217e565b606086015201612011565b910152565b90602080835192838152019201905f5b8181106122995750505090565b909192602060606001926001600160801b0360408851805160020b84528581015160020b868501520151166040820152019401910191909161228c565b602080825282516001600160a01b0316828201529190910151604080830152612302916060019061227c565b90565b80516001600160a01b03908116835260208083015182169084015260408083015162ffffff169084015260608083015160020b9084015260809182015116910152565b906101a0600319830112611d6a576004356001600160a01b0381168103611d6a579160a0602319820112611d6a57602491608060c319830112611d6a5760c4916101443591610164359161018435906001600160401b038211611d6a576120b191600401612025565b60c435906001600160a01b0382168203611d6a57565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b610120600319820112611d6a576004356001600160a01b0381168103611d6a579160a0602319830112611d6a5760249160c4359160e4359161010435906001600160401b038211611d6a576120b191600401612025565b6040519061244f826120b5565b60606020835f81520152565b6001600160401b0381116104c85760051b60200190565b9060405161247f81612122565b60406001600160801b038294548060020b84528060181c60020b602085015260301c16910152565b9081546124b38161245b565b926124c1604051948561213d565b81845260208401905f5260205f205f915b8383106124df5750505050565b6001602081926124ee85612472565b8152019201920191906124d2565b60405190612509826120eb565b5f6080838281528260208201528260408201528260608201520152565b90816020910312611d6a57518015158103611d6a5790565b6001600160401b0381116104c857601f01601f191660200190565b6024356001600160a01b0381168103611d6a5790565b6044356001600160a01b0381168103611d6a5790565b358060020b8103611d6a5790565b51908160020b8203611d6a57565b6040516125b2602082018093612305565b60a081526125c160c08261213d565b51902090565b81601f82011215611d6a578051906125de8261253e565b926125ec604051948561213d565b82845260208383010111611d6a57815f9260208093018386015e8301015290565b90602082820312611d6a5781516001600160401b038111611d6a5761230292016125c7565b51906001600160801b0382168203611d6a57565b908060209392818452848401375f828201840152601f01601f1916010190565b519060ff82168203611d6a57565b6001600160a01b038116308114612eb55760405163442f7de960e11b8152600481018290526020816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115611d06575f91612e76575b5060ff6004911603612e64576004905f90806001600160a01b036126fe366024612213565b51161460e05260405163b80945e960e01b815292839182905afa8015611d06575f60c052612c8c575b50602060c051019061273d61ffff835116613726565b5f608081905260c0805160a081810151519052019391929190805b60a05181106128e8575061278c907f0000000000000000000000000000000000000000000000000000000000000000613927565b60a060c05101515f1960a0510160a051811161288a576127af816127ba936137ba565b5160020b96516137ba565b5160020b6127c6613708565b5060e051156128c957945b60e051156128c457506127e2614a43565b8060020b918660020b96838812156128ad579061281161280b6001600160801b03959493613a91565b92613a91565b60e0511561289e57612822926145b6565b905b6040519661283188612122565b8752602087015216604085015261ffff5f199151160161ffff811161288a5761287f9361ffff61286e92169061286782866137ba565b52836137ba565b5061287a366024612213565b6137ce565b636fe7e6eb60e01b90565b634e487b7160e01b5f52601160045260245ffd5b6128a792614573565b90612824565b838863352d1ec160e11b5f5260045260245260445ffd5b6127e2565b506128e260c86128dd81620d89e7196149ab565b614413565b946127d1565b90936129246128fd8360e060c05101516137ba565b517f000000000000000000000000000000000000000000000000000000000000000061460a565b906129358360a060c05101516137ba565b5160020b916129458489516137ba565b5160020b9261ffff61295d86608060c05101516137ba565b51169060e0515f14612c835761297e85915b60e05115612c7d578096614445565b9061298881613a91565b670de0b6b3a76400008402848104670de0b6b3a7640000148515171561288a576129b29086614685565b935f975f5b828110612a1157505050505050508211612a02576001916129d89196613fa2565b916129f961ffff6129ef83608060c05101516137ba565b5116608051613fa2565b60805201612758565b6366bf045960e01b5f5260045ffd5b60e05115612c5757612a42612a3a62ffffff612a3086828b16866147e8565b1660020b8461447d565b60e0516149cd565b8560020b8160020b03612a59575b506001016129b7565b612a6281613a91565b5f908a612ae7575b60019392612ad1928d926001600160a01b03908116908a161015612ad8576001600160801b03908a925b60405193612aa185612122565b60020b845260020b6020840152166040820152612aca612ac385608051613fa2565b80936137ba565b528b6137ba565b5090612a50565b6001600160801b03908a612a94565b60e051909c929392915015612c45578b612b028a88836145b6565b915b8c88849360e0515f14612bf75791506001600160a01b038a811690831611612bed575b6001600160a01b038216908115612be1578f956001600160a01b038281169260609290921b6fffffffffffffffffffffffffffffffff60601b169190612b7390849087840316846147e8565b948315612bcd5790036001600160a01b03169009612bb5575b600196928282612ba893612ad198979506151591040190613fa2565b9e92509250929350612a6a565b95919350600101918215611d6a57918d939195612b8c565b634e487b7160e01b5f52601260045260245ffd5b62bfc9215f526004601cfd5b50508d8890612b27565b92612ad19560016001600160801b03612ba894829b97838060a09b999b1b031690838060a01b0316038060ff1d908101189216612c34838261471c565b928260601b91091515160190613fa2565b8b612c518a8289614573565b91612b04565b612a42612c7862ffffff612c6e86828b16866147e8565b1660020b84614445565b612a3a565b86614445565b61297e8161296f565b3d805f833e612c9b818361213d565b810190602081830312611d6a578051906001600160401b038211611d6a57019061010082820312611d6a576040519161010083018381106001600160401b038211176104c857604052612ced81612666565b8352612cfb60208201613969565b6020840152612d0c60408201612ed7565b6040840152612d1d60608201612593565b606084015260808101516001600160401b038111611d6a57810182601f82011215611d6a57805190612d4e8261245b565b91612d5c604051938461213d565b80835260208084019160051b83010191858311611d6a57602001905b828210612e4c57505050608084015260a08101516001600160401b038111611d6a5782612da6918301613978565b60a084015260c08101516001600160401b038111611d6a5782612dca918301613978565b60c084015260e0810151906001600160401b038211611d6a57019080601f83011215611d6a578151612dfb8161245b565b92612e09604051948561213d565b81845260208085019260051b820101928311611d6a57602001905b828210612e3c5750505060e082015260c0525f612727565b8151815260209182019101612e24565b60208091612e5984613969565b815201910190612d78565b63fb9d975f60e01b5f5260045260245ffd5b90506020813d602011612ead575b81612e916020938361213d565b81010312611d6a5760ff612ea6600492612666565b91506126d9565b3d9150612e84565b50636fe7e6eb60e01b919050565b51906001600160a01b0382168203611d6a57565b519062ffffff82168203611d6a57565b91908260a0910312611d6a57604051612eff816120eb565b6080612277818395612f1081612ec3565b8552612f1e60208201612ec3565b6020860152612f2f60408201612ed7565b6040860152612f4060608201612593565b606086015201612ec3565b81601f82011215611d6a57805190612f628261245b565b92612f70604051948561213d565b82845260206060818601940283010191818311611d6a57602001925b828410612f9a575050505090565b606084830312611d6a576020606091604051612fb581612122565b612fbe87612593565b8152612fcb838801612593565b83820152612fdb60408801612632565b6040820152815201930192612f8c565b919060609281518201604083820312611d6a5761300a60208401612666565b926040810151906001600160401b038211611d6a576020613032928160ff95019201016125c7565b92169360018514613439575060028414613059578363621319a560e11b5f5260045260245ffd5b9080929350518201916020830190602081850312611d6a576020810151906001600160401b038211611d6a5701926101009084900312611d6a57604051906130a0826120d0565b6130ad8160208601612ee7565b825260c0840151906001600160401b038211611d6a576130da6101009160206130f9948896980101612f4b565b92602086019384526130ee60e08201612ec3565b604087015201612ec3565b906060840191825261310f60a0855120846144bb565b5050509284519151958651946131248661245b565b95613132604051978861213d565b808752613141601f199161245b565b015f5b81811061341c5750506001600160a01b038316945f5b89518110156132e3576131918a60206131828461317781856137ba565b515160020b936137ba565b51015160020b908830896142e8565b908a6001600160801b0360206131b6846131ab81866137ba565b515160020b946137ba565b51015160020b9316905f82126132d45761320d936131d5604093613faf565b908351926131e2846120d0565b83526020830152828201525f6060820152815180948192632d35e7ed60e11b83528b60048401613a17565b03815f8c5af1918215611d06576001600160801b038c916001945f915f916132b2575b508290613275602061325188613246818a6137ba565b515160020b986137ba565b51015160020b936132688360801d8260801d613a6b565b92600f0b90600f0b613a6b565b9260405195613283876120d0565b865260208601521660408401521660608201526132a0828b6137ba565b526132ab818a6137ba565b500161315a565b8392506132cd915060403d81116111bd576111af818361213d565b9091613230565b6393dafdf160e01b5f5260045ffd5b5096935094935095506133349061330560018060a01b03845151163083613fbf565b928361331f60018060a01b03602084510151163085613fbf565b978892519060018060a01b039051169361400c565b60405192613341846120d0565b60018060a01b0316835260208301918252604083019081526060830193845260405193849260208085015260c084019460018060a01b0390511660408501525191608060608501528251809552602060e085019301945f5b8181106133c15750505160808401525160a083015203601f198101835261230291508261213d565b919360019193955061340b6020918851906001600160801b036060608093805160020b8452602081015160020b602085015282604082015116604085015201511660608201520190565b960191019186949295939195613399565b60209061342a9997996139dd565b82828b01015201979597613144565b935090805181016020810191602081830312611d6a576020810151906001600160401b038211611d6a57019060c09082900312611d6a576040519161347d836120b5565b61348a8160208401612ee7565b835260c0820151916001600160401b038311611d6a576134ad9201602001612f4b565b938460208301528151905f955f906134c36139dd565b508051935f926001600160a01b038816905b868510613535575050505050505061352192935051906134ff60018060a01b038351163083613fbf565b602083015130939061351b906001600160a01b03168585613fbf565b9261400c565b60405161352f60208261213d565b5f815290565b5f9a61354186866137ba565b515160020b602061355288886137ba565b51015160020b906001600160801b03604061356d8a8a6137ba565b510151169d8e126132d4576135b59d60409283519261358b846120d0565b83526020830152828201525f898201528151809e8192632d35e7ed60e11b83528860048401613a17565b03815f875af19b8c15611d06575f9c6135f0575b506001916135de6135e8928e60801d90613a6b565b9c600f0b90613a6b565b9401936134d5565b6135e8919c50916135de61361360019460403d81116111bd576111af818361213d565b509d925050916135c9565b6024356001600160a01b03811690819003611d6a5781526044356001600160a01b03811690819003611d6a57602082015260643562ffffff8116809103611d6a5760408201526084358060020b809103611d6a57606082015260a4356001600160a01b0381169190829003611d6a5760800152565b6080906001600160a01b036136a782612011565b1683526001600160a01b036136be60208301612011565b16602084015262ffffff6136d46040830161215e565b1660408401526136e66060820161217e565b60020b60608401526001600160a01b0390613702908301612011565b16910152565b6040519061371582612122565b5f6040838281528260208201520152565b906137308261245b565b61373d604051918261213d565b828152809261374e601f199161245b565b01905f5b82811061375e57505050565b602090613769613708565b82828501015201613752565b91908110156137855760071b0190565b634e487b7160e01b5f52603260045260245ffd5b356001600160801b0381168103611d6a5790565b8051156137855760200190565b80518210156137855760209160051b010190565b90604051906137dc826120b5565b6001600160a01b0316815260208101838152906001906137fb846125a1565b5f528160205260405f2090828060a01b039051166bffffffffffffffffffffffff60a01b825416178155019051908151916801000000000000000083116104c8578154838355808410613901575b50602001905f5260205f205f915b83831061388f57505050509061388d917f0000000000000000000000000000000000000000000000000000000000000000613e59565b565b60016020826138f56001600160801b0360408596518051895462ffffff8884015160181b65ffffff0000001692169065ffffffffffff1916171789550151168690600160301b600160b01b0382549160301b1690600160301b600160b01b031916179055565b01920192019190613857565b825f528360205f2091820191015b81811061391c5750613849565b5f815560010161390f565b9190820391821161288a57565b8054821015613785575f5260205f2001905f90565b906001600160801b03809116911601906001600160801b03821161288a57565b519061ffff82168203611d6a57565b9080601f83011215611d6a57815161398f8161245b565b9261399d604051948561213d565b81845260208085019260051b820101928311611d6a57602001905b8282106139c55750505090565b602080916139d284612593565b8152019101906139b8565b604051906139ea826120d0565b5f6060838281528260208201528260408201520152565b9190826040910312611d6a576020825192015190565b9061016092613a2983613a5793612305565b8051600290810b60a08501526020820151900b60c0840152604081015160e084015260600151610100830152565b6101406101208201525f6101408201520190565b90600f0b90600f0b019060016001607f1b0319821260016001607f1b0383131761288a57565b60020b908160ff1d82810118620d89e88111613dab5763ffffffff9192600182167001fffcb933bd6fad37aa2d162d1a59400102600160801b189160028116613d8f575b60048116613d73575b60088116613d57575b60108116613d3b575b60208116613d1f575b60408116613d03575b60808116613ce7575b6101008116613ccb575b6102008116613caf575b6104008116613c93575b6108008116613c77575b6110008116613c5b575b6120008116613c3f575b6140008116613c23575b6180008116613c07575b620100008116613beb575b620200008116613bd0575b620400008116613bb5575b6208000016613b9c575b5f12613b94575b0160201c90565b5f1904613b8d565b6b048a170391f7dc42444e8fa290910260801c90613b86565b6d2216e584f5fa1ea926041bedfe9890920260801c91613b7c565b916e5d6af8dedb81196699c329225ee6040260801c91613b71565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c91613b66565b916f31be135f97d08fd981231505542fcfa60260801c91613b5b565b916f70d869a156d2a1b890bb3df62baf32f70260801c91613b51565b916fa9f746462d870fdf8a65dc1f90e061e50260801c91613b47565b916fd097f3bdfd2022b8845ad8f792aa58250260801c91613b3d565b916fe7159475a2c29b7443b29c7fa6e889d90260801c91613b33565b916ff3392b0822b70005940c7a398e4b70f30260801c91613b29565b916ff987a7253ac413176f2b074cf7815e540260801c91613b1f565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c91613b15565b916ffe5dee046a99a2a811c461f1969c30530260801c91613b0b565b916fff2ea16466c96a3843ec78b326b528610260801c91613b02565b916fff973b41fa98c081472e6896dfb254c00260801c91613af9565b916fffcb9843d60f6159c9db58835c9266440260801c91613af0565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91613ae7565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c91613ade565b916ffff97272373d413259a46990580e213a0260801c91613ad5565b826345c3193d60e11b5f5260045260245ffd5b936001600160a01b0383811690831611613e51575b6001600160a01b03858116959083168611613df457505061230293506145b6565b919490939192906001600160a01b0382161115613e45578291613e1b91613e2195946145b6565b93614573565b6001600160801b0381166001600160801b038316105f14613e40575090565b905090565b91505061230292614573565b909190613dd3565b613ef290611a84613ece613e9e613eb15f9796611a84899860405192613e7e846120b5565b835260208301908152604051948593602080860152604085019051612305565b5160c060e084015261010083019061227c565b6040519283916001602084015260408084015260608301906123c7565b6040519485809481936348c8949160e01b83526020600484015260248301906123c7565b03926001600160a01b03165af18015611d0657613f0c5750565b613f1f903d805f833e611e1a818361213d565b50565b90816020910312611d6a575190565b6001600160a01b031680613f4457504790565b6020602491604051928380926370a0823160e01b82523060048301525afa908115611d06575f91613f73575090565b90506020813d602011613f9a575b81613f8e6020938361213d565b81010312611d6a575190565b3d9150613f81565b9190820180921161288a57565b600160ff1b811461288a575f0390565b6001600160a01b039182165f9081529282166020908152604093849020935163789add5560e11b815260048101949094529183916024918391165afa908115611d06575f91613f73575090565b9091949392945f935f8213614272575b8487136141eb575b5083811261412e575b5082851261403d575b5050509050565b60209190910180516001600160a01b039081169592169190823b156106a05760405195632961046560e21b87526004870152838660248183875af195861561412357849596614106575b5051602092916140ac916001600160a01b03169083906140a690613faf565b91614868565b600460405180958193630476982d60e21b83525af190811561140757506140d7575b80808392614036565b6140f89060203d6020116140ff575b6140f0818361213d565b810190613f22565b505f6140ce565b503d6140e6565b8461411591959293949561213d565b6106a057908392915f614087565b6040513d86823e3d90fd5b82516001600160a01b03838116929116823b156106985760405190632961046560e21b82526004820152858160248183875af1801561068d5790869392916141d0575b50845160209291614191916001600160a01b03169083906140a690613faf565b600460405180948193630476982d60e21b83525af18015614123571561402d576141c99060203d6020116140ff576140f0818361213d565b505f61402d565b836141de919492939461213d565b61069c579084915f614171565b60208401516001600160a01b03848116929116823b1561064357604051630b0d9c0960e01b81526001600160a01b03918216600482015291166024820152604481018890529085908290606490829084905af1801561426757908591614252575b50614024565b8161425c9161213d565b6106a057835f61424c565b6040513d87823e3d90fd5b83516001600160a01b03908116908416803b15611d6a57604051630b0d9c0960e01b81526001600160a01b0392831660048201529183166024830152604482018490525f908290606490829084905af18015611d06576142d3575b5061401c565b6142e09195505f9061213d565b5f935f6142cd565b93929160a09161432493604051955f60268801526006870152600386015284525f603a600c860120948160408201528160208201525220614d79565b906006820180921161288a576020916040519083820192835260408201526040815261435160608261213d565b519020604051631e2eaeaf60e01b8152600481019190915291829060249082906001600160a01b03165afa8015611d06575f90614397575b6001600160801b0391501690565b506020813d6020116143c8575b816143b16020938361213d565b81010312611d6a576001600160801b039051614389565b3d91506143a4565b6001600160801b0316610d05810290808204610d05149015171561288a576127106001600160801b0391041690565b60020b60011b908160020b91820361288a57565b9060020b9060020b02908160020b91820361288a57565b60020b5f190190627fffff198212627fffff83131761288a57565b600291820b910b0390627fffff198212627fffff83131761288a57565b60020b60010190627fffff8213627fffff1983121761288a57565b9060020b9060020b0190627fffff198212627fffff83131761288a57565b600f0b6f7fffffffffffffffffffffffffffffff19811461288a575f0390565b91906144c8602091614d79565b604051631e2eaeaf60e01b8152600481019190915292839060249082906001600160a01b03165afa918215611d06575f92614526575b506001600160a01b0382169160a081901c60020b9162ffffff60b883901c81169260d01c1690565b9091506020813d602011614552575b816145426020938361213d565b81010312611d6a5751905f6144fe565b3d9150614535565b6001600160a01b03918216908216039190821161288a57565b612302926145ab9290916001600160a01b03808316908216116145b0575b6001600160a01b03916145a4919061455a565b1690614765565b614d99565b90614591565b612302926145ab929091906001600160a01b0380821690831611614604575b6145fd6145ee6001600160a01b0383811690851661471c565b926001600160a01b039261455a565b16916147e8565b906145d5565b808202905f1983820990828083109203918083039283670de0b6b3a76400001115611d6a5714614674577faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac1066993670de0b6b3a7640000910990828211900360ee1b910360121c170290565b5050670de0b6b3a764000091500490565b90670de0b6b3a76400008202905f19670de0b6b3a7640000840992828085109403938085039485841115611d6a571461471557670de0b6b3a764000082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b81810291905f1982820991838084109303928084039384600160601b1115611d6a571461475c57600160601b910990828211900360a01b910360601c1790565b50505060601c90565b90606082901b905f19600160601b840992828085109403938085039485841115611d6a5714614715578190600160601b900981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b91818302915f1981850993838086109503948086039586851115611d6a5714614860579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b9091906001600160a01b03811690816148f65750505f80808093855af11561488d5750565b6040516390bfb86560e01b81526001600160a01b0390911660048201525f602482018190526080604483015260a03d601f01601f191690810160648401523d6084840152903d9060a484013e808201600460a482015260c4633d2cec6f60e21b91015260e40190fd5b60205f604481949682604095865198899363a9059cbb60e01b855260018060a01b0316600485015260248401525af13d15601f3d116001855114161716928281528260208201520152156149475750565b6040516390bfb86560e01b8152600481019190915263a9059cbb60e01b602482015260806044820152601f3d01601f191660a0810160648301523d60848301523d5f60a484013e808201600460a482015260c4633c9fd93960e21b91015260e40190fd5b60020b9060020b908115612bcd57627fffff1981145f1983141661288a570590565b15614a0d575f8160020b125f146149fe5760c86128dd816149f96149f48261230296614445565b614462565b6149ab565b60c86128dd81612302936149ab565b5f8160020b125f14614a285760c86128dd81612302936149ab565b60c86128dd816149f9614a3e826123029661447d565b61442a565b61230260c86128dd81620d89e86149ab565b905f8260020b125f14614a6f576128dd81612302936149ab565b6128dd816149f9614a3e826123029661447d565b905f8260020b125f14614aa4576128dd816149f96149f48261230296614445565b6128dd81612302936149ab565b5f81126132d4576001600160801b031690565b90614acd6124fc565b5081516001600160a01b038281169291169081831015614b44575b60018060a01b03168092149262ffffff602082015116604082015160020b91606060018060a01b03910151169260405194614b22866120eb565b85526001600160a01b0316602085015260408401526060830152608082015291565b508190614ae8565b909392916020918115614c4857614bb45f6401000276a4975b614be560405195614b7587612122565b15158087528787018981526001600160a01b03909b16604080890191825251633cf3645360e21b81529b919a8c98899788969294926004880190612305565b51151560a48601525160c4850152516001600160a01b031660e48401526101206101048401526101248301906123c7565b03926001600160a01b03165af1928315611d06575f93614c14575b505f1303614c0e57600f0b90565b60801d90565b9092506020813d602011614c40575b81614c306020938361213d565b81010312611d6a5751915f614c00565b3d9150614c23565b614bb45f73fffd8963efd1fc6a506488495d951d5263988d2597614b65565b3d15614c91573d90614c788261253e565b91614c86604051938461213d565b82523d5f602084013e565b606090565b9190918215614d74576001600160a01b031680614ce057505f918291829182916001600160a01b03165af1614cc9614c67565b5015614cd157565b630db2c7f160e31b5f5260045ffd5b915f614d3192819260405190602082019263a9059cbb60e01b845260018060a01b03166024830152604482015260448152614d1c60648261213d565b519082865af1614d2a614c67565b9083614de7565b8051908115159182614d59575b5050614d475750565b635274afe760e01b5f5260045260245ffd5b614d6c9250602080918301019101612526565b155f80614d3e565b505050565b6040516020810191825260066040820152604081526125c160608261213d565b906001600160801b038216918203614dad57565b60405162461bcd60e51b81526020600482015260126024820152716c6971756964697479206f766572666c6f7760701b6044820152606490fd5b90614e0b5750805115614dfc57805190602001fd5b630a12f52160e11b5f5260045ffd5b81511580614e3c575b614e1c575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b15614e1456fea26469706673582212204bb135ddd6b920f815d8d9ba6bbfaecb32d14f025523d5353fba8e713b3a521e64736f6c634300081c0033000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b000000000000000000000000777777751622c0d3258f214f9df38e35bf45baf30000000000000000000000000000000000000000000000000000000000000080000000000000000000000000d88f6bdd765313cafa5888c177c325e2c3abf2d200000000000000000000000000000000000000000000000000000000000000020000000000000000000000006ff5693b99212da76ad316178a184ab56d299b430000000000000000000000007c5f5a4bbd8fd63184577525326123b519429bdc
Deployed Bytecode
0x61010080604052600436101561005c575b50361561001b575f80fd5b7f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b6001600160a01b0316330361004d57005b63570c108560e11b5f5260045ffd5b5f905f3560e01c90816301ffc9a714611f905750806321d0ee7014611f3c578063259982e514611f3c5780632c5fe5a914611e815780634a862f63146118da578063575e24b4146118465780635859e6d0146117d15780636c2bbe7e1461161f5780636fe7e6eb1461173a57806391dd7346146116765780639f063efc1461161f578063a0a8e460146115d2578063b47b2fb114610966578063b6a8b0fa146106a9578063bc9113b314610928578063c4e833ce146107bf578063dc4c90d31461077a578063dc98354e1461070b578063e1b4af69146106a95763fee56dd90361001057346106a657366003190161012081126106a45760a0136106a65760a4356001600160a01b03811681036106a4576101756123b1565b60e4356001600160401b0381116106a057366023820112156106a0578060040135906001600160401b03821161069c576024810190602436918460071b01011161069c57610104356001600160401b038111610698576101d9903690600401612025565b50506040516321f7434760e01b81523360048201523060248201526020816044816001600160a01b037f000000000000000000000000d88f6bdd765313cafa5888c177c325e2c3abf2d2165afa90811561068d57869161065e575b5015610647576004356001600160a01b03811692908381036106435750610259612559565b9460443562ffffff811680910361063f57606435908160020b9182810361063b575060405195610288876120eb565b8652602086019760018060a01b03168852604086015260608501523060808501527f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b9260405163313b65df60e11b81526102e56004820187612305565b6001600160a01b0387811660a4830152602090829060c49082908d908a165af18015610630576105f5575b5061031a83613726565b92885b8181106104f9575050509061033291846137ce565b815161035a9061034a906001600160a01b0316613f31565b94516001600160a01b0316613f31565b610363836125a1565b86526001602052600160408720019480158015906104f0575b610384578680f35b85545f1981019081116104dc57906103a06103c5939288613934565b509586546103bf6103b38260020b613a91565b9160181c60020b613a91565b91613dbe565b6040805194906103d5818761213d565b60018652601f1901875b8181106104b157505084604094610435946001600160801b03979461040661043095612472565b61040f856137ad565b52610419846137ad565b508888610425866137ad565b510191169052613e59565b6137ad565b51015182549116915f19820191821161049d57610459610493939261046e92613934565b50916001600160801b03835460301c16613949565b600160301b600160b01b0382549160301b1690600160301b600160b01b031916179055565b5f80808080808680f35b634e487b7160e01b84526011600452602484fd5b6020906104bc613708565b82828a010152016103df565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b88526011600452602488fd5b5081151561037c565b610504818385613775565b61050d90612585565b61051690613a91565b610521828486613775565b60200161052d90612585565b61053690613a91565b610541838587613775565b60400161054d90613799565b90610559848688613775565b60600161056590613799565b6001600160801b0316916001600160801b031690610583938c613dbe565b61058e828486613775565b61059790612585565b906105a3838587613775565b6020016105af90612585565b604051926105bc84612122565b60020b835260020b60208301526001600160801b031660408201526105e182876137ba565b526105ec81866137ba565b5060010161031d565b6020813d602011610628575b8161060e6020938361213d565b810103126106245761061f90612593565b610310565b8880fd5b3d9150610601565b6040513d8b823e3d90fd5b8980fd5b8780fd5b8680fd5b63abeba34560e01b85523360045230602452604485fd5b610680915060203d602011610686575b610678818361213d565b810190612526565b5f610234565b503d61066e565b6040513d88823e3d90fd5b8580fd5b8480fd5b8380fd5b505b80fd5b50346106a6576004906106bb366123eb565b5050507f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b6001600160a01b0316330392506106ff91505057630a85dc2960e01b8152fd5b63570c108560e11b8152fd5b50346106a65760e03660031901126106a657610725611ffb565b5060a03660231901126106a65760049061073d6123b1565b507f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b6001600160a01b031633036106ff57630a85dc2960e01b8152fd5b50346106a657806003193601126106a6576040517f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b6001600160a01b03168152602090f35b50346106a657806003193601126106a657806101c0916101a06040516107e481612106565b8281528260208201528260408201528260608201528260808201528260a08201528260c08201528260e0820152826101008201528261012082015282610140820152826101608201528261018082015201526040519061084382612106565b80825260208201916001835260408101828152606082018381526080830184815260a0840185815260c0850186815260e0860190600182526101008701928884526101208801948986526101408901968a88526101608a01988b8a526101a06101808c019b8d8d52019b808d5260206040519e8f92835251151591015251151560408d015251151560608c015251151560808b015251151560a08a015251151560c089015251151560e08801525115156101008701525115156101208601525115156101408501525115156101608401525115156101808301525115156101a0820152f35b50346106a65760203660031901126106a65760209060ff906040906001600160a01b03610953611ffb565b1681528084522054166040519015158152f35b50346106a6576101603660031901126106a657610981611ffb565b60a03660231901126106a45760603660c31901126106a45761012435610144356001600160401b0381116106a0576109bd903690600401612025565b90917f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b9060018060a01b038216928333036115c357610a036109fe3661218c565b6125a1565b808852600160205260408820546001600160a01b0316919082156115a55760405163f3ffe14b60e01b81527f000000000000000000000000777777751622c0d3258f214f9df38e35bf45baf36001600160a01b03166004820152928984602481845afa93841561159a578a9461141f575b50818a526001602052600160408b2001610a8d3661218c565b8b908c8093610a9a6139dd565b5080549082935b8d8d8487106112f6575050505050905081600f0b136111e1575b508a81600f0b1361104a575b50610ae2610add610ad6612559565b3089613fbf565b614ab1565b97610af8610add610af161256f565b308a613fbf565b60208601519551805190966001600160a01b0316901561103b57610b268d91610b20896137ad565b51614ac4565b801561102d576001600160801b038d945b821561101c5760208401516001600160a01b03169e5b83156110145750945b1680610fc957505050509a999597989a5b9a976001966020995b8751891015610c00576001600160801b03610bb28e9f8f9e9f8e908e610bca938f8f98610b20610ba29260019b6137ba565b9681988894929316600f0b61449b565b600f0b93610bc3604051968761213d565b8552614b4c565b6001600160801b03169d5015610bf2578b828060a01b03910151165b9801979c9b9a9c610b70565b818060a01b03905116610be6565b8c94928b9694928f928e6001600160801b038e95168015918215610f62575b508b15610f5d578a878d8101031261063b5786356001600160a01b03811690819003610e8057505b604051633fb80b1560e01b8152918b836004818c5afa928315610f52578b93610f1b575b50604051637a9f55c760e11b8152908c826004818d5afa918215610f10578c92610ed5575b50611388830290838204611388141715610ec1579260a0928a95928e610cdc6127107fea92473287be4e55f8279d0b8395a45960a217ae2f1a76ac9cae84af58a751ed98048094613927565b93610ce8818588614c96565b610cf3838688614c96565b60405195600180891b03168652600180881b031690850152600180861b0316604084015260608301526080820152a260018060a01b03169283875286885260ff6040882054169260405163d737d0c760e01b81528981600481895afa899181610e8a575b50610e84575087925b60c4359687151597888103610e8057610d9f919015610e68576001600160a01b03610d8961256f565b1614925b60a0610d983661218c565b20906144bb565b505050966040519515158652610db68b870161361e565b60c086015260e43560e0860152610104356001600160a01b0381169081900361063b579260409b869593610e3f9387966101007fd0565428a2140862827b5b6126002556c70acb52db537fae9cf41a18a470ec4a9a01528060801d600f0b610120880152600f0b61014087015215156101608601526101c06101808601526101c0850191612646565b6001600160a01b039687166101a08401529516940390a4825163b47b2fb160e01b815291820152f35b6001600160a01b03610e78612559565b161492610d8d565b8a80fd5b92610d60565b9091508a81813d8311610eba575b610ea2818361213d565b8101031261063b57610eb390612ec3565b908c610d57565b503d610e98565b634e487b7160e01b8c52601160045260248cfd5b9091508c81813d8311610f09575b610eed818361213d565b81010312610f0557610efe90612ec3565b908e610c90565b8b80fd5b503d610ee3565b6040513d8e823e3d90fd5b9092508b81813d8311610f4b575b610f33818361213d565b81010312610e8057610f4490612ec3565b918d610c6b565b503d610f29565b6040513d8d823e3d90fd5b610c47565b803b15610e8057604051630b0d9c0960e01b81526001600160a01b038516600482015230602482015260448101839052908b908290606490829084905af18015610f5257908b91610fb4575b50610c1f565b81610fbe9161213d565b61063b57898d610fae565b91611009949391610fdf610ffa94600f0b61449b565b60405193610fee60208661213d565b8452600f0b918d614b4c565b6001600160801b031690613949565b9a999597989a610b67565b905094610b56565b83516001600160a01b03169e610b4d565b6001600160801b0384610b37565b6319dcad4d60e31b8d5260048dfd5b61105d6001600160801b039182166143d0565b168015610ac75761107b60a0611074366024612213565b20886144bb565b50509050608435908c8260020b83036106a6576110bc6110b5846110b06001600160801b03956110aa836143ff565b90614445565b614a55565b9384614445565b936110c685613a91565b916110d085613a91565b90156111d3576110df926145b6565b1690816110ee575b5050610ac7565b8c82126111c4576101648d936040936111719385519261110d846120d0565b60020b835260020b60208301528482015284606082015283519485938492632d35e7ed60e11b8452611143600485016024613693565b8051600290810b60a48601526020820151900b60c4850152604081015160e485015260600151610104840152565b610140610124830152806101448301528c5af18015610f5257611196575b80806110e7565b6111b79060403d6040116111bd575b6111af818361213d565b810190613a01565b5061118f565b503d6111a5565b6393dafdf160e01b8d5260048dfd5b6111dc92614573565b6110df565b6111f46001600160801b039182166143d0565b168015610abb578b61121360a061120c366024612213565b208a6144bb565b5050929050608435928360020b84036112f2576001600160801b03916112586112518661124c61127295611246836143ff565b9061447d565b614a83565b958661447d565b9361126286613a91565b61126b86613a91565b91506145b6565b169081611281575b5050610abb565b8d82126112e3576101648e936040936112a09385519261110d846120d0565b610140610124830152806101448301528d5af18015610f10576112c5575b808061127a565b6112dd9060403d6040116111bd576111af818361213d565b506112be565b6393dafdf160e01b8e5260048efd5b8280fd5b6113336001600160801b03916113138987999b96989a9c97613934565b505460020b876113238d8b613934565b505460181c60020b9230906142e8565b161561141357604061139b889261134a8b89613934565b505460020b6113598c8a613934565b505460181c60020b84519161136d836120d0565b8252602082015284848201528460608201528351948580948193632d35e7ed60e11b83528b60048401613a17565b03925af196871561140757966113d8575b506001916113c16113cb928860801d90613a6b565b96600f0b90613a6b565b955b019290918f92610aa1565b6113cb919650916113c16113fb60019460403d81116111bd576111af818361213d565b905097925050916113ac565b604051903d90823e3d90fd5b509450946001906113cd565b9093503d808b833e611431818361213d565b810190602081830312610e80578051906001600160401b038211610f055701604081830312610e805760405191611467836120b5565b81516001600160401b03811161159657820181601f82011215611596578051906114908261245b565b9261149e604051948561213d565b82845260208085019360051b830101918183116115925760208101935b8385106114e25750505050506114d691602091845201612ec3565b6020820152925f610a74565b84516001600160401b03811161158f5782019060a0828503601f19011261158f5760405190611510826120eb565b61151c60208401612ec3565b825261152a60408401612ed7565b602083015261153b60608401612593565b604083015261154c60808401612ec3565b606083015260a0830151916001600160401b03831161158757611577866020809695819601016125c7565b60808201528152019401936114bb565b505050508f80fd5b50505b8f80fd5b8c80fd5b6040513d8c823e3d90fd5b604051632653ac6960e21b815260a4906115c16004820161361e565bfd5b63570c108560e11b8752600487fd5b50346106a657806003193601126106a6575061161b6040516115f560408261213d565b6005815264189718971960d91b60208201526040519182916020835260208301906123c7565b0390f35b50346106a65760049061163136612348565b5050507f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b6001600160a01b0316330393506106ff9250505057630a85dc2960e01b8152fd5b50346106a65760203660031901126106a6576004356001600160401b0381116106a4576116a7903690600401612025565b7f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b906001600160a01b038216330361172b576116e28161253e565b926116f0604051948561213d565b818452368282011161069c579360208285949361161b978361171798013784010152612feb565b6040519182916020835260208301906123c7565b63570c108560e11b8452600484fd5b50346106a6576101003660031901126106a657611755611ffb565b9060a03660231901126106a65761176a6123b1565b5061177361216e565b507f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b6001600160a01b031633036117c25760206117af83612674565b6040516001600160e01b03199091168152f35b63570c108560e11b8152600490fd5b50346106a65760203660031901126106a65760043568ffffffffffffffffff1981168091036106a45761161b91604091611809612442565b508152600160205220611835600160405192611824846120b5565b818060a01b038154168452016124a7565b6020820152604051918291826122d6565b50346106a6576101403660031901126106a657611861611ffb565b5060a03660231901126106a65760603660c31901126106a657610124356001600160401b0381116106a4579061189c60049236908401612025565b50507f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b6001600160a01b031633036106ff57630a85dc2960e01b8152fd5b34611d6a5760e0366003190112611d6a576118f3611ffb565b6118fc3661218c565b60c4356001600160401b038111611d6a5761191b903690600401612025565b92906119256124fc565b5061192f836125a1565b5f52600160205260405f209360018060a01b0385541691338303611e6a576040516321f7434760e01b81523060048201526001600160a01b0385166024820152602081806044810103817f000000000000000000000000d88f6bdd765313cafa5888c177c325e2c3abf2d26001600160a01b03165afa908115611d06575f91611e4b575b5015611e29575f611a84611a92611a29611a676119d56001611ab49c016124a7565b986119de6124fc565b50604051906119ec826120d0565b8b8252602082019a8b5260408201908a8252611a3d606084019160018060a01b03169c8d8352604051968795602080880152604087019051612305565b5161010060e086015261014085019061227c565b91516001600160a01b0390811661010085015290511661012083015203601f19810183528261213d565b6040519283916002602084015260408084015260608301906123c7565b03601f19810183528261213d565b604051809881926348c8949160e01b83526020600484015260248301906123c7565b0381837f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b6001600160a01b03165af1958615611d06575f96611e05575b50855186016020810196602081830312611d6a576020810151906001600160401b038211611d6a5701608081830312611d6a5760405191611b31836120d0565b60208201516001600160a01b0381168103611d6a57835260408201516001600160401b038111611d6a576020908301019880601f8b011215611d6a57895191611b798361245b565b9a611b876040519c8d61213d565b838c526020808d019460071b820101928311611d6a57602001925b828410611da057505050506080906020830198895260608101516040840152015160608201526040516301ffc9a760e01b815263fee56dd960e01b6004820152602081602481895afa908115611d06575f91611d81575b5015611d6e575195516001600160a01b039096169592843b15611d6a579591929060405196879363fee56dd960e01b8552610124850191611c3d600487018a612305565b60a486015260c485015261012060e48501528251809152602061014485019301905f5b818110611d115750505082915f94611c849260031985840301610104860152612646565b038183855af1928315611d065760a093611cf6575b50600180841b0382511691600180851b0360208201511690606062ffffff60408301511691015160020b9160405194611cd1866120eb565b85526020850152604084015260608301526080820152611cf46040518092612305565bf35b5f611d009161213d565b5f611c99565b6040513d5f823e3d90fd5b9195945091926020611d5b6001928851906001600160801b036060608093805160020b8452602081015160020b602085015282604082015116604085015201511660608201520190565b96019101918894959392611c60565b5f80fd5b84630f83548360e41b5f5260045260245ffd5b611d9a915060203d60201161068657610678818361213d565b88611bf9565b608060208584030112611d6a576020608091604051611dbe816120d0565b611dc787612593565b8152611dd4838801612593565b83820152611de460408801612632565b6040820152611df560608801612632565b6060820152815201930192611ba2565b611e229196503d805f833e611e1a818361213d565b81019061260d565b9486611af1565b63abeba34560e01b5f908152306004526001600160a01b038516602452604490fd5b611e64915060203d60201161068657610678818361213d565b876119b3565b82631f798e2b60e31b5f523360045260245260445ffd5b34611d6a5760a0366003190112611d6a57604051611e9e816120eb565b6004356001600160a01b0381168103611d6a5781526024356001600160a01b0381168103611d6a57602082015260443562ffffff81168103611d6a5760408201526064358060020b8103611d6a576060820152608435906001600160a01b0382168203611d6a57611f1c916080820152611f16612442565b506125a1565b5f52600160205261161b60405f20611835600160405192611824846120b5565b34611d6a57611f4a36612052565b5050507f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b6001600160a01b03163303915061004d905057630a85dc2960e01b5f5260045ffd5b34611d6a576020366003190112611d6a576004359063ffffffff60e01b8216809203611d6a576020916301ffc9a760e01b8114908115611fea575b8115611fd9575b5015158152f35b630505472360e51b14905083611fd2565b63fee56dd960e01b81149150611fcb565b600435906001600160a01b0382168203611d6a57565b35906001600160a01b0382168203611d6a57565b9181601f84011215611d6a578235916001600160401b038311611d6a5760208381860195010111611d6a57565b90610160600319830112611d6a576004356001600160a01b0381168103611d6a579160a0602319820112611d6a57602491608060c319830112611d6a5760c49161014435906001600160401b038211611d6a576120b191600401612025565b9091565b604081019081106001600160401b038211176104c857604052565b608081019081106001600160401b038211176104c857604052565b60a081019081106001600160401b038211176104c857604052565b6101c081019081106001600160401b038211176104c857604052565b606081019081106001600160401b038211176104c857604052565b90601f801991011681019081106001600160401b038211176104c857604052565b359062ffffff82168203611d6a57565b60e435908160020b8203611d6a57565b35908160020b8203611d6a57565b60a0906023190112611d6a57604051906121a5826120eb565b816024356001600160a01b0381168103611d6a5781526044356001600160a01b0381168103611d6a57602082015260643562ffffff81168103611d6a5760408201526084358060020b8103611d6a57606082015260a435906001600160a01b0382168203611d6a5760800152565b91908260a0910312611d6a5760405161222b816120eb565b608061227781839561223c81612011565b855261224a60208201612011565b602086015261225b6040820161215e565b604086015261226c6060820161217e565b606086015201612011565b910152565b90602080835192838152019201905f5b8181106122995750505090565b909192602060606001926001600160801b0360408851805160020b84528581015160020b868501520151166040820152019401910191909161228c565b602080825282516001600160a01b0316828201529190910151604080830152612302916060019061227c565b90565b80516001600160a01b03908116835260208083015182169084015260408083015162ffffff169084015260608083015160020b9084015260809182015116910152565b906101a0600319830112611d6a576004356001600160a01b0381168103611d6a579160a0602319820112611d6a57602491608060c319830112611d6a5760c4916101443591610164359161018435906001600160401b038211611d6a576120b191600401612025565b60c435906001600160a01b0382168203611d6a57565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b610120600319820112611d6a576004356001600160a01b0381168103611d6a579160a0602319830112611d6a5760249160c4359160e4359161010435906001600160401b038211611d6a576120b191600401612025565b6040519061244f826120b5565b60606020835f81520152565b6001600160401b0381116104c85760051b60200190565b9060405161247f81612122565b60406001600160801b038294548060020b84528060181c60020b602085015260301c16910152565b9081546124b38161245b565b926124c1604051948561213d565b81845260208401905f5260205f205f915b8383106124df5750505050565b6001602081926124ee85612472565b8152019201920191906124d2565b60405190612509826120eb565b5f6080838281528260208201528260408201528260608201520152565b90816020910312611d6a57518015158103611d6a5790565b6001600160401b0381116104c857601f01601f191660200190565b6024356001600160a01b0381168103611d6a5790565b6044356001600160a01b0381168103611d6a5790565b358060020b8103611d6a5790565b51908160020b8203611d6a57565b6040516125b2602082018093612305565b60a081526125c160c08261213d565b51902090565b81601f82011215611d6a578051906125de8261253e565b926125ec604051948561213d565b82845260208383010111611d6a57815f9260208093018386015e8301015290565b90602082820312611d6a5781516001600160401b038111611d6a5761230292016125c7565b51906001600160801b0382168203611d6a57565b908060209392818452848401375f828201840152601f01601f1916010190565b519060ff82168203611d6a57565b6001600160a01b038116308114612eb55760405163442f7de960e11b8152600481018290526020816024817f000000000000000000000000777777751622c0d3258f214f9df38e35bf45baf36001600160a01b03165afa908115611d06575f91612e76575b5060ff6004911603612e64576004905f90806001600160a01b036126fe366024612213565b51161460e05260405163b80945e960e01b815292839182905afa8015611d06575f60c052612c8c575b50602060c051019061273d61ffff835116613726565b5f608081905260c0805160a081810151519052019391929190805b60a05181106128e8575061278c907f0000000000000000000000000000000000000000019d971e4fe8401e74000000613927565b60a060c05101515f1960a0510160a051811161288a576127af816127ba936137ba565b5160020b96516137ba565b5160020b6127c6613708565b5060e051156128c957945b60e051156128c457506127e2614a43565b8060020b918660020b96838812156128ad579061281161280b6001600160801b03959493613a91565b92613a91565b60e0511561289e57612822926145b6565b905b6040519661283188612122565b8752602087015216604085015261ffff5f199151160161ffff811161288a5761287f9361ffff61286e92169061286782866137ba565b52836137ba565b5061287a366024612213565b6137ce565b636fe7e6eb60e01b90565b634e487b7160e01b5f52601160045260245ffd5b6128a792614573565b90612824565b838863352d1ec160e11b5f5260045260245260445ffd5b6127e2565b506128e260c86128dd81620d89e7196149ab565b614413565b946127d1565b90936129246128fd8360e060c05101516137ba565b517f0000000000000000000000000000000000000000019d971e4fe8401e7400000061460a565b906129358360a060c05101516137ba565b5160020b916129458489516137ba565b5160020b9261ffff61295d86608060c05101516137ba565b51169060e0515f14612c835761297e85915b60e05115612c7d578096614445565b9061298881613a91565b670de0b6b3a76400008402848104670de0b6b3a7640000148515171561288a576129b29086614685565b935f975f5b828110612a1157505050505050508211612a02576001916129d89196613fa2565b916129f961ffff6129ef83608060c05101516137ba565b5116608051613fa2565b60805201612758565b6366bf045960e01b5f5260045ffd5b60e05115612c5757612a42612a3a62ffffff612a3086828b16866147e8565b1660020b8461447d565b60e0516149cd565b8560020b8160020b03612a59575b506001016129b7565b612a6281613a91565b5f908a612ae7575b60019392612ad1928d926001600160a01b03908116908a161015612ad8576001600160801b03908a925b60405193612aa185612122565b60020b845260020b6020840152166040820152612aca612ac385608051613fa2565b80936137ba565b528b6137ba565b5090612a50565b6001600160801b03908a612a94565b60e051909c929392915015612c45578b612b028a88836145b6565b915b8c88849360e0515f14612bf75791506001600160a01b038a811690831611612bed575b6001600160a01b038216908115612be1578f956001600160a01b038281169260609290921b6fffffffffffffffffffffffffffffffff60601b169190612b7390849087840316846147e8565b948315612bcd5790036001600160a01b03169009612bb5575b600196928282612ba893612ad198979506151591040190613fa2565b9e92509250929350612a6a565b95919350600101918215611d6a57918d939195612b8c565b634e487b7160e01b5f52601260045260245ffd5b62bfc9215f526004601cfd5b50508d8890612b27565b92612ad19560016001600160801b03612ba894829b97838060a09b999b1b031690838060a01b0316038060ff1d908101189216612c34838261471c565b928260601b91091515160190613fa2565b8b612c518a8289614573565b91612b04565b612a42612c7862ffffff612c6e86828b16866147e8565b1660020b84614445565b612a3a565b86614445565b61297e8161296f565b3d805f833e612c9b818361213d565b810190602081830312611d6a578051906001600160401b038211611d6a57019061010082820312611d6a576040519161010083018381106001600160401b038211176104c857604052612ced81612666565b8352612cfb60208201613969565b6020840152612d0c60408201612ed7565b6040840152612d1d60608201612593565b606084015260808101516001600160401b038111611d6a57810182601f82011215611d6a57805190612d4e8261245b565b91612d5c604051938461213d565b80835260208084019160051b83010191858311611d6a57602001905b828210612e4c57505050608084015260a08101516001600160401b038111611d6a5782612da6918301613978565b60a084015260c08101516001600160401b038111611d6a5782612dca918301613978565b60c084015260e0810151906001600160401b038211611d6a57019080601f83011215611d6a578151612dfb8161245b565b92612e09604051948561213d565b81845260208085019260051b820101928311611d6a57602001905b828210612e3c5750505060e082015260c0525f612727565b8151815260209182019101612e24565b60208091612e5984613969565b815201910190612d78565b63fb9d975f60e01b5f5260045260245ffd5b90506020813d602011612ead575b81612e916020938361213d565b81010312611d6a5760ff612ea6600492612666565b91506126d9565b3d9150612e84565b50636fe7e6eb60e01b919050565b51906001600160a01b0382168203611d6a57565b519062ffffff82168203611d6a57565b91908260a0910312611d6a57604051612eff816120eb565b6080612277818395612f1081612ec3565b8552612f1e60208201612ec3565b6020860152612f2f60408201612ed7565b6040860152612f4060608201612593565b606086015201612ec3565b81601f82011215611d6a57805190612f628261245b565b92612f70604051948561213d565b82845260206060818601940283010191818311611d6a57602001925b828410612f9a575050505090565b606084830312611d6a576020606091604051612fb581612122565b612fbe87612593565b8152612fcb838801612593565b83820152612fdb60408801612632565b6040820152815201930192612f8c565b919060609281518201604083820312611d6a5761300a60208401612666565b926040810151906001600160401b038211611d6a576020613032928160ff95019201016125c7565b92169360018514613439575060028414613059578363621319a560e11b5f5260045260245ffd5b9080929350518201916020830190602081850312611d6a576020810151906001600160401b038211611d6a5701926101009084900312611d6a57604051906130a0826120d0565b6130ad8160208601612ee7565b825260c0840151906001600160401b038211611d6a576130da6101009160206130f9948896980101612f4b565b92602086019384526130ee60e08201612ec3565b604087015201612ec3565b906060840191825261310f60a0855120846144bb565b5050509284519151958651946131248661245b565b95613132604051978861213d565b808752613141601f199161245b565b015f5b81811061341c5750506001600160a01b038316945f5b89518110156132e3576131918a60206131828461317781856137ba565b515160020b936137ba565b51015160020b908830896142e8565b908a6001600160801b0360206131b6846131ab81866137ba565b515160020b946137ba565b51015160020b9316905f82126132d45761320d936131d5604093613faf565b908351926131e2846120d0565b83526020830152828201525f6060820152815180948192632d35e7ed60e11b83528b60048401613a17565b03815f8c5af1918215611d06576001600160801b038c916001945f915f916132b2575b508290613275602061325188613246818a6137ba565b515160020b986137ba565b51015160020b936132688360801d8260801d613a6b565b92600f0b90600f0b613a6b565b9260405195613283876120d0565b865260208601521660408401521660608201526132a0828b6137ba565b526132ab818a6137ba565b500161315a565b8392506132cd915060403d81116111bd576111af818361213d565b9091613230565b6393dafdf160e01b5f5260045ffd5b5096935094935095506133349061330560018060a01b03845151163083613fbf565b928361331f60018060a01b03602084510151163085613fbf565b978892519060018060a01b039051169361400c565b60405192613341846120d0565b60018060a01b0316835260208301918252604083019081526060830193845260405193849260208085015260c084019460018060a01b0390511660408501525191608060608501528251809552602060e085019301945f5b8181106133c15750505160808401525160a083015203601f198101835261230291508261213d565b919360019193955061340b6020918851906001600160801b036060608093805160020b8452602081015160020b602085015282604082015116604085015201511660608201520190565b960191019186949295939195613399565b60209061342a9997996139dd565b82828b01015201979597613144565b935090805181016020810191602081830312611d6a576020810151906001600160401b038211611d6a57019060c09082900312611d6a576040519161347d836120b5565b61348a8160208401612ee7565b835260c0820151916001600160401b038311611d6a576134ad9201602001612f4b565b938460208301528151905f955f906134c36139dd565b508051935f926001600160a01b038816905b868510613535575050505050505061352192935051906134ff60018060a01b038351163083613fbf565b602083015130939061351b906001600160a01b03168585613fbf565b9261400c565b60405161352f60208261213d565b5f815290565b5f9a61354186866137ba565b515160020b602061355288886137ba565b51015160020b906001600160801b03604061356d8a8a6137ba565b510151169d8e126132d4576135b59d60409283519261358b846120d0565b83526020830152828201525f898201528151809e8192632d35e7ed60e11b83528860048401613a17565b03815f875af19b8c15611d06575f9c6135f0575b506001916135de6135e8928e60801d90613a6b565b9c600f0b90613a6b565b9401936134d5565b6135e8919c50916135de61361360019460403d81116111bd576111af818361213d565b509d925050916135c9565b6024356001600160a01b03811690819003611d6a5781526044356001600160a01b03811690819003611d6a57602082015260643562ffffff8116809103611d6a5760408201526084358060020b809103611d6a57606082015260a4356001600160a01b0381169190829003611d6a5760800152565b6080906001600160a01b036136a782612011565b1683526001600160a01b036136be60208301612011565b16602084015262ffffff6136d46040830161215e565b1660408401526136e66060820161217e565b60020b60608401526001600160a01b0390613702908301612011565b16910152565b6040519061371582612122565b5f6040838281528260208201520152565b906137308261245b565b61373d604051918261213d565b828152809261374e601f199161245b565b01905f5b82811061375e57505050565b602090613769613708565b82828501015201613752565b91908110156137855760071b0190565b634e487b7160e01b5f52603260045260245ffd5b356001600160801b0381168103611d6a5790565b8051156137855760200190565b80518210156137855760209160051b010190565b90604051906137dc826120b5565b6001600160a01b0316815260208101838152906001906137fb846125a1565b5f528160205260405f2090828060a01b039051166bffffffffffffffffffffffff60a01b825416178155019051908151916801000000000000000083116104c8578154838355808410613901575b50602001905f5260205f205f915b83831061388f57505050509061388d917f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b613e59565b565b60016020826138f56001600160801b0360408596518051895462ffffff8884015160181b65ffffff0000001692169065ffffffffffff1916171789550151168690600160301b600160b01b0382549160301b1690600160301b600160b01b031916179055565b01920192019190613857565b825f528360205f2091820191015b81811061391c5750613849565b5f815560010161390f565b9190820391821161288a57565b8054821015613785575f5260205f2001905f90565b906001600160801b03809116911601906001600160801b03821161288a57565b519061ffff82168203611d6a57565b9080601f83011215611d6a57815161398f8161245b565b9261399d604051948561213d565b81845260208085019260051b820101928311611d6a57602001905b8282106139c55750505090565b602080916139d284612593565b8152019101906139b8565b604051906139ea826120d0565b5f6060838281528260208201528260408201520152565b9190826040910312611d6a576020825192015190565b9061016092613a2983613a5793612305565b8051600290810b60a08501526020820151900b60c0840152604081015160e084015260600151610100830152565b6101406101208201525f6101408201520190565b90600f0b90600f0b019060016001607f1b0319821260016001607f1b0383131761288a57565b60020b908160ff1d82810118620d89e88111613dab5763ffffffff9192600182167001fffcb933bd6fad37aa2d162d1a59400102600160801b189160028116613d8f575b60048116613d73575b60088116613d57575b60108116613d3b575b60208116613d1f575b60408116613d03575b60808116613ce7575b6101008116613ccb575b6102008116613caf575b6104008116613c93575b6108008116613c77575b6110008116613c5b575b6120008116613c3f575b6140008116613c23575b6180008116613c07575b620100008116613beb575b620200008116613bd0575b620400008116613bb5575b6208000016613b9c575b5f12613b94575b0160201c90565b5f1904613b8d565b6b048a170391f7dc42444e8fa290910260801c90613b86565b6d2216e584f5fa1ea926041bedfe9890920260801c91613b7c565b916e5d6af8dedb81196699c329225ee6040260801c91613b71565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c91613b66565b916f31be135f97d08fd981231505542fcfa60260801c91613b5b565b916f70d869a156d2a1b890bb3df62baf32f70260801c91613b51565b916fa9f746462d870fdf8a65dc1f90e061e50260801c91613b47565b916fd097f3bdfd2022b8845ad8f792aa58250260801c91613b3d565b916fe7159475a2c29b7443b29c7fa6e889d90260801c91613b33565b916ff3392b0822b70005940c7a398e4b70f30260801c91613b29565b916ff987a7253ac413176f2b074cf7815e540260801c91613b1f565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c91613b15565b916ffe5dee046a99a2a811c461f1969c30530260801c91613b0b565b916fff2ea16466c96a3843ec78b326b528610260801c91613b02565b916fff973b41fa98c081472e6896dfb254c00260801c91613af9565b916fffcb9843d60f6159c9db58835c9266440260801c91613af0565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91613ae7565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c91613ade565b916ffff97272373d413259a46990580e213a0260801c91613ad5565b826345c3193d60e11b5f5260045260245ffd5b936001600160a01b0383811690831611613e51575b6001600160a01b03858116959083168611613df457505061230293506145b6565b919490939192906001600160a01b0382161115613e45578291613e1b91613e2195946145b6565b93614573565b6001600160801b0381166001600160801b038316105f14613e40575090565b905090565b91505061230292614573565b909190613dd3565b613ef290611a84613ece613e9e613eb15f9796611a84899860405192613e7e846120b5565b835260208301908152604051948593602080860152604085019051612305565b5160c060e084015261010083019061227c565b6040519283916001602084015260408084015260608301906123c7565b6040519485809481936348c8949160e01b83526020600484015260248301906123c7565b03926001600160a01b03165af18015611d0657613f0c5750565b613f1f903d805f833e611e1a818361213d565b50565b90816020910312611d6a575190565b6001600160a01b031680613f4457504790565b6020602491604051928380926370a0823160e01b82523060048301525afa908115611d06575f91613f73575090565b90506020813d602011613f9a575b81613f8e6020938361213d565b81010312611d6a575190565b3d9150613f81565b9190820180921161288a57565b600160ff1b811461288a575f0390565b6001600160a01b039182165f9081529282166020908152604093849020935163789add5560e11b815260048101949094529183916024918391165afa908115611d06575f91613f73575090565b9091949392945f935f8213614272575b8487136141eb575b5083811261412e575b5082851261403d575b5050509050565b60209190910180516001600160a01b039081169592169190823b156106a05760405195632961046560e21b87526004870152838660248183875af195861561412357849596614106575b5051602092916140ac916001600160a01b03169083906140a690613faf565b91614868565b600460405180958193630476982d60e21b83525af190811561140757506140d7575b80808392614036565b6140f89060203d6020116140ff575b6140f0818361213d565b810190613f22565b505f6140ce565b503d6140e6565b8461411591959293949561213d565b6106a057908392915f614087565b6040513d86823e3d90fd5b82516001600160a01b03838116929116823b156106985760405190632961046560e21b82526004820152858160248183875af1801561068d5790869392916141d0575b50845160209291614191916001600160a01b03169083906140a690613faf565b600460405180948193630476982d60e21b83525af18015614123571561402d576141c99060203d6020116140ff576140f0818361213d565b505f61402d565b836141de919492939461213d565b61069c579084915f614171565b60208401516001600160a01b03848116929116823b1561064357604051630b0d9c0960e01b81526001600160a01b03918216600482015291166024820152604481018890529085908290606490829084905af1801561426757908591614252575b50614024565b8161425c9161213d565b6106a057835f61424c565b6040513d87823e3d90fd5b83516001600160a01b03908116908416803b15611d6a57604051630b0d9c0960e01b81526001600160a01b0392831660048201529183166024830152604482018490525f908290606490829084905af18015611d06576142d3575b5061401c565b6142e09195505f9061213d565b5f935f6142cd565b93929160a09161432493604051955f60268801526006870152600386015284525f603a600c860120948160408201528160208201525220614d79565b906006820180921161288a576020916040519083820192835260408201526040815261435160608261213d565b519020604051631e2eaeaf60e01b8152600481019190915291829060249082906001600160a01b03165afa8015611d06575f90614397575b6001600160801b0391501690565b506020813d6020116143c8575b816143b16020938361213d565b81010312611d6a576001600160801b039051614389565b3d91506143a4565b6001600160801b0316610d05810290808204610d05149015171561288a576127106001600160801b0391041690565b60020b60011b908160020b91820361288a57565b9060020b9060020b02908160020b91820361288a57565b60020b5f190190627fffff198212627fffff83131761288a57565b600291820b910b0390627fffff198212627fffff83131761288a57565b60020b60010190627fffff8213627fffff1983121761288a57565b9060020b9060020b0190627fffff198212627fffff83131761288a57565b600f0b6f7fffffffffffffffffffffffffffffff19811461288a575f0390565b91906144c8602091614d79565b604051631e2eaeaf60e01b8152600481019190915292839060249082906001600160a01b03165afa918215611d06575f92614526575b506001600160a01b0382169160a081901c60020b9162ffffff60b883901c81169260d01c1690565b9091506020813d602011614552575b816145426020938361213d565b81010312611d6a5751905f6144fe565b3d9150614535565b6001600160a01b03918216908216039190821161288a57565b612302926145ab9290916001600160a01b03808316908216116145b0575b6001600160a01b03916145a4919061455a565b1690614765565b614d99565b90614591565b612302926145ab929091906001600160a01b0380821690831611614604575b6145fd6145ee6001600160a01b0383811690851661471c565b926001600160a01b039261455a565b16916147e8565b906145d5565b808202905f1983820990828083109203918083039283670de0b6b3a76400001115611d6a5714614674577faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac1066993670de0b6b3a7640000910990828211900360ee1b910360121c170290565b5050670de0b6b3a764000091500490565b90670de0b6b3a76400008202905f19670de0b6b3a7640000840992828085109403938085039485841115611d6a571461471557670de0b6b3a764000082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b81810291905f1982820991838084109303928084039384600160601b1115611d6a571461475c57600160601b910990828211900360a01b910360601c1790565b50505060601c90565b90606082901b905f19600160601b840992828085109403938085039485841115611d6a5714614715578190600160601b900981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b91818302915f1981850993838086109503948086039586851115611d6a5714614860579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b9091906001600160a01b03811690816148f65750505f80808093855af11561488d5750565b6040516390bfb86560e01b81526001600160a01b0390911660048201525f602482018190526080604483015260a03d601f01601f191690810160648401523d6084840152903d9060a484013e808201600460a482015260c4633d2cec6f60e21b91015260e40190fd5b60205f604481949682604095865198899363a9059cbb60e01b855260018060a01b0316600485015260248401525af13d15601f3d116001855114161716928281528260208201520152156149475750565b6040516390bfb86560e01b8152600481019190915263a9059cbb60e01b602482015260806044820152601f3d01601f191660a0810160648301523d60848301523d5f60a484013e808201600460a482015260c4633c9fd93960e21b91015260e40190fd5b60020b9060020b908115612bcd57627fffff1981145f1983141661288a570590565b15614a0d575f8160020b125f146149fe5760c86128dd816149f96149f48261230296614445565b614462565b6149ab565b60c86128dd81612302936149ab565b5f8160020b125f14614a285760c86128dd81612302936149ab565b60c86128dd816149f9614a3e826123029661447d565b61442a565b61230260c86128dd81620d89e86149ab565b905f8260020b125f14614a6f576128dd81612302936149ab565b6128dd816149f9614a3e826123029661447d565b905f8260020b125f14614aa4576128dd816149f96149f48261230296614445565b6128dd81612302936149ab565b5f81126132d4576001600160801b031690565b90614acd6124fc565b5081516001600160a01b038281169291169081831015614b44575b60018060a01b03168092149262ffffff602082015116604082015160020b91606060018060a01b03910151169260405194614b22866120eb565b85526001600160a01b0316602085015260408401526060830152608082015291565b508190614ae8565b909392916020918115614c4857614bb45f6401000276a4975b614be560405195614b7587612122565b15158087528787018981526001600160a01b03909b16604080890191825251633cf3645360e21b81529b919a8c98899788969294926004880190612305565b51151560a48601525160c4850152516001600160a01b031660e48401526101206101048401526101248301906123c7565b03926001600160a01b03165af1928315611d06575f93614c14575b505f1303614c0e57600f0b90565b60801d90565b9092506020813d602011614c40575b81614c306020938361213d565b81010312611d6a5751915f614c00565b3d9150614c23565b614bb45f73fffd8963efd1fc6a506488495d951d5263988d2597614b65565b3d15614c91573d90614c788261253e565b91614c86604051938461213d565b82523d5f602084013e565b606090565b9190918215614d74576001600160a01b031680614ce057505f918291829182916001600160a01b03165af1614cc9614c67565b5015614cd157565b630db2c7f160e31b5f5260045ffd5b915f614d3192819260405190602082019263a9059cbb60e01b845260018060a01b03166024830152604482015260448152614d1c60648261213d565b519082865af1614d2a614c67565b9083614de7565b8051908115159182614d59575b5050614d475750565b635274afe760e01b5f5260045260245ffd5b614d6c9250602080918301019101612526565b155f80614d3e565b505050565b6040516020810191825260066040820152604081526125c160608261213d565b906001600160801b038216918203614dad57565b60405162461bcd60e51b81526020600482015260126024820152716c6971756964697479206f766572666c6f7760701b6044820152606490fd5b90614e0b5750805115614dfc57805190602001fd5b630a12f52160e11b5f5260045ffd5b81511580614e3c575b614e1c575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b15614e1456fea26469706673582212204bb135ddd6b920f815d8d9ba6bbfaecb32d14f025523d5353fba8e713b3a521e64736f6c634300081c0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b000000000000000000000000777777751622c0d3258f214f9df38e35bf45baf30000000000000000000000000000000000000000000000000000000000000080000000000000000000000000d88f6bdd765313cafa5888c177c325e2c3abf2d200000000000000000000000000000000000000000000000000000000000000020000000000000000000000006ff5693b99212da76ad316178a184ab56d299b430000000000000000000000007c5f5a4bbd8fd63184577525326123b519429bdc
-----Decoded View---------------
Arg [0] : poolManager_ (address): 0x498581fF718922c3f8e6A244956aF099B2652b2b
Arg [1] : coinVersionLookup_ (address): 0x777777751622c0d3258f214F9DF38E35BF45baF3
Arg [2] : trustedMessageSenders_ (address[]): 0x6fF5693b99212Da76ad316178A184AB56D299b43,0x7C5f5A4bBd8fD63184577525326123B519429bDc
Arg [3] : upgradeGate (address): 0xD88f6BdD765313CaFA5888C177c325E2C3AbF2D2
-----Encoded View---------------
7 Constructor Arguments found :
Arg [0] : 000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b
Arg [1] : 000000000000000000000000777777751622c0d3258f214f9df38e35bf45baf3
Arg [2] : 0000000000000000000000000000000000000000000000000000000000000080
Arg [3] : 000000000000000000000000d88f6bdd765313cafa5888c177c325e2c3abf2d2
Arg [4] : 0000000000000000000000000000000000000000000000000000000000000002
Arg [5] : 0000000000000000000000006ff5693b99212da76ad316178a184ab56d299b43
Arg [6] : 0000000000000000000000007c5f5a4bbd8fd63184577525326123b519429bdc
Loading...
Loading
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 34 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
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.