Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Cross-Chain Transactions
Loading...
Loading
Contract Name:
MirrorTokenManager
Compiler Version
v0.8.26+commit.8a97fa7a
Optimization Enabled:
Yes with 200 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {Owned} from "solmate/src/auth/Owned.sol";
import {ERC6909} from "./external/solmate/ERC6909.sol";
import {IMirrorTokenManager} from "./interfaces/IMirrorTokenManager.sol";
import {IPairPoolManager} from "./interfaces/IPairPoolManager.sol";
contract MirrorTokenManager is IMirrorTokenManager, ERC6909, Owned {
mapping(address => bool) public poolManagers;
constructor(address initialOwner) Owned(initialOwner) {}
modifier onlyPoolManager() {
require(poolManagers[msg.sender], "UNAUTHORIZED");
_;
}
function mint(uint256 id, uint256 amount) external onlyPoolManager {
unchecked {
_mint(msg.sender, id, amount);
}
}
function mintInStatus(address receiver, uint256 id, uint256 amount) external onlyPoolManager {
unchecked {
_mint(receiver, id, amount);
}
}
function burn(uint256 id, uint256 amount) external onlyPoolManager {
unchecked {
_burn(msg.sender, id, amount);
}
}
function burn(address lendingPoolManager, uint256 id, uint256 amount)
external
onlyPoolManager
returns (uint256 pairAmount, uint256 lendingAmount)
{
uint256 balance = balanceOf[msg.sender][id];
if (balance >= amount) {
pairAmount = amount;
unchecked {
_burn(msg.sender, id, amount);
}
} else {
if (balance > 0) {
pairAmount = balance;
unchecked {
_burn(msg.sender, id, balance);
}
amount -= balance;
}
if (amount > 0) {
balance = balanceOf[lendingPoolManager][id];
if (balance > 0) {
amount = amount < balance ? amount : balance;
lendingAmount = amount;
unchecked {
_burn(lendingPoolManager, id, amount);
}
}
}
}
}
// ******************** OWNER CALL ********************
function addPoolManager(address _manager) external onlyOwner {
poolManagers[_manager] = true;
address statusManager = address(IPairPoolManager(_manager).statusManager());
require(statusManager != address(0), "STATUS_MANAGER_ERROR");
poolManagers[statusManager] = true;
address lendingPoolManager = address(IPairPoolManager(_manager).lendingPoolManager());
require(lendingPoolManager != address(0), "LENDING_MANAGER_ERROR");
poolManagers[lendingPoolManager] = true;
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Simple single owner authorization mixin.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
abstract contract Owned {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OwnershipTransferred(address indexed user, address indexed newOwner);
/*//////////////////////////////////////////////////////////////
OWNERSHIP STORAGE
//////////////////////////////////////////////////////////////*/
address public owner;
modifier onlyOwner() virtual {
require(msg.sender == owner, "UNAUTHORIZED");
_;
}
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(address _owner) {
owner = _owner;
emit OwnershipTransferred(address(0), _owner);
}
/*//////////////////////////////////////////////////////////////
OWNERSHIP LOGIC
//////////////////////////////////////////////////////////////*/
function transferOwnership(address newOwner) public virtual onlyOwner {
owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {IERC6909} from "../../interfaces/external/IERC6909.sol";
/// @notice Minimalist and gas efficient standard ERC6909 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC6909.sol)
abstract contract ERC6909 is IERC6909 {
/*//////////////////////////////////////////////////////////////
ERC6909 STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => mapping(address => bool)) public isOperator;
mapping(address => mapping(uint256 => uint256)) public balanceOf;
mapping(address => mapping(address => mapping(uint256 => uint256))) public allowance;
/*//////////////////////////////////////////////////////////////
ERC6909 LOGIC
//////////////////////////////////////////////////////////////*/
function transfer(address receiver, uint256 id, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender][id] -= amount;
balanceOf[receiver][id] += amount;
emit Transfer(msg.sender, msg.sender, receiver, id, amount);
return true;
}
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) public virtual returns (bool) {
if (msg.sender != sender && !isOperator[sender][msg.sender]) {
uint256 allowed = allowance[sender][msg.sender][id];
if (allowed != type(uint256).max) allowance[sender][msg.sender][id] = allowed - amount;
}
balanceOf[sender][id] -= amount;
balanceOf[receiver][id] += amount;
emit Transfer(msg.sender, sender, receiver, id, amount);
return true;
}
function approve(address spender, uint256 id, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender][id] = amount;
emit Approval(msg.sender, spender, id, amount);
return true;
}
function setOperator(address operator, bool approved) public virtual returns (bool) {
isOperator[msg.sender][operator] = approved;
emit OperatorSet(msg.sender, operator, approved);
return true;
}
/*//////////////////////////////////////////////////////////////
ERC165 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == 0x01ffc9a7 // ERC165 Interface ID for ERC165
|| interfaceId == 0x0f632fb3; // ERC165 Interface ID for ERC6909
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address receiver, uint256 id, uint256 amount) internal virtual {
balanceOf[receiver][id] += amount;
emit Transfer(msg.sender, address(0), receiver, id, amount);
}
function _burn(address sender, uint256 id, uint256 amount) internal virtual {
balanceOf[sender][id] -= amount;
emit Transfer(msg.sender, sender, address(0), id, amount);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {IERC6909} from "../interfaces/external/IERC6909.sol";
interface IMirrorTokenManager is IERC6909 {
function mint(uint256 id, uint256 amount) external;
function mintInStatus(address receiver, uint256 id, uint256 amount) external;
function burn(uint256 id, uint256 amount) external;
function burn(address lendingPool, uint256 id, uint256 amount)
external
returns (uint256 pairAmount, uint256 lendingAmount);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {BeforeSwapDelta, toBeforeSwapDelta} from "v4-core/types/BeforeSwapDelta.sol";
import {AddLiquidityParams, RemoveLiquidityParams} from "../types/LiquidityParams.sol";
import {ReleaseParams} from "../types/ReleaseParams.sol";
import {PoolStatus} from "../types/PoolStatus.sol";
import {IPairMarginManager} from "./IPairMarginManager.sol";
import {IMarginFees} from "./IMarginFees.sol";
import {IMarginLiquidity} from "./IMarginLiquidity.sol";
import {ILendingPoolManager} from "./ILendingPoolManager.sol";
import {IPoolStatusManager} from "./IPoolStatusManager.sol";
interface IPairPoolManager is IPairMarginManager {
function hooks() external view returns (IHooks hook);
function positionManagers(address _positionManager) external view returns (bool);
function lendingPoolManager() external view returns (ILendingPoolManager);
function statusManager() external view returns (IPoolStatusManager);
/// @notice Get current IMarginFees
function marginFees() external view returns (IMarginFees);
/// @notice Get current IMarginLiquidity
function marginLiquidity() external view returns (IMarginLiquidity);
/// @notice Get status of a pool
/// @param poolId The poolId of the pool to query
/// @return status The current status of the pool
function getStatus(PoolId poolId) external view returns (PoolStatus memory);
/// @notice Get the reserves of a pool
/// @param poolId The poolId of the pool to query
/// @return _reserve0 The reserve of the first token in the pool
/// @return _reserve1 The reserve of the second token in the pool
function getReserves(PoolId poolId) external view returns (uint256 _reserve0, uint256 _reserve1);
/// @notice Given an output amount of an asset and pair reserve, returns a required input amount of the other asset
/// @param poolId The poolId of the pool to query
/// @param zeroForOne If true, the input asset is the first token of the pair, otherwise it is the second token
/// @param amountOut an output amount
/// @return amountIn a required input amount
function getAmountIn(PoolId poolId, bool zeroForOne, uint256 amountOut) external view returns (uint256 amountIn);
/// @notice Given an input amount of an asset and pair reserve, returns the expected output amount of the other asset
/// @param poolId The poolId of the pool to query
/// @param zeroForOne If true, the input asset is the first token of the pair, otherwise it is the second token
/// @param amountIn a input amount
/// @return amountOut an output amount
function getAmountOut(PoolId poolId, bool zeroForOne, uint256 amountIn) external view returns (uint256 amountOut);
// ******************** HOOK CALL ********************
function initialize(PoolKey calldata key) external;
function swap(address sender, PoolKey calldata key, IPoolManager.SwapParams calldata params)
external
returns (
Currency specified,
Currency unspecified,
uint256 specifiedAmount,
uint256 unspecifiedAmount,
uint24 swapFee
);
// ******************** USER CALL ********************
/// @notice Add liquidity to a pool
/// @param params The parameters for the add liquidity hook
/// @return liquidity The amount of liquidity minted
function addLiquidity(AddLiquidityParams calldata params) external payable returns (uint256 liquidity);
/// @notice Remove liquidity from a pool
/// @param params The parameters for the remove liquidity hook
/// @return amount0 The amount of token0 repaid
/// @return amount1 The amount of token1 repaid
function removeLiquidity(RemoveLiquidityParams calldata params)
external
returns (uint256 amount0, uint256 amount1);
// ******************** EXTERNAL FUNCTIONS ********************
function mirrorInRealOut(PoolId poolId, PoolStatus memory status, Currency currency, uint256 amount)
external
returns (bool success);
function swapMirror(address recipient, PoolId poolId, bool zeroForOne, uint256 amountIn, uint256 amountOutMin)
external
payable
returns (uint256 amountOut);
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount) external returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for accrues over a contract balance, wrapped as a ERC6909
interface IERC6909 {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IPoolManager} from "./IPoolManager.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
IPoolManager.ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
bytes calldata hookData
) external returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
IPoolManager.SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Currency} from "v4-core/types/Currency.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
/// @notice Liquidity parameters for addLiquidity
struct AddLiquidityParams {
/// @notice The id of the pool
PoolId poolId;
/// @notice The token0 amount to add
uint256 amount0;
/// @notice The token1 amount to add
uint256 amount1;
/// @notice The token0 min amount to get
uint256 amount0Min;
/// @notice The token1 min amount to get
uint256 amount1Min;
/// @notice LP level 1: x*y, 2: (x+x')*y, 3: x*(y+y'), 4: (x+x')*(y+y')
uint8 level;
/// @notice The address of source
address source;
/// @notice Deadline for the transaction
uint256 deadline;
}
/// @notice Liquidity parameters for removeLiquidity
struct RemoveLiquidityParams {
/// @notice The id of the pool
PoolId poolId;
/// @notice LP level
uint8 level;
/// @notice LP amount to remove
uint256 liquidity;
/// @notice The token0 min amount to get
uint256 amount0Min;
/// @notice The token1 min amount to get
uint256 amount1Min;
/// @notice Deadline for the transaction
uint256 deadline;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {PoolId} from "v4-core/types/PoolId.sol";
/// @notice ReleaseParams is a struct that contains all the parameters needed to release margin position.
struct ReleaseParams {
/// @notice The poolId of the pool.
PoolId poolId;
/// @notice true: currency1 is marginToken, false: currency0 is marginToken
bool marginForOne;
/// @notice Payment address.
address payer;
/// @notice Debt amount.
uint256 debtAmount;
/// @notice Repay amount.
uint256 repayAmount;
/// @notice Release amount.
uint256 releaseAmount;
/// @notice The raw amount of borrowed tokens.
uint256 rawBorrowAmount;
/// @notice Deadline for the transaction
uint256 deadline;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {UQ112x112} from "../libraries/UQ112x112.sol";
import {FeeLibrary} from "../libraries/FeeLibrary.sol";
/// @notice Returns the status of a hook.
struct PoolStatus {
/// @notice The block timestamp of the last update of the pool.
uint32 blockTimestampLast;
/// @notice The real reserve of the first currency in the pool.(x)
uint112 realReserve0;
/// @notice The real reserve of the second currency in the pool.(y)
uint112 realReserve1;
/// @notice The mirror reserve of the first currency in the pool.(x')
uint112 mirrorReserve0;
/// @notice The mirror reserve of the second currency in the pool.(y')
uint112 mirrorReserve1;
/// @notice The margin fee of the pool.
uint24 marginFee;
/// @notice The real reserve of the first currency in the lending pool.
uint112 lendingRealReserve0;
/// @notice The real reserve of the second currency in the lending pool.
uint112 lendingRealReserve1;
/// @notice The mirror reserve of the first currency in the lending pool.
uint112 lendingMirrorReserve0;
/// @notice The mirror reserve of the second currency in the lending pool.
uint112 lendingMirrorReserve1;
/// @notice The truncated reserve of the first currency in the lending pool.
uint112 truncatedReserve0;
/// @notice The truncated reserve of the second currency in the lending pool.
uint112 truncatedReserve1;
/// @notice The cumulative borrow rate of the first currency in the pool.
uint256 rate0CumulativeLast;
/// @notice The cumulative borrow rate of the second currency in the pool.
uint256 rate1CumulativeLast;
/// @notice The the key for identifying a pool
PoolKey key;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {Currency} from "v4-core/types/Currency.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {MarginParamsVo} from "../types/MarginParams.sol";
import {ReleaseParams} from "../types/ReleaseParams.sol";
import {PoolStatus} from "../types/PoolStatus.sol";
import {IMarginFees} from "../interfaces/IMarginFees.sol";
import {IMarginLiquidity} from "../interfaces/IMarginLiquidity.sol";
import {ILendingPoolManager} from "../interfaces/ILendingPoolManager.sol";
import {IPoolStatusManager} from "../interfaces/IPoolStatusManager.sol";
interface IPairMarginManager {
function lendingPoolManager() external view returns (ILendingPoolManager);
function statusManager() external view returns (IPoolStatusManager);
/// @notice Get current IMarginFees
function marginFees() external view returns (IMarginFees);
/// @notice Get current IMarginLiquidity
function marginLiquidity() external view returns (IMarginLiquidity);
/// @notice Get status of a pool
/// @param poolId The poolId of the pool to query
/// @return status The current status of the pool
function getStatus(PoolId poolId) external view returns (PoolStatus memory);
/// @notice Get the reserves of a pool
/// @param poolId The poolId of the pool to query
/// @return _reserve0 The reserve of the first token in the pool
/// @return _reserve1 The reserve of the second token in the pool
function getReserves(PoolId poolId) external view returns (uint256 _reserve0, uint256 _reserve1);
/// @notice Given an output amount of an asset and pair reserve, returns a required input amount of the other asset
/// @param poolId The poolId of the pool to query
/// @param zeroForOne If true, the input asset is the first token of the pair, otherwise it is the second token
/// @param amountOut an output amount
/// @return amountIn a required input amount
function getAmountIn(PoolId poolId, bool zeroForOne, uint256 amountOut) external view returns (uint256 amountIn);
/// @notice Given an input amount of an asset and pair reserve, returns the expected output amount of the other asset
/// @param poolId The poolId of the pool to query
/// @param zeroForOne If true, the input asset is the first token of the pair, otherwise it is the second token
/// @param amountIn a input amount
/// @return amountOut an output amount
function getAmountOut(PoolId poolId, bool zeroForOne, uint256 amountIn) external view returns (uint256 amountOut);
// ******************** MARGIN FUNCTIONS ********************
function setBalances(address sender, PoolId poolId) external returns (PoolStatus memory _status);
/// @notice Margin
/// @param sender The address of sender
/// @param status The status for the pool
/// @param paramsVo The parameters for the margin hook
/// @return The updated parameters for the margin hook
function margin(address sender, PoolStatus memory status, MarginParamsVo memory paramsVo)
external
payable
returns (MarginParamsVo memory);
/// @notice Release
/// @param sender The address of sender
/// @param status The status for the pool
/// @param params The parameters for the release hook
/// @return The amount of tokens repaid
function release(address sender, PoolStatus memory status, ReleaseParams memory params)
external
payable
returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "v4-core/types/Currency.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {MarginParams} from "../types/MarginParams.sol";
import {ReleaseParams} from "../types/ReleaseParams.sol";
import {PoolStatus} from "../types/PoolStatus.sol";
import {IMarginLiquidity} from "./IMarginLiquidity.sol";
interface IMarginFees {
/// @notice Get the address of the fee receiver
/// @return feeTo The address of the fee receiver
function feeTo() external view returns (address);
function marginFee() external view returns (uint24);
/// @notice Get the dynamic swap fee from the status of pool
/// @param status The status of the pool
/// @param zeroForOne if true amountIn is currency0,else amountIn is currency1
/// @param amountIn The amount swap in
/// @param amountOut The amount swap out
/// @return _fee The dynamic fee of swap transaction
function dynamicFee(PoolStatus memory status, bool zeroForOne, uint256 amountIn, uint256 amountOut)
external
view
returns (uint24 _fee);
/// @notice Get the dynamic liquidity fee from the status of pool
/// @param _poolManager The address of pool manager
/// @param poolId The pool id
/// @param zeroForOne if true amountIn is currency0,else amountIn is currency1
/// @param amountIn The amount swap in
/// @param amountOut The amount swap out
/// @return _fee The dynamic fee of swap transaction
/// @return _marginFee The fee of margin transaction
function getPoolFees(address _poolManager, PoolId poolId, bool zeroForOne, uint256 amountIn, uint256 amountOut)
external
view
returns (uint24 _fee, uint24 _marginFee);
/// @notice Get the borrow rate from the reserves
/// @param realReserve The real reserve of the pool
/// @param mirrorReserve The mirror reserve of the pool
/// @return The borrow rate
function getBorrowRateByReserves(uint256 realReserve, uint256 mirrorReserve) external view returns (uint256);
/// @notice Get the last cumulative multiplication of rate
/// @param interestReserve0 The interest reserve of the first currency
/// @param interestReserve1 The interest reserve of the second currency
/// @param status The status of the pairPool
/// @return rate0CumulativeLast The currency0 last cumulative multiplication of rate
/// @return rate1CumulativeLast The currency1 last cumulative multiplication of rate
function getBorrowRateCumulativeLast(uint256 interestReserve0, uint256 interestReserve1, PoolStatus memory status)
external
view
returns (uint256 rate0CumulativeLast, uint256 rate1CumulativeLast);
/// @notice Get the last cumulative multiplication of rate
/// @param pairPoolManager The address of pairPoolManager
/// @param poolId The pool id
/// @param marginForOne true: currency1 is marginToken, false: currency0 is marginToken
/// @return The last cumulative multiplication of rate
function getBorrowRateCumulativeLast(address pairPoolManager, PoolId poolId, bool marginForOne)
external
view
returns (uint256);
/// @notice Get the current borrow rate
/// @param pairPoolManager The address of pairPoolManager
/// @param status The status of the pool
/// @param marginForOne true: currency1 is marginToken, false: currency0 is marginToken
/// @return The current borrow rate
function getBorrowRate(address pairPoolManager, PoolStatus memory status, bool marginForOne)
external
view
returns (uint256);
/// @notice Get the current borrow rate
/// @param pairPoolManager The address of pairPoolManager
/// @param poolId The pool id
/// @param marginForOne true: currency1 is marginToken, false: currency0 is marginToken
/// @return The current borrow rate
function getBorrowRate(address pairPoolManager, PoolId poolId, bool marginForOne) external view returns (uint256);
/// @notice Get the protocol part of the totalFee
/// @param totalFee Total fee amount
/// @return feeAmount The protocol part fee amount
function getProtocolSwapFeeAmount(uint256 totalFee) external view returns (uint256 feeAmount);
function getProtocolMarginFeeAmount(uint256 totalFee) external view returns (uint256 feeAmount);
function getProtocolInterestFeeAmount(uint256 totalFee) external view returns (uint256 feeAmount);
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @param poolManager The address of pool manager
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address poolManager, address recipient, Currency currency, uint256 amount)
external
returns (uint256);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {PoolId} from "v4-core/types/PoolId.sol";
import {IERC6909} from "../interfaces/external/IERC6909.sol";
import {PoolStatus} from "../types/PoolStatus.sol";
interface IMarginLiquidity is IERC6909 {
function addLiquidity(address sender, uint256 id, uint8 level, uint256 amount) external;
function removeLiquidity(address sender, uint256 id, uint8 level, uint256 amount) external returns (uint256);
function changeLiquidity(PoolId poolId, uint256 _reserve0, uint256 _reserve1, int256 interest0, int256 interest1)
external
returns (uint256 liquidity);
function addInterests(PoolId poolId, uint256 _reserve0, uint256 _reserve1, uint256 interest0, uint256 interest1)
external
returns (uint256 liquidity);
function getMaxSliding() external view returns (uint24);
function getPoolId(PoolId poolId) external pure returns (uint256 uPoolId);
function getSupplies(uint256 uPoolId)
external
view
returns (uint256 totalSupply, uint256 retainSupply0, uint256 retainSupply1);
/// Get the supplies of pool status
/// @param poolManager The address of pool manager
/// @param poolId The pool id
/// @return totalSupply The total supply
/// @return retainSupply0 The level1+level3 supply(can't mirror x)
/// @return retainSupply1 The level1+level2 supply(can't mirror y)
function getPoolSupplies(address poolManager, PoolId poolId)
external
view
returns (uint256 totalSupply, uint256 retainSupply0, uint256 retainSupply1);
/// Get the reserves can claim interests
/// @param pairPoolManager The address of pool manager
/// @param poolId The pool Id
/// @param status The status of pool
/// @return reserve0 The reserve can claim interest0
/// @return reserve1 The reserve can claim interest1
function getInterestReserves(address pairPoolManager, PoolId poolId, PoolStatus memory status)
external
view
returns (uint256 reserve0, uint256 reserve1);
function getFlowReserves(address pairPoolManager, PoolId poolId, PoolStatus memory status)
external
view
returns (uint256 reserve0, uint256 reserve1);
function getMarginReserves(address pairPoolManager, PoolId poolId, PoolStatus memory status)
external
view
returns (
uint256 marginReserve0,
uint256 marginReserve1,
uint256 incrementMaxMirror0,
uint256 incrementMaxMirror1
);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {Currency} from "v4-core/types/Currency.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
// Local
import {IERC6909Accrues} from "../interfaces/external/IERC6909Accrues.sol";
import {PoolStatus} from "../types/PoolStatus.sol";
interface ILendingPoolManager is IERC6909Accrues {
// ******************** EXTERNAL CALL ********************
function getGrownRatioX112(uint256 id, uint256 growAmount) external view returns (uint256 accruesRatioX112Grown);
function computeRealAmount(PoolId poolId, Currency currency, uint256 originalAmount)
external
view
returns (uint256 amount);
// ******************** POOL CALL ********************
function updateInterests(uint256 id, int256 interest) external;
function updateProtocolInterests(address caller, PoolId poolId, Currency currency, uint256 interest)
external
returns (uint256 originalAmount);
function sync(PoolId poolId, PoolStatus memory status) external;
function mirrorIn(address caller, address receiver, PoolId poolId, Currency currency, uint256 amount)
external
returns (uint256 originalAmount);
function mirrorInRealOut(PoolId poolId, PoolStatus memory status, Currency currency, uint256 amount)
external
returns (uint256 exchangeAmount);
function realIn(address caller, address recipient, PoolId poolId, Currency currency, uint256 amount)
external
returns (uint256 originalAmount);
function reserveOut(
address caller,
address payer,
PoolId poolId,
PoolStatus memory status,
Currency currency,
uint256 amount
) external;
// ******************** USER CALL ********************
function deposit(address sender, address recipient, PoolId poolId, Currency currency, uint256 amount)
external
payable
returns (uint256 originalAmount);
function deposit(address recipient, PoolId poolId, Currency currency, uint256 amount)
external
payable
returns (uint256 originalAmount);
function withdraw(address recipient, PoolId poolId, Currency currency, uint256 amount)
external
returns (uint256 originalAmount);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {PoolId} from "v4-core/types/PoolId.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {Currency, CurrencyLibrary} from "v4-core/types/Currency.sol";
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {IStatusBase} from "./IStatusBase.sol";
import {IMarginFees} from "./IMarginFees.sol";
import {BalanceStatus} from "../types/BalanceStatus.sol";
import {PoolStatus} from "../types/PoolStatus.sol";
import {GlobalStatus} from "../types/GlobalStatus.sol";
interface IPoolStatusManager is IStatusBase {
function hooks() external view returns (IHooks hook);
/// @notice Get current IMarginFees
function marginFees() external view returns (IMarginFees hook);
function initialize(PoolKey calldata key) external;
function getGlobalStatus(PoolId poolId) external view returns (GlobalStatus memory _status);
function getStatus(PoolId poolId) external view returns (PoolStatus memory _status);
function getAmountOut(PoolStatus memory status, bool zeroForOne, uint256 amountIn)
external
view
returns (uint256 amountOut, uint24 fee, uint256 feeAmount);
function getAmountIn(PoolStatus memory status, bool zeroForOne, uint256 amountOut)
external
view
returns (uint256 amountIn, uint24 fee, uint256 feeAmount);
function protocolFeesAccrued(Currency currency) external view returns (uint256);
function setBalances(address sender, PoolId poolId) external returns (PoolStatus memory _status);
function update(PoolId poolId) external;
function updateSwapProtocolFees(Currency currency, uint256 amount) external returns (uint256 restAmount);
function updateMarginProtocolFees(Currency currency, uint256 amount) external returns (uint256 restAmount);
function collectProtocolFees(Currency currency, uint256 amount) external returns (uint256 amountCollected);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
library UQ112x112 {
error Overflow();
uint224 constant Q112 = 2 ** 112;
/// @notice Cast a uint256 to a uint112, revert on overflow or underflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type uint112
function toUint112(uint256 x) internal pure returns (uint112 y) {
y = uint112(x);
if (x != y) revert Overflow();
}
/// @notice Cast a uint256 to a uint224, revert on overflow or underflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type uint224
function toUint224(uint256 x) internal pure returns (uint224 y) {
y = uint224(x);
if (x != y) revert Overflow();
}
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// decode UQ112x112 as a uint112
function decode(uint224 x) internal pure returns (uint112 z) {
z = uint112(x / Q112); // never overflows
}
function encode256(uint256 y) internal pure returns (uint256 z) {
z = y * Q112;
}
function decode256(uint256 x) internal pure returns (uint256 z) {
z = x / Q112;
}
function add(uint112 x, uint256 y) internal pure returns (uint112 z) {
z = x + toUint112(y);
}
// subtract
function sub(uint112 x, uint256 y) internal pure returns (uint112 z) {
z = x - toUint112(y);
}
function mul(uint112 x, uint256 y) internal pure returns (uint224 z) {
z = toUint224(x) * toUint224(y);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / toUint224(y);
}
function scaleDown(uint112 x, uint256 scaler, uint256 denominator) internal pure returns (uint112 z) {
z = toUint112(Math.mulDiv(x, denominator - scaler, denominator));
}
function growRatioX112(uint256 ratio, uint256 numerator, uint256 denominator)
internal
pure
returns (uint256 result)
{
result = ratio;
if (numerator > 0 && denominator > 0) result += Math.mulDiv(Q112, numerator, denominator);
}
function reduceRatioX112(uint256 ratio, uint256 numerator, uint256 denominator)
internal
pure
returns (uint256 result)
{
result = ratio;
if (numerator > 0 && denominator > 0) {
uint256 cut = Math.mulDiv(Q112, numerator, denominator, Math.Rounding.Ceil);
if (result > cut) {
result -= cut;
} else {
result = 0;
}
}
}
function mulRatioX112(uint256 input, uint256 ratioX112) internal pure returns (uint256 result) {
result = Math.mulDiv(input, ratioX112, Q112);
}
function divRatioX112(uint256 input, uint256 ratioX112) internal pure returns (uint256 result) {
result = Math.mulDiv(input, Q112, ratioX112);
}
function increaseInterestCeil(uint128 current, uint256 rateCumulativeOld, uint256 rateCumulativeLast)
internal
pure
returns (uint128 result)
{
result = toUint112(Math.mulDiv(current, rateCumulativeLast, rateCumulativeOld, Math.Rounding.Ceil));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {PerLibrary} from "./PerLibrary.sol";
library FeeLibrary {
function deductFrom(uint24 fee, uint256 amount) internal pure returns (uint256 amountWithoutFee) {
uint256 ratio = PerLibrary.ONE_MILLION - fee;
amountWithoutFee = Math.mulDiv(amount, ratio, PerLibrary.ONE_MILLION);
}
function deduct(uint24 fee, uint256 amount) internal pure returns (uint256 amountWithoutFee, uint256 feeAmount) {
amountWithoutFee = deductFrom(fee, amount);
feeAmount = amount - amountWithoutFee;
}
function attachFrom(uint24 fee, uint256 amount) internal pure returns (uint256 amountWithFee) {
uint256 ratio = PerLibrary.ONE_MILLION - fee;
amountWithFee = Math.mulDiv(amount, PerLibrary.ONE_MILLION, ratio);
}
function attach(uint24 fee, uint256 amount) internal pure returns (uint256 amountWithFee, uint256 feeAmount) {
amountWithFee = attachFrom(fee, amount);
feeAmount = amountWithFee - amount;
}
function part(uint24 fee, uint256 amount) internal pure returns (uint256 feeAmount) {
feeAmount = Math.mulDiv(amount, uint256(fee), PerLibrary.ONE_MILLION);
}
function bound(uint24 fee, uint256 amount) internal pure returns (uint256 lower, uint256 upper) {
lower = deductFrom(fee, amount);
upper = attachFrom(fee, amount);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {PoolId} from "v4-core/types/PoolId.sol";
import {Currency, CurrencyLibrary} from "v4-core/types/Currency.sol";
/// @notice MarginParams is a struct that contains all the parameters needed to open a margin position.
struct MarginParams {
/// @notice The poolId of the pool.
PoolId poolId;
/// @notice true: currency1 is marginToken, false: currency0 is marginToken
bool marginForOne;
/// @notice Leverage factor of the margin position.
uint24 leverage;
/// @notice The amount of margin
uint256 marginAmount;
/// @notice The borrow amount of the margin position.When the parameter is passed in, it is 0.
uint256 borrowAmount;
/// @notice The maximum borrow amount of the margin position.
uint256 borrowMaxAmount;
/// @notice The address of recipient
address recipient;
/// @notice Deadline for the transaction
uint256 deadline;
}
struct MarginParamsVo {
MarginParams params;
/// @notice The total amount of margin,equals to marginAmount * leverage * (1-marginFee).
uint256 marginTotal;
/// @notice Min margin level.
uint24 minMarginLevel;
/// @notice Min margin level.
Currency marginCurrency;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC6909} from "./IERC6909.sol";
/// @notice Interface for accrues over a contract balance, wrapped as a ERC6909
interface IERC6909Accrues is IERC6909 {
function accruesRatioX112Of(uint256 id) external view returns (uint256);
function totalSupply(uint256 id) external view returns (uint256);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
interface IStatusBase {
function pairPoolManager() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @notice Returns the balances of a pool.
struct BalanceStatus {
/// @notice The balance of token0 in the pool.
uint256 balance0;
/// @notice The balance of token1 in the pool.
uint256 balance1;
/// @notice The mirror balance of token0 in the pool.
uint256 mirrorBalance0;
/// @notice The mirror balance of token1 in the pool.
uint256 mirrorBalance1;
/// @notice The total balance of token0 in the lending pool.
uint256 lendingBalance0;
/// @notice The total balance of token1 in the lending pool.
uint256 lendingBalance1;
/// @notice The mirror balance of token0 in the lending pool.
uint256 lendingMirrorBalance0;
/// @notice The mirror balance of token1 in the lending pool.
uint256 lendingMirrorBalance1;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {PoolStatus} from "./PoolStatus.sol";
import {LendingStatus} from "./LendingStatus.sol";
/// @notice Returns the status of global.
struct GlobalStatus {
/// @notice The status of pair pool.
PoolStatus pairPoolStatus;
/// @notice The status of lending pool.
LendingStatus lendingStatus;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
library PerLibrary {
uint256 public constant ONE_MILLION = 10 ** 6;
uint256 public constant ONE_TRILLION = 10 ** 12;
uint256 public constant TRILLION_YEAR_SECONDS = ONE_TRILLION * 365 * 24 * 3600;
function mulMillion(uint256 x) internal pure returns (uint256 y) {
y = x * ONE_MILLION;
}
function divMillion(uint256 x) internal pure returns (uint256 y) {
y = x / ONE_MILLION;
}
function mulMillionDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = Math.mulDiv(x, ONE_MILLION, y);
}
function mulDivMillion(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = Math.mulDiv(x, y, ONE_MILLION);
}
function upperMillion(uint256 x, uint256 per) internal pure returns (uint256 z) {
z = Math.mulDiv(x, ONE_MILLION + per, ONE_MILLION);
}
function lowerMillion(uint256 x, uint256 per) internal pure returns (uint256 z) {
if (per >= ONE_MILLION) {
return z;
}
z = Math.mulDiv(x, ONE_MILLION - per, ONE_MILLION);
}
function isWithinTolerance(uint256 a, uint256 b, uint256 t) internal pure returns (bool) {
return a >= b ? (a - b) <= t : (b - a) <= t;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @notice Returns the status of a lending pool.
struct LendingStatus {
/// @notice The accrues ratio of the first currency in the pool.(x)
uint256 accruesRatio0X112;
/// @notice The accrues ratio of the second currency in the pool.(y)
uint256 accruesRatio1X112;
}{
"remappings": [
"@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"@openzeppelin/contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/",
"@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
"ds-test/=lib/v4-periphery/lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/forge-gas-snapshot/src/",
"forge-std/=lib/forge-std/src/",
"hardhat/=lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"permit2/=lib/v4-periphery/lib/permit2/",
"solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
"v4-core/=lib/v4-periphery/lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": true,
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"initialOwner","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"OperatorSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"_manager","type":"address"}],"name":"addPoolManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"lendingPoolManager","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[{"internalType":"uint256","name":"pairAmount","type":"uint256"},{"internalType":"uint256","name":"lendingAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"isOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"mintInStatus","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"poolManagers","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
608034609457601f610be438819003918201601f19168301916001600160401b03831184841017609857808492602094604052833981010312609457516001600160a01b03811690819003609457600380546001600160a01b03191682179055604051905f7f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08180a3610b3790816100ad8239f35b5f80fd5b634e487b7160e01b5f52604160045260245ffdfe6080806040526004361015610012575f80fd5b5f3560e01c908162fdd58e146109135750806301ffc9a7146108bd578063095bcdb6146108365780631b2ef1ca146108065780632748c5c7146107d7578063426a84931461075d57806345077e711461056b578063558a7297146104da578063598af9e7146104805780638a64e0c4146104435780638da5cb5b1461041b578063b390c0ab146103e9578063b6363cf214610393578063f2fde38b14610320578063f5298aca146102275763fe99049a146100cb575f80fd5b34610223576080366003190112610223576100e4610952565b6100ec610968565b60443591606435916001600160a01b03909116905f80516020610ae283398151915290610189903384141580610202575b610197575b835f52600160205260405f20865f5260205260405f206101438682546109be565b905560018060a01b031693845f52600160205260405f20865f5260205260405f2061016f8282546109df565b905560408051338152602081019290925290918291820190565b0390a4602060405160018152f35b5f848152600260209081526040808320338452825280832089845290915290205485600182016101c9575b5050610122565b6101d2916109be565b845f52600260205260405f2060018060a01b0333165f5260205260405f20875f5260205260405f20555f856101c2565b505f8481526020818152604080832033845290915290205460ff161561011d565b5f80fd5b346102235760406102373661097e565b9091335f52600460205261025060ff855f2054166109ec565b81905f905f93335f526001602052865f20865f52602052865f2054818110155f14610291575050505080610285919333610aa2565b82519182526020820152f35b80969396949294610300575b5050806102ad575b505050610285565b60018060a01b0383165f526001602052855f20825f52602052855f2054806102d6575b506102a5565b6102ef9394508082105f146102f85750905b8193610aa2565b838080806102d0565b9050906102e8565b955061031991508590610314828533610aa2565b6109be565b868061029d565b3461022357602036600319011261022357610339610952565b60035490610351336001600160a01b038416146109ec565b6001600160a01b03166001600160a01b0319919091168117600355337f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3005b34610223576040366003190112610223576103ac610952565b6103b4610968565b9060018060a01b03165f525f60205260405f209060018060a01b03165f52602052602060ff60405f2054166040519015158152f35b34610223576104196103fa366109a8565b90335f52600460205261041360ff60405f2054166109ec565b33610aa2565b005b34610223575f366003190112610223576003546040516001600160a01b039091168152602090f35b34610223576020366003190112610223576001600160a01b03610464610952565b165f526004602052602060ff60405f2054166040519015158152f35b3461022357606036600319011261022357610499610952565b6104a1610968565b6001600160a01b039182165f90815260026020908152604080832094909316825292835281812060443582528352819020549051908152f35b34610223576040366003190112610223576104f3610952565b6024359081151580920361022357335f525f60205260405f2060018060a01b0382165f5260205260405f2060ff1981541660ff841617905560405191825260018060a01b0316907fceb576d9f15e4e200fdb5096d64d5dfd667e16def20c1eefd14256d8e3faa26760203392a3602060405160018152f35b3461022357602036600319011261022357610584610952565b61059960018060a01b036003541633146109ec565b6001600160a01b03165f81815260046020818152604092839020805460ff191660011790559151637436595f60e11b81529190829081855afa9081156106d4575f9161071b575b506001600160a01b031680156106df576004916020915f5282825260405f20600160ff1982541617905560405192838092635e6263eb60e01b82525afa9081156106d4575f91610692575b506001600160a01b03168015610655575f908152600460205260409020805460ff19166001179055005b60405162461bcd60e51b81526020600482015260156024820152742622a72224a723afa6a0a720a3a2a92fa2a92927a960591b6044820152606490fd5b90506020813d6020116106cc575b816106ad60209383610a27565b8101031261022357516001600160a01b0381168103610223578161062b565b3d91506106a0565b6040513d5f823e3d90fd5b60405162461bcd60e51b815260206004820152601460248201527329aa20aa2aa9afa6a0a720a3a2a92fa2a92927a960611b6044820152606490fd5b90506020813d602011610755575b8161073660209383610a27565b8101031261022357516001600160a01b038116810361022357826105e0565b3d9150610729565b346102235761076b3661097e565b9091335f52600260205260405f2060018060a01b0382165f5260205260405f20835f526020528160405f205560405191825260018060a01b0316907fb3fd5071835887567a0671151121894ddccc2842f1d10bedad13e0d17cace9a760203392a4602060405160018152f35b34610223576104196107e83661097e565b91335f52600460205261080160ff60405f2054166109ec565b610a5d565b3461022357610419610817366109a8565b90335f52600460205261083060ff60405f2054166109ec565b33610a5d565b34610223576108443661097e565b9091335f52600160205260405f20835f5260205260405f206108678382546109be565b905560018060a01b031690815f52600160205260405f20835f5260205260405f206108938282546109df565b9055604080513380825260208201939093525f80516020610ae28339815191529181908101610189565b346102235760203660031901126102235760043563ffffffff60e01b8116809103610223576020906301ffc9a760e01b8114908115610902575b506040519015158152f35b630f632fb360e01b149050826108f7565b34610223576040366003190112610223576020906001600160a01b03610937610952565b165f526001825260405f206024355f52825260405f20548152f35b600435906001600160a01b038216820361022357565b602435906001600160a01b038216820361022357565b6060906003190112610223576004356001600160a01b038116810361022357906024359060443590565b6040906003190112610223576004359060243590565b919082039182116109cb57565b634e487b7160e01b5f52601160045260245ffd5b919082018092116109cb57565b156109f357565b60405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606490fd5b90601f8019910116810190811067ffffffffffffffff821117610a4957604052565b634e487b7160e01b5f52604160045260245ffd5b5f80516020610ae2833981519152610a9d5f9294939460018060a01b0316938484526001602052604084208685526020526040842061016f8282546109df565b0390a4565b915f80516020610ae2833981519152610a9d5f939460018060a01b0316928385526001602052604085208686526020526040852061016f8282546109be56fe1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac728859a26469706673582212207ebbece69acca98baf5cc023f853612bf125e4d75d19b6ed356f8acbcc460a1464736f6c634300081a00330000000000000000000000004945b4d356edc02caab24d2407e8796269642673
Deployed Bytecode
0x6080806040526004361015610012575f80fd5b5f3560e01c908162fdd58e146109135750806301ffc9a7146108bd578063095bcdb6146108365780631b2ef1ca146108065780632748c5c7146107d7578063426a84931461075d57806345077e711461056b578063558a7297146104da578063598af9e7146104805780638a64e0c4146104435780638da5cb5b1461041b578063b390c0ab146103e9578063b6363cf214610393578063f2fde38b14610320578063f5298aca146102275763fe99049a146100cb575f80fd5b34610223576080366003190112610223576100e4610952565b6100ec610968565b60443591606435916001600160a01b03909116905f80516020610ae283398151915290610189903384141580610202575b610197575b835f52600160205260405f20865f5260205260405f206101438682546109be565b905560018060a01b031693845f52600160205260405f20865f5260205260405f2061016f8282546109df565b905560408051338152602081019290925290918291820190565b0390a4602060405160018152f35b5f848152600260209081526040808320338452825280832089845290915290205485600182016101c9575b5050610122565b6101d2916109be565b845f52600260205260405f2060018060a01b0333165f5260205260405f20875f5260205260405f20555f856101c2565b505f8481526020818152604080832033845290915290205460ff161561011d565b5f80fd5b346102235760406102373661097e565b9091335f52600460205261025060ff855f2054166109ec565b81905f905f93335f526001602052865f20865f52602052865f2054818110155f14610291575050505080610285919333610aa2565b82519182526020820152f35b80969396949294610300575b5050806102ad575b505050610285565b60018060a01b0383165f526001602052855f20825f52602052855f2054806102d6575b506102a5565b6102ef9394508082105f146102f85750905b8193610aa2565b838080806102d0565b9050906102e8565b955061031991508590610314828533610aa2565b6109be565b868061029d565b3461022357602036600319011261022357610339610952565b60035490610351336001600160a01b038416146109ec565b6001600160a01b03166001600160a01b0319919091168117600355337f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3005b34610223576040366003190112610223576103ac610952565b6103b4610968565b9060018060a01b03165f525f60205260405f209060018060a01b03165f52602052602060ff60405f2054166040519015158152f35b34610223576104196103fa366109a8565b90335f52600460205261041360ff60405f2054166109ec565b33610aa2565b005b34610223575f366003190112610223576003546040516001600160a01b039091168152602090f35b34610223576020366003190112610223576001600160a01b03610464610952565b165f526004602052602060ff60405f2054166040519015158152f35b3461022357606036600319011261022357610499610952565b6104a1610968565b6001600160a01b039182165f90815260026020908152604080832094909316825292835281812060443582528352819020549051908152f35b34610223576040366003190112610223576104f3610952565b6024359081151580920361022357335f525f60205260405f2060018060a01b0382165f5260205260405f2060ff1981541660ff841617905560405191825260018060a01b0316907fceb576d9f15e4e200fdb5096d64d5dfd667e16def20c1eefd14256d8e3faa26760203392a3602060405160018152f35b3461022357602036600319011261022357610584610952565b61059960018060a01b036003541633146109ec565b6001600160a01b03165f81815260046020818152604092839020805460ff191660011790559151637436595f60e11b81529190829081855afa9081156106d4575f9161071b575b506001600160a01b031680156106df576004916020915f5282825260405f20600160ff1982541617905560405192838092635e6263eb60e01b82525afa9081156106d4575f91610692575b506001600160a01b03168015610655575f908152600460205260409020805460ff19166001179055005b60405162461bcd60e51b81526020600482015260156024820152742622a72224a723afa6a0a720a3a2a92fa2a92927a960591b6044820152606490fd5b90506020813d6020116106cc575b816106ad60209383610a27565b8101031261022357516001600160a01b0381168103610223578161062b565b3d91506106a0565b6040513d5f823e3d90fd5b60405162461bcd60e51b815260206004820152601460248201527329aa20aa2aa9afa6a0a720a3a2a92fa2a92927a960611b6044820152606490fd5b90506020813d602011610755575b8161073660209383610a27565b8101031261022357516001600160a01b038116810361022357826105e0565b3d9150610729565b346102235761076b3661097e565b9091335f52600260205260405f2060018060a01b0382165f5260205260405f20835f526020528160405f205560405191825260018060a01b0316907fb3fd5071835887567a0671151121894ddccc2842f1d10bedad13e0d17cace9a760203392a4602060405160018152f35b34610223576104196107e83661097e565b91335f52600460205261080160ff60405f2054166109ec565b610a5d565b3461022357610419610817366109a8565b90335f52600460205261083060ff60405f2054166109ec565b33610a5d565b34610223576108443661097e565b9091335f52600160205260405f20835f5260205260405f206108678382546109be565b905560018060a01b031690815f52600160205260405f20835f5260205260405f206108938282546109df565b9055604080513380825260208201939093525f80516020610ae28339815191529181908101610189565b346102235760203660031901126102235760043563ffffffff60e01b8116809103610223576020906301ffc9a760e01b8114908115610902575b506040519015158152f35b630f632fb360e01b149050826108f7565b34610223576040366003190112610223576020906001600160a01b03610937610952565b165f526001825260405f206024355f52825260405f20548152f35b600435906001600160a01b038216820361022357565b602435906001600160a01b038216820361022357565b6060906003190112610223576004356001600160a01b038116810361022357906024359060443590565b6040906003190112610223576004359060243590565b919082039182116109cb57565b634e487b7160e01b5f52601160045260245ffd5b919082018092116109cb57565b156109f357565b60405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606490fd5b90601f8019910116810190811067ffffffffffffffff821117610a4957604052565b634e487b7160e01b5f52604160045260245ffd5b5f80516020610ae2833981519152610a9d5f9294939460018060a01b0316938484526001602052604084208685526020526040842061016f8282546109df565b0390a4565b915f80516020610ae2833981519152610a9d5f939460018060a01b0316928385526001602052604085208686526020526040852061016f8282546109be56fe1b3d7edb2e9c0b0e7c525b20aaaef0f5940d2ed71663c7d39266ecafac728859a26469706673582212207ebbece69acca98baf5cc023f853612bf125e4d75d19b6ed356f8acbcc460a1464736f6c634300081a0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000004945b4d356edc02caab24d2407e8796269642673
-----Decoded View---------------
Arg [0] : initialOwner (address): 0x4945b4D356edC02caab24d2407e8796269642673
-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 0000000000000000000000004945b4d356edc02caab24d2407e8796269642673
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.