Source Code
Overview
MON Balance
MON Value
$0.00View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Loading...
Loading
Contract Name:
UV3Math
Compiler Version
v0.8.20+commit.a1b79de6
Optimization Enabled:
Yes with 200 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.4;
import { TickMath } from "@cryptoalgebra/integral-core/contracts/libraries/TickMath.sol";
import { LiquidityAmounts } from "@cryptoalgebra/integral-periphery/contracts/libraries/LiquidityAmounts.sol";
import { IAlgebraPool } from "@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol";
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { OracleLibrary } from "./OracleLibrary.sol";
import { IICHIVaultFactory } from "../../interfaces/IICHIVaultFactory.sol";
library UV3Math {
using SafeMath for uint256;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
uint256 internal constant PRECISION = 10 ** 18;
/*******************
* Tick Math
*******************/
function getSqrtRatioAtTick(int24 currentTick) public pure returns (uint160 sqrtPriceX96) {
sqrtPriceX96 = TickMath.getSqrtRatioAtTick(currentTick);
}
/*******************
* LiquidityAmounts
*******************/
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) public pure returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
sqrtRatioAX96,
sqrtRatioBX96,
liquidity
);
}
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) public pure returns (uint128 liquidity) {
liquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
sqrtRatioAX96,
sqrtRatioBX96,
amount0,
amount1
);
}
/*******************
* OracleLibrary
*******************/
function consult(address _basePlugin, uint32 _twapPeriod) public view returns (int24 timeWeightedAverageTick) {
timeWeightedAverageTick = OracleLibrary.consult(_basePlugin, _twapPeriod);
}
function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
) public pure returns (uint256 quoteAmount) {
quoteAmount = OracleLibrary.getQuoteAtTick(tick, baseAmount, baseToken, quoteToken);
}
function lastTimepointMetadata(address oracleAddress) public view returns (uint16 index, uint32 timestamp) {
(index, timestamp) = OracleLibrary.lastTimepointMetadata(oracleAddress);
}
function isOracleConnectedToPool(address oracleAddress, address poolAddress) public view returns (bool connected) {
if (oracleAddress == address(0))
return false;
connected = OracleLibrary.isOracleConnectedToPool(oracleAddress, poolAddress);
}
/*******************
* SafeUnit128
*******************/
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint128
function toUint128(uint256 y) public pure returns (uint128 z) {
require((z = uint128(y)) == y, "SafeUint128: overflow");
}
function checkHysteresis(address basePlugin) public view returns (bool) {
// get latest timestamp from the plugin
(, uint32 blockTimestamp) = lastTimepointMetadata(basePlugin);
return (block.timestamp != blockTimestamp);
}
function _checkPriceManipulation(
uint256 price,
uint256 twap,
uint256 auxTwap,
uint256 auxTwapPeriod,
uint256 hysteresis,
address basePlugin
) public view {
uint256 delta = (price > twap)
? price.sub(twap).mul(PRECISION).div(price)
: twap.sub(price).mul(PRECISION).div(twap);
if (auxTwapPeriod > 0) {
uint256 auxDelta = (price > auxTwap)
? price.sub(auxTwap).mul(PRECISION).div(price)
: auxTwap.sub(price).mul(PRECISION).div(auxTwap);
if (delta > hysteresis || auxDelta > hysteresis)
require(checkHysteresis(basePlugin), "DTL");
} else if (delta > hysteresis) {
require(checkHysteresis(basePlugin), "DTL");
}
}
/******************************
* ICHIVault specific functions
******************************/
/**
@dev Computes a unique vault's symbol for vaults created through Ramses factory.
@param value index of the vault to be created
*/
function computeIVsymbol(uint256 value, address pool, bool allowToken0) public view returns (string memory) {
IAlgebraPool algebraPool = IAlgebraPool(pool);
string memory token0Symbol = ERC20(algebraPool.token0()).symbol();
string memory token1Symbol = ERC20(algebraPool.token1()).symbol();
// Format: IV-[ammName]-index-deposit-quote
return string(abi.encodePacked(
"IV-",
IICHIVaultFactory(msg.sender).ammName(),
"-",
Strings.toString(value),
"-",
allowToken0 ? token0Symbol : token1Symbol,
"-",
allowToken0 ? token1Symbol : token0Symbol
));
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Algebra volatility oracle
/// @dev This contract stores timepoints and calculates statistical averages
interface IVolatilityOracle {
/// @notice Returns data belonging to a certain timepoint
/// @param index The index of timepoint in the array
/// @dev There is more convenient function to fetch a timepoint: getTimepoints(). Which requires not an index but seconds
/// @return initialized Whether the timepoint has been initialized and the values are safe to use
/// @return blockTimestamp The timestamp of the timepoint
/// @return tickCumulative The tick multiplied by seconds elapsed for the life of the pool as of the timepoint timestamp
/// @return volatilityCumulative Cumulative standard deviation for the life of the pool as of the timepoint timestamp
/// @return tick The tick at blockTimestamp
/// @return averageTick Time-weighted average tick
/// @return windowStartIndex Index of closest timepoint >= WINDOW seconds ago
function timepoints(
uint256 index
)
external
view
returns (
bool initialized,
uint32 blockTimestamp,
int56 tickCumulative,
uint88 volatilityCumulative,
int24 tick,
int24 averageTick,
uint16 windowStartIndex
);
/// @notice Returns the index of the last timepoint that was written.
/// @return index of the last timepoint written
function timepointIndex() external view returns (uint16);
/// @notice Initialize the plugin externally
/// @dev This function allows to initialize the plugin if it was created after the pool was created
function initialize() external;
/// @notice Returns the timestamp of the last timepoint that was written.
/// @return timestamp of the last timepoint
function lastTimepointTimestamp() external view returns (uint32);
/// @notice Returns information about whether oracle is initialized
/// @return true if oracle is initialized, otherwise false
function isInitialized() external view returns (bool);
/// @dev Reverts if a timepoint at or before the desired timepoint timestamp does not exist.
/// 0 may be passed as `secondsAgo' to return the current cumulative values.
/// If called with a timestamp falling between two timepoints, returns the counterfactual accumulator values
/// at exactly the timestamp between the two timepoints.
/// @dev `volatilityCumulative` values for timestamps after the last timepoint _should not_ be compared because they may differ due to interpolation errors
/// @param secondsAgo The amount of time to look back, in seconds, at which point to return a timepoint
/// @return tickCumulative The cumulative tick since the pool was first initialized, as of `secondsAgo`
/// @return volatilityCumulative The cumulative volatility value since the pool was first initialized, as of `secondsAgo`
function getSingleTimepoint(uint32 secondsAgo) external view returns (int56 tickCumulative, uint88 volatilityCumulative);
/// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
/// @dev Reverts if `secondsAgos` > oldest timepoint
/// @dev `volatilityCumulative` values for timestamps after the last timepoint _should not_ be compared because they may differ due to interpolation errors
/// @param secondsAgos Each amount of time to look back, in seconds, at which point to return a timepoint
/// @return tickCumulatives The cumulative tick since the pool was first initialized, as of each `secondsAgo`
/// @return volatilityCumulatives The cumulative volatility values since the pool was first initialized, as of each `secondsAgo`
function getTimepoints(uint32[] memory secondsAgos) external view returns (int56[] memory tickCumulatives, uint88[] memory volatilityCumulatives);
/// @notice Fills uninitialized timepoints with nonzero value
/// @dev Can be used to reduce the gas cost of future swaps
/// @param startIndex The start index, must be not initialized
/// @param amount of slots to fill, startIndex + amount must be <= type(uint16).max
function prepayTimepointsStorageSlots(uint16 startIndex, uint16 amount) external;
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
import './pool/IAlgebraPoolImmutables.sol';
import './pool/IAlgebraPoolState.sol';
import './pool/IAlgebraPoolActions.sol';
import './pool/IAlgebraPoolPermissionedActions.sol';
import './pool/IAlgebraPoolEvents.sol';
import './pool/IAlgebraPoolErrors.sol';
/// @title The interface for a Algebra Pool
/// @dev The pool interface is broken up into many smaller pieces.
/// This interface includes custom error definitions and cannot be used in older versions of Solidity.
/// For older versions of Solidity use #IAlgebraPoolLegacy
/// Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPool is
IAlgebraPoolImmutables,
IAlgebraPoolState,
IAlgebraPoolActions,
IAlgebraPoolPermissionedActions,
IAlgebraPoolEvents,
IAlgebraPoolErrors
{
// used only for combining interfaces
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @dev Initialization should be done in one transaction with pool creation to avoid front-running
/// @param initialPrice The initial sqrt price of the pool as a Q64.96
function initialize(uint160 initialPrice) external;
/// @notice Adds liquidity for the given recipient/bottomTick/topTick position
/// @dev The caller of this method receives a callback in the form of IAlgebraMintCallback#algebraMintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on bottomTick, topTick, the amount of liquidity, and the current price.
/// @param leftoversRecipient The address which will receive potential surplus of paid tokens
/// @param recipient The address for which the liquidity will be created
/// @param bottomTick The lower tick of the position in which to add liquidity
/// @param topTick The upper tick of the position in which to add liquidity
/// @param liquidityDesired The desired 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
/// @return liquidityActual The actual minted amount of liquidity
function mint(
address leftoversRecipient,
address recipient,
int24 bottomTick,
int24 topTick,
uint128 liquidityDesired,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1, uint128 liquidityActual);
/// @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 bottomTick The lower tick of the position for which to collect fees
/// @param topTick 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 bottomTick,
int24 topTick,
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 bottomTick The lower tick of the position for which to burn liquidity
/// @param topTick The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @param data Any data that should be passed through to the plugin
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(int24 bottomTick, int24 topTick, uint128 amount, bytes calldata data) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IAlgebraSwapCallback#algebraSwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback. If using the Router it should contain SwapRouter#SwapCallbackData
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Swap token0 for token1, or token1 for token0 with prepayment
/// @dev The caller of this method receives a callback in the form of IAlgebraSwapCallback#algebraSwapCallback
/// caller must send tokens in callback before swap calculation
/// the actually sent amount of tokens is used for further calculations
/// @param leftoversRecipient The address which will receive potential surplus of paid tokens
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountToSell The amount of the swap, only positive (exact input) amount allowed
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback. If using the Router it should contain SwapRouter#SwapCallbackData
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swapWithPaymentInAdvance(
address leftoversRecipient,
address recipient,
bool zeroToOne,
int256 amountToSell,
uint160 limitSqrtPrice,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IAlgebraFlashCallback#algebraFlashCallback
/// @dev All excess tokens paid in the callback are distributed to currently in-range liquidity providers as an additional fee.
/// If there are no in-range liquidity providers, the fee will be transferred to the first active provider in the future
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external;
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
/// @title Errors emitted by a pool
/// @notice Contains custom errors emitted by the pool
/// @dev Custom errors are separated from the common pool interface for compatibility with older versions of Solidity
interface IAlgebraPoolErrors {
// #### pool errors ####
/// @notice Emitted by the reentrancy guard
error locked();
/// @notice Emitted if arithmetic error occurred
error arithmeticError();
/// @notice Emitted if an attempt is made to initialize the pool twice
error alreadyInitialized();
/// @notice Emitted if an attempt is made to mint or swap in uninitialized pool
error notInitialized();
/// @notice Emitted if 0 is passed as amountRequired to swap function
error zeroAmountRequired();
/// @notice Emitted if invalid amount is passed as amountRequired to swap function
error invalidAmountRequired();
/// @notice Emitted if plugin fee param greater than fee/override fee
error incorrectPluginFee();
/// @notice Emitted if the pool received fewer tokens than it should have
error insufficientInputAmount();
/// @notice Emitted if there was an attempt to mint zero liquidity
error zeroLiquidityDesired();
/// @notice Emitted if actual amount of liquidity is zero (due to insufficient amount of tokens received)
error zeroLiquidityActual();
/// @notice Emitted if the pool received fewer tokens0 after flash than it should have
error flashInsufficientPaid0();
/// @notice Emitted if the pool received fewer tokens1 after flash than it should have
error flashInsufficientPaid1();
/// @notice Emitted if limitSqrtPrice param is incorrect
error invalidLimitSqrtPrice();
/// @notice Tick must be divisible by tickspacing
error tickIsNotSpaced();
/// @notice Emitted if a method is called that is accessible only to the factory owner or dedicated role
error notAllowed();
/// @notice Emitted if new tick spacing exceeds max allowed value
error invalidNewTickSpacing();
/// @notice Emitted if new community fee exceeds max allowed value
error invalidNewCommunityFee();
/// @notice Emitted if an attempt is made to manually change the fee value, but dynamic fee is enabled
error dynamicFeeActive();
/// @notice Emitted if an attempt is made by plugin to change the fee value, but dynamic fee is disabled
error dynamicFeeDisabled();
/// @notice Emitted if an attempt is made to change the plugin configuration, but the plugin is not connected
error pluginIsNotConnected();
/// @notice Emitted if a plugin returns invalid selector after hook call
/// @param expectedSelector The expected selector
error invalidHookResponse(bytes4 expectedSelector);
// #### LiquidityMath errors ####
/// @notice Emitted if liquidity underflows
error liquiditySub();
/// @notice Emitted if liquidity overflows
error liquidityAdd();
// #### TickManagement errors ####
/// @notice Emitted if the topTick param not greater then the bottomTick param
error topTickLowerOrEqBottomTick();
/// @notice Emitted if the bottomTick param is lower than min allowed value
error bottomTickLowerThanMIN();
/// @notice Emitted if the topTick param is greater than max allowed value
error topTickAboveMAX();
/// @notice Emitted if the liquidity value associated with the tick exceeds MAX_LIQUIDITY_PER_TICK
error liquidityOverflow();
/// @notice Emitted if an attempt is made to interact with an uninitialized tick
error tickIsNotInitialized();
/// @notice Emitted if there is an attempt to insert a new tick into the list of ticks with incorrect indexes of the previous and next ticks
error tickInvalidLinks();
// #### SafeTransfer errors ####
/// @notice Emitted if token transfer failed internally
error transferFailed();
// #### TickMath errors ####
/// @notice Emitted if tick is greater than the maximum or less than the minimum allowed value
error tickOutOfRange();
/// @notice Emitted if price is greater than the maximum or less than the minimum allowed value
error priceOutOfRange();
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swaps cannot be emitted by the pool before Initialize
/// @param price The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 price, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param liquidityAmount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed bottomTick,
int24 indexed topTick,
uint128 liquidityAmount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @param owner The owner of the position for which fees are collected
/// @param recipient The address that received fees
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(address indexed owner, address recipient, int24 indexed bottomTick, int24 indexed topTick, uint128 amount0, uint128 amount1);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param liquidityAmount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
/// @param pluginFee The fee to be sent to the plugin
event Burn(
address indexed owner,
int24 indexed bottomTick,
int24 indexed topTick,
uint128 liquidityAmount,
uint256 amount0,
uint256 amount1,
uint24 pluginFee
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param price 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 price of the pool after the swap
/// @param overrideFee The fee to be applied to the trade
/// @param pluginFee The fee to be sent to the plugin
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 price,
uint128 liquidity,
int24 tick,
uint24 overrideFee,
uint24 pluginFee
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);
/// @notice Emitted when the pool has higher balances than expected.
/// Any excess of tokens will be distributed between liquidity providers as fee.
/// @dev Fees after flash also will trigger this event due to mechanics of flash.
/// @param amount0 The excess of token0
/// @param amount1 The excess of token1
event ExcessTokens(uint256 amount0, uint256 amount1);
/// @notice Emitted when the community fee is changed by the pool
/// @param communityFeeNew The updated value of the community fee in thousandths (1e-3)
event CommunityFee(uint16 communityFeeNew);
/// @notice Emitted when the tick spacing changes
/// @param newTickSpacing The updated value of the new tick spacing
event TickSpacing(int24 newTickSpacing);
/// @notice Emitted when the plugin address changes
/// @param newPluginAddress New plugin address
event Plugin(address newPluginAddress);
/// @notice Emitted when the plugin config changes
/// @param newPluginConfig New plugin config
event PluginConfig(uint8 newPluginConfig);
/// @notice Emitted when the fee changes inside the pool
/// @param fee The current fee in hundredths of a bip, i.e. 1e-6
event Fee(uint16 fee);
/// @notice Emitted when the community vault address changes
/// @param newCommunityVault New community vault
event CommunityVault(address newCommunityVault);
/// @notice Emitted when the plugin does skim the excess of tokens
/// @param to THe receiver of tokens (plugin)
/// @param amount0 The amount of token0
/// @param amount1 The amount of token1
event Skim(address indexed to, uint256 amount0, uint256 amount1);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolImmutables {
/// @notice The Algebra factory contract, which must adhere to the IAlgebraFactory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by permissioned addresses
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolPermissionedActions {
/// @notice Set the community's % share of the fees. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newCommunityFee The new community fee percent in thousandths (1e-3)
function setCommunityFee(uint16 newCommunityFee) external;
/// @notice Set the new tick spacing values. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newTickSpacing The new tick spacing value
function setTickSpacing(int24 newTickSpacing) external;
/// @notice Set the new plugin address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newPluginAddress The new plugin address
function setPlugin(address newPluginAddress) external;
/// @notice Set new plugin config. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newConfig In the new configuration of the plugin,
/// each bit of which is responsible for a particular hook.
function setPluginConfig(uint8 newConfig) external;
/// @notice Set new community fee vault address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @dev Community fee vault receives collected community fees.
/// **accumulated but not yet sent to the vault community fees once will be sent to the `newCommunityVault` address**
/// @param newCommunityVault The address of new community fee vault
function setCommunityVault(address newCommunityVault) external;
/// @notice Set new pool fee. Can be called by owner if dynamic fee is disabled.
/// Called by the plugin if dynamic fee is enabled
/// @param newFee The new fee value
function setFee(uint16 newFee) external;
/// @notice Forces balances to match reserves. Excessive tokens will be distributed between active LPs
/// @dev Only plugin can call this function
function sync() external;
/// @notice Forces balances to match reserves. Excessive tokens will be sent to msg.sender
/// @dev Only plugin can call this function
function skim() external;
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @dev Important security note: when using this data by external contracts, it is necessary to take into account the possibility
/// of manipulation (including read-only reentrancy).
/// This interface is based on the UniswapV3 interface, credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolState {
/// @notice Safely get most important state values of Algebra Integral AMM
/// @dev Several values exposed as a single method to save gas when accessed externally.
/// **Important security note: this method checks reentrancy lock and should be preferred in most cases**.
/// @return sqrtPrice The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
/// @return tick The current global tick of the pool. May not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
/// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
/// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @return activeLiquidity The currently in-range liquidity available to the pool
/// @return nextTick The next initialized tick after current global tick
/// @return previousTick The previous initialized tick before (or at) current global tick
function safelyGetStateOfAMM()
external
view
returns (uint160 sqrtPrice, int24 tick, uint16 lastFee, uint8 pluginConfig, uint128 activeLiquidity, int24 nextTick, int24 previousTick);
/// @notice Allows to easily get current reentrancy lock status
/// @dev can be used to prevent read-only reentrancy.
/// This method just returns `globalState.unlocked` value
/// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
function isUnlocked() external view returns (bool unlocked);
// ! IMPORTANT security note: the pool state can be manipulated.
// ! The following methods do not check reentrancy lock themselves.
/// @notice The globalState structure in the pool stores many values but requires only one slot
/// and is exposed as a single method to save gas when accessed externally.
/// @dev **important security note: caller should check `unlocked` flag to prevent read-only reentrancy**
/// @return price The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
/// @return tick The current tick of the pool, i.e. according to the last tick transition that was run
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
/// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
/// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @return communityFee The community fee represented as a percent of all collected fee in thousandths, i.e. 1e-3 (so 100 is 10%)
/// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
function globalState() external view returns (uint160 price, int24 tick, uint16 lastFee, uint8 pluginConfig, uint16 communityFee, bool unlocked);
/// @notice Look up information about a specific tick in the pool
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @param tick The tick to look up
/// @return liquidityTotal The total amount of position liquidity that uses the pool either as tick lower or tick upper
/// @return liquidityDelta How much liquidity changes when the pool price crosses the tick
/// @return prevTick The previous tick in tick list
/// @return nextTick The next tick in tick list
/// @return outerFeeGrowth0Token The fee growth on the other side of the tick from the current tick in token0
/// @return outerFeeGrowth1Token The fee growth on the other side of the tick from the current tick in token1
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(
int24 tick
)
external
view
returns (
uint256 liquidityTotal,
int128 liquidityDelta,
int24 prevTick,
int24 nextTick,
uint256 outerFeeGrowth0Token,
uint256 outerFeeGrowth1Token
);
/// @notice The timestamp of the last sending of tokens to vault/plugin
/// @return The timestamp truncated to 32 bits
function lastFeeTransferTimestamp() external view returns (uint32);
/// @notice The amounts of token0 and token1 that will be sent to the vault
/// @dev Will be sent FEE_TRANSFER_FREQUENCY after communityFeeLastTimestamp
/// @return communityFeePending0 The amount of token0 that will be sent to the vault
/// @return communityFeePending1 The amount of token1 that will be sent to the vault
function getCommunityFeePending() external view returns (uint128 communityFeePending0, uint128 communityFeePending1);
/// @notice The amounts of token0 and token1 that will be sent to the plugin
/// @dev Will be sent FEE_TRANSFER_FREQUENCY after feeLastTransferTimestamp
/// @return pluginFeePending0 The amount of token0 that will be sent to the plugin
/// @return pluginFeePending1 The amount of token1 that will be sent to the plugin
function getPluginFeePending() external view returns (uint128 pluginFeePending0, uint128 pluginFeePending1);
/// @notice Returns the address of currently used plugin
/// @dev The plugin is subject to change
/// @return pluginAddress The address of currently used plugin
function plugin() external view returns (address pluginAddress);
/// @notice The contract to which community fees are transferred
/// @return communityVaultAddress The communityVault address
function communityVault() external view returns (address communityVaultAddress);
/// @notice Returns 256 packed tick initialized boolean values. See TickTree for more information
/// @param wordPosition Index of 256-bits word with ticks
/// @return The 256-bits word with packed ticks info
function tickTable(int16 wordPosition) external view returns (uint256);
/// @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
/// @return The fee growth accumulator for token0
function totalFeeGrowth0Token() 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
/// @return The fee growth accumulator for token1
function totalFeeGrowth1Token() external view returns (uint256);
/// @notice The current pool fee value
/// @dev In case dynamic fee is enabled in the pool, this method will call the plugin to get the current fee.
/// If the plugin implements complex fee logic, this method may return an incorrect value or revert.
/// In this case, see the plugin implementation and related documentation.
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return currentFee The current pool fee value in hundredths of a bip, i.e. 1e-6
function fee() external view returns (uint16 currentFee);
/// @notice The tracked token0 and token1 reserves of pool
/// @dev If at any time the real balance is larger, the excess will be transferred to liquidity providers as additional fee.
/// If the balance exceeds uint128, the excess will be sent to the communityVault.
/// @return reserve0 The last known reserve of token0
/// @return reserve1 The last known reserve of token1
function getReserves() external view returns (uint128 reserve0, uint128 reserve1);
/// @notice Returns the information about a position by the position's key
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @param key The position's key is a packed concatenation of the owner address, bottomTick and topTick indexes
/// @return liquidity The amount of liquidity in the position
/// @return innerFeeGrowth0Token Fee growth of token0 inside the tick range as of the last mint/burn/poke
/// @return innerFeeGrowth1Token Fee growth of token1 inside the tick range as of the last mint/burn/poke
/// @return fees0 The computed amount of token0 owed to the position as of the last mint/burn/poke
/// @return fees1 The computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(
bytes32 key
) external view returns (uint256 liquidity, uint256 innerFeeGrowth0Token, uint256 innerFeeGrowth1Token, uint128 fees0, uint128 fees1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks.
/// Returned value cannot exceed type(uint128).max
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The current in range liquidity
function liquidity() external view returns (uint128);
/// @notice The current tick spacing
/// @dev Ticks can only be initialized by new mints at multiples of this value
/// e.g.: a tickSpacing of 60 means ticks can be initialized every 60th tick, i.e., ..., -120, -60, 0, 60, 120, ...
/// However, tickspacing can be changed after the ticks have been initialized.
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The current tick spacing
function tickSpacing() external view returns (int24);
/// @notice The previous initialized tick before (or at) current global tick
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The previous initialized tick
function prevTickGlobal() external view returns (int24);
/// @notice The next initialized tick after current global tick
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The next initialized tick
function nextTickGlobal() external view returns (int24);
/// @notice The root of tick search tree
/// @dev Each bit corresponds to one node in the second layer of tick tree: '1' if node has at least one active bit.
/// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The root of tick search tree as bitmap
function tickTreeRoot() external view returns (uint32);
/// @notice The second layer of tick search tree
/// @dev Each bit in node corresponds to one node in the leafs layer (`tickTable`) of tick tree: '1' if leaf has at least one active bit.
/// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The node of tick search tree second layer
function tickTreeSecondLayer(int16) external view returns (uint256);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.9.0;
/// @title Contains common constants for Algebra contracts
/// @dev Constants moved to the library, not the base contract, to further emphasize their constant nature
library Constants {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 1 << 96;
uint256 internal constant Q128 = 1 << 128;
uint24 internal constant FEE_DENOMINATOR = 1e6;
uint16 internal constant FLASH_FEE = 0.01e4; // fee for flash loan in hundredths of a bip (0.01%)
uint16 internal constant INIT_DEFAULT_FEE = 0.05e4; // init default fee value in hundredths of a bip (0.05%)
uint16 internal constant MAX_DEFAULT_FEE = 5e4; // max default fee value in hundredths of a bip (5%)
int24 internal constant INIT_DEFAULT_TICK_SPACING = 60;
int24 internal constant MAX_TICK_SPACING = 500;
int24 internal constant MIN_TICK_SPACING = 1;
// the frequency with which the accumulated community fees are sent to the vault
uint32 internal constant FEE_TRANSFER_FREQUENCY = 8 hours;
// max(uint128) / (MAX_TICK - MIN_TICK)
uint128 internal constant MAX_LIQUIDITY_PER_TICK = 191757638537527648490752896198553;
uint16 internal constant MAX_COMMUNITY_FEE = 1e3; // 100%
uint256 internal constant COMMUNITY_FEE_DENOMINATOR = 1e3;
// role that can change settings in pools
bytes32 internal constant POOLS_ADMINISTRATOR_ROLE = keccak256('POOLS_ADMINISTRATOR');
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
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 {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
// Subtract 256 bit remainder from 512 bit number
assembly {
let remainder := mulmod(a, b, denominator)
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 {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
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 {
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 {
if (a == 0 || ((result = a * b) / a == b)) {
require(denominator > 0);
assembly {
result := add(div(result, denominator), gt(mod(result, denominator), 0))
}
} else {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
}
/// @notice Returns ceil(x / y)
/// @dev division by 0 has unspecified behavior, and must be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function unsafeDivRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IAlgebraPoolErrors.sol';
/// @title Contains logic and constants for interacting with the plugin through hooks
/// @dev Allows pool to check which hooks are enabled, as well as control the return selector
library Plugins {
function hasFlag(uint8 pluginConfig, uint256 flag) internal pure returns (bool res) {
assembly {
res := gt(and(pluginConfig, flag), 0)
}
}
function shouldReturn(bytes4 selector, bytes4 expectedSelector) internal pure {
if (selector != expectedSelector) revert IAlgebraPoolErrors.invalidHookResponse(expectedSelector);
}
uint256 internal constant BEFORE_SWAP_FLAG = 1;
uint256 internal constant AFTER_SWAP_FLAG = 1 << 1;
uint256 internal constant BEFORE_POSITION_MODIFY_FLAG = 1 << 2;
uint256 internal constant AFTER_POSITION_MODIFY_FLAG = 1 << 3;
uint256 internal constant BEFORE_FLASH_FLAG = 1 << 4;
uint256 internal constant AFTER_FLASH_FLAG = 1 << 5;
uint256 internal constant AFTER_INIT_FLAG = 1 << 6;
uint256 internal constant DYNAMIC_FEE = 1 << 7;
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IAlgebraPoolErrors.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
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return price A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 price) {
unchecked {
// get abs value
int24 absTickMask = tick >> (24 - 1);
uint256 absTick = uint24((tick + absTickMask) ^ absTickMask);
if (absTick > uint24(MAX_TICK)) revert IAlgebraPoolErrors.tickOutOfRange();
uint256 ratio = 0x100000000000000000000000000000000;
if (absTick & 0x1 != 0) ratio = 0xfffcb933bd6fad37aa2d162d1a594001;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick >= 0x40000) {
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
}
if (tick > 0) {
assembly {
ratio := div(not(0), ratio)
}
}
// 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 getTickAtSqrtRatio of the output price is always consistent
price = uint160((ratio + 0xFFFFFFFF) >> 32);
}
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case price < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param price The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 price) internal pure returns (int24 tick) {
unchecked {
// second inequality must be >= because the price can never reach the price at the max tick
if (price < MIN_SQRT_RATIO || price >= MAX_SQRT_RATIO) revert IAlgebraPoolErrors.priceOutOfRange();
uint256 ratio = uint256(price) << 32;
uint256 r = ratio;
uint256 msb;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
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; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= price ? tickHi : tickLow;
}
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '@cryptoalgebra/integral-core/contracts/libraries/FullMath.sol';
import '@cryptoalgebra/integral-core/contracts/libraries/Constants.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
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);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, Constants.Q96);
unchecked {
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
unchecked {
return toUint128(FullMath.mulDiv(amount1, Constants.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
unchecked {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << Constants.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
unchecked {
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, Constants.Q96);
}
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the poolDeployer and tokens
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xb3fc09be5eb433d99b1ec89fd8435aaf5ffea75c1879e19028aa2414a14b3c85;
/// @notice The identifying key of the pool
struct PoolKey {
address deployer;
address token0;
address token1;
}
/// @notice Returns PoolKey: the ordered tokens
/// @param deployer The custom pool deployer address
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(address deployer, address tokenA, address tokenB) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({deployer: deployer, token0: tokenA, token1: tokenB});
}
/// @notice Deterministically computes the pool address given the poolDeployer and PoolKey
/// @param poolDeployer The Algebra poolDeployer contract address
/// @param key The PoolKey
/// @return pool The contract address of the Algebra pool
function computeAddress(address poolDeployer, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1, 'Invalid order of tokens');
pool = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
poolDeployer,
keccak256(
key.deployer == address(0)
? abi.encode(key.token0, key.token1)
: abi.encode(key.deployer, key.token0, key.token1)
),
POOL_INIT_CODE_HASH
)
)
)
)
);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* 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 ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
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 override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` 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 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* 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 `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `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.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` 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.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
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 v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @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 Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @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 up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (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; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
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.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 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.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
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 (rounding == Rounding.Up && 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 down.
*
* 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
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.
*
* _Available since v3.4._
*/
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.
*
* _Available since v3.4._
*/
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.
*
* _Available since v3.4._
*/
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.
*
* _Available since v3.4._
*/
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 addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @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), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(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) {
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] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
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 keccak256(bytes(a)) == keccak256(bytes(b));
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
import "@cryptoalgebra/integral-core/contracts/libraries/FullMath.sol";
import "@cryptoalgebra/integral-core/contracts/libraries/TickMath.sol";
import "@cryptoalgebra/integral-core/contracts/libraries/Plugins.sol";
import "@cryptoalgebra/integral-core/contracts/interfaces/IAlgebraPool.sol";
import "@cryptoalgebra/integral-periphery/contracts/libraries/PoolAddress.sol";
import "@cryptoalgebra/integral-base-plugin/contracts/interfaces/plugins/IVolatilityOracle.sol";
/// @title Oracle library
/// @notice Provides functions to integrate with Algebra pool TWAP VolatilityOracle
library OracleLibrary {
/// @notice Fetches time-weighted average tick using Algebra VolatilityOracle
/// @param oracleAddress The address of oracle
/// @param period Number of seconds in the past to start calculating time-weighted average
/// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp-period) to block.timestamp
function consult(address oracleAddress, uint32 period) internal view returns (int24 timeWeightedAverageTick) {
require(period != 0, "Period is zero");
uint32[] memory secondAgos = new uint32[](2);
secondAgos[0] = period;
secondAgos[1] = 0;
IVolatilityOracle oracle = IVolatilityOracle(oracleAddress);
(int56[] memory tickCumulatives, ) = oracle.getTimepoints(secondAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
timeWeightedAverageTick = int24(tickCumulativesDelta / int56(uint56(period)));
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(period)) != 0)) timeWeightedAverageTick--;
}
/// @notice Given a tick and a token amount, calculates the amount of token received in exchange
/// @param tick Tick value used to calculate the quote
/// @param baseAmount Amount of token to be converted
/// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
/// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
/// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
) internal pure returns (uint256 quoteAmount) {
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
// Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
if (sqrtRatioX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
} else {
uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
: FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
}
}
/// @notice Fetches metadata of last available record (most recent) in oracle
/// @param oracleAddress The address of oracle
/// @return index The index of last available record (most recent) in oracle
/// @return timestamp The timestamp of last available record (most recent) in oracle, truncated to uint32
function lastTimepointMetadata(address oracleAddress) internal view returns (uint16 index, uint32 timestamp) {
index = latestIndex(oracleAddress);
timestamp = IVolatilityOracle(oracleAddress).lastTimepointTimestamp();
}
/// @notice Fetches metadata of oldest available record in oracle
/// @param oracleAddress The address of oracle
/// @return index The index of oldest available record in oracle
/// @return timestamp The timestamp of oldest available record in oracle, truncated to uint32
function oldestTimepointMetadata(address oracleAddress) internal view returns (uint16 index, uint32 timestamp) {
uint16 lastIndex = latestIndex(oracleAddress);
bool initialized;
unchecked {
// overflow is desired
index = lastIndex + 1;
(initialized, timestamp) = timepointMetadata(oracleAddress, index);
}
if (initialized) return (index, timestamp);
(, timestamp) = timepointMetadata(oracleAddress, 0);
return (0, timestamp);
}
/// @notice Gets information about whether the oracle has been initialized
function isInitialized(address oracleAddress) internal view returns (bool result) {
(result, ) = timepointMetadata(oracleAddress, 0);
return result;
}
/// @notice Fetches the index of last available record (most recent) in oracle
function latestIndex(address oracle) internal view returns (uint16) {
return (IVolatilityOracle(oracle).timepointIndex());
}
/// @notice Fetches the metadata of record in oracle
/// @param oracleAddress The address of oracle
/// @param index The index of record in oracle
/// @return initialized Whether or not the timepoint is initialized
/// @return timestamp The timestamp of timepoint
function timepointMetadata(
address oracleAddress,
uint16 index
) internal view returns (bool initialized, uint32 timestamp) {
(initialized, timestamp, , , , , ) = IVolatilityOracle(oracleAddress).timepoints(index);
}
/// @notice Checks if the oracle is currently connected to the pool
/// @param oracleAddress The address of oracle
/// @param oracleAddress The address of the pool
/// @return connected Whether or not the oracle is connected
function isOracleConnectedToPool(
address oracleAddress,
address poolAddress
) internal view returns (bool connected) {
IAlgebraPool pool = IAlgebraPool(poolAddress);
if (oracleAddress == pool.plugin()) {
(, , , uint8 pluginConfig, , ) = pool.globalState();
connected = Plugins.hasFlag(pluginConfig, Plugins.BEFORE_SWAP_FLAG);
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.4;
interface IICHIVaultFactory {
event FeeRecipient(address indexed sender, address feeRecipient);
event AmmFee(address indexed sender, uint256 ammFee);
event BaseFee(address indexed sender, uint256 baseFee);
event BaseFeeSplit(address indexed sender, uint256 baseFeeSplit);
event DeployICHIVaultFactory(address indexed sender, address algebraFactory);
event ICHIVaultCreated(
address indexed sender,
address indexed ichiVault,
address tokenA,
address tokenB,
bool allowTokenA,
bool allowTokenB,
uint256 count,
uint24 fee,
address token0,
address token1,
uint8 decimals0,
uint8 decimals1
);
function getICHIVault(bytes32 vaultKey) external view returns(address);
function algebraFactory() external view returns (address);
function nftManager() external view returns (address);
function farmingCenter() external view returns (address);
function incentiveMaker() external view returns (address);
function ammName() external view returns (string memory);
function feeRecipient() external view returns (address);
function ammFee() external view returns (uint256);
function baseFee() external view returns (uint256);
function baseFeeSplit() external view returns (uint256);
function setFeeRecipient(address _feeRecipient) external;
function setAmmFee(uint256 _ammFee) external;
function setBaseFee(uint256 _baseFee) external;
function setBaseFeeSplit(uint256 _baseFeeSplit) external;
function createICHIVault(
address tokenA,
bool allowTokenA,
address tokenB,
bool allowTokenB
) external returns (address ichiVault);
function genKey(
address deployer,
address token0,
address token1,
bool allowToken0,
bool allowToken1
) external pure returns (bytes32 key);
}{
"metadata": {
"bytecodeHash": "none"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"viaIR": true,
"evmVersion": "paris",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[],"name":"tickOutOfRange","type":"error"},{"inputs":[{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"uint256","name":"twap","type":"uint256"},{"internalType":"uint256","name":"auxTwap","type":"uint256"},{"internalType":"uint256","name":"auxTwapPeriod","type":"uint256"},{"internalType":"uint256","name":"hysteresis","type":"uint256"},{"internalType":"address","name":"basePlugin","type":"address"}],"name":"_checkPriceManipulation","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"basePlugin","type":"address"}],"name":"checkHysteresis","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"pool","type":"address"},{"internalType":"bool","name":"allowToken0","type":"bool"}],"name":"computeIVsymbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_basePlugin","type":"address"},{"internalType":"uint32","name":"_twapPeriod","type":"uint32"}],"name":"consult","outputs":[{"internalType":"int24","name":"timeWeightedAverageTick","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint160","name":"sqrtRatioX96","type":"uint160"},{"internalType":"uint160","name":"sqrtRatioAX96","type":"uint160"},{"internalType":"uint160","name":"sqrtRatioBX96","type":"uint160"},{"internalType":"uint128","name":"liquidity","type":"uint128"}],"name":"getAmountsForLiquidity","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint160","name":"sqrtRatioX96","type":"uint160"},{"internalType":"uint160","name":"sqrtRatioAX96","type":"uint160"},{"internalType":"uint160","name":"sqrtRatioBX96","type":"uint160"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"getLiquidityForAmounts","outputs":[{"internalType":"uint128","name":"liquidity","type":"uint128"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"int24","name":"tick","type":"int24"},{"internalType":"uint128","name":"baseAmount","type":"uint128"},{"internalType":"address","name":"baseToken","type":"address"},{"internalType":"address","name":"quoteToken","type":"address"}],"name":"getQuoteAtTick","outputs":[{"internalType":"uint256","name":"quoteAmount","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"int24","name":"currentTick","type":"int24"}],"name":"getSqrtRatioAtTick","outputs":[{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"oracleAddress","type":"address"},{"internalType":"address","name":"poolAddress","type":"address"}],"name":"isOracleConnectedToPool","outputs":[{"internalType":"bool","name":"connected","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"oracleAddress","type":"address"}],"name":"lastTimepointMetadata","outputs":[{"internalType":"uint16","name":"index","type":"uint16"},{"internalType":"uint32","name":"timestamp","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"y","type":"uint256"}],"name":"toUint128","outputs":[{"internalType":"uint128","name":"z","type":"uint128"}],"stateMutability":"pure","type":"function"}]Contract Creation Code
6080806040523461001a576119889081610020823930815050f35b600080fdfe60406080815260048036101561001457600080fd5b600090813560e01c90816343c57a2714610ce45781636098fd4a14610c0f57816361d4d94e14610be65781636672efe014610a5557816375fa56f21461065b578163809fdd33146105f257816382413489146102cd578163986cfba31461029b578163987cdc221461018a57508063ac2bca421461015c5763c72e160b1461009b57600080fd5b6080366003190112610159576100af610df5565b906100b8610e0b565b906100c1610ddf565b91606435916001600160801b0383168303610159579290836001600160a01b0383838282168382161161014e575b505086811690838116821161011a5750505061010c9394506111bb565b905b82519182526020820152f35b9295509091831611156101435750926101388261013e9495836111bb565b9361152b565b61010e565b935061013e9261152b565b9450925038806100ef565b80fd5b509060203660031901126101865760209061017d610178610df5565b6117c4565b90519015158152f35b5080fd5b916020915036600319018213610159576001600160a01b036101aa610df5565b85516303c37f5b60e11b815294911683858381845afa948515610291578395610255575b50839086519283809263f5985d3560e01b82525afa90811561024b578291610209575b5063ffffffff915061ffff8551941684521690820152f35b90508281813d8311610244575b61022081836115d2565b8101031261018657519063ffffffff82168203610159575063ffffffff90386101f1565b503d610216565b85513d84823e3d90fd5b9094508381813d831161028a575b61026d81836115d2565b810103126102865761027f8491611655565b94906101ce565b8280fd5b503d610263565b86513d85823e3d90fd5b82846020366003190112610186576020906102bc6102b7610dca565b610e44565b90516001600160a01b039091168152f35b90508280600319360112610286576102e3610df5565b92602480359163ffffffff958684168094036101865783156105bf5784519667ffffffffffffffff91606089018381118a8210176105ad578752600289526020989184918a91828501908a3683378961033b87611622565b528461034687611645565b528b8b51968795639d3a524160e01b87528b870192870152518091528d60448601939287915b83831061058c5750505091849003928492506001600160a01b031690505afa918215610291578392610472575b50506103ae6103a782611645565b5191611622565b5160060b9060060b0394667fffffffffffff1993667fffffffffffff8713858812176104505760060b9560060b861561046157600019948114878614166104505786810560020b968382129182610441575b5050610414575b50505050519060020b8152f35b93949293627fffff19841461043157505050019083808080610407565b634e487b7160e01b825260119052fd5b0760060b151590508880610400565b50634e487b7160e01b825260119052fd5b50634e487b7160e01b825260129052fd5b9091503d8084843e61048481846115d2565b82019086838303126105675782518181116105635783019282601f85011215610563578351936104b38561160a565b946104c08a5196876115d2565b8086528b8087019160051b83010191858311610588578c01905b82821061056b5750505089810151918211610563570181601f820112156105675780519089806105098461160a565b6105158b5191826115d2565b848152019260051b820101928311610563578901905b82821061053c575050508780610399565b81516affffffffffffffffffffff8116810361055f57815290890190890161052b565b8580fd5b8480fd5b8380fd5b81518060060b8103610584578152908c01908c016104da565b8880fd5b8780fd5b8451821686528b98508997509485019493909301926001909101908f61036c565b634e487b7160e01b8552604189528585fd5b845162461bcd60e51b8152602081880152600e818501526d506572696f64206973207a65726f60901b6044820152606490fd5b919050602036600319011261015957508035906001600160801b038216918203610620575060209151908152f35b606490602084519162461bcd60e51b835282015260156024820152745361666555696e743132383a206f766572666c6f7760581b6044820152fd5b839150606036600319011261028657803590610675610e0b565b93604435908115158203610159578451630dfe168160e01b81526020966001600160a01b03919082169088818781855afa9081156109b3578491610a38575b5087519184838881876395d89b4160e01b96878352165afa928315610a12578792918b918795610a1c575b508a5163d21220a760e01b815293849182905afa918215610a1257859291889184936109e3575b508a5195869384928352165afa9182156109d95783926109bd575b508651620a9a2d60e91b81529383858781335afa9485156109b357918895939185938b969561098f575b5088978990859a7a184f03e93ff9f4daa797ed6e38ed64bf6a1f0100000000000000009081811015610980575b50506d04ee2d6d415b85acef810000000080831015610972575b50662386f26fc1000080831015610963575b506305f5e10080831015610954575b5061271080831015610948575b5050606481101561093a575b600a80911015610930575b60016107fc818c016107f46107eb82611900565b9b519b8c6115d2565b808b52611900565b998160218a8c019d8e601f199e8f01903690378c0101905b6108fa575b50505050956108c694928492601f9860269650806000146108f35781945b50156108eb5750915b8a51998a94610865898701996249562d60e81b8b52825192839160238a019101610e21565b8501610883602d60f81b948560238401525180936024840190610e21565b0182602482015261089e8d8351938491602585019101610e21565b019060258201526108b7825180938d8785019101610e21565b010360068101875201856115d2565b6108e28551968795818752519283809288015287870190610e21565b01168101030190f35b905091610840565b8294610837565b600019019083906f181899199a1a9b1b9c1cb0b131b232b360811b8282061a83530491821561092b57919082610814565b610819565b98600101986107d7565b6064600291049901986107cc565b9a019990048c806107c0565b6008919b92049101998d6107b3565b6010919b92049101998d6107a4565b88919b92049101998d610792565b919b5091500487998d80610778565b6109ac9195503d8086833e6109a481836115d2565b81019061191c565b938b61074b565b88513d86823e3d90fd5b6109d29192503d8085833e6109a481836115d2565b9088610721565b87513d85823e3d90fd5b610a049193508c8d3d10610a0b575b6109fc81836115d2565b8101906117a5565b918c610706565b503d6109f2565b89513d87823e3d90fd5b610a319195503d8089833e6109a481836115d2565b938c6106df565b610a4f9150893d8b11610a0b576109fc81836115d2565b896106b4565b905060c03660031901126101865760a4359060443590608435908035906024356001600160a01b0386168603610be25780831115610b9b57610a9790836118dd565b670de0b6b3a764000090818102918183041490151715610b885782610abb9161119b565b935b60643515610b7c5780831115610b4457610ad790836118dd565b90670de0b6b3a764000091828102928184041490151715610b3157508291610afe9161119b565b925b11918215610b27575b5050610b13575080f35b610b1f610b24916117c4565b6118ab565b80f35b1190508380610b09565b634e487b7160e01b875260119052602486fd5b91610b4f90836118dd565b90670de0b6b3a764000091828102928184041490151715610b3157508291610b769161119b565b92610b00565b50505010610b13575080f35b634e487b7160e01b875260118252602487fd5b610ba583826118dd565b670de0b6b3a764000090818102918183041490151715610bcf5790610bc99161119b565b93610abd565b634e487b7160e01b885260118352602488fd5b8680fd5b8284806003193601126101865760209061017d610c01610df5565b610c09610e0b565b90611664565b828460a0366003190112610186576001600160801b03602092610c30610df5565b610c38610e0b565b91610c41610ddf565b60643592909190608435906001600160a01b03848782821683821611610cd8575b5050818116908781168211610c88575050505050610c7f9261155d565b915b5191168152f35b8592949693951611600014610cca578291610ca791610cad959461155d565b946115a9565b90508281168284161015610cc357505b91610c81565b9050610cbd565b9293505050610cbd926115a9565b90975094508a80610c62565b8383608036600319011261015957610cfa610dca565b602435916001600160801b039182841680940361018657610d19610ddf565b6001600160a01b036064358181169491939085900361018657610d3c8491610e44565b16948511610d945784800294808604811490151715610d81575060209650161015610d735790610d6b916113aa565b905b51908152f35b610d7c9161132d565b610d6b565b634e487b7160e01b815260118852602490fd5b936020975080610da391611215565b9350161015610dbc5790610db6916112e6565b90610d6d565b610dc591611261565b610db6565b600435908160020b8203610dda57565b600080fd5b604435906001600160a01b0382168203610dda57565b600435906001600160a01b0382168203610dda57565b602435906001600160a01b0382168203610dda57565b60005b838110610e345750506000910152565b8181015183820152602001610e24565b8060020b908160171d60020b80910160020b189062ffffff8216620d89e8811161118957600160801b9260018116611171575b60028116611155575b60048116611139575b6008811661111d575b60108116611101575b602081166110e5575b604081166110c9575b6080918282166110ae575b6101008216611093575b6102008216611078575b610400821661105d575b6108008216611042575b6110008216611027575b612000821661100c575b6140008216610ff1575b6180008216610fd6575b620100008216610fbb575b620200008216610fa1575b6204000080911015610f54575b505050600012610f4b575b63ffffffff0160201c6001600160a01b031690565b60001904610f36565b8116610f87575b6208000016610f6c575b8080610f2b565b6b048a170391f7dc42444e8fa26000929302901c9190610f65565b6d2216e584f5fa1ea926041bedfe98909302811c92610f5b565b936e5d6af8dedb81196699c329225ee60402821c93610f1e565b936f09aa508b5b7a84e1c677de54f3e99bc902821c93610f13565b936f31be135f97d08fd981231505542fcfa602821c93610f08565b936f70d869a156d2a1b890bb3df62baf32f702821c93610efe565b936fa9f746462d870fdf8a65dc1f90e061e502821c93610ef4565b936fd097f3bdfd2022b8845ad8f792aa582502821c93610eea565b936fe7159475a2c29b7443b29c7fa6e889d902821c93610ee0565b936ff3392b0822b70005940c7a398e4b70f302821c93610ed6565b936ff987a7253ac413176f2b074cf7815e5402821c93610ecc565b936ffcbe86c7900a88aedcffc83b479aa3a402821c93610ec2565b936ffe5dee046a99a2a811c461f1969c305302821c93610eb8565b926fff2ea16466c96a3843ec78b326b528610260801c92610ead565b926fff973b41fa98c081472e6896dfb254c00260801c92610ea4565b926fffcb9843d60f6159c9db58835c9266440260801c92610e9b565b926fffe5caca7e10e4e61c3624eaa0941cd00260801c92610e92565b926ffff2e50f5f656932ef12357cf3c7fdcc0260801c92610e89565b926ffff97272373d413259a46990580e213a0260801c92610e80565b6ffffcb933bd6fad37aa2d162d1a5940019350610e77565b604051633c10250f60e01b8152600490fd5b81156111a5570490565b634e487b7160e01b600052601260045260246000fd5b61120a9290916001600160a01b03918282168385161161120d575b61120291838116919085900384169060601b6fffffffffffffffffffffffffffffffff60601b166114b5565b91169061119b565b90565b9092906111d6565b8181029190600019828209918380841093039183830393680100000000000000009385851115610dda5714611257570990828211900360c01b910360401c1790565b5050505060401c90565b600160801b91608082901b9160001981850993838086109503948086039586851115610dda57146112de579082910981806000031680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b505091500490565b8181029190600019828209918380841093039183830393600160801b9385851115610dda5714611323570990828211900360801b910360801c1790565b5050505060801c90565b600160c01b9160c082901b9160001981850993838086109503948086039586851115610dda57146112de579082910981806000031680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b8181029190600019828209918380841093039183830393600160c01b9385851115610dda57146113e7570990828211900360401b910360c01c1790565b5050505060c01c90565b8181029190600019828209918380841093039183830393600160601b9385851115610dda571461142e570990828211900360a01b910360601c1790565b5050505060601c90565b90606082901b90600160601b60001981850993838086109503948086039586851115610dda57146112de579082910981806000031680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b918183029160001981850993838086109503948086039586851115610dda57146112de579082910981806000031680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b61120a92916001600160801b03916001600160a01b039182811683831611611557575b031691166113f1565b9061154e565b61158f9291906001600160a01b0390818316828216116115a3575b6115868284168383166113f1565b920316916114b5565b6001600160801b038116908103610dda5790565b91611578565b61158f92916001600160a01b039190828116838316116115cc575b031690611438565b906115c4565b90601f8019910116810190811067ffffffffffffffff8211176115f457604052565b634e487b7160e01b600052604160045260246000fd5b67ffffffffffffffff81116115f45760051b60200190565b80511561162f5760200190565b634e487b7160e01b600052603260045260246000fd5b80516001101561162f5760400190565b519061ffff82168203610dda57565b6001600160a01b03908116801561179d5760405163ef01df4f60e01b815260009383169190602081600481865afa908115611792579084918691611774575b5016146116af57505090565b9160c0600493604051948580926339db007960e21b82525afa9182156117675781926116e2575b50506001915016151590565b90915060c0833d821161175f575b816116fd60c093836115d2565b81010312610186578251908116036101595760208201518060020b036101595761172960408301611655565b5060608201519160ff831683036101865780611749608060a09301611655565b50015180151503610159575060019038806116d6565b3d91506116f0565b50604051903d90823e3d90fd5b61178c915060203d8111610a0b576109fc81836115d2565b386116a3565b6040513d87823e3d90fd5b505050600090565b90816020910312610dda57516001600160a01b0381168103610dda5790565b6040516303c37f5b60e11b81526020916001600160a01b0316908281600481855afa908115611867578391611873575b5060405163f5985d3560e01b815291829060049082905afa91821561186757600092611829575b505063ffffffff1642141590565b81813d8311611860575b61183d81836115d2565b8101031261018657519063ffffffff82168203610159575063ffffffff3861181b565b503d611833565b6040513d6000823e3d90fd5b9081813d83116118a4575b61188881836115d2565b81010312610dda5760049161189d8492611655565b50916117f4565b503d61187e565b156118b257565b60405162461bcd60e51b815260206004820152600360248201526211151360ea1b6044820152606490fd5b919082039182116118ea57565b634e487b7160e01b600052601160045260246000fd5b67ffffffffffffffff81116115f457601f01601f191660200190565b602081830312610dda5780519067ffffffffffffffff8211610dda570181601f82011215610dda57805161194f81611900565b9261195d60405194856115d2565b81845260208284010111610dda5761120a9160208085019101610e2156fea164736f6c6343000814000a
Deployed Bytecode
0x60406080815260048036101561001457600080fd5b600090813560e01c90816343c57a2714610ce45781636098fd4a14610c0f57816361d4d94e14610be65781636672efe014610a5557816375fa56f21461065b578163809fdd33146105f257816382413489146102cd578163986cfba31461029b578163987cdc221461018a57508063ac2bca421461015c5763c72e160b1461009b57600080fd5b6080366003190112610159576100af610df5565b906100b8610e0b565b906100c1610ddf565b91606435916001600160801b0383168303610159579290836001600160a01b0383838282168382161161014e575b505086811690838116821161011a5750505061010c9394506111bb565b905b82519182526020820152f35b9295509091831611156101435750926101388261013e9495836111bb565b9361152b565b61010e565b935061013e9261152b565b9450925038806100ef565b80fd5b509060203660031901126101865760209061017d610178610df5565b6117c4565b90519015158152f35b5080fd5b916020915036600319018213610159576001600160a01b036101aa610df5565b85516303c37f5b60e11b815294911683858381845afa948515610291578395610255575b50839086519283809263f5985d3560e01b82525afa90811561024b578291610209575b5063ffffffff915061ffff8551941684521690820152f35b90508281813d8311610244575b61022081836115d2565b8101031261018657519063ffffffff82168203610159575063ffffffff90386101f1565b503d610216565b85513d84823e3d90fd5b9094508381813d831161028a575b61026d81836115d2565b810103126102865761027f8491611655565b94906101ce565b8280fd5b503d610263565b86513d85823e3d90fd5b82846020366003190112610186576020906102bc6102b7610dca565b610e44565b90516001600160a01b039091168152f35b90508280600319360112610286576102e3610df5565b92602480359163ffffffff958684168094036101865783156105bf5784519667ffffffffffffffff91606089018381118a8210176105ad578752600289526020989184918a91828501908a3683378961033b87611622565b528461034687611645565b528b8b51968795639d3a524160e01b87528b870192870152518091528d60448601939287915b83831061058c5750505091849003928492506001600160a01b031690505afa918215610291578392610472575b50506103ae6103a782611645565b5191611622565b5160060b9060060b0394667fffffffffffff1993667fffffffffffff8713858812176104505760060b9560060b861561046157600019948114878614166104505786810560020b968382129182610441575b5050610414575b50505050519060020b8152f35b93949293627fffff19841461043157505050019083808080610407565b634e487b7160e01b825260119052fd5b0760060b151590508880610400565b50634e487b7160e01b825260119052fd5b50634e487b7160e01b825260129052fd5b9091503d8084843e61048481846115d2565b82019086838303126105675782518181116105635783019282601f85011215610563578351936104b38561160a565b946104c08a5196876115d2565b8086528b8087019160051b83010191858311610588578c01905b82821061056b5750505089810151918211610563570181601f820112156105675780519089806105098461160a565b6105158b5191826115d2565b848152019260051b820101928311610563578901905b82821061053c575050508780610399565b81516affffffffffffffffffffff8116810361055f57815290890190890161052b565b8580fd5b8480fd5b8380fd5b81518060060b8103610584578152908c01908c016104da565b8880fd5b8780fd5b8451821686528b98508997509485019493909301926001909101908f61036c565b634e487b7160e01b8552604189528585fd5b845162461bcd60e51b8152602081880152600e818501526d506572696f64206973207a65726f60901b6044820152606490fd5b919050602036600319011261015957508035906001600160801b038216918203610620575060209151908152f35b606490602084519162461bcd60e51b835282015260156024820152745361666555696e743132383a206f766572666c6f7760581b6044820152fd5b839150606036600319011261028657803590610675610e0b565b93604435908115158203610159578451630dfe168160e01b81526020966001600160a01b03919082169088818781855afa9081156109b3578491610a38575b5087519184838881876395d89b4160e01b96878352165afa928315610a12578792918b918795610a1c575b508a5163d21220a760e01b815293849182905afa918215610a1257859291889184936109e3575b508a5195869384928352165afa9182156109d95783926109bd575b508651620a9a2d60e91b81529383858781335afa9485156109b357918895939185938b969561098f575b5088978990859a7a184f03e93ff9f4daa797ed6e38ed64bf6a1f0100000000000000009081811015610980575b50506d04ee2d6d415b85acef810000000080831015610972575b50662386f26fc1000080831015610963575b506305f5e10080831015610954575b5061271080831015610948575b5050606481101561093a575b600a80911015610930575b60016107fc818c016107f46107eb82611900565b9b519b8c6115d2565b808b52611900565b998160218a8c019d8e601f199e8f01903690378c0101905b6108fa575b50505050956108c694928492601f9860269650806000146108f35781945b50156108eb5750915b8a51998a94610865898701996249562d60e81b8b52825192839160238a019101610e21565b8501610883602d60f81b948560238401525180936024840190610e21565b0182602482015261089e8d8351938491602585019101610e21565b019060258201526108b7825180938d8785019101610e21565b010360068101875201856115d2565b6108e28551968795818752519283809288015287870190610e21565b01168101030190f35b905091610840565b8294610837565b600019019083906f181899199a1a9b1b9c1cb0b131b232b360811b8282061a83530491821561092b57919082610814565b610819565b98600101986107d7565b6064600291049901986107cc565b9a019990048c806107c0565b6008919b92049101998d6107b3565b6010919b92049101998d6107a4565b88919b92049101998d610792565b919b5091500487998d80610778565b6109ac9195503d8086833e6109a481836115d2565b81019061191c565b938b61074b565b88513d86823e3d90fd5b6109d29192503d8085833e6109a481836115d2565b9088610721565b87513d85823e3d90fd5b610a049193508c8d3d10610a0b575b6109fc81836115d2565b8101906117a5565b918c610706565b503d6109f2565b89513d87823e3d90fd5b610a319195503d8089833e6109a481836115d2565b938c6106df565b610a4f9150893d8b11610a0b576109fc81836115d2565b896106b4565b905060c03660031901126101865760a4359060443590608435908035906024356001600160a01b0386168603610be25780831115610b9b57610a9790836118dd565b670de0b6b3a764000090818102918183041490151715610b885782610abb9161119b565b935b60643515610b7c5780831115610b4457610ad790836118dd565b90670de0b6b3a764000091828102928184041490151715610b3157508291610afe9161119b565b925b11918215610b27575b5050610b13575080f35b610b1f610b24916117c4565b6118ab565b80f35b1190508380610b09565b634e487b7160e01b875260119052602486fd5b91610b4f90836118dd565b90670de0b6b3a764000091828102928184041490151715610b3157508291610b769161119b565b92610b00565b50505010610b13575080f35b634e487b7160e01b875260118252602487fd5b610ba583826118dd565b670de0b6b3a764000090818102918183041490151715610bcf5790610bc99161119b565b93610abd565b634e487b7160e01b885260118352602488fd5b8680fd5b8284806003193601126101865760209061017d610c01610df5565b610c09610e0b565b90611664565b828460a0366003190112610186576001600160801b03602092610c30610df5565b610c38610e0b565b91610c41610ddf565b60643592909190608435906001600160a01b03848782821683821611610cd8575b5050818116908781168211610c88575050505050610c7f9261155d565b915b5191168152f35b8592949693951611600014610cca578291610ca791610cad959461155d565b946115a9565b90508281168284161015610cc357505b91610c81565b9050610cbd565b9293505050610cbd926115a9565b90975094508a80610c62565b8383608036600319011261015957610cfa610dca565b602435916001600160801b039182841680940361018657610d19610ddf565b6001600160a01b036064358181169491939085900361018657610d3c8491610e44565b16948511610d945784800294808604811490151715610d81575060209650161015610d735790610d6b916113aa565b905b51908152f35b610d7c9161132d565b610d6b565b634e487b7160e01b815260118852602490fd5b936020975080610da391611215565b9350161015610dbc5790610db6916112e6565b90610d6d565b610dc591611261565b610db6565b600435908160020b8203610dda57565b600080fd5b604435906001600160a01b0382168203610dda57565b600435906001600160a01b0382168203610dda57565b602435906001600160a01b0382168203610dda57565b60005b838110610e345750506000910152565b8181015183820152602001610e24565b8060020b908160171d60020b80910160020b189062ffffff8216620d89e8811161118957600160801b9260018116611171575b60028116611155575b60048116611139575b6008811661111d575b60108116611101575b602081166110e5575b604081166110c9575b6080918282166110ae575b6101008216611093575b6102008216611078575b610400821661105d575b6108008216611042575b6110008216611027575b612000821661100c575b6140008216610ff1575b6180008216610fd6575b620100008216610fbb575b620200008216610fa1575b6204000080911015610f54575b505050600012610f4b575b63ffffffff0160201c6001600160a01b031690565b60001904610f36565b8116610f87575b6208000016610f6c575b8080610f2b565b6b048a170391f7dc42444e8fa26000929302901c9190610f65565b6d2216e584f5fa1ea926041bedfe98909302811c92610f5b565b936e5d6af8dedb81196699c329225ee60402821c93610f1e565b936f09aa508b5b7a84e1c677de54f3e99bc902821c93610f13565b936f31be135f97d08fd981231505542fcfa602821c93610f08565b936f70d869a156d2a1b890bb3df62baf32f702821c93610efe565b936fa9f746462d870fdf8a65dc1f90e061e502821c93610ef4565b936fd097f3bdfd2022b8845ad8f792aa582502821c93610eea565b936fe7159475a2c29b7443b29c7fa6e889d902821c93610ee0565b936ff3392b0822b70005940c7a398e4b70f302821c93610ed6565b936ff987a7253ac413176f2b074cf7815e5402821c93610ecc565b936ffcbe86c7900a88aedcffc83b479aa3a402821c93610ec2565b936ffe5dee046a99a2a811c461f1969c305302821c93610eb8565b926fff2ea16466c96a3843ec78b326b528610260801c92610ead565b926fff973b41fa98c081472e6896dfb254c00260801c92610ea4565b926fffcb9843d60f6159c9db58835c9266440260801c92610e9b565b926fffe5caca7e10e4e61c3624eaa0941cd00260801c92610e92565b926ffff2e50f5f656932ef12357cf3c7fdcc0260801c92610e89565b926ffff97272373d413259a46990580e213a0260801c92610e80565b6ffffcb933bd6fad37aa2d162d1a5940019350610e77565b604051633c10250f60e01b8152600490fd5b81156111a5570490565b634e487b7160e01b600052601260045260246000fd5b61120a9290916001600160a01b03918282168385161161120d575b61120291838116919085900384169060601b6fffffffffffffffffffffffffffffffff60601b166114b5565b91169061119b565b90565b9092906111d6565b8181029190600019828209918380841093039183830393680100000000000000009385851115610dda5714611257570990828211900360c01b910360401c1790565b5050505060401c90565b600160801b91608082901b9160001981850993838086109503948086039586851115610dda57146112de579082910981806000031680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b505091500490565b8181029190600019828209918380841093039183830393600160801b9385851115610dda5714611323570990828211900360801b910360801c1790565b5050505060801c90565b600160c01b9160c082901b9160001981850993838086109503948086039586851115610dda57146112de579082910981806000031680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b8181029190600019828209918380841093039183830393600160c01b9385851115610dda57146113e7570990828211900360401b910360c01c1790565b5050505060c01c90565b8181029190600019828209918380841093039183830393600160601b9385851115610dda571461142e570990828211900360a01b910360601c1790565b5050505060601c90565b90606082901b90600160601b60001981850993838086109503948086039586851115610dda57146112de579082910981806000031680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b918183029160001981850993838086109503948086039586851115610dda57146112de579082910981806000031680920460028082600302188083028203028083028203028083028203028083028203028083028203028092029003029360018380600003040190848311900302920304170290565b61120a92916001600160801b03916001600160a01b039182811683831611611557575b031691166113f1565b9061154e565b61158f9291906001600160a01b0390818316828216116115a3575b6115868284168383166113f1565b920316916114b5565b6001600160801b038116908103610dda5790565b91611578565b61158f92916001600160a01b039190828116838316116115cc575b031690611438565b906115c4565b90601f8019910116810190811067ffffffffffffffff8211176115f457604052565b634e487b7160e01b600052604160045260246000fd5b67ffffffffffffffff81116115f45760051b60200190565b80511561162f5760200190565b634e487b7160e01b600052603260045260246000fd5b80516001101561162f5760400190565b519061ffff82168203610dda57565b6001600160a01b03908116801561179d5760405163ef01df4f60e01b815260009383169190602081600481865afa908115611792579084918691611774575b5016146116af57505090565b9160c0600493604051948580926339db007960e21b82525afa9182156117675781926116e2575b50506001915016151590565b90915060c0833d821161175f575b816116fd60c093836115d2565b81010312610186578251908116036101595760208201518060020b036101595761172960408301611655565b5060608201519160ff831683036101865780611749608060a09301611655565b50015180151503610159575060019038806116d6565b3d91506116f0565b50604051903d90823e3d90fd5b61178c915060203d8111610a0b576109fc81836115d2565b386116a3565b6040513d87823e3d90fd5b505050600090565b90816020910312610dda57516001600160a01b0381168103610dda5790565b6040516303c37f5b60e11b81526020916001600160a01b0316908281600481855afa908115611867578391611873575b5060405163f5985d3560e01b815291829060049082905afa91821561186757600092611829575b505063ffffffff1642141590565b81813d8311611860575b61183d81836115d2565b8101031261018657519063ffffffff82168203610159575063ffffffff3861181b565b503d611833565b6040513d6000823e3d90fd5b9081813d83116118a4575b61188881836115d2565b81010312610dda5760049161189d8492611655565b50916117f4565b503d61187e565b156118b257565b60405162461bcd60e51b815260206004820152600360248201526211151360ea1b6044820152606490fd5b919082039182116118ea57565b634e487b7160e01b600052601160045260246000fd5b67ffffffffffffffff81116115f457601f01601f191660200190565b602081830312610dda5780519067ffffffffffffffff8211610dda570181601f82011215610dda57805161194f81611900565b9261195d60405194856115d2565b81845260208284010111610dda5761120a9160208085019101610e2156fea164736f6c6343000814000a
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in MON
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.