Verified contractPartialMIT
PriceVelocityGuardExtension
Address0xebc53e61078976118e384f110c262a263decb84b
- Balance
0 ETH
- Transactions
274
- Compiler
solc 0.8.35
- Same code
Only this contract
Details
- Compiler
- solc 0.8.35+commit.47b9dedd
- Language
- solidity
- Optimization
- Yes, 99,999 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,984,387
- Creation transaction
- 0x2fc9f4926a…a849d98ddd
10 files
- lib/metric-periphery/contracts/extensions/PriceVelocityGuardExtension.solmain4.12 KB
- lib/metric-periphery/contracts/extensions/base/BaseMetricExtension.sol2.93 KB
- lib/metric-periphery/contracts/interfaces/extensions/IPriceVelocityGuardExtension.sol1.17 KB
- lib/metric-periphery/lib/metric-core/contracts/interfaces/IMetricOmmPoolFactory/IMetricOmmPoolFactory.sol9.11 KB
- lib/metric-periphery/lib/metric-core/contracts/interfaces/IMetricOmmPoolFactory/IMetricOmmPoolFactoryOwner.sol6.98 KB
- lib/metric-periphery/lib/metric-core/contracts/interfaces/IMetricOmmPoolFactory/IMetricOmmPoolFactoryPoolAdmin.sol3.77 KB
- lib/metric-periphery/lib/metric-core/contracts/interfaces/extensions/IMetricOmmExtensions.sol2.31 KB
- lib/metric-periphery/lib/metric-core/contracts/types/FactoryOperation.sol3.12 KB
- lib/metric-periphery/lib/metric-core/contracts/types/PoolExtensionsConfig.sol990 B
- lib/metric-periphery/lib/metric-core/contracts/types/PoolOperation.sol794 B
lib/metric-periphery/contracts/extensions/PriceVelocityGuardExtension.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {IMetricOmmExtensions} from "@metric-core/interfaces/extensions/IMetricOmmExtensions.sol";
import {IPriceVelocityGuardExtension} from "../interfaces/extensions/IPriceVelocityGuardExtension.sol";
import {BaseMetricExtension} from "./base/BaseMetricExtension.sol";
/// @title PriceVelocityGuardExtension
/// @notice Caps how fast the provided price can move between blocks, per pool.
/// @dev This extension allows the pool admin to increase security of the pool by limiting price
/// manipulation through velocity constraints. However, it assumes that the pool admin is not
/// an adversary and acts to optimize pool profitability. The pool admin must be trusted.
///
/// Allowed deviation scales as `maxChangePerBlockE18 * sqrt(1 + blockDifference)`.
/// Comparison is performed on squares to avoid an on-chain sqrt:
/// changeE18^2 <= maxChangePerBlockE18^2 * (1 + blockDiff)
/// where 1e18 = 100% (full unit).
///
/// Per-block budget: `anchorMidPriceX64` is the check reference and stays fixed until a swap
/// lands in a block after `lastObservedBlock`. `blockDiff` is measured from `anchorBlock`, not
/// from the swap's own block, so every swap checked against the same anchor gets the same
/// allowance regardless of how many swaps already landed in that block.
contract PriceVelocityGuardExtension is BaseMetricExtension, IPriceVelocityGuardExtension {
mapping(address pool => PriceVelocityState) public priceVelocityState;
constructor(address factory_) BaseMetricExtension(factory_) {}
function setMaxChangePerBlock(address pool_, uint64 newMaxPctChangePerBlockE18) external onlyPoolAdmin(pool_) {
priceVelocityState[pool_].maxChangePerBlockE18 = newMaxPctChangePerBlockE18;
emit MaxChangePerBlockSet(pool_, newMaxPctChangePerBlockE18);
}
function setAnchorMidPrice(address pool_, uint128 newAnchorMidPriceX64) external onlyPoolAdmin(pool_) {
PriceVelocityState storage s = priceVelocityState[pool_];
s.anchorMidPriceX64 = newAnchorMidPriceX64;
s.lastObservedMidPriceX64 = newAnchorMidPriceX64;
s.anchorBlock = uint64(block.number);
s.lastObservedBlock = uint64(block.number);
emit AnchorMidPriceUpdated(pool_, newAnchorMidPriceX64);
}
function beforeSwap(
address,
address,
bool,
int128,
uint128,
uint256,
uint128,
uint128,
uint128 referencePriceX64,
bytes calldata
) external override returns (bytes4) {
// onlyPool omitted: state is keyed by msg.sender, so a non-pool caller cannot affect another pool.
address pool_ = msg.sender;
// Pool passes `referencePriceX64` as the mid/price-path anchor from `getQuote()`.
uint128 midPrice = referencePriceX64;
PriceVelocityState storage s = priceVelocityState[pool_];
uint128 anchorMid = s.anchorMidPriceX64;
if (anchorMid == 0) {
s.anchorMidPriceX64 = midPrice;
s.anchorBlock = uint64(block.number);
s.lastObservedMidPriceX64 = midPrice;
s.lastObservedBlock = uint64(block.number);
return IMetricOmmExtensions.beforeSwap.selector;
}
if (block.number > s.lastObservedBlock) {
// Left the last-observed block behind: roll the anchor to that block's final mid.
anchorMid = s.lastObservedMidPriceX64;
s.anchorMidPriceX64 = anchorMid;
s.anchorBlock = s.lastObservedBlock;
}
uint256 blockDiff = block.number - s.anchorBlock;
uint64 maxChange = s.maxChangePerBlockE18;
if (maxChange != 0) {
uint256 delta = midPrice > anchorMid ? uint256(midPrice - anchorMid) : uint256(anchorMid - midPrice);
uint256 changeE18 = (delta * 1e18) / uint256(anchorMid);
uint256 actualSq = changeE18 * changeE18;
uint256 allowedSq = uint256(maxChange) * uint256(maxChange) * (1 + blockDiff);
if (actualSq > allowedSq) {
revert PriceVelocityExceeded(actualSq, allowedSq);
}
}
s.lastObservedMidPriceX64 = midPrice;
s.lastObservedBlock = uint64(block.number);
return IMetricOmmExtensions.beforeSwap.selector;
}
}
lib/metric-periphery/contracts/extensions/base/BaseMetricExtension.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {IMetricOmmExtensions} from "@metric-core/interfaces/extensions/IMetricOmmExtensions.sol";
import {IMetricOmmPoolFactory} from "@metric-core/interfaces/IMetricOmmPoolFactory/IMetricOmmPoolFactory.sol";
import {LiquidityDelta} from "@metric-core/types/PoolOperation.sol";
/// @title BaseMetricExtension
/// @notice Base for pool extensions: enforces pool-only entry and default-unimplemented callbacks.
/// A single extension instance may serve any number of pools deployed from `FACTORY`.
abstract contract BaseMetricExtension is IMetricOmmExtensions {
address public immutable FACTORY;
error OnlyPool(address caller, address factory);
error OnlyPoolAdmin(address pool, address caller, address admin);
error OnlyFactory(address caller, address factory);
error ExtensionNotImplemented();
modifier onlyPool() {
if (!IMetricOmmPoolFactory(FACTORY).isPool(msg.sender)) {
revert OnlyPool(msg.sender, FACTORY);
}
_;
}
modifier onlyFactory() {
if (msg.sender != FACTORY) revert OnlyFactory(msg.sender, FACTORY);
_;
}
modifier onlyPoolAdmin(address pool_) {
address poolAdmin = IMetricOmmPoolFactory(FACTORY).poolAdmin(pool_);
if (msg.sender != poolAdmin) revert OnlyPoolAdmin(pool_, msg.sender, poolAdmin);
_;
}
constructor(address factory_) {
FACTORY = factory_;
}
function initialize(address, bytes calldata) external virtual onlyFactory returns (bytes4) {
return IMetricOmmExtensions.initialize.selector;
}
function beforeAddLiquidity(address, address, uint80, LiquidityDelta calldata, bytes calldata)
external
virtual
onlyPool
returns (bytes4)
{
revert ExtensionNotImplemented();
}
function afterAddLiquidity(address, address, uint80, LiquidityDelta calldata, uint256, uint256, bytes calldata)
external
virtual
onlyPool
returns (bytes4)
{
revert ExtensionNotImplemented();
}
function beforeRemoveLiquidity(address, address, uint80, LiquidityDelta calldata, bytes calldata)
external
virtual
onlyPool
returns (bytes4)
{
revert ExtensionNotImplemented();
}
function afterRemoveLiquidity(address, address, uint80, LiquidityDelta calldata, uint256, uint256, bytes calldata)
external
virtual
onlyPool
returns (bytes4)
{
revert ExtensionNotImplemented();
}
function beforeSwap(address, address, bool, int128, uint128, uint256, uint128, uint128, uint128, bytes calldata)
external
virtual
onlyPool
returns (bytes4)
{
revert ExtensionNotImplemented();
}
function afterSwap(
address,
address,
bool,
int128,
uint128,
uint256,
uint256,
uint128,
uint128,
uint128,
int128,
int128,
uint256,
bytes calldata
) external virtual onlyPool returns (bytes4) {
revert ExtensionNotImplemented();
}
}
lib/metric-periphery/contracts/interfaces/extensions/IPriceVelocityGuardExtension.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
/// @title IPriceVelocityGuardExtension
/// @notice Per-pool oracle mid-price velocity guard admin and read API.
interface IPriceVelocityGuardExtension {
struct PriceVelocityState {
/// @dev Velocity check reference. Fixed until a swap lands in a block after `lastObservedBlock`.
uint128 anchorMidPriceX64;
/// @dev Mid from the latest swap; becomes the next anchor once its block is left behind.
uint128 lastObservedMidPriceX64;
/// @dev Block number `anchorMidPriceX64` was observed in; blockDiff is measured from here.
uint64 anchorBlock;
/// @dev Block number of the latest swap.
uint64 lastObservedBlock;
uint64 maxChangePerBlockE18;
}
error PriceVelocityExceeded(uint256 actualDeltaSqE36, uint256 allowedDeltaSqE36);
event MaxChangePerBlockSet(address indexed pool, uint64 newMaxPctChangePerBlockE18);
event AnchorMidPriceUpdated(address indexed pool, uint128 newAnchorMidPriceX64);
function setMaxChangePerBlock(address pool, uint64 newMaxPctChangePerBlockE18) external;
function setAnchorMidPrice(address pool, uint128 newAnchorMidPriceX64) external;
}
lib/metric-periphery/lib/metric-core/contracts/interfaces/IMetricOmmPoolFactory/IMetricOmmPoolFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {PoolParameters} from "../../types/FactoryOperation.sol";
import {ExtensionOrders} from "../../types/PoolExtensionsConfig.sol";
import {IMetricOmmPoolFactoryOwner} from "./IMetricOmmPoolFactoryOwner.sol";
import {IMetricOmmPoolFactoryPoolAdmin} from "./IMetricOmmPoolFactoryPoolAdmin.sol";
/// @title IMetricOmmPoolFactory
/// @notice Full factory API: pool creation, views, deployment validation, factory owner actions (`IMetricOmmPoolFactoryOwner`), and pool admin actions (`IMetricOmmPoolFactoryPoolAdmin`).
/// @dev `createPool` is permissionless once `poolDeployer` is set (not `onlyOwner`). Role interfaces hold only events and errors for that role’s mutators; views and `createPool` live here. Errors shared by `createPool` and one or both roles (`ProtocolFeeTooHigh`, `AdminFeeTooHigh`, `InvalidPauseTransition`) are declared only on this aggregate to avoid duplicate declarations across parents.
interface IMetricOmmPoolFactory is IMetricOmmPoolFactoryOwner, IMetricOmmPoolFactoryPoolAdmin {
// ============ Events ============
// --- Deployment ---
event PoolCreated(
address indexed poolAddress,
address indexed token0,
address indexed token1,
uint256 poolIdx,
address factory,
address admin,
address priceProvider,
address[] extensions,
ExtensionOrders extensionOrders,
uint256 priceProviderTimelock,
uint256 initialScaledAmount0PerE18Shares,
uint256 initialScaledAmount1PerE18Shares,
uint256 minimalOperationalLiquidity,
uint24 spreadProtocolFeeE6,
uint24 protocolNotionalFeeE8,
uint24 adminSpreadFeeE6,
uint24 adminNotionalFeeE8,
address adminFeeDestination,
int24 curBinDistFromProvidedPriceE6,
uint256[] nonNegativeBinDataArray,
uint256[] negativeBinDataArray
);
// ============ Errors ============
// --- Deployment and validation (`createPool`; several also revert from pool-admin mutators) ---
error PoolDeployerNotSet();
error InvalidTokenConfig();
error InvalidAdmin();
error InvalidPriceProvider();
error PriceProviderTokenMismatch();
error InvalidAdminFeeDestination();
error InvalidInitialAmount();
error MinimalOperationalLiquidityTooSmallComparedToInitialScaledTokenAmounts(
uint256 provided, uint256 minimalRequired
);
/// @notice More bins were supplied on one side of the grid than a bin index can address.
error BinIndexRangeExceededInt16();
error BinArraysEmpty();
error BinLengthZero(int256 binIdx);
error BinDistanceOutOfRange(int256 binIdx, int256 cumulativeDistanceE6);
// --- Shared by `createPool` and owner or pool-admin paths (single declaration) ---
error ProtocolFeeTooHigh();
error AdminFeeTooHigh();
error InvalidPauseTransition(uint8 currentLevel, uint8 requestedLevel);
error BidAskRefAsymmetryTooHigh();
error BidAskRefAsymmetryTooLow();
// ============ View ============
/// @notice Passive protocol-fee sink; protocol fees route here at collection. Owner-settable.
function feeReceiver() external view returns (address);
// --- Hard limits ---
/// @notice Hard protocol spread fee cap limit used by `setFeeCaps` (`1e6 = 100%`, `5e5 = 50%`).
function maxOwnerProtocolSpreadCapE6() external pure returns (uint24);
/// @notice Hard admin spread fee cap limit used by `setFeeCaps` (`1e6 = 100%`, `5e5 = 50%`).
function maxOwnerAdminSpreadCapE6() external pure returns (uint24);
/// @notice Hard protocol notional fee cap limit used by `setFeeCaps` (`1e8 = 100%`, `1e6 = 1%`).
function maxOwnerProtocolNotionalCapE8() external pure returns (uint24);
/// @notice Hard admin notional fee cap limit used by `setFeeCaps` (`1e8 = 100%`, `1e6 = 1%`).
function maxOwnerAdminNotionalCapE8() external pure returns (uint24);
// --- Global configuration ---
/// @notice `MetricOmmPoolDeployer` authorized to create pools; set once by owner.
function poolDeployer() external view returns (address);
/// @notice Default protocol spread fee floor applied to new pools (E6).
function spreadProtocolFeeE6() external view returns (uint24);
/// @notice Default protocol notional fee floor applied to new pools (E8).
function protocolNotionalFeeE8() external view returns (uint24);
/// @notice Upper bound owner may set for per-pool protocol spread fee (E6).
function maxProtocolSpreadFeeE6() external view returns (uint24);
/// @notice Upper bound owner may set for per-pool admin spread fee (E6).
function maxAdminSpreadFeeE6() external view returns (uint24);
/// @notice Upper bound owner may set for per-pool protocol notional fee (E8).
function maxProtocolNotionalFeeE8() external view returns (uint24);
/// @notice Upper bound owner may set for per-pool admin notional fee (E8).
function maxAdminNotionalFeeE8() external view returns (uint24);
/// @notice Cap for `bidAskRefAsymmetryX8` slack `m` in X8 (`M = 1 + m`), enforced only at `createPool`.
function onCreationMaxBidAskRefAsymmetryX8() external view returns (uint16);
/// @notice Inclusive lower bound on the cumulative bin distance enforced at pool creation (E6).
function minBinDistanceE6() external view returns (int128);
/// @notice Inclusive upper bound on the cumulative bin distance enforced at pool creation (E6).
function maxBinDistanceE6() external view returns (int128);
/// @notice All four fee caps in one call.
/// @return maxProtocolSpreadFeeE6 Cap for protocol spread (E6).
/// @return maxAdminSpreadFeeE6 Cap for admin spread (E6).
/// @return maxProtocolNotionalFeeE8 Cap for protocol notional (E8).
/// @return maxAdminNotionalFeeE8 Cap for admin notional (E8).
function getFeeCaps()
external
view
returns (
uint24 maxProtocolSpreadFeeE6,
uint24 maxAdminSpreadFeeE6,
uint24 maxProtocolNotionalFeeE8,
uint24 maxAdminNotionalFeeE8
);
// --- Pool registry and metadata ---
/// @notice Monotonic pool creation counter; next index to assign is this value. Starts at 1; index 0 is reserved.
function nextPoolIdx() external view returns (uint256);
/// @notice Pool deployed at creation order `idx`. Index 0 is reserved and never assigned.
function idxToPool(uint256 idx) external view returns (address);
/// @notice Creation index for `pool`; zero if the pool was not created by this factory.
function poolToIdx(address pool) external view returns (uint256);
/// @notice Whether `pool` was deployed and registered by this factory.
/// @return true if `pool` is a pool deployed/tracked by this factory.
function isPool(address pool) external view returns (bool);
/// @notice Persisted protocol and admin fee components for `pool`.
function poolFeeConfig(address pool)
external
view
returns (
uint24 protocolSpreadFeeE6,
uint24 adminSpreadFeeE6,
uint24 protocolNotionalFeeE8,
uint24 adminNotionalFeeE8
);
/// @notice Admin fee sweep destination for `pool`.
function poolAdminFeeDestination(address pool) external view returns (address);
/// @notice Current pool admin for governance actions on `pool`.
function poolAdmin(address pool) external view returns (address);
/// @notice Pending admin during two-step transfer, or zero if none.
function pendingPoolAdmin(address pool) external view returns (address);
/// @notice Timelock duration in seconds for price provider updates; `type(uint256).max` if immutable.
function priceProviderTimelock(address pool) external view returns (uint256);
/// @notice Proposed next price provider after `proposePoolPriceProvider`, or zero if none.
function pendingPriceProvider(address pool) external view returns (address);
/// @notice Timestamp after which `executePoolPriceProviderUpdate` succeeds, if a proposal exists.
function pendingPriceProviderExecuteAfter(address pool) external view returns (uint256);
// ============ Mutating: Fee collection (permissionless) ============
/// @notice Pull accrued protocol and admin fees from `pool` using stored `poolFeeConfig` splits.
/// @dev Callable by any address (keepers, admins, or bots). Does not change fee configuration.
/// @dev Pool accounting errors propagate; rejected token payouts remain pending on the pool.
function collectPoolFees(address pool) external;
// ============ Mutating: Pool creation ============
/// @notice Deploy a new pool via `poolDeployer` using validated `params`.
/// @dev Callers should follow `docs/POOL_CONFIGURATION_AND_MANAGEMENT.md` when choosing
/// `PoolParameters` (densities, minimalOperationalLiquidity, fees, bins, extensions, salt).
/// Exotic token pairs with a very large `decimals()` spread may result in revert (overflow) at creation, or may later result in revert on
/// `addLiquidity` (`SafeCast` overflow) or `swap` (`OverflowedOnFittingBinBalances`) when scaled amounts exceed internal `uint104`/`uint128` bounds.
/// @return pool Address of the pool the deployer created with `CREATE2`.
function createPool(PoolParameters calldata params) external returns (address pool);
}
lib/metric-periphery/lib/metric-core/contracts/interfaces/IMetricOmmPoolFactory/IMetricOmmPoolFactoryOwner.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
/// @title IMetricOmmPoolFactoryOwner
/// @notice Factory owner mutators on `MetricOmmPoolFactory` (excluding permissionless `createPool`, which stays on `IMetricOmmPoolFactory`). All are gated by `requiresAuth` (owner or the configured `Authority`).
/// @dev Events and custom errors declared here are only those emitted or exclusively reverted by owner mutators. Errors also used by `createPool` or pool-admin paths are declared on `IMetricOmmPoolFactory` only.
interface IMetricOmmPoolFactoryOwner {
// ============ Events ============
event SpreadProtocolFeeDefaultUpdated(uint24 newFeeE6);
event ProtocolNotionalFeeDefaultUpdated(uint24 newFeeE8);
event OnCreationMaxBidAskRefAsymmetryUpdated(uint16 newMaxX8);
event PoolBidAskRefAsymmetryUpdated(address indexed pool, uint16 newBidAskRefAsymmetryX8);
event PoolProtocolSpreadFeeUpdated(address indexed pool, uint24 newProtocolSpreadFeeE6);
event PoolProtocolNotionalFeeUpdated(address indexed pool, uint24 newProtocolNotionalFeeE8);
event FeeCapsUpdated(
uint24 maxProtocolSpreadFeeE6,
uint24 maxAdminSpreadFeeE6,
uint24 maxProtocolNotionalFeeE8,
uint24 maxAdminNotionalFeeE8
);
event PoolDeployerSet(address indexed poolDeployer);
event TokensCollected(address indexed token, address indexed to, uint256 amount);
event FeeReceiverUpdated(address indexed newReceiver);
event BinDistanceLimitsUpdated(int256 newMinBinDistanceE6, int256 newMaxBinDistanceE6);
// ============ Errors ============
error PoolDeployerAlreadySet();
error FeeCapsExceedHardLimit();
error InvalidFeeReceiver();
error InvalidBinDistanceLimits();
error ArrayLengthMismatch();
// ============ Mutating: Factory owner ============
// --- Initialization and treasury ---
/// @notice One-time wire of the pool deployer contract. Reverts `PoolDeployerAlreadySet` if non-zero.
function setPoolDeployer(address _poolDeployer) external;
/// @notice Set the passive protocol-fee sink. Protocol fees route directly here at collection; the
/// owner never custodies them. Reverts `InvalidFeeReceiver` on the zero address.
function setFeeReceiver(address newFeeReceiver) external;
/// @notice Rescue ERC20 held by the factory. Stray-token only — protocol fees route straight to
/// `feeReceiver` at collection and no longer accumulate here.
function collectTokens(address token, address to, uint256 amount) external;
/// @notice Rescue native ETH held by the factory (stray funds only; see `collectTokens`).
function collectEth(address payable to, uint256 amount) external;
/// @notice Update per-component fee caps; each must be at most the matching `maxOwner*Cap*` hard limit.
function setFeeCaps(
uint24 newMaxProtocolSpreadFeeE6,
uint24 newMaxAdminSpreadFeeE6,
uint24 newMaxProtocolNotionalFeeE8,
uint24 newMaxAdminNotionalFeeE8
) external;
// --- Default and per-pool protocol fees ---
/// @notice Override protocol fee components for a specific `pool` within the current fee caps.
/// @dev Bounded by the owner-adjustable `maxProtocolSpreadFeeE6` / `maxProtocolNotionalFeeE8`, not by the
/// `HARD_MAX_*` ceilings. Allocates accrued fees at the old rates first; accounting errors propagate
/// unchanged, while failed token payouts remain pending on the pool. Admin
/// components are clamped to the current admin caps if they now exceed them.
function setPoolProtocolFee(address pool, uint24 newProtocolSpreadFeeE6, uint24 newProtocolNotionalFeeE8) external;
/// @notice Batch form of `setPoolProtocolFee`, applied in array order.
/// @dev Reverts `ArrayLengthMismatch` unless all three arrays are the same length. Atomic: any per-entry
/// revert rolls back the whole call, and the revert carries no entry index. Entries must be unique —
/// duplicates re-run settlement and the last write wins. Failed payouts emit `FeeTransferFailed` on the pool.
function setPoolProtocolFeeBatch(
address[] calldata pools,
uint24[] calldata newProtocolSpreadFeeE6s,
uint24[] calldata newProtocolNotionalFeeE8s
) external;
/// @notice Update default protocol spread fee floor for future pools (create-time values below this clamp up).
function setDefaultSpreadProtocolFeeE6(uint24 newFeeE6) external;
/// @notice Update default protocol notional fee floor for future pools (create-time values below this clamp up).
function setDefaultProtocolNotionalFeeE8(uint24 newFeeE8) external;
/// @notice Most permissive negative cumulative bin distance the owner may configure (E6).
function hardMinBinDistanceLimitE6() external pure returns (int256);
/// @notice Most permissive positive cumulative bin distance the owner may configure (E6).
function hardMaxBinDistanceLimitE6() external pure returns (int256);
/// @notice Update the inclusive cumulative bin distance bounds enforced at pool creation (E6).
function setBinDistanceLimits(int128 newMinBinDistanceE6, int128 newMaxBinDistanceE6) external;
/// @notice Update the cap on `bidAskRefAsymmetryX8` enforced at `createPool` for new pools.
/// @dev Reverts `BidAskRefAsymmetryTooLow` on `0`: a zero cap admits no valid value, since `createPool`
/// rejects both values above the cap and `0` itself, and would block pool creation entirely.
function setOnCreationMaxBidAskRefAsymmetryX8(uint16 newMaxX8) external;
/// @notice Update bid/ask/ref asymmetry bound for an existing `pool`. Any non-zero `uint16` is valid.
/// @dev Deliberately NOT gated by `onCreationMaxBidAskRefAsymmetryX8` — that cap bounds only what third-party
/// `createPool` callers may request, never the owner. Consequence: `type(uint16).max` disables the pool's
/// bid/ask/ref quote validation outright in a single owner call, with no cap-level event emitted.
/// `0` reverts `BidAskRefAsymmetryTooLow` because it makes every quote on the pool revert.
function setPoolBidAskRefAsymmetryX8(address pool, uint16 newBidAskRefAsymmetryX8) external;
/// @notice Batch form of `setPoolBidAskRefAsymmetryX8`, applied in array order.
/// @dev Reverts `ArrayLengthMismatch` unless both arrays are the same length. Atomic: any per-entry revert
/// rolls back the whole call, and the revert carries no entry index. Entries must be unique.
function setPoolBidAskRefAsymmetryX8Batch(address[] calldata pools, uint16[] calldata newBidAskRefAsymmetryX8s)
external;
// --- Protocol pause ---
/// @notice Force pool to protocol pause level `2`. Callable by the owner or an `Authority`-approved caller.
function protocolPausePool(address pool) external;
/// @notice Clear protocol pause on `pool` when allowed by pause rules.
/// @dev Intentionally transitions only **2 → 1**. Full resume to level **0** requires the pool admin to call `unpausePool`.
function protocolUnpausePool(address pool) external;
}
lib/metric-periphery/lib/metric-core/contracts/interfaces/IMetricOmmPoolFactory/IMetricOmmPoolFactoryPoolAdmin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
/// @title IMetricOmmPoolFactoryPoolAdmin
/// @notice Per-pool admin (`poolAdmin[pool] == msg.sender`) mutators on `MetricOmmPoolFactory`.
/// @dev Events and custom errors declared here are only those emitted or exclusively reverted by pool-admin mutators. Errors also used by `createPool` or the factory owner are declared on `IMetricOmmPoolFactory` only.
interface IMetricOmmPoolFactoryPoolAdmin {
// ============ Events ============
event PoolAdminSpreadFeeUpdated(address indexed pool, uint24 newAdminSpreadFeeE6);
event PoolAdminNotionalFeeUpdated(address indexed pool, uint24 newAdminNotionalFeeE8);
event PoolAdminFeeDestinationUpdated(address indexed pool, address newAdminFeeDestination);
event PoolAdminTransferred(address indexed pool, address indexed previousAdmin, address indexed newAdmin);
event PoolAdminTransferProposed(address indexed pool, address indexed currentAdmin, address indexed newAdmin);
event PoolAdminTransferCancelled(address indexed pool, address indexed cancelledPendingAdmin);
event PoolPriceProviderChangeProposed(
address indexed pool, address indexed currentPriceProvider, address indexed newPriceProvider, uint256 executeAfter
);
event PoolPriceProviderUpdated(address indexed pool, address indexed newPriceProvider);
// ============ Errors ============
error NotPoolAdmin();
error NoPriceProviderChangeProposed();
/// @notice Thrown when scheduling or applying a price provider rotation for a pool whose oracle is immutable at creation.
error PriceProviderImmutable();
error PriceProviderTimelockNotElapsed(uint256 executeAfter, uint256 currentTimestamp);
error NoPendingPoolAdminTransfer();
error NotPendingPoolAdmin(address pool, address caller, address pendingAdmin);
// ============ Mutating: Pool admin ============
// --- Fees and per-bin ---
/// @notice Update admin spread and notional components for `pool` within configured caps.
/// @dev Allocates accrued fees at the old rates first. Accounting failure reverts; failed payouts remain pending.
function setPoolAdminFees(address pool, uint24 newAdminSpreadFeeE6, uint24 newAdminNotionalFeeE8) external;
/// @notice Update admin fee destination for `pool`, including the recipient of pending admin fees.
/// @dev Attempts collection first. Pool accounting errors propagate and prevent the destination update.
function setPoolAdminFeeDestination(address pool, address newAdminFeeDestination) external;
/// @notice Configure per-bin additional fees on `pool`.
function setPoolBinAdditionalFees(address pool, int16 bin, uint16 addFeeBuyE6, uint16 addFeeSellE6) external;
// --- Pause (admin level) ---
/// @notice Set pool to admin pause level `1`.
function pausePool(address pool) external;
/// @notice Clear admin pause on `pool` when allowed by pause rules.
function unpausePool(address pool) external;
// --- Price provider (mutable oracle only) ---
/// @notice Schedule price provider rotation for `pool` after timelock; reverts if the pool oracle is immutable.
function proposePoolPriceProvider(address pool, address newPriceProvider) external;
/// @notice Finalize scheduled provider update after `pendingPriceProviderExecuteAfter`.
function executePoolPriceProviderUpdate(address pool) external;
// --- Admin transfer ---
/// @notice Start two-step admin transfer to `newAdmin`.
function proposePoolAdminTransfer(address pool, address newAdmin) external;
/// @notice Accept pending admin role for `pool` (must be pending admin).
function acceptPoolAdmin(address pool) external;
/// @notice Cancel a pending admin transfer for `pool`.
function cancelPoolAdminTransfer(address pool) external;
}
lib/metric-periphery/lib/metric-core/contracts/interfaces/extensions/IMetricOmmExtensions.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {LiquidityDelta} from "../../types/PoolOperation.sol";
/// @title IMetricOmmExtensions
/// @notice Optional per-pool extension invoked by `MetricOmmPool` at liquidity and swap extension points.
/// @dev Each function below (except for `initialize`) is an extension point function: the pool calls it at the matching extension
/// point (before/after add, remove, swap). Return the function selector on success.
interface IMetricOmmExtensions {
/// @notice One-time extension setup invoked by the factory immediately after pool deployment.
function initialize(address pool, bytes calldata data) external returns (bytes4);
function beforeAddLiquidity(
address sender,
address owner,
uint80 salt,
LiquidityDelta calldata deltas,
bytes calldata extensionData
) external returns (bytes4);
function afterAddLiquidity(
address sender,
address owner,
uint80 salt,
LiquidityDelta calldata deltas,
uint256 amount0Added,
uint256 amount1Added,
bytes calldata extensionData
) external returns (bytes4);
function beforeRemoveLiquidity(
address sender,
address owner,
uint80 salt,
LiquidityDelta calldata deltas,
bytes calldata extensionData
) external returns (bytes4);
function afterRemoveLiquidity(
address sender,
address owner,
uint80 salt,
LiquidityDelta calldata deltas,
uint256 amount0Removed,
uint256 amount1Removed,
bytes calldata extensionData
) external returns (bytes4);
function beforeSwap(
address sender,
address recipient,
bool zeroForOne,
int128 amountSpecified,
uint128 priceLimitX64,
uint256 packedSlot0Initial,
uint128 bidPriceX64,
uint128 askPriceX64,
uint128 referencePriceX64,
bytes calldata extensionData
) external returns (bytes4);
function afterSwap(
address sender,
address recipient,
bool zeroForOne,
int128 amountSpecified,
uint128 priceLimitX64,
uint256 packedSlot0Initial,
uint256 packedSlot0Final,
uint128 bidPriceX64,
uint128 askPriceX64,
uint128 referencePriceX64,
int128 amount0Delta,
int128 amount1Delta,
uint256 platformFeeAmount,
bytes calldata extensionData
) external returns (bytes4);
}
lib/metric-periphery/lib/metric-core/contracts/types/FactoryOperation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {ExtensionOrders} from "./PoolExtensionsConfig.sol";
/// @notice Inputs used by `IMetricOmmPoolFactory.createPool`.
/// @dev Parameter selection guidelines (initial scaled densities, minimalOperationalLiquidity,
/// fees, bins, extensions, salt): see `docs/POOL_CONFIGURATION_AND_MANAGEMENT.md`.
struct PoolParameters {
address token0;
address token1;
address priceProvider;
/// @dev Up to seven extension contracts; stored as immutables on the pool in array order.
address[] extensions;
/// @dev Per-action extension call orders; each value encodes up to seven 3-bit extension indices.
ExtensionOrders extensionOrders;
/// @dev Per-extension initialization calldata; length must match `extensions`.
bytes[] extensionInitData;
/// @notice Delay for mutable provider rotation; `type(uint256).max` means immutable provider.
uint256 priceProviderTimelock;
address admin;
/// @notice Token0 empty-bin mint density in **internal (scaled) precision** for `1e18` shares.
/// @dev Stored on the pool as `INITIAL_SCALED_TOKEN_0_PER_SHARE_E18`. Liquidity uses
/// `amountScaled = initialScaledAmount0PerE18Shares * shares / 1e18`.
/// Whole tokens for `1e18` shares are `A0 = this / 10^D` where `D = max(18, d0, d1)`.
/// Must be non-zero and `< 2^128`.
uint256 initialScaledAmount0PerE18Shares;
/// @notice Token1 empty-bin mint density in **internal (scaled) precision** for `1e18` shares.
/// @dev Same semantics as `initialScaledAmount0PerE18Shares` for token1.
uint256 initialScaledAmount1PerE18Shares;
/// @notice Minimum per-bin share delta for add/remove and minimum non-zero position size.
/// @dev Must be at least `1e6 * 1e18 / min(initialScaledAmount0PerE18Shares, initialScaledAmount1PerE18Shares)`.
uint256 minimalOperationalLiquidity;
/// @notice Protocol spread fee for this pool in E6 (`1e6 = 100%`).
/// @dev Must be `<= factory.maxProtocolSpreadFeeE6`. Values below `factory.spreadProtocolFeeE6` are clamped up to the default.
uint24 protocolSpreadFeeE6;
/// @notice Admin spread fee component in E6 (`1e6 = 100%`).
uint24 adminSpreadFeeE6;
/// @notice Protocol notional fee for this pool in E8 (`1e8 = 100%`).
/// @dev Must be `<= factory.maxProtocolNotionalFeeE8`. Values below `factory.protocolNotionalFeeE8` are clamped up to the default.
uint24 protocolNotionalFeeE8;
/// @notice Admin notional fee component in E8 (`1e8 = 100%`).
uint24 adminNotionalFeeE8;
address adminFeeDestination;
int24 curBinDistFromProvidedPriceE6;
uint256[] nonNegativeBinDataArray;
uint256[] negativeBinDataArray;
/// @dev Caller-chosen CREATE2 salt input. The factory deploys with
/// `keccak256(abi.encode(salt, admin, adminFeeDestination, extensionInitData))`.
bytes32 salt;
/// @notice Bid/ask/ref asymmetry slack `m` in X8 (`M = 1 + m`). Must be non-zero and
/// `<= factory.onCreationMaxBidAskRefAsymmetryX8`.
/// @dev `type(uint16).max` disables the provider bid/ask/ref asymmetry check on the pool.
uint16 bidAskRefAsymmetryX8;
}
lib/metric-periphery/lib/metric-core/contracts/types/PoolExtensionsConfig.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
/// @notice Each field encodes the invocation order for an extension action.
/// @dev Pool contains up to 7 extensions that are numbered from 1 to 7 in the pool's `extensions` array.
/// To encode invocation order we pack array of 3-bit (values 0-7) into a single uint256.
/// Least significant slot is first element of the array.
/// 0 represents termination of the sequence.
/// The sequence defines which extensions will be called for a given action.
struct ExtensionOrders {
uint256 beforeAddLiquidity;
uint256 afterAddLiquidity;
uint256 beforeRemoveLiquidity;
uint256 afterRemoveLiquidity;
uint256 beforeSwap;
uint256 afterSwap;
}
/// @notice Contains addresses of all extensions that are configured for the pool.
struct PoolExtensions {
address extension1;
address extension2;
address extension3;
address extension4;
address extension5;
address extension6;
address extension7;
}
lib/metric-periphery/lib/metric-core/contracts/types/PoolOperation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
/// @notice Batched per-bin liquidity add or remove payload (parallel arrays).
/// @param binIdxs Bin indices to modify.
/// @param shares Shares to add or remove per corresponding bin index.
struct LiquidityDelta {
int256[] binIdxs;
uint256[] shares;
}
/// @notice Per-bin balance change used in liquidity and swap events.
/// @dev `delta0Scaled` and `delta1Scaled` are scaled token balances inside bins (not raw ERC20 amounts).
/// Positive means net token entered the bin; negative means net token left the bin.
/// @param delta0Scaled Net change in the bin scaled token0 balance.
/// @param delta1Scaled Net change in the bin scaled token1 balance.
struct BinBalanceDelta {
int256 delta0Scaled;
int256 delta1Scaled;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 99999,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"lib/metric-periphery/:@metric-core/=lib/metric-periphery/lib/metric-core/contracts/",
"lib/metric-periphery/:@openzeppelin/contracts/=lib/metric-periphery/lib/metric-core/lib/openzeppelin-contracts/contracts/",
"metric-periphery/=lib/metric-periphery/contracts/",
"@metric-core/=lib/metric-core/contracts/",
"@openzeppelin/contracts/=lib/metric-core/lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"@openzeppelin/contracts-v5/=lib/openzeppelin-contracts/contracts/",
"@metric-core-test/=lib/metric-periphery/lib/metric-core/test/",
"erc4626-tests/=lib/metric-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/metric-core/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"metric-core/=lib/metric-core/contracts/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.