Source Code
Latest 1 from a total of 1 transactions
| Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| Approve | 37917870 | 5 days ago | IN | 0 ETH | 0.00000006 |
Cross-Chain Transactions
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
CreatorCoin
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 {ICreatorCoin} from "./interfaces/ICreatorCoin.sol";
import {CreatorCoinConstants} from "./libs/CreatorCoinConstants.sol";
import {IHooks, PoolConfiguration, PoolKey, IPoolManager, ICoinV4, CoinV4} from "./CoinV4.sol";
contract CreatorCoin is ICreatorCoin, CoinV4 {
uint256 public vestingStartTime;
uint256 public vestingEndTime;
uint256 public totalClaimed;
constructor(
address _protocolRewardRecipient,
address _protocolRewards,
IPoolManager _poolManager,
address _airlock
) CoinV4(_protocolRewardRecipient, _protocolRewards, _poolManager, _airlock) initializer {}
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_
) public override(CoinV4, ICoinV4) {
require(currency_ == CreatorCoinConstants.CURRENCY, InvalidCurrency());
super.initialize(payoutRecipient_, owners_, tokenURI_, name_, symbol_, platformReferrer_, currency_, poolKey_, sqrtPriceX96, poolConfiguration_);
vestingStartTime = block.timestamp;
vestingEndTime = block.timestamp + CreatorCoinConstants.CREATOR_VESTING_DURATION;
}
/// @dev The initial mint and distribution of the coin supply.
/// Overrides the CoinV4._handleInitialDistribution to transfer the market supply to the hook.
function _handleInitialDistribution() internal override {
_mint(address(this), CreatorCoinConstants.TOTAL_SUPPLY);
_transfer(address(this), address(poolKey.hooks), CreatorCoinConstants.MARKET_SUPPLY);
}
/// @notice Allows the creator payout recipient to claim vested tokens
/// @dev Optimized for frequent calls from Uniswap V4 hooks
/// @return claimAmount The amount of tokens claimed
function claimVesting() external returns (uint256) {
uint256 claimAmount = getClaimableAmount();
// Early return if nothing to claim (gas efficient for frequent calls)
if (claimAmount == 0) {
return 0;
}
// Update total claimed before transfer
totalClaimed += claimAmount;
// Transfer directly to the payout recipient
_transfer(address(this), payoutRecipient, claimAmount);
emit CreatorVestingClaimed(payoutRecipient, claimAmount, totalClaimed, vestingStartTime, vestingEndTime);
return claimAmount;
}
/// @notice Get currently claimable amount without claiming
/// @return The amount that can be claimed right now
function getClaimableAmount() public view returns (uint256) {
uint256 vestedAmount = _calculateVestedAmount(block.timestamp);
return vestedAmount > totalClaimed ? vestedAmount - totalClaimed : 0;
}
/// @notice Calculate total vested amount at given timestamp
/// @param timestamp The timestamp to calculate vesting for
/// @return The total amount vested at the given timestamp
function _calculateVestedAmount(uint256 timestamp) internal view returns (uint256) {
// Before vesting starts
if (timestamp <= vestingStartTime) {
return 0;
}
// After vesting ends - fully vested
if (timestamp >= vestingEndTime) {
return CreatorCoinConstants.CREATOR_VESTING_SUPPLY;
}
// Linear vesting: (elapsed_time / total_duration) * total_amount
uint256 elapsedTime = timestamp - vestingStartTime;
// Multiply first to avoid precision loss
return (CreatorCoinConstants.CREATOR_VESTING_SUPPLY * elapsedTime) / CreatorCoinConstants.CREATOR_VESTING_DURATION;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {ICoinV4} from "./ICoinV4.sol";
interface ICreatorCoin is ICoinV4 {
/// @notice Emitted when creator vesting tokens are claimed
/// @param recipient The address that received the vested tokens
/// @param claimAmount The amount of tokens claimed in this transaction
/// @param totalClaimed The total amount of tokens claimed so far
/// @param vestingStartTime The timestamp when vesting started
/// @param vestingEndTime The timestamp when vesting ends
event CreatorVestingClaimed(address indexed recipient, uint256 claimAmount, uint256 totalClaimed, uint256 vestingStartTime, uint256 vestingEndTime);
/// @notice Thrown when an invalid currency is used for creator coin operations
error InvalidCurrency();
/// @notice Allows the creator payout recipient to claim vested tokens
/// @return claimAmount The amount of tokens claimed
function claimVesting() external returns (uint256);
}// 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.23;
import {IPoolManager, PoolKey, Currency, IHooks} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {BaseCoin} from "./BaseCoin.sol";
import {ICoinV4, IHasPoolKey, IHasSwapPath} from "./interfaces/ICoinV4.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {PoolConfiguration} from "./types/PoolConfiguration.sol";
import {UniV4SwapToCurrency} from "./libs/UniV4SwapToCurrency.sol";
import {PathKey} from "@uniswap/v4-periphery/src/libraries/PathKey.sol";
import {IDeployedCoinVersionLookup} from "./interfaces/IDeployedCoinVersionLookup.sol";
import {CoinConstants} from "./libs/CoinConstants.sol";
import {IUpgradeableV4Hook} from "./interfaces/IUpgradeableV4Hook.sol";
import {CoinCommon} from "./libs/CoinCommon.sol";
contract CoinV4 is BaseCoin, ICoinV4 {
/// @notice The Uniswap v4 pool manager singleton contract reference.
IPoolManager public immutable poolManager;
/// @notice The pool key for the coin. Type from Uniswap V4 core.
PoolKey internal poolKey;
/// @notice The configuration for the pool.
PoolConfiguration internal poolConfiguration;
/// @notice The constructor for the static CoinV4 contract deployment shared across all Coins.
/// @dev All arguments are required and cannot be set to teh 0 address.
/// @param protocolRewardRecipient_ The address of the protocol reward recipient
/// @param protocolRewards_ The address of the protocol rewards contract
/// @param poolManager_ The address of the pool manager
/// @param airlock_ The address of the Airlock contract, ownership is used for a protocol fee split.
/// @notice Returns the pool key for the coin
constructor(
address protocolRewardRecipient_,
address protocolRewards_,
IPoolManager poolManager_,
address airlock_
) BaseCoin(protocolRewardRecipient_, protocolRewards_, airlock_) {
if (address(poolManager_) == address(0)) {
revert AddressZero();
}
poolManager = poolManager_;
}
/// @inheritdoc IHasPoolKey
function getPoolKey() public view returns (PoolKey memory) {
return poolKey;
}
/// @inheritdoc ICoinV4
function getPoolConfiguration() public view returns (PoolConfiguration memory) {
return poolConfiguration;
}
/// @inheritdoc ICoinV4
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_
) public virtual initializer {
currency = currency_;
// we need to set this before initialization, because
// distributing currency relies on the poolkey being set since the hooks
// are retrieved from there
poolKey = poolKey_;
poolConfiguration = poolConfiguration_;
super._initialize(payoutRecipient_, owners_, tokenURI_, name_, symbol_, platformReferrer_);
// initialize the pool - the hook will mint its positions in the afterInitialize callback
poolManager.initialize(poolKey, sqrtPriceX96);
}
/// @dev The initial mint and distribution of the coin supply.
/// Overrides the BaseCoin._handleInitialDistribution to transfer the market supply to the hook.
function _handleInitialDistribution() internal virtual override {
// Mint the total supply to the coin contract
_mint(address(this), CoinConstants.MAX_TOTAL_SUPPLY);
// Distribute the creator launch reward to the payout recipient
_transfer(address(this), payoutRecipient, CoinConstants.CREATOR_LAUNCH_REWARD);
// Transfer the market supply to the hook for liquidity
_transfer(address(this), address(poolKey.hooks), balanceOf(address(this)));
}
/// @inheritdoc ICoinV4
function hooks() external view returns (IHooks) {
return poolKey.hooks;
}
/// @notice Migrate liquidity from current hook to a new hook implementation
/// @param newHook Address of the new hook implementation
/// @param additionalData Additional data to pass to the new hook during initialization
function migrateLiquidity(address newHook, bytes calldata additionalData) external onlyOwner returns (PoolKey memory newPoolKey) {
newPoolKey = IUpgradeableV4Hook(address(poolKey.hooks)).migrateLiquidity(newHook, poolKey, additionalData);
emit LiquidityMigrated(poolKey, CoinCommon.hashPoolKey(poolKey), newPoolKey, CoinCommon.hashPoolKey(newPoolKey));
poolKey = newPoolKey;
}
function supportsInterface(bytes4 interfaceId) public pure virtual override(BaseCoin, IERC165) returns (bool) {
return interfaceId == type(IHasPoolKey).interfaceId || type(IHasSwapPath).interfaceId == interfaceId || super.supportsInterface(interfaceId);
}
/// @inheritdoc IHasSwapPath
function getPayoutSwapPath(IDeployedCoinVersionLookup coinVersionLookup) external view returns (IHasSwapPath.PayoutSwapPath memory payoutSwapPath) {
// if to swap in is this currency,
// if backing currency is a coin, then recursively get the path from the coin
payoutSwapPath.currencyIn = Currency.wrap(address(this));
// swap to backing currency
PathKey memory thisPathKey = PathKey({
intermediateCurrency: Currency.wrap(currency),
fee: poolKey.fee,
tickSpacing: poolKey.tickSpacing,
hooks: poolKey.hooks,
hookData: ""
});
// get backing currency swap path - if the backing currency is a v4 coin and has a swap path.
PathKey[] memory subPath = UniV4SwapToCurrency.getSubSwapPath(currency, coinVersionLookup);
if (subPath.length > 0) {
payoutSwapPath.path = new PathKey[](1 + subPath.length);
payoutSwapPath.path[0] = thisPathKey;
for (uint256 i = 0; i < subPath.length; i++) {
payoutSwapPath.path[i + 1] = subPath[i];
}
} else {
payoutSwapPath.path = new PathKey[](1);
payoutSwapPath.path[0] = thisPathKey;
}
}
}// 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.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.23;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ICoin} from "./interfaces/ICoin.sol";
import {IHasRewardsRecipients} from "./interfaces/IHasRewardsRecipients.sol";
import {ICoinComments} from "./interfaces/ICoinComments.sol";
import {IERC7572} from "./interfaces/IERC7572.sol";
import {IUniswapV3Factory} from "./interfaces/IUniswapV3Factory.sol";
import {IUniswapV3Pool} from "./interfaces/IUniswapV3Pool.sol";
import {ISwapRouter} from "./interfaces/ISwapRouter.sol";
import {IAirlock} from "./interfaces/IAirlock.sol";
import {IProtocolRewards} from "./interfaces/IProtocolRewards.sol";
import {IWETH} from "./interfaces/IWETH.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {ERC20PermitUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ContractVersionBase} from "./version/ContractVersionBase.sol";
import {MultiOwnable} from "./utils/MultiOwnable.sol";
import {FullMath} from "./utils/uniswap/FullMath.sol";
import {TickMath} from "./utils/uniswap/TickMath.sol";
import {LiquidityAmounts} from "./utils/uniswap/LiquidityAmounts.sol";
import {CoinConstants} from "./libs/CoinConstants.sol";
import {MarketConstants} from "./libs/MarketConstants.sol";
import {LpPosition} from "./types/LpPosition.sol";
import {PoolState} from "./types/PoolState.sol";
import {CoinSetupV3, UniV3Config, CoinV3Config} from "./libs/CoinSetupV3.sol";
import {UniV3BuySell, CoinConfig} from "./libs/UniV3BuySell.sol";
/*
$$$$$$\ $$$$$$\ $$$$$$\ $$\ $$\
$$ __$$\ $$ __$$\ \_$$ _|$$$\ $$ |
$$ / \__|$$ / $$ | $$ | $$$$\ $$ |
$$ | $$ | $$ | $$ | $$ $$\$$ |
$$ | $$ | $$ | $$ | $$ \$$$$ |
$$ | $$\ $$ | $$ | $$ | $$ |\$$$ |
\$$$$$$ | $$$$$$ |$$$$$$\ $$ | \$$ |
\______/ \______/ \______|\__| \__|
*/
abstract contract BaseCoin is ICoin, ContractVersionBase, ERC20PermitUpgradeable, MultiOwnable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
/// @notice The address of the protocol rewards contract
address public immutable protocolRewards;
/// @notice The address of the protocol reward recipient
address public immutable protocolRewardRecipient;
/// @notice The address of the Airlock contract, ownership is used for a protocol fee split.
address public immutable airlock;
/// @notice The metadata URI
string public tokenURI;
/// @notice The address of the coin creator
address public payoutRecipient;
/// @notice The address of the platform referrer
address public platformReferrer;
/// @notice The address of the currency
address public currency;
/// @notice The name of the token
string private _name;
/// @notice The symbol of the token
string private _symbol;
/**
* @notice The constructor for the static Coin contract deployment shared across all Coins.
* @param _protocolRewardRecipient The address of the protocol reward recipient
* @param _protocolRewards The address of the protocol rewards contract
* @param _airlock The address of the Airlock contract
*/
constructor(address _protocolRewardRecipient, address _protocolRewards, address _airlock) initializer {
if (_protocolRewardRecipient == address(0)) {
revert AddressZero();
}
if (_protocolRewards == address(0)) {
revert AddressZero();
}
if (_airlock == address(0)) {
revert AddressZero();
}
protocolRewardRecipient = _protocolRewardRecipient;
protocolRewards = _protocolRewards;
airlock = _airlock;
}
/// @notice Initializes a new coin
/// @param payoutRecipient_ The address of the coin creator
/// @param tokenURI_ The metadata URI
/// @param name_ The coin name
/// @param symbol_ The coin symbol
/// @param platformReferrer_ The address of the platform referrer
function _initialize(
address payoutRecipient_,
address[] memory owners_,
string memory tokenURI_,
string memory name_,
string memory symbol_,
address platformReferrer_
) internal {
// Validate the creation parameters
if (payoutRecipient_ == address(0)) {
revert AddressZero();
}
_setNameAndSymbol(name_, symbol_);
// Set base contract state, leave name and symbol empty to save space.
__ERC20_init("", "");
// Set permit support without name later overriding name to match contract name.
__ERC20Permit_init("");
__MultiOwnable_init(owners_);
__ReentrancyGuard_init();
// Set mutable state
_setPayoutRecipient(payoutRecipient_);
_setContractURI(tokenURI_);
// Store the referrer or use the protocol reward recipient if not set
platformReferrer = platformReferrer_ == address(0) ? protocolRewardRecipient : platformReferrer_;
// Distribute the initial supply
_handleInitialDistribution();
}
/// @dev The initial mint and distribution of the coin supply.
function _handleInitialDistribution() internal virtual {
// Mint the total supply to the coin contract
_mint(address(this), CoinConstants.MAX_TOTAL_SUPPLY);
// Distribute the creator launch reward to the payout recipient
_transfer(address(this), payoutRecipient, CoinConstants.CREATOR_LAUNCH_REWARD);
}
/// @notice Returns the name of the token for EIP712 domain.
/// @notice This can change when the user changes the "name" of the token.
/// @dev Overrides the default implementation to align name getter with Permit support.
function _EIP712Name() internal view override returns (string memory) {
return "Coin";
}
/// @notice Enables a user to burn their tokens
/// @param amount The amount of tokens to burn
function burn(uint256 amount) external {
// This burn function sets the from as msg.sender, so having an unauthed call is safe.
_burn(msg.sender, amount);
}
/// @notice Set the creator's payout address
/// @param newPayoutRecipient The new recipient address
function setPayoutRecipient(address newPayoutRecipient) external onlyOwner {
_setPayoutRecipient(newPayoutRecipient);
}
/// @notice Set the contract URI
/// @param newURI The new URI
function setContractURI(string memory newURI) external onlyOwner {
_setContractURI(newURI);
}
/// @notice The contract metadata
function contractURI() external view returns (string memory) {
return tokenURI;
}
/**
* @dev Returns the name of the token.
*/
function name() public view override returns (string memory) {
return _name;
}
function setNameAndSymbol(string memory newName, string memory newSymbol) external onlyOwner {
_setNameAndSymbol(newName, newSymbol);
}
function _setNameAndSymbol(string memory newName, string memory newSymbol) internal {
if (bytes(newName).length == 0) {
revert NameIsRequired();
}
_name = newName;
_symbol = newSymbol;
emit NameAndSymbolUpdated(msg.sender, newName, newSymbol);
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/// @notice ERC165 interface support
/// @param interfaceId The interface ID to check
function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) {
return
interfaceId == type(ICoin).interfaceId ||
interfaceId == type(ICoinComments).interfaceId ||
interfaceId == type(IERC7572).interfaceId ||
interfaceId == type(IERC165).interfaceId ||
interfaceId == type(IHasRewardsRecipients).interfaceId;
}
/// @dev Overrides ERC20's _update function to emit a superset `CoinTransfer` event
function _update(address from, address to, uint256 value) internal virtual override {
super._update(from, to, value);
emit CoinTransfer(from, to, value, balanceOf(from), balanceOf(to));
}
/// @dev Used to set the payout recipient on coin creation and updates
/// @param newPayoutRecipient The new recipient address
function _setPayoutRecipient(address newPayoutRecipient) internal {
if (newPayoutRecipient == address(0)) {
revert AddressZero();
}
emit CoinPayoutRecipientUpdated(msg.sender, payoutRecipient, newPayoutRecipient);
payoutRecipient = newPayoutRecipient;
}
/// @dev Used to set the contract URI on coin creation and updates
/// @param newURI The new URI
function _setContractURI(string memory newURI) internal {
emit ContractMetadataUpdated(msg.sender, newURI, name());
emit ContractURIUpdated();
tokenURI = newURI;
}
/// @notice Returns the address of the Doppler protocol fee recipient
function dopplerFeeRecipient() public view returns (address) {
return IAirlock(airlock).owner();
}
}// 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: 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.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;
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.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;
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
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 {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 {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.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @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 {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 {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.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
// 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
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.0;
interface ICoinComments {
function isOwner(address) external view returns (bool);
function payoutRecipient() external view returns (address);
function balanceOf(address) external view returns (uint256);
}// 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
/// @notice Emitted when the owner of the factory is changed
/// @param oldOwner The owner before the owner was changed
/// @param newOwner The owner after the owner was changed
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token 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 pool The address of the created pool
event PoolCreated(address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool);
/// @notice Emitted when a new fee amount is enabled for pool creation via the factory
/// @param fee The enabled fee, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via setOwner
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
/// @return The tick spacing
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The pool address
function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param fee The desired fee for the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
/// are invalid.
/// @return pool The address of the newly created pool
function createPool(address tokenA, address tokenB, uint24 fee) external returns (address pool);
/// @notice Updates the owner of the factory
/// @dev Must be called by the current owner
/// @param _owner The new owner of the factory
function setOwner(address _owner) external;
/// @notice Enables a fee amount with the given tickSpacing
/// @dev Fee amounts may never be removed once enabled
/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
interface IUniswapV3Pool {
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes memory data
) external returns (int256 amount0, int256 amount1);
function token0() external returns (address);
function token1() external returns (address);
struct Slot0 {
// the current price
uint160 sqrtPriceX96;
// the current tick
int24 tick;
// the most-recently updated index of the observations array
uint16 observationIndex;
// the current maximum number of observations that are being stored
uint16 observationCardinality;
// the next maximum number of observations to store, triggered in observations.write
uint16 observationCardinalityNext;
// the current protocol fee as a percentage of the swap fee taken on withdrawal
// represented as an integer denominator (1/x)%
uint8 feeProtocol;
// whether the pool is locked
bool unlocked;
}
function slot0() external view returns (Slot0 memory slot0);
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(int24 tickLower, int24 tickUpper, uint128 amount) external returns (uint256 amount0, uint256 amount1);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {ISwapRouter} from "@zoralabs/shared-contracts/interfaces/uniswap/ISwapRouter.sol";// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
interface IAirlock {
function owner() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IProtocolRewards {
function balanceOf(address account) external view returns (uint256);
function deposit(address to, bytes4 why, string calldata comment) external payable;
function depositBatch(address[] calldata recipients, uint256[] calldata amounts, bytes4[] calldata reasons, string calldata comment) external payable;
function withdrawFor(address to, uint256 amount) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 wad) external;
function approve(address guy, uint256 wad) external returns (bool);
function transfer(address dst, uint256 wad) external returns (bool);
function transferFrom(address src, address dst, uint256 wad) external returns (bool);
function balanceOf(address guy) external view returns (uint256);
}// 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
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.20;
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {EIP712Upgradeable} from "../../../utils/cryptography/EIP712Upgradeable.sol";
import {NoncesUpgradeable} from "../../../utils/NoncesUpgradeable.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 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.
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20Permit, EIP712Upgradeable, NoncesUpgradeable {
bytes32 private constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Permit deadline has expired.
*/
error ERC2612ExpiredSignature(uint256 deadline);
/**
* @dev Mismatched signature.
*/
error ERC2612InvalidSigner(address signer, address owner);
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC-20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {}
/**
* @inheritdoc IERC20Permit
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (block.timestamp > deadline) {
revert ERC2612ExpiredSignature(deadline);
}
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
if (signer != owner) {
revert ERC2612InvalidSigner(signer, owner);
}
_approve(owner, spender, value);
}
/**
* @inheritdoc IERC20Permit
*/
function nonces(address owner) public view virtual override(IERC20Permit, NoncesUpgradeable) returns (uint256) {
return super.nonces(owner);
}
/**
* @inheritdoc IERC20Permit
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
return _domainSeparatorV4();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}// 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;
}
}// 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.0";
}
}// 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
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.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;
}
}
}// 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.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.23;
struct LpPosition {
int24 tickLower;
int24 tickUpper;
uint128 liquidity;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
/// @notice The state of the pool configuration, as a doppler configuration
struct PoolState {
/// @notice The address of the base asset
address asset;
/// @notice The address of the currency to trade the base asset for
address numeraire;
/// @notice The lower tick of the LP range set
int24 tickLower;
/// @notice The upper tick of the LP range set
int24 tickUpper;
/// @notice The number of positions in the LP range set
uint16 numPositions;
/// @notice Whether the pool is initialized (true for this implementation)
bool isInitialized;
/// @notice Whether the pool is exited to a market (false for this implementation)
bool isExited;
/// @notice The maximum share to be sold – the size of the discovery supply
uint256 maxShareToBeSold;
/// @notice The total tokens on the bonding curve
uint256 totalTokensOnBondingCurve;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {PoolConfiguration} from "../interfaces/ICoin.sol";
import {CoinDopplerUniV3} from "./CoinDopplerUniV3.sol";
import {CoinConfigurationVersions} from "./CoinConfigurationVersions.sol";
import {LpPosition} from "../types/LpPosition.sol";
import {IUniswapV3Factory} from "../interfaces/IUniswapV3Factory.sol";
import {MarketConstants} from "./MarketConstants.sol";
import {IUniswapV3Pool} from "../interfaces/IUniswapV3Pool.sol";
import {ICoin} from "../interfaces/ICoin.sol";
import {CoinCommon} from "./CoinCommon.sol";
struct UniV3Config {
address weth;
address v3Factory;
address airlock;
address swapRouter;
}
struct CoinV3Config {
address currency;
PoolConfiguration poolConfiguration;
address poolAddress;
}
library CoinSetupV3 {
/// @dev Deploys the Uniswap V3 pool and mints initial liquidity based on the pool configuration
function deployLiquidity(LpPosition[] memory positions, address poolAddress) internal {
// Calculate and mint positions
_mintPositions(positions, poolAddress);
}
/// @dev Mints the calculated liquidity positions into the Uniswap V3 pool
function _mintPositions(LpPosition[] memory lbpPositions, address poolAddress) internal {
for (uint256 i; i < lbpPositions.length; i++) {
IUniswapV3Pool(poolAddress).mint(address(this), lbpPositions[i].tickLower, lbpPositions[i].tickUpper, lbpPositions[i].liquidity, "");
}
}
/// @dev Creates the Uniswap V3 pool for the coin/currency pair
function createV3Pool(address coin, address currency, bool isCoinToken0, uint160 sqrtPriceX96, address v3Factory) internal returns (address pool) {
address token0 = isCoinToken0 ? coin : currency;
address token1 = isCoinToken0 ? currency : coin;
pool = IUniswapV3Factory(v3Factory).createPool(token0, token1, MarketConstants.LP_FEE);
// This pool should be new, if it has already been initialized
// then we will fail the creation step prompting the user to try again.
IUniswapV3Pool(pool).initialize(sqrtPriceX96);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ISwapRouter} from "../interfaces/ISwapRouter.sol";
import {IWETH} from "../interfaces/IWETH.sol";
import {MarketConstants} from "./MarketConstants.sol";
import {CoinConstants} from "./CoinConstants.sol";
import {ICoin} from "../interfaces/ICoin.sol";
import {IProtocolRewards} from "../interfaces/IProtocolRewards.sol";
import {LpPosition} from "../types/LpPosition.sol";
import {PoolConfiguration} from "../interfaces/ICoin.sol";
import {IUniswapV3Pool} from "../interfaces/IUniswapV3Pool.sol";
import {IAirlock} from "../interfaces/IAirlock.sol";
import {CoinV3Config} from "./CoinSetupV3.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {CoinDopplerUniV3} from "./CoinDopplerUniV3.sol";
import {CoinConfigurationVersions} from "./CoinConfigurationVersions.sol";
import {CoinRewards, CoinConfig} from "./CoinRewards.sol";
struct SellResult {
uint256 payoutSize;
uint256 tradeReward;
uint256 trueOrderSize;
}
library UniV3BuySell {
using SafeERC20 for IERC20;
error AddressZero();
error InvalidPoolVersion();
function handleBuy(
address recipient,
uint256 orderSize,
uint256 minAmountOut,
uint160 sqrtPriceLimitX96,
address tradeReferrer,
CoinConfig memory coinConfig,
address currency,
ISwapRouter swapRouter,
IWETH weth
) internal returns (uint256 amountOut, uint256 tradeReward, uint256 trueOrderSize) {
if (recipient == address(0)) {
revert AddressZero();
}
// Calculate the trade reward
tradeReward = _calculateReward(orderSize, CoinConstants.TOTAL_FEE_BPS);
// Calculate the remaining size
trueOrderSize = orderSize - tradeReward;
// Handle incoming currency
_handleIncomingCurrency(orderSize, trueOrderSize, currency, swapRouter, weth);
// Set up the swap parameters
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
tokenIn: currency,
tokenOut: address(this),
fee: MarketConstants.LP_FEE,
recipient: recipient,
amountIn: trueOrderSize,
amountOutMinimum: minAmountOut,
sqrtPriceLimitX96: sqrtPriceLimitX96
});
// Execute the swap
amountOut = ISwapRouter(swapRouter).exactInputSingle(params);
CoinRewards.handleTradeRewards(tradeReward, tradeReferrer, coinConfig, currency, weth);
}
function _executeSwap(
uint256 orderSize,
uint256 minAmountOut,
uint160 sqrtPriceLimitX96,
address currency,
ISwapRouter swapRouter
) internal returns (uint256 amountOut) {
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
tokenIn: address(this),
tokenOut: currency,
fee: MarketConstants.LP_FEE,
recipient: address(this),
amountIn: orderSize,
amountOutMinimum: minAmountOut,
sqrtPriceLimitX96: sqrtPriceLimitX96
});
amountOut = swapRouter.exactInputSingle(params);
}
function _handleRefund(uint256 beforeCoinBalance, uint256 orderSize, address recipient) internal returns (uint256 trueOrderSize) {
uint256 afterCoinBalance = IERC20(address(this)).balanceOf(address(this));
trueOrderSize = orderSize;
if (afterCoinBalance > beforeCoinBalance) {
uint256 coinRefund = afterCoinBalance - beforeCoinBalance;
trueOrderSize -= coinRefund;
IERC20(address(this)).safeTransfer(recipient, coinRefund);
}
}
function _handlePayoutAndRewards(
uint256 amountOut,
address recipient,
address tradeReferrer,
CoinConfig memory coinConfig,
address currency,
IWETH weth
) internal returns (uint256 payoutSize, uint256 tradeReward) {
if (currency == address(weth)) {
weth.withdraw(amountOut);
}
tradeReward = _calculateReward(amountOut, CoinConstants.TOTAL_FEE_BPS);
payoutSize = amountOut - tradeReward;
_handlePayout(payoutSize, recipient, currency, weth);
CoinRewards.handleTradeRewards(tradeReward, tradeReferrer, coinConfig, currency, weth);
}
function handleSell(
address recipient,
uint256 beforeCoinBalance,
uint256 orderSize,
uint256 minAmountOut,
uint160 sqrtPriceLimitX96,
address tradeReferrer,
CoinConfig memory coinConfig,
address currency,
ISwapRouter swapRouter,
IWETH weth
) internal returns (SellResult memory result) {
if (recipient == address(0)) {
revert AddressZero();
}
uint256 amountOut = _executeSwap(orderSize, minAmountOut, sqrtPriceLimitX96, currency, swapRouter);
result.trueOrderSize = _handleRefund(beforeCoinBalance, orderSize, recipient);
(result.payoutSize, result.tradeReward) = _handlePayoutAndRewards(amountOut, recipient, tradeReferrer, coinConfig, currency, weth);
}
/// @dev Handles incoming currency transfers for buy orders; if WETH is the currency the caller has the option to send native-ETH
/// @param orderSize The total size of the order in the currency
/// @param trueOrderSize The actual amount being used for the swap after fees
function _handleIncomingCurrency(uint256 orderSize, uint256 trueOrderSize, address currency, ISwapRouter swapRouter, IWETH weth) internal {
if (currency == address(weth) && msg.value > 0) {
if (msg.value != orderSize) {
revert ICoin.EthAmountMismatch();
}
if (msg.value < CoinConstants.MIN_ORDER_SIZE) {
revert ICoin.EthAmountTooSmall();
}
IWETH(weth).deposit{value: trueOrderSize}();
IWETH(weth).approve(address(swapRouter), trueOrderSize);
} else {
// Ensure ETH is not sent with a non-ETH pair
if (msg.value != 0) {
revert ICoin.EthTransferInvalid();
}
uint256 beforeBalance = IERC20(currency).balanceOf(address(this));
IERC20(currency).safeTransferFrom(msg.sender, address(this), orderSize);
uint256 afterBalance = IERC20(currency).balanceOf(address(this));
if ((afterBalance - beforeBalance) != orderSize) {
revert ICoin.ERC20TransferAmountMismatch();
}
IERC20(currency).approve(address(swapRouter), trueOrderSize);
}
}
/// @dev Handles sending ETH and ERC20 payouts and refunds to recipients
/// @param orderPayout The amount of currency to pay out
/// @param recipient The address to receive the payout
function _handlePayout(uint256 orderPayout, address recipient, address currency, IWETH weth) internal {
if (currency == address(weth)) {
Address.sendValue(payable(recipient), orderPayout);
} else {
IERC20(currency).safeTransfer(recipient, orderPayout);
}
}
function _collectFees(LpPosition[] storage positions, address poolAddress) internal returns (uint256 totalAmountToken0, uint256 totalAmountToken1) {
for (uint256 i; i < positions.length; i++) {
// Must burn to update the collect mapping on the pool
IUniswapV3Pool(poolAddress).burn(positions[i].tickLower, positions[i].tickUpper, 0);
(uint256 amount0, uint256 amount1) = IUniswapV3Pool(poolAddress).collect(
address(this),
positions[i].tickLower,
positions[i].tickUpper,
type(uint128).max,
type(uint128).max
);
totalAmountToken0 += amount0;
totalAmountToken1 += amount1;
}
}
/// @dev Collects and distributes accrued fees from all LP positions
function handleMarketRewards(
CoinConfig memory coinConfig,
address currency,
address poolAddress,
LpPosition[] storage positions,
IWETH weth,
address doppler
) internal returns (ICoin.MarketRewards memory rewards) {
address coin = address(this);
(uint256 totalAmountToken0, uint256 totalAmountToken1) = _collectFees(positions, poolAddress);
address token0 = currency < coin ? currency : coin;
address token1 = currency < coin ? coin : currency;
rewards = CoinRewards.transferBothRewards(token0, totalAmountToken0, token1, totalAmountToken1, coin, coinConfig, currency, weth, doppler);
emit ICoin.CoinMarketRewards(coinConfig.payoutRecipient, coinConfig.platformReferrer, coinConfig.protocolRewardRecipient, currency, rewards);
}
function _calculateReward(uint256 amount, uint256 bps) internal pure returns (uint256) {
return CoinRewards.calculateReward(amount, bps);
}
}// 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 {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.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;
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;
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;
// 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;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {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: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {IUniswapV3SwapCallback} from "./IUniswapV3SwapCallback.sol";
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// that may remain in the router after the swap.
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// that may remain in the router after the swap.
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}// 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.2.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20
struct ERC20Storage {
mapping(address account => uint256) _balances;
mapping(address account => mapping(address spender => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
function _getERC20Storage() private pure returns (ERC20Storage storage $) {
assembly {
$.slot := ERC20StorageLocation
}
}
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC20Storage storage $ = _getERC20Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
$._totalSupply += value;
} else {
uint256 fromBalance = $._balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
$._balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
$._totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
$._balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
$._allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError, bytes32) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*/
abstract contract EIP712Upgradeable is Initializable, IERC5267 {
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @custom:storage-location erc7201:openzeppelin.storage.EIP712
struct EIP712Storage {
/// @custom:oz-renamed-from _HASHED_NAME
bytes32 _hashedName;
/// @custom:oz-renamed-from _HASHED_VERSION
bytes32 _hashedVersion;
string _name;
string _version;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;
function _getEIP712Storage() private pure returns (EIP712Storage storage $) {
assembly {
$.slot := EIP712StorageLocation
}
}
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
EIP712Storage storage $ = _getEIP712Storage();
$._name = name;
$._version = version;
// Reset prior values in storage if upgrading
$._hashedName = 0;
$._hashedVersion = 0;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator();
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {IERC-5267}.
*/
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
EIP712Storage storage $ = _getEIP712Storage();
// If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
// and the EIP712 domain is not reliable, as it will be missing name and version.
require($._hashedName == 0 && $._hashedVersion == 0, "EIP712: Uninitialized");
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Name() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._name;
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Version() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._version;
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
*/
function _EIP712NameHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory name = _EIP712Name();
if (bytes(name).length > 0) {
return keccak256(bytes(name));
} else {
// If the name is empty, the contract may have been upgraded without initializing the new storage.
// We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
bytes32 hashedName = $._hashedName;
if (hashedName != 0) {
return hashedName;
} else {
return keccak256("");
}
}
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
*/
function _EIP712VersionHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory version = _EIP712Version();
if (bytes(version).length > 0) {
return keccak256(bytes(version));
} else {
// If the version is empty, the contract may have been upgraded without initializing the new storage.
// We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
bytes32 hashedVersion = $._hashedVersion;
if (hashedVersion != 0) {
return hashedVersion;
} else {
return keccak256("");
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides tracking nonces for addresses. Nonces will only increment.
*/
abstract contract NoncesUpgradeable is Initializable {
/**
* @dev The nonce used for an `account` is not the expected current nonce.
*/
error InvalidAccountNonce(address account, uint256 currentNonce);
/// @custom:storage-location erc7201:openzeppelin.storage.Nonces
struct NoncesStorage {
mapping(address account => uint256) _nonces;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Nonces")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant NoncesStorageLocation = 0x5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00;
function _getNoncesStorage() private pure returns (NoncesStorage storage $) {
assembly {
$.slot := NoncesStorageLocation
}
}
function __Nonces_init() internal onlyInitializing {
}
function __Nonces_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the next unused nonce for an address.
*/
function nonces(address owner) public view virtual returns (uint256) {
NoncesStorage storage $ = _getNoncesStorage();
return $._nonces[owner];
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256) {
NoncesStorage storage $ = _getNoncesStorage();
// For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
// decremented or reset. This guarantees that the nonce never overflows.
unchecked {
// It is important to do x++ and not ++x here.
return $._nonces[owner]++;
}
}
/**
* @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
*/
function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
uint256 current = _useNonce(owner);
if (nonce != current) {
revert InvalidAccountNonce(owner, current);
}
}
}// 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.17;
interface IVersionedContract {
function contractVersion() external pure returns (string memory);
}// 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
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.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.23;
import {TickMath} from "../utils/uniswap/TickMath.sol";
import {CoinConfigurationVersions} from "./CoinConfigurationVersions.sol";
import {ICoin} from "../interfaces/ICoin.sol";
import {LpPosition} from "../types/LpPosition.sol";
import {MarketConstants} from "./MarketConstants.sol";
import {FullMath} from "../utils/uniswap/FullMath.sol";
import {SqrtPriceMath} from "../utils/uniswap/SqrtPriceMath.sol";
import {LiquidityAmounts} from "../utils/uniswap/LiquidityAmounts.sol";
import {IDopplerErrors} from "../interfaces/IDopplerErrors.sol";
import {DopplerMath} from "./DopplerMath.sol";
import {PoolConfiguration} from "../types/PoolConfiguration.sol";
library CoinDopplerUniV3 {
function setupPool(bool isCoinToken0, bytes memory poolConfig_) internal pure returns (uint160 sqrtPriceX96, PoolConfiguration memory poolConfiguration) {
(, , int24 tickLower_, int24 tickUpper_, uint16 numDiscoveryPositions_, uint256 maxDiscoverySupplyShare_) = CoinConfigurationVersions
.decodeDopplerUniV3(poolConfig_);
require(numDiscoveryPositions_ > 1 && numDiscoveryPositions_ <= 200, IDopplerErrors.NumDiscoveryPositionsOutOfRange());
if (maxDiscoverySupplyShare_ > MarketConstants.WAD) {
revert IDopplerErrors.MaxShareToBeSoldExceeded(maxDiscoverySupplyShare_, MarketConstants.WAD);
}
uint256[] memory maxDiscoverySupplyShare = new uint256[](1);
uint16[] memory numDiscoveryPositions = new uint16[](1);
int24[] memory savedTickLower = new int24[](1);
int24[] memory savedTickUpper = new int24[](1);
maxDiscoverySupplyShare[0] = maxDiscoverySupplyShare_;
numDiscoveryPositions[0] = numDiscoveryPositions_;
savedTickLower[0] = isCoinToken0 ? tickLower_ : -tickUpper_;
savedTickUpper[0] = isCoinToken0 ? tickUpper_ : -tickLower_;
sqrtPriceX96 = TickMath.getSqrtPriceAtTick(isCoinToken0 ? savedTickLower[0] : savedTickUpper[0]);
poolConfiguration = PoolConfiguration({
version: CoinConfigurationVersions.DOPPLER_UNI_V3_POOL_VERSION,
fee: MarketConstants.LP_FEE,
tickSpacing: MarketConstants.TICK_SPACING,
tickLower: savedTickLower,
tickUpper: savedTickUpper,
numPositions: numDiscoveryPositions_ + 1, // Add one for the final tail position
maxDiscoverySupplyShare: maxDiscoverySupplyShare,
numDiscoveryPositions: numDiscoveryPositions
});
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IProtocolRewards} from "../interfaces/IProtocolRewards.sol";
import {ICoin} from "../interfaces/ICoin.sol";
import {CoinConstants} from "./CoinConstants.sol";
import {IWETH} from "../interfaces/IWETH.sol";
struct CoinConfig {
address protocolRewardRecipient;
address platformReferrer;
address payoutRecipient;
address protocolRewards;
}
library CoinRewards {
using SafeERC20 for IERC20;
/// @dev Handles sending ETH and ERC20 payouts and refunds to recipients
/// @param orderPayout The amount of currency to pay out
/// @param recipient The address to receive the payout
function handlePayout(uint256 orderPayout, address recipient, address currency, address weth) internal {
if (currency == weth) {
Address.sendValue(payable(recipient), orderPayout);
} else {
IERC20(currency).safeTransfer(recipient, orderPayout);
}
}
/// @dev Handles calculating and depositing fees to an escrow protocol rewards contract
function handleTradeRewards(uint256 totalValue, address _tradeReferrer, CoinConfig memory coinConfig, address currency, IWETH weth) internal {
address protocolRewardRecipient = coinConfig.protocolRewardRecipient;
address platformReferrer = coinConfig.platformReferrer;
address payoutRecipient = coinConfig.payoutRecipient;
IProtocolRewards protocolRewards = IProtocolRewards(coinConfig.protocolRewards);
if (_tradeReferrer == address(0)) {
_tradeReferrer = protocolRewardRecipient;
}
uint256 tokenCreatorFee = calculateReward(totalValue, CoinConstants.TOKEN_CREATOR_FEE_BPS);
uint256 platformReferrerFee = calculateReward(totalValue, CoinConstants.PLATFORM_REFERRER_FEE_BPS);
uint256 tradeReferrerFee = calculateReward(totalValue, CoinConstants.TRADE_REFERRER_FEE_BPS);
uint256 protocolFee = totalValue - tokenCreatorFee - platformReferrerFee - tradeReferrerFee;
if (currency == address(weth)) {
address[] memory recipients = new address[](4);
uint256[] memory amounts = new uint256[](4);
bytes4[] memory reasons = new bytes4[](4);
recipients[0] = payoutRecipient;
amounts[0] = tokenCreatorFee;
reasons[0] = bytes4(keccak256("COIN_CREATOR_REWARD"));
recipients[1] = platformReferrer;
amounts[1] = platformReferrerFee;
reasons[1] = bytes4(keccak256("COIN_PLATFORM_REFERRER_REWARD"));
recipients[2] = _tradeReferrer;
amounts[2] = tradeReferrerFee;
reasons[2] = bytes4(keccak256("COIN_TRADE_REFERRER_REWARD"));
recipients[3] = protocolRewardRecipient;
amounts[3] = protocolFee;
reasons[3] = bytes4(keccak256("COIN_PROTOCOL_REWARD"));
IProtocolRewards(protocolRewards).depositBatch{value: totalValue}(recipients, amounts, reasons, "");
}
if (currency != address(weth)) {
IERC20(currency).safeTransfer(payoutRecipient, tokenCreatorFee);
IERC20(currency).safeTransfer(platformReferrer, platformReferrerFee);
IERC20(currency).safeTransfer(_tradeReferrer, tradeReferrerFee);
IERC20(currency).safeTransfer(protocolRewardRecipient, protocolFee);
}
emit ICoin.CoinTradeRewards(
payoutRecipient,
platformReferrer,
_tradeReferrer,
protocolRewardRecipient,
tokenCreatorFee,
platformReferrerFee,
tradeReferrerFee,
protocolFee,
currency
);
}
function calculateReward(uint256 amount, uint256 bps) internal pure returns (uint256) {
return (amount * bps) / 10_000;
}
function transferBothRewards(
address token0,
uint256 totalAmountToken0,
address token1,
uint256 totalAmountToken1,
address coin,
CoinConfig memory coinConfig,
address currency,
IWETH weth,
address doppler
) internal returns (ICoin.MarketRewards memory rewards) {
rewards = transferMarketRewards(token0, currency, totalAmountToken0, rewards, coin, coinConfig, weth, doppler);
rewards = transferMarketRewards(token1, currency, totalAmountToken1, rewards, coin, coinConfig, weth, doppler);
}
struct Distribution {
bool isCurrency;
uint256 totalAmount;
uint256 creatorPayout;
uint256 platformReferrerPayout;
uint256 protocolPayout;
}
function transferMarketRewards(
address token,
address currency,
uint256 totalAmount,
ICoin.MarketRewards memory rewards,
address coin,
CoinConfig memory coinConfig,
IWETH weth,
address dopplerRecipient
) internal returns (ICoin.MarketRewards memory) {
address payoutRecipient = coinConfig.payoutRecipient;
address platformReferrer = coinConfig.platformReferrer;
address protocolRewardRecipient = coinConfig.protocolRewardRecipient;
address protocolRewards = coinConfig.protocolRewards;
if (totalAmount > 0) {
uint256 dopplerPayout = calculateReward(totalAmount, CoinConstants.DOPPLER_MARKET_REWARD_BPS);
uint256 creatorPayout = calculateReward(totalAmount, CoinConstants.CREATOR_MARKET_REWARD_BPS);
uint256 platformReferrerPayout = calculateReward(totalAmount, CoinConstants.PLATFORM_REFERRER_MARKET_REWARD_BPS);
uint256 protocolPayout = totalAmount - creatorPayout - platformReferrerPayout - dopplerPayout;
bool isCurrency = token == currency;
if (token == address(weth)) {
IWETH(weth).withdraw(totalAmount);
address[] memory recipients = new address[](4);
recipients[0] = payoutRecipient;
recipients[1] = platformReferrer;
recipients[2] = protocolRewardRecipient;
recipients[3] = dopplerRecipient;
uint256[] memory amounts = new uint256[](4);
amounts[0] = creatorPayout;
amounts[1] = platformReferrerPayout;
amounts[2] = protocolPayout;
amounts[3] = dopplerPayout;
bytes4[] memory reasons = new bytes4[](4);
reasons[0] = bytes4(keccak256("COIN_CREATOR_MARKET_REWARD"));
reasons[1] = bytes4(keccak256("COIN_PLATFORM_REFERRER_MARKET_REWARD"));
reasons[2] = bytes4(keccak256("COIN_PROTOCOL_MARKET_REWARD"));
reasons[3] = bytes4(keccak256("COIN_DOPPLER_MARKET_REWARD"));
IProtocolRewards(protocolRewards).depositBatch{value: totalAmount}(recipients, amounts, reasons, "");
IProtocolRewards(protocolRewards).withdrawFor(dopplerRecipient, dopplerPayout);
} else {
if (!isCurrency) {
IERC20(coin).safeTransfer(payoutRecipient, creatorPayout);
IERC20(coin).safeTransfer(platformReferrer, platformReferrerPayout);
IERC20(coin).safeTransfer(protocolRewardRecipient, protocolPayout);
IERC20(coin).safeTransfer(dopplerRecipient, dopplerPayout);
} else {
IERC20(currency).safeTransfer(payoutRecipient, creatorPayout);
IERC20(currency).safeTransfer(platformReferrer, platformReferrerPayout);
IERC20(currency).safeTransfer(protocolRewardRecipient, protocolPayout);
IERC20(currency).safeTransfer(dopplerRecipient, dopplerPayout);
}
}
if (isCurrency) {
rewards.totalAmountCurrency = totalAmount;
rewards.creatorPayoutAmountCurrency = creatorPayout;
rewards.platformReferrerAmountCurrency = platformReferrerPayout;
rewards.protocolAmountCurrency = protocolPayout;
} else {
rewards.totalAmountCoin = totalAmount;
rewards.creatorPayoutAmountCoin = creatorPayout;
rewards.platformReferrerAmountCoin = platformReferrerPayout;
rewards.protocolAmountCoin = protocolPayout;
}
}
return rewards;
}
}// 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: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.20;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}// 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: 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
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}// 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)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// 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 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
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 for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the 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.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // 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 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}{
"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":"address","name":"_protocolRewardRecipient","type":"address"},{"internalType":"address","name":"_protocolRewards","type":"address"},{"internalType":"contract IPoolManager","name":"_poolManager","type":"address"},{"internalType":"address","name":"_airlock","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AddressZero","type":"error"},{"inputs":[],"name":"AlreadyOwner","type":"error"},{"inputs":[],"name":"CannotMintZeroLiquidity","type":"error"},{"inputs":[],"name":"DopplerPoolMustHaveMoreThan2DiscoveryPositions","type":"error"},{"inputs":[],"name":"ECDSAInvalidSignature","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"ECDSAInvalidSignatureLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"ECDSAInvalidSignatureS","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[],"name":"ERC20TransferAmountMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"ERC2612ExpiredSignature","type":"error"},{"inputs":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"ERC2612InvalidSigner","type":"error"},{"inputs":[],"name":"EthAmountMismatch","type":"error"},{"inputs":[],"name":"EthAmountTooSmall","type":"error"},{"inputs":[],"name":"EthTransferFailed","type":"error"},{"inputs":[],"name":"EthTransferInvalid","type":"error"},{"inputs":[],"name":"InitialOrderSizeTooLarge","type":"error"},{"inputs":[],"name":"InsufficientFunds","type":"error"},{"inputs":[],"name":"InsufficientLiquidity","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"currentNonce","type":"uint256"}],"name":"InvalidAccountNonce","type":"error"},{"inputs":[],"name":"InvalidCurrency","type":"error"},{"inputs":[],"name":"InvalidCurrencyLowerTick","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"InvalidMarketType","type":"error"},{"inputs":[],"name":"InvalidPoolVersion","type":"error"},{"inputs":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"}],"name":"InvalidTickRangeMisordered","type":"error"},{"inputs":[],"name":"InvalidWethLowerTick","type":"error"},{"inputs":[],"name":"LegacyPoolMustHaveOneDiscoveryPosition","type":"error"},{"inputs":[],"name":"MarketAlreadyGraduated","type":"error"},{"inputs":[],"name":"MarketNotGraduated","type":"error"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"MaxShareToBeSoldExceeded","type":"error"},{"inputs":[],"name":"NameIsRequired","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"NotOwner","type":"error"},{"inputs":[],"name":"NumDiscoveryPositionsOutOfRange","type":"error"},{"inputs":[],"name":"OneOwnerRequired","type":"error"},{"inputs":[],"name":"OnlyOwner","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"pool","type":"address"}],"name":"OnlyPool","type":"error"},{"inputs":[],"name":"OnlyWeth","type":"error"},{"inputs":[],"name":"OwnerCannotBeAddressZero","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[],"name":"SlippageBoundsExceeded","type":"error"},{"inputs":[],"name":"UseRevokeOwnershipToRemoveSelf","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"buyer","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":true,"internalType":"address","name":"tradeReferrer","type":"address"},{"indexed":false,"internalType":"uint256","name":"coinsPurchased","type":"uint256"},{"indexed":false,"internalType":"address","name":"currency","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountSold","type":"uint256"}],"name":"CoinBuy","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"payoutRecipient","type":"address"},{"indexed":true,"internalType":"address","name":"platformReferrer","type":"address"},{"indexed":false,"internalType":"address","name":"protocolRewardRecipient","type":"address"},{"indexed":false,"internalType":"address","name":"currency","type":"address"},{"components":[{"internalType":"uint256","name":"totalAmountCurrency","type":"uint256"},{"internalType":"uint256","name":"totalAmountCoin","type":"uint256"},{"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":"protocolAmountCurrency","type":"uint256"},{"internalType":"uint256","name":"protocolAmountCoin","type":"uint256"}],"indexed":false,"internalType":"struct ICoin.MarketRewards","name":"marketRewards","type":"tuple"}],"name":"CoinMarketRewards","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"prevRecipient","type":"address"},{"indexed":true,"internalType":"address","name":"newRecipient","type":"address"}],"name":"CoinPayoutRecipientUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"seller","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":true,"internalType":"address","name":"tradeReferrer","type":"address"},{"indexed":false,"internalType":"uint256","name":"coinsSold","type":"uint256"},{"indexed":false,"internalType":"address","name":"currency","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountPurchased","type":"uint256"}],"name":"CoinSell","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"payoutRecipient","type":"address"},{"indexed":true,"internalType":"address","name":"platformReferrer","type":"address"},{"indexed":true,"internalType":"address","name":"tradeReferrer","type":"address"},{"indexed":false,"internalType":"address","name":"protocolRewardRecipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"creatorReward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"platformReferrerReward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"traderReferrerReward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"protocolReward","type":"uint256"},{"indexed":false,"internalType":"address","name":"currency","type":"address"}],"name":"CoinTradeRewards","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"senderBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"recipientBalance","type":"uint256"}],"name":"CoinTransfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":false,"internalType":"string","name":"newURI","type":"string"},{"indexed":false,"internalType":"string","name":"name","type":"string"}],"name":"ContractMetadataUpdated","type":"event"},{"anonymous":false,"inputs":[],"name":"ContractURIUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"claimAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalClaimed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"vestingStartTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"vestingEndTime","type":"uint256"}],"name":"CreatorVestingClaimed","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"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"}],"indexed":false,"internalType":"struct PoolKey","name":"fromPoolKey","type":"tuple"},{"indexed":false,"internalType":"bytes32","name":"fromPoolKeyHash","type":"bytes32"},{"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":"toPoolKey","type":"tuple"},{"indexed":false,"internalType":"bytes32","name":"toPoolKeyHash","type":"bytes32"}],"name":"LiquidityMigrated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":false,"internalType":"string","name":"newName","type":"string"},{"indexed":false,"internalType":"string","name":"newSymbol","type":"string"}],"name":"NameAndSymbolUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"prevOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"addOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"accounts","type":"address[]"}],"name":"addOwners","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"airlock","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimVesting","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"contractURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"contractVersion","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"currency","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dopplerFeeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getClaimableAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IDeployedCoinVersionLookup","name":"coinVersionLookup","type":"address"}],"name":"getPayoutSwapPath","outputs":[{"components":[{"components":[{"internalType":"Currency","name":"intermediateCurrency","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"internalType":"struct PathKey[]","name":"path","type":"tuple[]"},{"internalType":"Currency","name":"currencyIn","type":"address"}],"internalType":"struct IHasSwapPath.PayoutSwapPath","name":"payoutSwapPath","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPoolConfiguration","outputs":[{"components":[{"internalType":"uint8","name":"version","type":"uint8"},{"internalType":"uint16","name":"numPositions","type":"uint16"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"uint16[]","name":"numDiscoveryPositions","type":"uint16[]"},{"internalType":"int24[]","name":"tickLower","type":"int24[]"},{"internalType":"int24[]","name":"tickUpper","type":"int24[]"},{"internalType":"uint256[]","name":"maxDiscoverySupplyShare","type":"uint256[]"}],"internalType":"struct PoolConfiguration","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPoolKey","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":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"hooks","outputs":[{"internalType":"contract IHooks","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"payoutRecipient_","type":"address"},{"internalType":"address[]","name":"owners_","type":"address[]"},{"internalType":"string","name":"tokenURI_","type":"string"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"address","name":"platformReferrer_","type":"address"},{"internalType":"address","name":"currency_","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":"uint160","name":"sqrtPriceX96","type":"uint160"},{"components":[{"internalType":"uint8","name":"version","type":"uint8"},{"internalType":"uint16","name":"numPositions","type":"uint16"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"uint16[]","name":"numDiscoveryPositions","type":"uint16[]"},{"internalType":"int24[]","name":"tickLower","type":"int24[]"},{"internalType":"int24[]","name":"tickUpper","type":"int24[]"},{"internalType":"uint256[]","name":"maxDiscoverySupplyShare","type":"uint256[]"}],"internalType":"struct PoolConfiguration","name":"poolConfiguration_","type":"tuple"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"isOwner","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newHook","type":"address"},{"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":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owners","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"payoutRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"platformReferrer","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolRewardRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolRewards","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"removeOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"accounts","type":"address[]"}],"name":"removeOwners","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"revokeOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"newURI","type":"string"}],"name":"setContractURI","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"newName","type":"string"},{"internalType":"string","name":"newSymbol","type":"string"}],"name":"setNameAndSymbol","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newPayoutRecipient","type":"address"}],"name":"setPayoutRecipient","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalClaimed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"vestingEndTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"vestingStartTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]Contract Creation Code
6101003461031457601f614dea38819003918201601f19168301916001600160401b0383118484101761031857808492608094604052833981010312610314576100488161032c565b906100556020820161032c565b6040820151926001600160a01b0384169290919083850361031457606061007c910161032c565b5f516020614dca5f395f51905f5254604081901c60ff161593919291906001600160401b0381168015908161030c575b6001149081610302575b1590816102f9575b5061024f576001600160401b031981166001175f516020614dca5f395f51905f5255846102cf575b506001600160a01b03811615610279576001600160a01b03821615610279576001600160a01b038316156102795760a05260805260c052610288575b156102795760e0525f516020614dca5f395f51905f5254604081901c60ff1615906001600160401b03811680159081610271575b6001149081610267575b15908161025e575b5061024f576001600160401b031981166001175f516020614dca5f395f51905f525581610225575b506101de575b604051614a6990816103418239608051816130c6015260a0518181816102a30152610f32015260c05181818161025e0152612f84015260e0518181816110c101526119390152f35b68ff0000000000000000195f516020614dca5f395f51905f5254165f516020614dca5f395f51905f52555f516020614daa5f395f51905f52602060405160018152a1610196565b6001600160481b03191668010000000000000001175f516020614dca5f395f51905f52555f610190565b63f92ee8a960e01b5f5260045ffd5b9050155f610168565b303b159150610160565b839150610156565b639fabe1c160e01b5f5260045ffd5b68ff0000000000000000195f516020614dca5f395f51905f5254165f516020614dca5f395f51905f52555f516020614daa5f395f51905f52602060405160018152a1610122565b6001600160481b03191668010000000000000001175f516020614dca5f395f51905f52555f6100e6565b9050155f6100be565b303b1591506100b6565b8691506100ac565b5f80fd5b634e487b7160e01b5f52604160045260245ffd5b51906001600160a01b03821682036103145756fe6080806040526004361015610012575f80fd5b5f905f3560e01c90816301ffc9a7146132ba5750806306fdde031461329f578063095ea7b314613279578063173825d9146131f657806318160ddd146131cd57806323b872dd146130f557806329df6479146130b15780632b968958146130675780632f54bf6e14613025578063313ce5671461300a578063346a21dc14612f5f5780633644e51514612f455780633c130d9014612f2a5780633fb80b1514612f0257806342966c6814612dd957806346bb595414612d9d57806351845bf614612d755780635a44621514612d03578063683e76e014612ce05780636c46a2c514612c175780637065cb4814612b9d57806370a0823114612b595780637a3b5a23146128a75780637ecebe001461285157806384b0196e1461273257806386fab45e14612715578063938e3d7b146126c257806395d89b411461260b578063a0a8e460146125c4578063a8660a78146125a7578063a9059cbb14612576578063a9a5e3af14612478578063affe39c1146123bb578063b80945e914611b2b578063c354bd6e14611b11578063cd7033c414611ae9578063d505accf14611985578063d54ad2a114611968578063dc4c90d314611924578063dd0371d514610675578063dd62ed3e1461062d578063e5a6b10f14610604578063e8a3d485146105d0578063f3ffe14b146102d2578063f53eab8e1461028d578063f78a8a3e146102485763fedda89c14610223575f80fd5b34610245578060031936011261024557602061023d613a00565b604051908152f35b80fd5b50346102455780600319360112610245576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102455780600319360112610245576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b5034610245576020366003190112610245576004356001600160a01b03811681036105cc5760405161030381613446565b606081523060208201908152600554600954600a5460405193956001600160a01b0393841693610378939192169061033a8661340f565b84865262ffffff8160a01c16602087015260b81c60020b6040860152606085015260209260405161036b8582613461565b8881526080860152614035565b80519092901561053a578251600101908160011161052657610399826136f9565b916103a76040519384613461565b8083526103b6601f19916136f9565b0183885b8281106104f157505050906103db918186526103d5826138f4565b526138f4565b50845b8251811015610434576103f18184613915565b5184516001830191828411610420579181600194936104138361041995613915565b52613915565b50016103de565b634e487b7160e01b89526011600452602489fd5b5091939290505b60405192828452606084019451926040818601528351809652608085018160808860051b880101950192905b8782106104845784516001600160a01b0316604088015286860387f35b9091929483806104e3600193607f198b820301865260a060808b518780841b03815116845262ffffff868201511686850152604081015160020b60408501528780841b0360608201511660608501520151918160808201520190613387565b970192019201909291610467565b6040516104fd8161340f565b8a81528a838201528a60408201528a6060820152606060808201528282870101520184906103ba565b634e487b7160e01b87526011600452602487fd5b604051939591949193919250602085016105548184613461565b60018352601f190185855b828110610583575050509061057a918187526103d5826138f4565b5091909161043b565b60405161058f8161340f565b87815287838201528760408201528760608201526060608082015282828701015201869061055f565b634e487b7160e01b5f52604160045260245ffd5b5080fd5b50346102455780600319360112610245576106006105ec613526565b604051918291602083526020830190613387565b0390f35b50346102455780600319360112610245576005546040516001600160a01b039091168152602090f35b5034610245576040366003190112610245576106476133ab565b6106586106526133c1565b91613929565b9060018060a01b03165f52602052602060405f2054604051908152f35b346111b0576101c03660031901126111b05761068f6133ab565b6024356001600160401b0381116111b0576106ae903690600401613710565b906044356001600160401b0381116111b0576106ce903690600401613670565b6064356001600160401b0381116111b0576106ed903690600401613670565b906084356001600160401b0381116111b05761070d903690600401613670565b9060a435906001600160a01b03821682036111b05760c435936001600160a01b03851685036111b05760a03660e31901126111b0576040519361074f8561340f565b60e4356001600160a01b03811681036111b0578552610104356001600160a01b03811681036111b05760208601526101243562ffffff811681036111b0576040860152610144358060020b81036111b0576060860152610164356001600160a01b03811681036111b057608086015261018435956001600160a01b03871687036111b0576101a435906001600160401b0382116111b05761010060031983360301126111b057604051916108028361342a565b806004013560ff811681036111b057835261081f602482016137f5565b6020840152604481013562ffffff811681036111b0576040840152610846606482016137e7565b606084015260848101356001600160401b0381116111b0578101366023820112156111b05760048101359061087a826136f9565b916108886040519384613461565b808352602060048185019260051b84010101913683116111b057602401905b82821061190c57505050608084015260a48101356001600160401b0381116111b0576108d99060043691840101613804565b60a084015260c48101356001600160401b0381116111b0576109019060043691840101613804565b60c084015260e4810135906001600160401b0382116111b05701366023820112156111b057600481013590610935826136f9565b916109436040519384613461565b808352602060048185019260051b84010101913683116111b057602401905b8282106118fc5750505060e0830152731111111111166b7fe7bd91427724b487980afc68196001600160a01b038216016118ed575f5160206149f45f395f51905f5254966001600160401b038816801590816118dd575b60011490816118d3575b1590816118ca575b506118bb57610a919160016001600160401b03198a16175f5160206149f45f395f51905f525560ff8960401c161561188f575b600580546001600160a01b03199081166001600160a01b03938416179091558251600880548316918416919091179055602083015160098054604086015160608701516001600160d01b03199092169386169390931760a09390931b62ffffff60a01b169290921762ffffff60b81b60b89390931b92909216919091179055608090920151600a80549093169116179055565b60ff815116600b5462ffff00602084015160081b1665ffffff000000604085015160181b1691606085015160301b68ffffff000000000000169368ffffff000000000000199165ffffffffffff19161716171717600b5560808101518051906001600160401b0382116105b857600160401b82116105b857602090600c5483600c55808410611839575b500190600c5f5260205f208160041c915f5b8381106117f95750600f1981169003806117ac575b5050505060a08101518051906001600160401b0382116105b857600160401b82116105b857602090600d5483600d5580841061177a575b500190600d5f5260205f20600a8204915f5b8381106117305750600a83029003806116e2575b5050505060c08101518051906001600160401b0382116105b857600160401b82116105b857602090600e5483600e5580841061168e575b500190600e5f5260205f20600a8204915f5b8381106116445750600a83029003806115f5575b5050505060e001518051906001600160401b0382116105b857600160401b82116105b857602090600f5483600f558084106115d9575b5001600f5f5260205f205f5b8381106115c557505050506001600160a01b038716156115b657610c6191613b42565b602094604051610c718782613461565b5f815260405190610c828883613461565b5f8252610c8d614888565b610c95614888565b8051906001600160401b0382116105b8578190610cbf5f5160206148d45f395f51905f52546133d7565b601f811161157b575b508990601f83116001146114fd575f926114f2575b50508160011b915f199060031b1c1916175f5160206148d45f395f51905f52555b8051906001600160401b0382116105b8578190610d285f5160206149345f395f51905f52546133d7565b601f81116114b7575b508890601f8311600114611439575f9261142e575b50508160011b915f199060031b1c1916175f5160206149345f395f51905f52555b60405196610d758789613461565b5f8852610d80614888565b604097885190610d908a83613461565b60018252603160f81b89830152610da5614888565b8051906001600160401b0382116105b8578190610dcf5f5160206149145f395f51905f52546133d7565b8b601f82116113f2575b50508a90601f8311600114611374575f92611369575b50508160011b915f199060031b1c1916175f5160206149145f395f51905f52555b8051906001600160401b0382116105b8578190610e3a5f5160206149745f395f51905f52546133d7565b601f8111611323575b508990601f83116001146112a5575f9261129a575b50508160011b915f199060031b1c1916175f5160206149745f395f51905f52555b5f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100555f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10155610ec7614888565b8051801561128b575f5b8181106111dd5750505090610f1c610f2192610eeb614888565b610ef3614888565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0055613ab5565b613e50565b6001600160a01b0381166111d857507f00000000000000000000000000000000000000000000000000000000000000005b60018060a01b03166001600160601b0360a01b600454161760045530156111c5575f5160206149545f395f51905f52546b033b2e3c9fd0803ce80000008101809111611115575f5160206149545f395f51905f5255305f525f5160206148f45f395f51905f528352835f206b033b2e3c9fd0803ce8000000815401905583516b033b2e3c9fd0803ce800000081525f7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef853093a35f80525f5160206148f45f395f51905f528352835f2054305f525f5160206148f45f395f51905f528452845f20548551916b033b2e3c9fd0803ce8000000835285830152858201525f5f516020614a145f395f51905f5260603093a3600a546001600160a01b031680156111c5576b019d971e4fe8401e7400000061108b91306143c2565b835163313b65df60e11b8152916110a46004840161397f565b6001600160a01b0390811660a48401528390839060c49082905f907f0000000000000000000000000000000000000000000000000000000000000000165af180156111bb57611182575b60ff915060401c1615611129575b5050426010556309660180420180421161111557601155005b634e487b7160e01b5f52601160045260245ffd5b7fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29168ff0000000000000000195f5160206149f45f395f51905f5254165f5160206149f45f395f51905f52555160018152a180806110fc565b8282813d83116111b4575b6111978183613461565b810103126111b0576111aa60ff92613971565b506110ee565b5f80fd5b503d61118d565b84513d5f823e3d90fd5b63ec442f0560e01b5f525f60045260245ffd5b610f52565b6001600160a01b036111ef8285613915565b51161561127c5761121e6001600160a01b0361120b8386613915565b51165f52600160205260405f2054151590565b61126d576001906112416001600160a01b0361123a8387613915565b511661459d565b50818060a01b036112528286613915565b51165f335f5160206149d45f395f51905f528280a401610ed1565b63600acf0760e11b5f5260045ffd5b630fc033dd60e41b5f5260045ffd5b63378a1ae160e11b5f5260045ffd5b015190508a80610e58565b5f5160206149745f395f51905f525f9081528b81209350601f198516905b8c82821061130d5750509084600195949392106112f5575b505050811b015f5160206149745f395f51905f5255610e79565b01515f1960f88460031b161c191690558a80806112db565b60018596829396860151815501950193016112c3565b611359905f5160206149745f395f51905f525f528b5f20601f850160051c8101918d861061135f575b601f0160051c0190613b07565b8b610e43565b909150819061134c565b015190508b80610def565b5f5160206149145f395f51905f525f9081528c81209350601f198516905b8d8282106113dc5750509084600195949392106113c4575b505050811b015f5160206149145f395f51905f5255610e10565b01515f1960f88460031b161c191690558b80806113aa565b6001859682939686015181550195019301611392565b611427915f5160206149145f395f51905f525f52815f2090601f860160051c820192861061135f57601f0160051c0190613b07565b8c8b610dd9565b015190508980610d46565b5f5160206149345f395f51905f525f9081528a81209350601f198516905b8b8282106114a1575050908460019594939210611489575b505050811b015f5160206149345f395f51905f5255610d67565b01515f1960f88460031b161c1916905589808061146f565b6001859682939686015181550195019301611457565b6114ec905f5160206149345f395f51905f525f528a5f20601f850160051c8101918c861061135f57601f0160051c0190613b07565b8a610d31565b015190508a80610cdd565b5f5160206148d45f395f51905f525f9081528b81209350601f198516905b8c82821061156557505090846001959493921061154d575b505050811b015f5160206148d45f395f51905f5255610cfe565b01515f1960f88460031b161c191690558a8080611533565b600185968293968601518155019501930161151b565b6115b0905f5160206148d45f395f51905f525f528b5f20601f850160051c8101918d861061135f57601f0160051c0190613b07565b8b610cc8565b639fabe1c160e01b5f5260045ffd5b600190602084519401938184015501610c3e565b6115ef90600f5f5284845f209182019101613b07565b8b610c32565b925f935f5b81811061161057505050015560e08a8080610bfc565b909194602061163a600192885160020b908560030262ffffff809160031b9316831b921b19161790565b96019291016115fa565b5f5f5b600a811061165c575083820155600101610be8565b95906020611685600192845160020b908a60030262ffffff809160031b9316831b921b19161790565b92019601611647565b6116bb90600e5f52835f20600a600981818901048301936003838a0602806116c1575b5001040190613b07565b8c610bd6565b6116dc905f198701908154905f199060200360031b1c169055565b5f6116b1565b925f935f5b8181106116fc57505050015589808080610b9f565b9091946020611726600192885160020b908560030262ffffff809160031b9316831b921b19161790565b96019291016116e7565b5f5f5b600a8110611748575083820155600101610b8b565b95906020611771600192845160020b908a60030262ffffff809160031b9316831b921b19161790565b92019601611733565b6117a690600d5f52835f20600a600981818901048301936003838a0602806116c1575001040190613b07565b8c610b79565b925f935f5b8181106117c657505050015589808080610b42565b90919460206117ef60019261ffff8951169085851b61ffff809160031b9316831b921b19161790565b96019291016117b1565b5f5f5b60108110611811575083820155600101610b2d565b865190969160019160209161ffff60048b901b81811b199092169216901b17920196016117fc565b61186890600c5f52835f20600f80870160041c820192601e8860011b168061186e575b500160041c0190613b07565b8c610b1b565b611889905f198601908154905f199060200360031b1c169055565b5f61185c565b68ffffffffffffffffff19891668010000000000000001175f5160206149f45f395f51905f52556109fe565b63f92ee8a960e01b5f5260045ffd5b9050158c6109cb565b303b1591506109c3565b60408a901c60ff161591506109b9565b631eb3268560e31b5f5260045ffd5b8135815260209182019101610962565b60208091611919846137f5565b8152019101906108a7565b346111b0575f3660031901126111b0576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b346111b0575f3660031901126111b0576020601254604051908152f35b346111b05760e03660031901126111b05761199e6133ab565b6119a66133c1565b604435906064359260843560ff811681036111b057844211611ad657611a99611aa29160018060a01b03841696875f527f5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb0060205260405f20908154916001830190556040519060208201927f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c984528a604084015260018060a01b038916606084015289608084015260a083015260c082015260c08152611a6760e082613461565b519020611a7261453c565b906040519161190160f01b83526002830152602282015260c43591604260a43592206145e9565b9092919261466b565b6001600160a01b0316848103611abf5750611abd935061427b565b005b84906325c0072360e11b5f5260045260245260445ffd5b8463313c898160e11b5f5260045260245ffd5b346111b0575f3660031901126111b057600a546040516001600160a01b039091168152602090f35b346111b0575f3660031901126111b057602061023d6139cd565b346111b0575f3660031901126111b057606060e0604051611b4b8161342a565b5f81525f60208201525f60408201525f838201528260808201528260a08201528260c08201520152604051611b7f8161342a565b600b5460ff81168252602082019061ffff8160081c168252604083019062ffffff8160181c168252606084019060301c60020b815260405180816020600c549283815201600c5f5260205f20925f905b80600f8301106122d357611c659454918181106122be575b8181106122a6575b81811061228f575b818110612277575b81811061225f575b818110612247575b81811061222f575b818110612217575b8181106121ff575b8181106121e7575b8181106121cf575b8181106121b7575b81811061219f575b818110612187575b81811061216f575b10612161575b500382613461565b6080850190815260405190600d548083528260208101600d5f5260205f20925f905b8060098301106120d257611ced9454918181106120be575b8181106120a7575b818110612090575b818110612079575b818110612062575b81811061204b575b818110612034575b81811061201d575b818110612006575b10611ff5575b500383613461565b60a0860191825260405192600e548085528460208101600e5f5260205f20925f905b806009830110611f6657611d75945491818110611f52575b818110611f3b575b818110611f24575b818110611f0d575b818110611ef6575b818110611edf575b818110611ec8575b818110611eb1575b818110611e9a575b10611e89575b500385613461565b60c08701938452604051948580966020600f54918281520190600f5f5260205f20905f5b818110611e705750505062ffffff9291611db4910388613461565b60e0890196875261ffff6040519860208a5260ff6101208b019b511660208b015251166040890152511660608701525160020b6080860152519461010060a08601528551809152602061014086019601905f5b818110611e5657868061060088611e4289611e2f8e8b51601f198883030160c08901526137b1565b9051858203601f190160e08701526137b1565b9051838203601f190161010085015261377e565b825161ffff16885260209788019790920191600101611e07565b825484528a945060209093019260019283019201611d99565b60d81c60020b81526020018a611d6d565b9260206001918460c01c60020b8152019301611d67565b9260206001918460a81c60020b8152019301611d5f565b9260206001918460901c60020b8152019301611d57565b9260206001918460781c60020b8152019301611d4f565b9260206001918460601c60020b8152019301611d47565b9260206001918460481c60020b8152019301611d3f565b9260206001918460301c60020b8152019301611d37565b9260206001918460181c60020b8152019301611d2f565b9260206001918460020b8152019301611d27565b91600a91935061014060019186548060020b82528060181c60020b60208301528060301c60020b60408301528060481c60020b60608301528060601c60020b60808301528060781c60020b60a08301528060901c60020b60c08301528060a81c60020b60e08301528060c01c60020b61010083015260d81c60020b610120820152019401920187929391611d0f565b60d81c60020b815260200189611ce5565b9260206001918460c01c60020b8152019301611cdf565b9260206001918460a81c60020b8152019301611cd7565b9260206001918460901c60020b8152019301611ccf565b9260206001918460781c60020b8152019301611cc7565b9260206001918460601c60020b8152019301611cbf565b9260206001918460481c60020b8152019301611cb7565b9260206001918460301c60020b8152019301611caf565b9260206001918460181c60020b8152019301611ca7565b9260206001918460020b8152019301611c9f565b91600a91935061014060019186548060020b82528060181c60020b60208301528060301c60020b60408301528060481c60020b60608301528060601c60020b60808301528060781c60020b60a08301528060901c60020b60c08301528060a81c60020b60e08301528060c01c60020b61010083015260d81c60020b610120820152019401920185929391611c87565b60f01c815260200188611c5d565b92602060019161ffff8560e01c168152019301611c57565b92602060019161ffff8560d01c168152019301611c4f565b92602060019161ffff8560c01c168152019301611c47565b92602060019161ffff8560b01c168152019301611c3f565b92602060019161ffff8560a01c168152019301611c37565b92602060019161ffff8560901c168152019301611c2f565b92602060019161ffff8560801c168152019301611c27565b92602060019161ffff8560701c168152019301611c1f565b92602060019161ffff8560601c168152019301611c17565b92602060019161ffff8560501c168152019301611c0f565b92602060019161ffff8560401c168152019301611c07565b92602060019161ffff8560301c168152019301611bff565b92602060019161ffff85831c168152019301611bf7565b92602060019161ffff8560101c168152019301611bef565b92602060019161ffff85168152019301611be7565b916010919350610200600191865461ffff8116825261ffff81861c16602083015261ffff8160201c16604083015261ffff8160301c16606083015261ffff8160401c16608083015261ffff8160501c1660a083015261ffff8160601c1660c083015261ffff8160701c1660e083015261ffff8160801c1661010083015261ffff8160901c1661012083015261ffff8160a01c1661014083015261ffff8160b01c1661016083015261ffff8160c01c1661018083015261ffff8160d01c166101a083015261ffff8160e01c166101c083015260f01c6101e0820152019401920184929391611bcf565b346111b0575f3660031901126111b0576040518060205f54928381520180925f80527f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563905f5b8181106124625750505081612417910382613461565b604051918291602083019060208452518091526040830191905f5b818110612440575050500390f35b82516001600160a01b0316845285945060209384019390920191600101612432565b8254845260209093019260019283019201612401565b346111b05760203660031901126111b0576004356001600160401b0381116111b0576124a8903690600401613710565b6124bd335f52600160205260405f2054151590565b15612567575f5b8151811015611abd576001600160a01b036124df8284613915565b5116906124f7335f52600160205260405f2054151590565b1561256757811561127c573382146125585761251e825f52600160205260405f2054151590565b15612549575f826125306001946142f3565b50335f5160206149d45f395f51905f528380a4016124c4565b6330cd747160e01b5f5260045ffd5b637c22c4dd60e01b5f5260045ffd5b635fc483c560e01b5f5260045ffd5b346111b05760403660031901126111b05761259c6125926133ab565b6024359033613a8c565b602060405160018152f35b346111b0575f3660031901126111b0576020601054604051908152f35b346111b0575f3660031901126111b0576106006040516125e5604082613461565b60058152640312e312e360dc1b6020820152604051918291602083526020830190613387565b346111b0575f3660031901126111b0576040515f60075461262b816133d7565b808452906001811690811561269e5750600114612653575b610600836105ec81850382613461565b60075f9081525f5160206149945f395f51905f52939250905b808210612684575090915081016020016105ec612643565b91926001816020925483858801015201910190929161266c565b60ff191660208086019190915291151560051b840190910191506105ec9050612643565b346111b05760203660031901126111b0576004356001600160401b0381116111b0576126f2903690600401613670565b612707335f52600160205260405f2054151590565b1561256757611abd90613e50565b346111b0575f3660031901126111b0576020601154604051908152f35b346111b0575f3660031901126111b0577fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100541580612828575b156127eb576127bd61277b613e2e565b6106006127866135a8565b6127cb60405191612798602084613461565b5f83525f368137604051958695600f60f81b875260e0602088015260e0870190613387565b908582036040870152613387565b904660608501523060808501525f60a085015283820360c085015261377e565b60405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b6044820152606490fd5b507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d101541561276b565b346111b05760203660031901126111b05761286a6133ab565b60018060a01b03165f527f5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00602052602060405f2054604051908152f35b346111b05760403660031901126111b0576128c06133ab565b602435906001600160401b0382116111b057366023830112156111b0578160040135916001600160401b0383116111b05736602484830101116111b05761290561387d565b5061291b335f52600160205260405f2054151590565b1561256757600a54604051634a862f6360e01b81526001600160a01b0393841660048201529360a093859392169183915f91610104918491819060249061296385830161397f565b60e060c48601528260e486015201848401378181018301849052601f01601f191681010301925af18015612b4e575f90612ac1575b60a0907f907fbdc07b1c9a591dc1287635b072fa848f4da7c86645dfc9b8bfb3b94f82ab6101806129cf6129ca6138a7565b613e08565b6129d884613e08565b604051916129e58361397f565b868301526129f660c08301866136b6565b610160820152a1612a26600180841b0382511660018060a01b03166001600160601b0360a01b6008541617600855565b612a52600180841b0360208301511660018060a01b03166001600160601b0360a01b6009541617600955565b6040810151600954606083015160b81b62ffffff60b81b169162ffffff851b90851b169065ffffffffffff851b19161717600955612ab2600180841b0360808301511660018060a01b03166001600160601b0360a01b600a541617600a55565b612abf60405180926136b6565bf35b5060a0813d60a011612b46575b81612adb60a09383613461565b810103126111b05760a090612b3c608060405192612af88461340f565b612b0181613869565b8452612b0f60208201613869565b6020850152612b2060408201613961565b6040850152612b3160608201613971565b606085015201613869565b6080820152612998565b3d9150612ace565b6040513d5f823e3d90fd5b346111b05760203660031901126111b0576001600160a01b03612b7a6133ab565b165f525f5160206148f45f395f51905f52602052602060405f2054604051908152f35b346111b05760203660031901126111b057612bb66133ab565b612bcb335f52600160205260405f2054151590565b15612567576001600160a01b0316801561127c57612bf4815f52600160205260405f2054151590565b61126d57612c018161459d565b505f335f5160206149d45f395f51905f528280a4005b346111b05760203660031901126111b0576004356001600160401b0381116111b057612c47903690600401613710565b612c5c335f52600160205260405f2054151590565b15612567575f5b8151811015611abd576001600160a01b03612c7e8284613915565b511690612c96335f52600160205260405f2054151590565b1561256757811561127c57612cb6825f52600160205260405f2054151590565b61126d5781612cc660019361459d565b505f335f5160206149d45f395f51905f528280a401612c63565b346111b0575f3660031901126111b057612cf861387d565b5060a0612ab26138a7565b346111b05760403660031901126111b0576004356001600160401b0381116111b057612d33903690600401613670565b6024356001600160401b0381116111b057612d52903690600401613670565b612d67335f52600160205260405f2054151590565b1561256757611abd91613b42565b346111b0575f3660031901126111b0576004546040516001600160a01b039091168152602090f35b346111b05760203660031901126111b057612db66133ab565b612dcb335f52600160205260405f2054151590565b1561256757611abd90613ab5565b346111b05760203660031901126111b0576004353315612eef57335f525f5160206148f45f395f51905f5260205260405f2054818110612ed65790805f923384525f5160206148f45f395f51905f52602052036040832055805f5160206149545f395f51905f5254035f5160206149545f395f51905f5255816040518281527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60203392a33382525f5160206148f45f395f51905f5260205260408220548280525f5160206148f45f395f51905f52602052604083205490604051928352602083015260408201525f516020614a145f395f51905f5260603392a3005b63391434e360e21b5f523360045260245260445260645ffd5b634b637e8f60e11b5f525f60045260245ffd5b346111b0575f3660031901126111b0576003546040516001600160a01b039091168152602090f35b346111b0575f3660031901126111b0576106006105ec613526565b346111b0575f3660031901126111b057602061023d61453c565b346111b0575f3660031901126111b057604051638da5cb5b60e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa8015612b4e575f90612fd0575b6040516001600160a01b039091168152602090f35b506020813d602011613002575b81612fea60209383613461565b810103126111b057612ffd602091613869565b612fbb565b3d9150612fdd565b346111b0575f3660031901126111b057602060405160128152f35b346111b05760203660031901126111b057602061305d6001600160a01b0361304b6133ab565b165f52600160205260405f2054151590565b6040519015158152f35b346111b0575f3660031901126111b05761308c335f52600160205260405f2054151590565b156125675761309a336142f3565b505f33335f5160206149d45f395f51905f528380a4005b346111b0575f3660031901126111b0576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b346111b05760603660031901126111b05761310e6133ab565b6131166133c1565b6044359061312383613929565b335f9081526020919091526040902054925f198410613147575b61259c9350613a8c565b8284106131b2576001600160a01b0381161561319f57331561318c5761259c9361317082613929565b60018060a01b0333165f526020528360405f209103905561313d565b634a1406b160e11b5f525f60045260245ffd5b63e602df0560e01b5f525f60045260245ffd5b8284637dc7a0d960e11b5f523360045260245260445260645ffd5b346111b0575f3660031901126111b05760205f5160206149545f395f51905f5254604051908152f35b346111b05760203660031901126111b05761320f6133ab565b613224335f52600160205260405f2054151590565b15612567576001600160a01b0316801561127c5733811461255857613254815f52600160205260405f2054151590565b1561254957806132645f926142f3565b50335f5160206149d45f395f51905f528380a4005b346111b05760403660031901126111b05761259c6132956133ab565b602435903361427b565b346111b0575f3660031901126111b0576106006105ec613482565b346111b05760203660031901126111b0576004359063ffffffff60e01b82168092036111b057602091630341f3b760e51b8114908115613376575b8115613303575b5015158152f35b630dbb4e3760e21b811491508115613365575b8115613354575b8115613343575b8115613332575b50836132fc565b63af68dab160e01b1490508361332b565b6301ffc9a760e01b81149150613324565b63e8a3d48560e01b8114915061331d565b6330261b2560e11b81149150613316565b63f3ffe14b60e01b811491506132f5565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b600435906001600160a01b03821682036111b057565b602435906001600160a01b03821682036111b057565b90600182811c92168015613405575b60208310146133f157565b634e487b7160e01b5f52602260045260245ffd5b91607f16916133e6565b60a081019081106001600160401b038211176105b857604052565b61010081019081106001600160401b038211176105b857604052565b604081019081106001600160401b038211176105b857604052565b90601f801991011681019081106001600160401b038211176105b857604052565b604051905f8260065491613495836133d7565b808352926001811690811561350757506001146134bb575b6134b992500383613461565b565b5060065f90815290915f5160206149b45f395f51905f525b8183106134eb5750509060206134b9928201016134ad565b60209193508060019154838589010152019101909184926134d3565b602092506134b994915060ff191682840152151560051b8201016134ad565b604051905f8260025491613539836133d7565b8083529260018116908115613507575060011461355c576134b992500383613461565b5060025f90815290915f5160206148b45f395f51905f525b81831061358c5750509060206134b9928201016134ad565b6020919350806001915483858901015201910190918492613574565b604051905f825f5160206149745f395f51905f5254916135c7836133d7565b808352926001811690811561350757506001146135ea576134b992500383613461565b505f5160206149745f395f51905f525f90815290917f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b755b8183106136395750509060206134b9928201016134ad565b6020919350806001915483858901015201910190918492613621565b6001600160401b0381116105b857601f01601f191660200190565b81601f820112156111b05780359061368782613655565b926136956040519485613461565b828452602083830101116111b057815f926020809301838601378301015290565b80516001600160a01b03908116835260208083015182169084015260408083015162ffffff169084015260608083015160020b9084015260809182015116910152565b6001600160401b0381116105b85760051b60200190565b9080601f830112156111b057813590613728826136f9565b926137366040519485613461565b82845260208085019360051b8201019182116111b057602001915b81831061375e5750505090565b82356001600160a01b03811681036111b057815260209283019201613751565b90602080835192838152019201905f5b81811061379b5750505090565b825184526020938401939092019160010161378e565b90602080835192838152019201905f5b8181106137ce5750505090565b825160020b8452602093840193909201916001016137c1565b35908160020b82036111b057565b359061ffff821682036111b057565b9080601f830112156111b057813561381b816136f9565b926138296040519485613461565b81845260208085019260051b8201019283116111b057602001905b8282106138515750505090565b6020809161385e846137e7565b815201910190613844565b51906001600160a01b03821682036111b057565b6040519061388a8261340f565b5f6080838281528260208201528260408201528260608201520152565b604051906138b48261340f565b6008546001600160a01b039081168352600954808216602085015260a081901c62ffffff16604085015260b81c60020b6060840152600a54166080830152565b8051156139015760200190565b634e487b7160e01b5f52603260045260245ffd5b80518210156139015760209160051b010190565b6001600160a01b03165f9081527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace016020526040902090565b519062ffffff821682036111b057565b51908160020b82036111b057565b6008546001600160a01b039081168252600954808216602084015260a081901c62ffffff16604084015260b81c60020b6060830152600a5416608090910152565b9190820391821161111557565b6139d642613fd7565b601254808211156139ed576139ea916139c0565b90565b50505f90565b9190820180921161111557565b613a086139cd565b8015613a8757613a1a816012546139f3565b601255600354613a359082906001600160a01b031630613a8c565b60018060a01b03600354167f547365a9b087790f946864e58c45cdbc0a4f8f2f884b7f79e9475154cc6b740a60806012546010546011549060405192878452602084015260408301526060820152a290565b505f90565b91906001600160a01b03831615612eef576001600160a01b038116156111c5576134b9926143c2565b6001600160a01b031680156115b657600354816001600160a01b038216337fa5377dd2e56b1960177c4c53e6e87ef5c7f8e15e7fbf615d56d21c8e821848915f80a46001600160a01b03191617600355565b818110613b12575050565b5f8155600101613b07565b9091613b346139ea93604084526040840190613387565b916020818403910152613387565b919091805115613df9578051926001600160401b0384116105b857613b686006546133d7565b601f8111613d9b575b50602093601f8111600114613d2e5780919293945f91613d23575b508160011b915f199060031b1c1916176006555b80516001600160401b0381116105b857613bbb6007546133d7565b601f8111613cc5575b506020601f8211600114613c33579181613c23927f336055ccb9a037f06b5fb6c1f62596553eeb62303f58c90b0929dd1deab23460945f91613c28575b508160011b915f199060031b1c1916176007555b604051918291339583613b1d565b0390a2565b90508201515f613c01565b601f1982169060075f525f5160206149945f395f51905f52915f5b818110613cad5750927f336055ccb9a037f06b5fb6c1f62596553eeb62303f58c90b0929dd1deab23460949260019282613c239610613c95575b5050811b01600755613c15565b8401515f1960f88460031b161c191690555f80613c88565b91926020600181928689015181550194019201613c4e565b613d089060075f52601f830160051c5f5160206149945f395f51905f52019060208410613d0e575b601f0160051c5f5160206149945f395f51905f520190613b07565b5f613bc4565b5f5160206149945f395f51905f529150613ced565b90508301515f613b8c565b601f1981169460065f525f5160206149b45f395f51905f52905f5b878110613d8357508260019495969710613d6b575b5050811b01600655613ba0565b8501515f1960f88460031b161c191690555f80613d5e565b90916020600181928589015181550193019101613d49565b613dde9060065f52601f860160051c5f5160206149b45f395f51905f52019060208710613de4575b601f0160051c5f5160206149b45f395f51905f520190613b07565b5f613b71565b5f5160206149b45f395f51905f529150613dc3565b63344486ff60e01b5f5260045ffd5b604051613e196020820180936136b6565b60a08152613e2860c082613461565b51902090565b60405190613e3d604083613461565b600482526321b7b4b760e11b6020830152565b90613e59613482565b7f74b7c2afa3f89c562b59674a101e2c48bceeb27cdb620afefa14446f1ffa487b60405180613e8a33948783613b1d565b0390a27fa5d4097edda6d87cb9329af83fb3712ef77eeb13738ffe43cc35a4ce305ad9625f80a181516001600160401b0381116105b857613ecc6002546133d7565b601f8111613f79575b50602092601f8211600114613f1057928192935f92613f05575b50508160011b915f199060031b1c191617600255565b015190505f80613eef565b601f1982169360025f525f5160206148b45f395f51905f52915f5b868110613f615750836001959610613f49575b505050811b01600255565b01515f1960f88460031b161c191690555f8080613f3e565b91926020600181928685015181550194019201613f2b565b613fbc9060025f52601f830160051c5f5160206148b45f395f51905f52019060208410613fc2575b601f0160051c5f5160206148b45f395f51905f520190613b07565b5f613ed5565b5f5160206148b45f395f51905f529150613fa1565b601054808211156139ed5760115482101561402357613ff5916139c0565b806b019d971e4fe8401e7400000002906b019d971e4fe8401e74000000820403611115576309660180900490565b50506b019d971e4fe8401e7400000090565b90606061404282846146df565b15614221575060405163f3ffe14b60e01b81526001600160a01b039182166004820152915f9183916024918391165afa908115612b4e575f9161408457505190565b90503d805f833e6140958183613461565b8101906020818303126111b0578051906001600160401b0382116111b057016040818303126111b057604051916140cb83613446565b81516001600160401b0381116111b05782019080601f830112156111b0578151916140f5836136f9565b926141036040519485613461565b80845260208085019160051b830101918383116111b05760208101915b83831061414457505050505061413b91602091845201613869565b60208201525190565b82516001600160401b0381116111b05782019060a0828703601f1901126111b057604051916141728361340f565b61417e60208201613869565b835261418c60408201613961565b602084015261419d60608201613971565b60408401526141ae60808201613869565b606084015260a08101516001600160401b0381116111b05760209101019086601f830112156111b0578151926141e384613655565b6141f06040519182613461565b84815288602086860101116111b0575f6020868197828098018386015e830101526080820152815201920191614120565b91505060405190614233602083613461565b5f82525f90815b8281106142475750505090565b6020906040516142568161340f565b5f81525f838201525f60408201525f848201528360808201528282870101520161423a565b916001600160a01b03831691821561319f576001600160a01b031692831561318c577f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925916142ca602092613929565b855f5282528060405f2055604051908152a3565b8054821015613901575f5260205f2001905f90565b5f8181526001602052604090205480156139ed575f198101818111611115575f545f1981019190821161111557818103614376575b5050505f548015614362575f1901614340815f6142de565b8154905f199060031b1b191690555f555f5260016020525f6040812055600190565b634e487b7160e01b5f52603160045260245ffd5b6143ac614386614396935f6142de565b90549060031b1c9283925f6142de565b819391549060031b91821b915f19901b19161790565b90555f52600160205260405f20555f8080614328565b6001600160a01b031690816144cf5760605f516020614a145f395f51905f52916143fa855f5160206149545f395f51905f52546139f3565b5f5160206149545f395f51905f52555b6001600160a01b031693846144ac57805f5160206149545f395f51905f5254035f5160206149545f395f51905f52555b84847fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef6020604051858152a3835f525f5160206148f45f395f51905f5260205260405f2054855f525f5160206148f45f395f51905f5260205260405f20549060405192835260208301526040820152a3565b845f525f5160206148f45f395f51905f5260205260405f2081815401905561443a565b815f525f5160206148f45f395f51905f5260205260405f2054838110614521575f516020614a145f395f51905f529184606092855f525f5160206148f45f395f51905f526020520360405f205561440a565b91905063391434e360e21b5f5260045260245260445260645ffd5b6145446147d9565b61454c614843565b6040519060208201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a08152613e2860c082613461565b805f52600160205260405f2054155f14613a87575f54600160401b8110156105b8576145d36143968260018594015f555f6142de565b90555f54905f52600160205260405f2055600190565b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411614660579160209360809260ff5f9560405194855216868401526040830152606082015282805260015afa15612b4e575f516001600160a01b0381161561465657905f905f90565b505f906001905f90565b5050505f9160039190565b60048110156146cb578061467d575050565b600181036146945763f645eedf60e01b5f5260045ffd5b600281036146af575063fce698f760e01b5f5260045260245ffd5b6003146146b95750565b6335e2f38360e21b5f5260045260245ffd5b634e487b7160e01b5f52602160045260245ffd5b60405163442f7de960e11b81526001600160a01b039182166004820181905292909160209183916024918391165afa908115612b4e575f9161479c575b5060ff1660041461472c57505f90565b6040516301ffc9a760e01b815263f3ffe14b60e01b600482015290602090829060249082905afa908115612b4e575f91614764575090565b90506020813d602011614794575b8161477f60209383613461565b810103126111b0575180151581036111b05790565b3d9150614772565b90506020813d6020116147d1575b816147b760209383613461565b810103126111b0575160ff811681036111b05760ff61471c565b3d91506147aa565b6147e1613e2e565b80519081156147f1576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10054801561481e5790565b507fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47090565b61484b6135a8565b805190811561485b576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10154801561481e5790565b60ff5f5160206149f45f395f51905f525460401c16156148a457565b631afcd79f60e31b5f5260045ffdfe405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0352c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00a16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10252c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0452c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02a16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d103a66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c688f652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3fb9312e2100469bd44e3f762c248f4dcc8d7788906fabf34f79db45920c37e269f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00a20126263d779da517a295859c8332765f45a215da1c42acac1b9e458a69a144a2646970667358221220c2ff16f44abdab583aa898229a6a8aea93fc50670b8608d9ee0705b731fedaa564736f6c634300081c0033c7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a000000000000000000000000007bf90111ad7c22bec9e9dff8a01a44713cc1b1b60000000000000000000000007777777f279eba3d3ad8f4e708545291a6fdba8b000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b000000000000000000000000660eaaedebc968f8f3694354fa8ec0b4c5ba8d12
Deployed Bytecode
0x6080806040526004361015610012575f80fd5b5f905f3560e01c90816301ffc9a7146132ba5750806306fdde031461329f578063095ea7b314613279578063173825d9146131f657806318160ddd146131cd57806323b872dd146130f557806329df6479146130b15780632b968958146130675780632f54bf6e14613025578063313ce5671461300a578063346a21dc14612f5f5780633644e51514612f455780633c130d9014612f2a5780633fb80b1514612f0257806342966c6814612dd957806346bb595414612d9d57806351845bf614612d755780635a44621514612d03578063683e76e014612ce05780636c46a2c514612c175780637065cb4814612b9d57806370a0823114612b595780637a3b5a23146128a75780637ecebe001461285157806384b0196e1461273257806386fab45e14612715578063938e3d7b146126c257806395d89b411461260b578063a0a8e460146125c4578063a8660a78146125a7578063a9059cbb14612576578063a9a5e3af14612478578063affe39c1146123bb578063b80945e914611b2b578063c354bd6e14611b11578063cd7033c414611ae9578063d505accf14611985578063d54ad2a114611968578063dc4c90d314611924578063dd0371d514610675578063dd62ed3e1461062d578063e5a6b10f14610604578063e8a3d485146105d0578063f3ffe14b146102d2578063f53eab8e1461028d578063f78a8a3e146102485763fedda89c14610223575f80fd5b34610245578060031936011261024557602061023d613a00565b604051908152f35b80fd5b50346102455780600319360112610245576040517f000000000000000000000000660eaaedebc968f8f3694354fa8ec0b4c5ba8d126001600160a01b03168152602090f35b50346102455780600319360112610245576040517f0000000000000000000000007bf90111ad7c22bec9e9dff8a01a44713cc1b1b66001600160a01b03168152602090f35b5034610245576020366003190112610245576004356001600160a01b03811681036105cc5760405161030381613446565b606081523060208201908152600554600954600a5460405193956001600160a01b0393841693610378939192169061033a8661340f565b84865262ffffff8160a01c16602087015260b81c60020b6040860152606085015260209260405161036b8582613461565b8881526080860152614035565b80519092901561053a578251600101908160011161052657610399826136f9565b916103a76040519384613461565b8083526103b6601f19916136f9565b0183885b8281106104f157505050906103db918186526103d5826138f4565b526138f4565b50845b8251811015610434576103f18184613915565b5184516001830191828411610420579181600194936104138361041995613915565b52613915565b50016103de565b634e487b7160e01b89526011600452602489fd5b5091939290505b60405192828452606084019451926040818601528351809652608085018160808860051b880101950192905b8782106104845784516001600160a01b0316604088015286860387f35b9091929483806104e3600193607f198b820301865260a060808b518780841b03815116845262ffffff868201511686850152604081015160020b60408501528780841b0360608201511660608501520151918160808201520190613387565b970192019201909291610467565b6040516104fd8161340f565b8a81528a838201528a60408201528a6060820152606060808201528282870101520184906103ba565b634e487b7160e01b87526011600452602487fd5b604051939591949193919250602085016105548184613461565b60018352601f190185855b828110610583575050509061057a918187526103d5826138f4565b5091909161043b565b60405161058f8161340f565b87815287838201528760408201528760608201526060608082015282828701015201869061055f565b634e487b7160e01b5f52604160045260245ffd5b5080fd5b50346102455780600319360112610245576106006105ec613526565b604051918291602083526020830190613387565b0390f35b50346102455780600319360112610245576005546040516001600160a01b039091168152602090f35b5034610245576040366003190112610245576106476133ab565b6106586106526133c1565b91613929565b9060018060a01b03165f52602052602060405f2054604051908152f35b346111b0576101c03660031901126111b05761068f6133ab565b6024356001600160401b0381116111b0576106ae903690600401613710565b906044356001600160401b0381116111b0576106ce903690600401613670565b6064356001600160401b0381116111b0576106ed903690600401613670565b906084356001600160401b0381116111b05761070d903690600401613670565b9060a435906001600160a01b03821682036111b05760c435936001600160a01b03851685036111b05760a03660e31901126111b0576040519361074f8561340f565b60e4356001600160a01b03811681036111b0578552610104356001600160a01b03811681036111b05760208601526101243562ffffff811681036111b0576040860152610144358060020b81036111b0576060860152610164356001600160a01b03811681036111b057608086015261018435956001600160a01b03871687036111b0576101a435906001600160401b0382116111b05761010060031983360301126111b057604051916108028361342a565b806004013560ff811681036111b057835261081f602482016137f5565b6020840152604481013562ffffff811681036111b0576040840152610846606482016137e7565b606084015260848101356001600160401b0381116111b0578101366023820112156111b05760048101359061087a826136f9565b916108886040519384613461565b808352602060048185019260051b84010101913683116111b057602401905b82821061190c57505050608084015260a48101356001600160401b0381116111b0576108d99060043691840101613804565b60a084015260c48101356001600160401b0381116111b0576109019060043691840101613804565b60c084015260e4810135906001600160401b0382116111b05701366023820112156111b057600481013590610935826136f9565b916109436040519384613461565b808352602060048185019260051b84010101913683116111b057602401905b8282106118fc5750505060e0830152731111111111166b7fe7bd91427724b487980afc68196001600160a01b038216016118ed575f5160206149f45f395f51905f5254966001600160401b038816801590816118dd575b60011490816118d3575b1590816118ca575b506118bb57610a919160016001600160401b03198a16175f5160206149f45f395f51905f525560ff8960401c161561188f575b600580546001600160a01b03199081166001600160a01b03938416179091558251600880548316918416919091179055602083015160098054604086015160608701516001600160d01b03199092169386169390931760a09390931b62ffffff60a01b169290921762ffffff60b81b60b89390931b92909216919091179055608090920151600a80549093169116179055565b60ff815116600b5462ffff00602084015160081b1665ffffff000000604085015160181b1691606085015160301b68ffffff000000000000169368ffffff000000000000199165ffffffffffff19161716171717600b5560808101518051906001600160401b0382116105b857600160401b82116105b857602090600c5483600c55808410611839575b500190600c5f5260205f208160041c915f5b8381106117f95750600f1981169003806117ac575b5050505060a08101518051906001600160401b0382116105b857600160401b82116105b857602090600d5483600d5580841061177a575b500190600d5f5260205f20600a8204915f5b8381106117305750600a83029003806116e2575b5050505060c08101518051906001600160401b0382116105b857600160401b82116105b857602090600e5483600e5580841061168e575b500190600e5f5260205f20600a8204915f5b8381106116445750600a83029003806115f5575b5050505060e001518051906001600160401b0382116105b857600160401b82116105b857602090600f5483600f558084106115d9575b5001600f5f5260205f205f5b8381106115c557505050506001600160a01b038716156115b657610c6191613b42565b602094604051610c718782613461565b5f815260405190610c828883613461565b5f8252610c8d614888565b610c95614888565b8051906001600160401b0382116105b8578190610cbf5f5160206148d45f395f51905f52546133d7565b601f811161157b575b508990601f83116001146114fd575f926114f2575b50508160011b915f199060031b1c1916175f5160206148d45f395f51905f52555b8051906001600160401b0382116105b8578190610d285f5160206149345f395f51905f52546133d7565b601f81116114b7575b508890601f8311600114611439575f9261142e575b50508160011b915f199060031b1c1916175f5160206149345f395f51905f52555b60405196610d758789613461565b5f8852610d80614888565b604097885190610d908a83613461565b60018252603160f81b89830152610da5614888565b8051906001600160401b0382116105b8578190610dcf5f5160206149145f395f51905f52546133d7565b8b601f82116113f2575b50508a90601f8311600114611374575f92611369575b50508160011b915f199060031b1c1916175f5160206149145f395f51905f52555b8051906001600160401b0382116105b8578190610e3a5f5160206149745f395f51905f52546133d7565b601f8111611323575b508990601f83116001146112a5575f9261129a575b50508160011b915f199060031b1c1916175f5160206149745f395f51905f52555b5f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100555f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10155610ec7614888565b8051801561128b575f5b8181106111dd5750505090610f1c610f2192610eeb614888565b610ef3614888565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0055613ab5565b613e50565b6001600160a01b0381166111d857507f0000000000000000000000007bf90111ad7c22bec9e9dff8a01a44713cc1b1b65b60018060a01b03166001600160601b0360a01b600454161760045530156111c5575f5160206149545f395f51905f52546b033b2e3c9fd0803ce80000008101809111611115575f5160206149545f395f51905f5255305f525f5160206148f45f395f51905f528352835f206b033b2e3c9fd0803ce8000000815401905583516b033b2e3c9fd0803ce800000081525f7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef853093a35f80525f5160206148f45f395f51905f528352835f2054305f525f5160206148f45f395f51905f528452845f20548551916b033b2e3c9fd0803ce8000000835285830152858201525f5f516020614a145f395f51905f5260603093a3600a546001600160a01b031680156111c5576b019d971e4fe8401e7400000061108b91306143c2565b835163313b65df60e11b8152916110a46004840161397f565b6001600160a01b0390811660a48401528390839060c49082905f907f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b165af180156111bb57611182575b60ff915060401c1615611129575b5050426010556309660180420180421161111557601155005b634e487b7160e01b5f52601160045260245ffd5b7fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29168ff0000000000000000195f5160206149f45f395f51905f5254165f5160206149f45f395f51905f52555160018152a180806110fc565b8282813d83116111b4575b6111978183613461565b810103126111b0576111aa60ff92613971565b506110ee565b5f80fd5b503d61118d565b84513d5f823e3d90fd5b63ec442f0560e01b5f525f60045260245ffd5b610f52565b6001600160a01b036111ef8285613915565b51161561127c5761121e6001600160a01b0361120b8386613915565b51165f52600160205260405f2054151590565b61126d576001906112416001600160a01b0361123a8387613915565b511661459d565b50818060a01b036112528286613915565b51165f335f5160206149d45f395f51905f528280a401610ed1565b63600acf0760e11b5f5260045ffd5b630fc033dd60e41b5f5260045ffd5b63378a1ae160e11b5f5260045ffd5b015190508a80610e58565b5f5160206149745f395f51905f525f9081528b81209350601f198516905b8c82821061130d5750509084600195949392106112f5575b505050811b015f5160206149745f395f51905f5255610e79565b01515f1960f88460031b161c191690558a80806112db565b60018596829396860151815501950193016112c3565b611359905f5160206149745f395f51905f525f528b5f20601f850160051c8101918d861061135f575b601f0160051c0190613b07565b8b610e43565b909150819061134c565b015190508b80610def565b5f5160206149145f395f51905f525f9081528c81209350601f198516905b8d8282106113dc5750509084600195949392106113c4575b505050811b015f5160206149145f395f51905f5255610e10565b01515f1960f88460031b161c191690558b80806113aa565b6001859682939686015181550195019301611392565b611427915f5160206149145f395f51905f525f52815f2090601f860160051c820192861061135f57601f0160051c0190613b07565b8c8b610dd9565b015190508980610d46565b5f5160206149345f395f51905f525f9081528a81209350601f198516905b8b8282106114a1575050908460019594939210611489575b505050811b015f5160206149345f395f51905f5255610d67565b01515f1960f88460031b161c1916905589808061146f565b6001859682939686015181550195019301611457565b6114ec905f5160206149345f395f51905f525f528a5f20601f850160051c8101918c861061135f57601f0160051c0190613b07565b8a610d31565b015190508a80610cdd565b5f5160206148d45f395f51905f525f9081528b81209350601f198516905b8c82821061156557505090846001959493921061154d575b505050811b015f5160206148d45f395f51905f5255610cfe565b01515f1960f88460031b161c191690558a8080611533565b600185968293968601518155019501930161151b565b6115b0905f5160206148d45f395f51905f525f528b5f20601f850160051c8101918d861061135f57601f0160051c0190613b07565b8b610cc8565b639fabe1c160e01b5f5260045ffd5b600190602084519401938184015501610c3e565b6115ef90600f5f5284845f209182019101613b07565b8b610c32565b925f935f5b81811061161057505050015560e08a8080610bfc565b909194602061163a600192885160020b908560030262ffffff809160031b9316831b921b19161790565b96019291016115fa565b5f5f5b600a811061165c575083820155600101610be8565b95906020611685600192845160020b908a60030262ffffff809160031b9316831b921b19161790565b92019601611647565b6116bb90600e5f52835f20600a600981818901048301936003838a0602806116c1575b5001040190613b07565b8c610bd6565b6116dc905f198701908154905f199060200360031b1c169055565b5f6116b1565b925f935f5b8181106116fc57505050015589808080610b9f565b9091946020611726600192885160020b908560030262ffffff809160031b9316831b921b19161790565b96019291016116e7565b5f5f5b600a8110611748575083820155600101610b8b565b95906020611771600192845160020b908a60030262ffffff809160031b9316831b921b19161790565b92019601611733565b6117a690600d5f52835f20600a600981818901048301936003838a0602806116c1575001040190613b07565b8c610b79565b925f935f5b8181106117c657505050015589808080610b42565b90919460206117ef60019261ffff8951169085851b61ffff809160031b9316831b921b19161790565b96019291016117b1565b5f5f5b60108110611811575083820155600101610b2d565b865190969160019160209161ffff60048b901b81811b199092169216901b17920196016117fc565b61186890600c5f52835f20600f80870160041c820192601e8860011b168061186e575b500160041c0190613b07565b8c610b1b565b611889905f198601908154905f199060200360031b1c169055565b5f61185c565b68ffffffffffffffffff19891668010000000000000001175f5160206149f45f395f51905f52556109fe565b63f92ee8a960e01b5f5260045ffd5b9050158c6109cb565b303b1591506109c3565b60408a901c60ff161591506109b9565b631eb3268560e31b5f5260045ffd5b8135815260209182019101610962565b60208091611919846137f5565b8152019101906108a7565b346111b0575f3660031901126111b0576040517f000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b6001600160a01b03168152602090f35b346111b0575f3660031901126111b0576020601254604051908152f35b346111b05760e03660031901126111b05761199e6133ab565b6119a66133c1565b604435906064359260843560ff811681036111b057844211611ad657611a99611aa29160018060a01b03841696875f527f5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb0060205260405f20908154916001830190556040519060208201927f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c984528a604084015260018060a01b038916606084015289608084015260a083015260c082015260c08152611a6760e082613461565b519020611a7261453c565b906040519161190160f01b83526002830152602282015260c43591604260a43592206145e9565b9092919261466b565b6001600160a01b0316848103611abf5750611abd935061427b565b005b84906325c0072360e11b5f5260045260245260445ffd5b8463313c898160e11b5f5260045260245ffd5b346111b0575f3660031901126111b057600a546040516001600160a01b039091168152602090f35b346111b0575f3660031901126111b057602061023d6139cd565b346111b0575f3660031901126111b057606060e0604051611b4b8161342a565b5f81525f60208201525f60408201525f838201528260808201528260a08201528260c08201520152604051611b7f8161342a565b600b5460ff81168252602082019061ffff8160081c168252604083019062ffffff8160181c168252606084019060301c60020b815260405180816020600c549283815201600c5f5260205f20925f905b80600f8301106122d357611c659454918181106122be575b8181106122a6575b81811061228f575b818110612277575b81811061225f575b818110612247575b81811061222f575b818110612217575b8181106121ff575b8181106121e7575b8181106121cf575b8181106121b7575b81811061219f575b818110612187575b81811061216f575b10612161575b500382613461565b6080850190815260405190600d548083528260208101600d5f5260205f20925f905b8060098301106120d257611ced9454918181106120be575b8181106120a7575b818110612090575b818110612079575b818110612062575b81811061204b575b818110612034575b81811061201d575b818110612006575b10611ff5575b500383613461565b60a0860191825260405192600e548085528460208101600e5f5260205f20925f905b806009830110611f6657611d75945491818110611f52575b818110611f3b575b818110611f24575b818110611f0d575b818110611ef6575b818110611edf575b818110611ec8575b818110611eb1575b818110611e9a575b10611e89575b500385613461565b60c08701938452604051948580966020600f54918281520190600f5f5260205f20905f5b818110611e705750505062ffffff9291611db4910388613461565b60e0890196875261ffff6040519860208a5260ff6101208b019b511660208b015251166040890152511660608701525160020b6080860152519461010060a08601528551809152602061014086019601905f5b818110611e5657868061060088611e4289611e2f8e8b51601f198883030160c08901526137b1565b9051858203601f190160e08701526137b1565b9051838203601f190161010085015261377e565b825161ffff16885260209788019790920191600101611e07565b825484528a945060209093019260019283019201611d99565b60d81c60020b81526020018a611d6d565b9260206001918460c01c60020b8152019301611d67565b9260206001918460a81c60020b8152019301611d5f565b9260206001918460901c60020b8152019301611d57565b9260206001918460781c60020b8152019301611d4f565b9260206001918460601c60020b8152019301611d47565b9260206001918460481c60020b8152019301611d3f565b9260206001918460301c60020b8152019301611d37565b9260206001918460181c60020b8152019301611d2f565b9260206001918460020b8152019301611d27565b91600a91935061014060019186548060020b82528060181c60020b60208301528060301c60020b60408301528060481c60020b60608301528060601c60020b60808301528060781c60020b60a08301528060901c60020b60c08301528060a81c60020b60e08301528060c01c60020b61010083015260d81c60020b610120820152019401920187929391611d0f565b60d81c60020b815260200189611ce5565b9260206001918460c01c60020b8152019301611cdf565b9260206001918460a81c60020b8152019301611cd7565b9260206001918460901c60020b8152019301611ccf565b9260206001918460781c60020b8152019301611cc7565b9260206001918460601c60020b8152019301611cbf565b9260206001918460481c60020b8152019301611cb7565b9260206001918460301c60020b8152019301611caf565b9260206001918460181c60020b8152019301611ca7565b9260206001918460020b8152019301611c9f565b91600a91935061014060019186548060020b82528060181c60020b60208301528060301c60020b60408301528060481c60020b60608301528060601c60020b60808301528060781c60020b60a08301528060901c60020b60c08301528060a81c60020b60e08301528060c01c60020b61010083015260d81c60020b610120820152019401920185929391611c87565b60f01c815260200188611c5d565b92602060019161ffff8560e01c168152019301611c57565b92602060019161ffff8560d01c168152019301611c4f565b92602060019161ffff8560c01c168152019301611c47565b92602060019161ffff8560b01c168152019301611c3f565b92602060019161ffff8560a01c168152019301611c37565b92602060019161ffff8560901c168152019301611c2f565b92602060019161ffff8560801c168152019301611c27565b92602060019161ffff8560701c168152019301611c1f565b92602060019161ffff8560601c168152019301611c17565b92602060019161ffff8560501c168152019301611c0f565b92602060019161ffff8560401c168152019301611c07565b92602060019161ffff8560301c168152019301611bff565b92602060019161ffff85831c168152019301611bf7565b92602060019161ffff8560101c168152019301611bef565b92602060019161ffff85168152019301611be7565b916010919350610200600191865461ffff8116825261ffff81861c16602083015261ffff8160201c16604083015261ffff8160301c16606083015261ffff8160401c16608083015261ffff8160501c1660a083015261ffff8160601c1660c083015261ffff8160701c1660e083015261ffff8160801c1661010083015261ffff8160901c1661012083015261ffff8160a01c1661014083015261ffff8160b01c1661016083015261ffff8160c01c1661018083015261ffff8160d01c166101a083015261ffff8160e01c166101c083015260f01c6101e0820152019401920184929391611bcf565b346111b0575f3660031901126111b0576040518060205f54928381520180925f80527f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563905f5b8181106124625750505081612417910382613461565b604051918291602083019060208452518091526040830191905f5b818110612440575050500390f35b82516001600160a01b0316845285945060209384019390920191600101612432565b8254845260209093019260019283019201612401565b346111b05760203660031901126111b0576004356001600160401b0381116111b0576124a8903690600401613710565b6124bd335f52600160205260405f2054151590565b15612567575f5b8151811015611abd576001600160a01b036124df8284613915565b5116906124f7335f52600160205260405f2054151590565b1561256757811561127c573382146125585761251e825f52600160205260405f2054151590565b15612549575f826125306001946142f3565b50335f5160206149d45f395f51905f528380a4016124c4565b6330cd747160e01b5f5260045ffd5b637c22c4dd60e01b5f5260045ffd5b635fc483c560e01b5f5260045ffd5b346111b05760403660031901126111b05761259c6125926133ab565b6024359033613a8c565b602060405160018152f35b346111b0575f3660031901126111b0576020601054604051908152f35b346111b0575f3660031901126111b0576106006040516125e5604082613461565b60058152640312e312e360dc1b6020820152604051918291602083526020830190613387565b346111b0575f3660031901126111b0576040515f60075461262b816133d7565b808452906001811690811561269e5750600114612653575b610600836105ec81850382613461565b60075f9081525f5160206149945f395f51905f52939250905b808210612684575090915081016020016105ec612643565b91926001816020925483858801015201910190929161266c565b60ff191660208086019190915291151560051b840190910191506105ec9050612643565b346111b05760203660031901126111b0576004356001600160401b0381116111b0576126f2903690600401613670565b612707335f52600160205260405f2054151590565b1561256757611abd90613e50565b346111b0575f3660031901126111b0576020601154604051908152f35b346111b0575f3660031901126111b0577fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100541580612828575b156127eb576127bd61277b613e2e565b6106006127866135a8565b6127cb60405191612798602084613461565b5f83525f368137604051958695600f60f81b875260e0602088015260e0870190613387565b908582036040870152613387565b904660608501523060808501525f60a085015283820360c085015261377e565b60405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b6044820152606490fd5b507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d101541561276b565b346111b05760203660031901126111b05761286a6133ab565b60018060a01b03165f527f5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00602052602060405f2054604051908152f35b346111b05760403660031901126111b0576128c06133ab565b602435906001600160401b0382116111b057366023830112156111b0578160040135916001600160401b0383116111b05736602484830101116111b05761290561387d565b5061291b335f52600160205260405f2054151590565b1561256757600a54604051634a862f6360e01b81526001600160a01b0393841660048201529360a093859392169183915f91610104918491819060249061296385830161397f565b60e060c48601528260e486015201848401378181018301849052601f01601f191681010301925af18015612b4e575f90612ac1575b60a0907f907fbdc07b1c9a591dc1287635b072fa848f4da7c86645dfc9b8bfb3b94f82ab6101806129cf6129ca6138a7565b613e08565b6129d884613e08565b604051916129e58361397f565b868301526129f660c08301866136b6565b610160820152a1612a26600180841b0382511660018060a01b03166001600160601b0360a01b6008541617600855565b612a52600180841b0360208301511660018060a01b03166001600160601b0360a01b6009541617600955565b6040810151600954606083015160b81b62ffffff60b81b169162ffffff851b90851b169065ffffffffffff851b19161717600955612ab2600180841b0360808301511660018060a01b03166001600160601b0360a01b600a541617600a55565b612abf60405180926136b6565bf35b5060a0813d60a011612b46575b81612adb60a09383613461565b810103126111b05760a090612b3c608060405192612af88461340f565b612b0181613869565b8452612b0f60208201613869565b6020850152612b2060408201613961565b6040850152612b3160608201613971565b606085015201613869565b6080820152612998565b3d9150612ace565b6040513d5f823e3d90fd5b346111b05760203660031901126111b0576001600160a01b03612b7a6133ab565b165f525f5160206148f45f395f51905f52602052602060405f2054604051908152f35b346111b05760203660031901126111b057612bb66133ab565b612bcb335f52600160205260405f2054151590565b15612567576001600160a01b0316801561127c57612bf4815f52600160205260405f2054151590565b61126d57612c018161459d565b505f335f5160206149d45f395f51905f528280a4005b346111b05760203660031901126111b0576004356001600160401b0381116111b057612c47903690600401613710565b612c5c335f52600160205260405f2054151590565b15612567575f5b8151811015611abd576001600160a01b03612c7e8284613915565b511690612c96335f52600160205260405f2054151590565b1561256757811561127c57612cb6825f52600160205260405f2054151590565b61126d5781612cc660019361459d565b505f335f5160206149d45f395f51905f528280a401612c63565b346111b0575f3660031901126111b057612cf861387d565b5060a0612ab26138a7565b346111b05760403660031901126111b0576004356001600160401b0381116111b057612d33903690600401613670565b6024356001600160401b0381116111b057612d52903690600401613670565b612d67335f52600160205260405f2054151590565b1561256757611abd91613b42565b346111b0575f3660031901126111b0576004546040516001600160a01b039091168152602090f35b346111b05760203660031901126111b057612db66133ab565b612dcb335f52600160205260405f2054151590565b1561256757611abd90613ab5565b346111b05760203660031901126111b0576004353315612eef57335f525f5160206148f45f395f51905f5260205260405f2054818110612ed65790805f923384525f5160206148f45f395f51905f52602052036040832055805f5160206149545f395f51905f5254035f5160206149545f395f51905f5255816040518281527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60203392a33382525f5160206148f45f395f51905f5260205260408220548280525f5160206148f45f395f51905f52602052604083205490604051928352602083015260408201525f516020614a145f395f51905f5260603392a3005b63391434e360e21b5f523360045260245260445260645ffd5b634b637e8f60e11b5f525f60045260245ffd5b346111b0575f3660031901126111b0576003546040516001600160a01b039091168152602090f35b346111b0575f3660031901126111b0576106006105ec613526565b346111b0575f3660031901126111b057602061023d61453c565b346111b0575f3660031901126111b057604051638da5cb5b60e01b81526020816004817f000000000000000000000000660eaaedebc968f8f3694354fa8ec0b4c5ba8d126001600160a01b03165afa8015612b4e575f90612fd0575b6040516001600160a01b039091168152602090f35b506020813d602011613002575b81612fea60209383613461565b810103126111b057612ffd602091613869565b612fbb565b3d9150612fdd565b346111b0575f3660031901126111b057602060405160128152f35b346111b05760203660031901126111b057602061305d6001600160a01b0361304b6133ab565b165f52600160205260405f2054151590565b6040519015158152f35b346111b0575f3660031901126111b05761308c335f52600160205260405f2054151590565b156125675761309a336142f3565b505f33335f5160206149d45f395f51905f528380a4005b346111b0575f3660031901126111b0576040517f0000000000000000000000007777777f279eba3d3ad8f4e708545291a6fdba8b6001600160a01b03168152602090f35b346111b05760603660031901126111b05761310e6133ab565b6131166133c1565b6044359061312383613929565b335f9081526020919091526040902054925f198410613147575b61259c9350613a8c565b8284106131b2576001600160a01b0381161561319f57331561318c5761259c9361317082613929565b60018060a01b0333165f526020528360405f209103905561313d565b634a1406b160e11b5f525f60045260245ffd5b63e602df0560e01b5f525f60045260245ffd5b8284637dc7a0d960e11b5f523360045260245260445260645ffd5b346111b0575f3660031901126111b05760205f5160206149545f395f51905f5254604051908152f35b346111b05760203660031901126111b05761320f6133ab565b613224335f52600160205260405f2054151590565b15612567576001600160a01b0316801561127c5733811461255857613254815f52600160205260405f2054151590565b1561254957806132645f926142f3565b50335f5160206149d45f395f51905f528380a4005b346111b05760403660031901126111b05761259c6132956133ab565b602435903361427b565b346111b0575f3660031901126111b0576106006105ec613482565b346111b05760203660031901126111b0576004359063ffffffff60e01b82168092036111b057602091630341f3b760e51b8114908115613376575b8115613303575b5015158152f35b630dbb4e3760e21b811491508115613365575b8115613354575b8115613343575b8115613332575b50836132fc565b63af68dab160e01b1490508361332b565b6301ffc9a760e01b81149150613324565b63e8a3d48560e01b8114915061331d565b6330261b2560e11b81149150613316565b63f3ffe14b60e01b811491506132f5565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b600435906001600160a01b03821682036111b057565b602435906001600160a01b03821682036111b057565b90600182811c92168015613405575b60208310146133f157565b634e487b7160e01b5f52602260045260245ffd5b91607f16916133e6565b60a081019081106001600160401b038211176105b857604052565b61010081019081106001600160401b038211176105b857604052565b604081019081106001600160401b038211176105b857604052565b90601f801991011681019081106001600160401b038211176105b857604052565b604051905f8260065491613495836133d7565b808352926001811690811561350757506001146134bb575b6134b992500383613461565b565b5060065f90815290915f5160206149b45f395f51905f525b8183106134eb5750509060206134b9928201016134ad565b60209193508060019154838589010152019101909184926134d3565b602092506134b994915060ff191682840152151560051b8201016134ad565b604051905f8260025491613539836133d7565b8083529260018116908115613507575060011461355c576134b992500383613461565b5060025f90815290915f5160206148b45f395f51905f525b81831061358c5750509060206134b9928201016134ad565b6020919350806001915483858901015201910190918492613574565b604051905f825f5160206149745f395f51905f5254916135c7836133d7565b808352926001811690811561350757506001146135ea576134b992500383613461565b505f5160206149745f395f51905f525f90815290917f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b755b8183106136395750509060206134b9928201016134ad565b6020919350806001915483858901015201910190918492613621565b6001600160401b0381116105b857601f01601f191660200190565b81601f820112156111b05780359061368782613655565b926136956040519485613461565b828452602083830101116111b057815f926020809301838601378301015290565b80516001600160a01b03908116835260208083015182169084015260408083015162ffffff169084015260608083015160020b9084015260809182015116910152565b6001600160401b0381116105b85760051b60200190565b9080601f830112156111b057813590613728826136f9565b926137366040519485613461565b82845260208085019360051b8201019182116111b057602001915b81831061375e5750505090565b82356001600160a01b03811681036111b057815260209283019201613751565b90602080835192838152019201905f5b81811061379b5750505090565b825184526020938401939092019160010161378e565b90602080835192838152019201905f5b8181106137ce5750505090565b825160020b8452602093840193909201916001016137c1565b35908160020b82036111b057565b359061ffff821682036111b057565b9080601f830112156111b057813561381b816136f9565b926138296040519485613461565b81845260208085019260051b8201019283116111b057602001905b8282106138515750505090565b6020809161385e846137e7565b815201910190613844565b51906001600160a01b03821682036111b057565b6040519061388a8261340f565b5f6080838281528260208201528260408201528260608201520152565b604051906138b48261340f565b6008546001600160a01b039081168352600954808216602085015260a081901c62ffffff16604085015260b81c60020b6060840152600a54166080830152565b8051156139015760200190565b634e487b7160e01b5f52603260045260245ffd5b80518210156139015760209160051b010190565b6001600160a01b03165f9081527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace016020526040902090565b519062ffffff821682036111b057565b51908160020b82036111b057565b6008546001600160a01b039081168252600954808216602084015260a081901c62ffffff16604084015260b81c60020b6060830152600a5416608090910152565b9190820391821161111557565b6139d642613fd7565b601254808211156139ed576139ea916139c0565b90565b50505f90565b9190820180921161111557565b613a086139cd565b8015613a8757613a1a816012546139f3565b601255600354613a359082906001600160a01b031630613a8c565b60018060a01b03600354167f547365a9b087790f946864e58c45cdbc0a4f8f2f884b7f79e9475154cc6b740a60806012546010546011549060405192878452602084015260408301526060820152a290565b505f90565b91906001600160a01b03831615612eef576001600160a01b038116156111c5576134b9926143c2565b6001600160a01b031680156115b657600354816001600160a01b038216337fa5377dd2e56b1960177c4c53e6e87ef5c7f8e15e7fbf615d56d21c8e821848915f80a46001600160a01b03191617600355565b818110613b12575050565b5f8155600101613b07565b9091613b346139ea93604084526040840190613387565b916020818403910152613387565b919091805115613df9578051926001600160401b0384116105b857613b686006546133d7565b601f8111613d9b575b50602093601f8111600114613d2e5780919293945f91613d23575b508160011b915f199060031b1c1916176006555b80516001600160401b0381116105b857613bbb6007546133d7565b601f8111613cc5575b506020601f8211600114613c33579181613c23927f336055ccb9a037f06b5fb6c1f62596553eeb62303f58c90b0929dd1deab23460945f91613c28575b508160011b915f199060031b1c1916176007555b604051918291339583613b1d565b0390a2565b90508201515f613c01565b601f1982169060075f525f5160206149945f395f51905f52915f5b818110613cad5750927f336055ccb9a037f06b5fb6c1f62596553eeb62303f58c90b0929dd1deab23460949260019282613c239610613c95575b5050811b01600755613c15565b8401515f1960f88460031b161c191690555f80613c88565b91926020600181928689015181550194019201613c4e565b613d089060075f52601f830160051c5f5160206149945f395f51905f52019060208410613d0e575b601f0160051c5f5160206149945f395f51905f520190613b07565b5f613bc4565b5f5160206149945f395f51905f529150613ced565b90508301515f613b8c565b601f1981169460065f525f5160206149b45f395f51905f52905f5b878110613d8357508260019495969710613d6b575b5050811b01600655613ba0565b8501515f1960f88460031b161c191690555f80613d5e565b90916020600181928589015181550193019101613d49565b613dde9060065f52601f860160051c5f5160206149b45f395f51905f52019060208710613de4575b601f0160051c5f5160206149b45f395f51905f520190613b07565b5f613b71565b5f5160206149b45f395f51905f529150613dc3565b63344486ff60e01b5f5260045ffd5b604051613e196020820180936136b6565b60a08152613e2860c082613461565b51902090565b60405190613e3d604083613461565b600482526321b7b4b760e11b6020830152565b90613e59613482565b7f74b7c2afa3f89c562b59674a101e2c48bceeb27cdb620afefa14446f1ffa487b60405180613e8a33948783613b1d565b0390a27fa5d4097edda6d87cb9329af83fb3712ef77eeb13738ffe43cc35a4ce305ad9625f80a181516001600160401b0381116105b857613ecc6002546133d7565b601f8111613f79575b50602092601f8211600114613f1057928192935f92613f05575b50508160011b915f199060031b1c191617600255565b015190505f80613eef565b601f1982169360025f525f5160206148b45f395f51905f52915f5b868110613f615750836001959610613f49575b505050811b01600255565b01515f1960f88460031b161c191690555f8080613f3e565b91926020600181928685015181550194019201613f2b565b613fbc9060025f52601f830160051c5f5160206148b45f395f51905f52019060208410613fc2575b601f0160051c5f5160206148b45f395f51905f520190613b07565b5f613ed5565b5f5160206148b45f395f51905f529150613fa1565b601054808211156139ed5760115482101561402357613ff5916139c0565b806b019d971e4fe8401e7400000002906b019d971e4fe8401e74000000820403611115576309660180900490565b50506b019d971e4fe8401e7400000090565b90606061404282846146df565b15614221575060405163f3ffe14b60e01b81526001600160a01b039182166004820152915f9183916024918391165afa908115612b4e575f9161408457505190565b90503d805f833e6140958183613461565b8101906020818303126111b0578051906001600160401b0382116111b057016040818303126111b057604051916140cb83613446565b81516001600160401b0381116111b05782019080601f830112156111b0578151916140f5836136f9565b926141036040519485613461565b80845260208085019160051b830101918383116111b05760208101915b83831061414457505050505061413b91602091845201613869565b60208201525190565b82516001600160401b0381116111b05782019060a0828703601f1901126111b057604051916141728361340f565b61417e60208201613869565b835261418c60408201613961565b602084015261419d60608201613971565b60408401526141ae60808201613869565b606084015260a08101516001600160401b0381116111b05760209101019086601f830112156111b0578151926141e384613655565b6141f06040519182613461565b84815288602086860101116111b0575f6020868197828098018386015e830101526080820152815201920191614120565b91505060405190614233602083613461565b5f82525f90815b8281106142475750505090565b6020906040516142568161340f565b5f81525f838201525f60408201525f848201528360808201528282870101520161423a565b916001600160a01b03831691821561319f576001600160a01b031692831561318c577f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925916142ca602092613929565b855f5282528060405f2055604051908152a3565b8054821015613901575f5260205f2001905f90565b5f8181526001602052604090205480156139ed575f198101818111611115575f545f1981019190821161111557818103614376575b5050505f548015614362575f1901614340815f6142de565b8154905f199060031b1b191690555f555f5260016020525f6040812055600190565b634e487b7160e01b5f52603160045260245ffd5b6143ac614386614396935f6142de565b90549060031b1c9283925f6142de565b819391549060031b91821b915f19901b19161790565b90555f52600160205260405f20555f8080614328565b6001600160a01b031690816144cf5760605f516020614a145f395f51905f52916143fa855f5160206149545f395f51905f52546139f3565b5f5160206149545f395f51905f52555b6001600160a01b031693846144ac57805f5160206149545f395f51905f5254035f5160206149545f395f51905f52555b84847fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef6020604051858152a3835f525f5160206148f45f395f51905f5260205260405f2054855f525f5160206148f45f395f51905f5260205260405f20549060405192835260208301526040820152a3565b845f525f5160206148f45f395f51905f5260205260405f2081815401905561443a565b815f525f5160206148f45f395f51905f5260205260405f2054838110614521575f516020614a145f395f51905f529184606092855f525f5160206148f45f395f51905f526020520360405f205561440a565b91905063391434e360e21b5f5260045260245260445260645ffd5b6145446147d9565b61454c614843565b6040519060208201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a08152613e2860c082613461565b805f52600160205260405f2054155f14613a87575f54600160401b8110156105b8576145d36143968260018594015f555f6142de565b90555f54905f52600160205260405f2055600190565b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411614660579160209360809260ff5f9560405194855216868401526040830152606082015282805260015afa15612b4e575f516001600160a01b0381161561465657905f905f90565b505f906001905f90565b5050505f9160039190565b60048110156146cb578061467d575050565b600181036146945763f645eedf60e01b5f5260045ffd5b600281036146af575063fce698f760e01b5f5260045260245ffd5b6003146146b95750565b6335e2f38360e21b5f5260045260245ffd5b634e487b7160e01b5f52602160045260245ffd5b60405163442f7de960e11b81526001600160a01b039182166004820181905292909160209183916024918391165afa908115612b4e575f9161479c575b5060ff1660041461472c57505f90565b6040516301ffc9a760e01b815263f3ffe14b60e01b600482015290602090829060249082905afa908115612b4e575f91614764575090565b90506020813d602011614794575b8161477f60209383613461565b810103126111b0575180151581036111b05790565b3d9150614772565b90506020813d6020116147d1575b816147b760209383613461565b810103126111b0575160ff811681036111b05760ff61471c565b3d91506147aa565b6147e1613e2e565b80519081156147f1576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10054801561481e5790565b507fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47090565b61484b6135a8565b805190811561485b576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10154801561481e5790565b60ff5f5160206149f45f395f51905f525460401c16156148a457565b631afcd79f60e31b5f5260045ffdfe405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0352c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00a16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10252c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0452c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02a16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d103a66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c688f652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3fb9312e2100469bd44e3f762c248f4dcc8d7788906fabf34f79db45920c37e269f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00a20126263d779da517a295859c8332765f45a215da1c42acac1b9e458a69a144a2646970667358221220c2ff16f44abdab583aa898229a6a8aea93fc50670b8608d9ee0705b731fedaa564736f6c634300081c0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000007bf90111ad7c22bec9e9dff8a01a44713cc1b1b60000000000000000000000007777777f279eba3d3ad8f4e708545291a6fdba8b000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b000000000000000000000000660eaaedebc968f8f3694354fa8ec0b4c5ba8d12
-----Decoded View---------------
Arg [0] : _protocolRewardRecipient (address): 0x7bf90111Ad7C22bec9E9dFf8A01A44713CC1b1B6
Arg [1] : _protocolRewards (address): 0x7777777F279eba3d3Ad8F4E708545291A6fDBA8B
Arg [2] : _poolManager (address): 0x498581fF718922c3f8e6A244956aF099B2652b2b
Arg [3] : _airlock (address): 0x660eAaEdEBc968f8f3694354FA8EC0b4c5Ba8D12
-----Encoded View---------------
4 Constructor Arguments found :
Arg [0] : 0000000000000000000000007bf90111ad7c22bec9e9dff8a01a44713cc1b1b6
Arg [1] : 0000000000000000000000007777777f279eba3d3ad8f4e708545291a6fdba8b
Arg [2] : 000000000000000000000000498581ff718922c3f8e6a244956af099b2652b2b
Arg [3] : 000000000000000000000000660eaaedebc968f8f3694354fa8ec0b4c5ba8d12
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.