Skip to content
Verified contractPartialMIT

ImmutableAppPoolHelper

Address0xd993832465f58306eda8f35d2d10a2b4bcf0c7fb
Balance

0 ETH

 

Transactions

137

 

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
26,047,798
Creation transaction
0x91b29550e0…ac31274ad9

36 files

contracts/helpers/ImmutableAppPoolHelper.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

import {IMetricOmmPoolFactory} from "@metric-core/interfaces/IMetricOmmPoolFactory/IMetricOmmPoolFactory.sol";
import {IMetricOmmPool} from "@metric-core/interfaces/IMetricOmmPool/IMetricOmmPool.sol";
import {PoolParameters} from "@metric-core/types/FactoryOperation.sol";
import {AnchoredProviderFactory} from "@smart-contracts-poc/AnchoredProviderFactory.sol";

/// @notice Overrides pool asymmetry for permanently bound APP providers.
/// @dev Requires factory authority for setPoolBidAskRefAsymmetryX8. APP parameters may remain mutable.
contract ImmutableAppPoolHelper {
  error UnknownPool();
  error MutablePoolPriceProvider();
  error UnrecognizedPriceProvider();
  error NotPoolAdmin();

  IMetricOmmPoolFactory public constant POOL_FACTORY =
    IMetricOmmPoolFactory(0x2a53833cc95548cf52c7b159110e22D3a9018f32);
  AnchoredProviderFactory public constant APP_FACTORY =
    AnchoredProviderFactory(0xb0eAE19259500Ac4Ca59b9a5cb8cDB2Da8076F0A);

  /// @dev params.bidAskRefAsymmetryX8 must satisfy the factory creation cap; the override is applied afterward.
  function createPool(PoolParameters calldata params, uint16 bidAskRefAsymmetryX8) external returns (address pool) {
    pool = POOL_FACTORY.createPool(params);
    _ppIsImmutableApp(pool);
    POOL_FACTORY.setPoolBidAskRefAsymmetryX8(pool, bidAskRefAsymmetryX8);
  }

  function setPoolBidAskRefAsymmetryX8(address pool, uint16 bidAskRefAsymmetryX8) external {
    _ppIsImmutableApp(pool);
    if (msg.sender != POOL_FACTORY.poolAdmin(pool)) revert NotPoolAdmin();
    POOL_FACTORY.setPoolBidAskRefAsymmetryX8(pool, bidAskRefAsymmetryX8);
  }

  function _ppIsImmutableApp(address pool) private view {
    if (!POOL_FACTORY.isPool(pool)) revert UnknownPool();
    address provider = IMetricOmmPool(pool).getImmutables().immutablePriceProvider;
    if (provider == address(0)) revert MutablePoolPriceProvider();
    if (!APP_FACTORY.isProvider(provider)) revert UnrecognizedPriceProvider();
  }
}

lib/metric-core/contracts/interfaces/IMetricOmmPool/IMetricOmmPool.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

import {IMetricOmmPoolActions} from "./IMetricOmmPoolActions.sol";
import {IMetricOmmPoolCollectFees} from "./IMetricOmmPoolCollectFees.sol";
import {IMetricOmmPoolFactoryActions} from "./IMetricOmmPoolFactoryActions.sol";

/// @notice All constructor-set immutables of a `MetricOmmPool`, returned by `getImmutables()`.
/// @dev Scale multipliers convert native token amounts to internal precision; initial scaled per-share
///      amounts are the `createPool` inputs `initialScaledAmount{0,1}PerE18Shares`, stored unchanged.
struct PoolImmutables {
  address factory;
  address token0;
  address token1;
  /// @notice `10^(max(18, token0Decimals, token1Decimals) - token0Decimals)`.
  uint256 token0ScaleMultiplier;
  /// @notice `10^(max(18, token0Decimals, token1Decimals) - token1Decimals)`.
  uint256 token1ScaleMultiplier;
  /// @notice Scaled token0 per `1e18` shares minted into an empty bin.
  uint256 initialScaledToken0PerShareE18;
  /// @notice Scaled token1 per `1e18` shares minted into an empty bin.
  uint256 initialScaledToken1PerShareE18;
  uint256 minimalOperationalLiquidity;
  address immutablePriceProvider;
  int256 lowestBin;
  int256 highestBin;
  address extension1;
  address extension2;
  address extension3;
  address extension4;
  address extension5;
  address extension6;
  address extension7;
  uint256 beforeAddLiquidityOrder;
  uint256 afterAddLiquidityOrder;
  uint256 beforeRemoveLiquidityOrder;
  uint256 afterRemoveLiquidityOrder;
  uint256 beforeSwapOrder;
  uint256 afterSwapOrder;
}

/// @title IMetricOmmPool
/// @notice Full external API of `MetricOmmPool` for typing integrators and the factory.
/// @dev Composition: user liquidity and swap (`IMetricOmmPoolActions`), factory fee sweep (`IMetricOmmPoolCollectFees`), factory-only pool controls (`IMetricOmmPoolFactoryActions`). User-facing custom errors are on `IMetricOmmPoolActions`; factory-only errors are on `IMetricOmmPoolFactoryActions`.
interface IMetricOmmPool is IMetricOmmPoolActions, IMetricOmmPoolCollectFees, IMetricOmmPoolFactoryActions {
  /// @notice Return every constructor-set immutable in a single call.
  /// @dev Immutables live in contract bytecode, not storage, so they cannot be read via EXTSLOAD.
  function getImmutables() external view returns (PoolImmutables memory);

  /// @notice Whether a live swap is executing and which price provider supplies its quotes.
  /// @return priceProvider Active price provider during swap; address(0) outside swap.
  function inSwap() external view returns (address priceProvider);

  /// @notice Live sell/buy prices (Q64.64) for token0 at the pool's current marginal bin position.
  /// @dev Informational only — not a guaranteed executable quote. Sell = token0 → token1; buy = token1 → token0.
  ///      Includes oracle spread, per-bin additional fees, and notional fees (zero-size exact-in marginal prices)
  ///      via the active price provider (same path as `swap`). For real pricing/execution decisions, call `swap`
  ///      and decide in the swap callback, or use the periphery quoter.
  /// @return sellPriceX64 Fee-adjusted sell price (token1 per token0, Q64.64).
  /// @return buyPriceX64 Fee-adjusted buy price (token1 per token0, Q64.64).
  function getSellAndBuyPrices() external returns (uint128 sellPriceX64, uint128 buyPriceX64);
}

lib/metric-core/contracts/interfaces/IMetricOmmPool/IMetricOmmPoolActions.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

import {BinBalanceDelta, LiquidityDelta} from "../../types/PoolOperation.sol";
import {Packed2Int128, Packed2Uint128, PackedSwapDetails} from "../../types/Packed.sol";

/// @title IMetricOmmPoolActions
/// @notice User-facing mutators on Metric OMM pools: liquidity (shares per bin) and swap execution.
/// @dev State reads live on the concrete pool or libraries. Liquidity paths use native ERC20 amounts in callbacks; bin events carry scaled balances (`BinBalanceDelta`, see `PoolOperation.sol`). Successful `swap` consults the live price provider and is blocked when `pauseLevel != 0` (`PoolPaused`); `addLiquidity` / `removeLiquidity` are not gated by pause so ops policy can diverge (e.g. unwind while swaps are off).
interface IMetricOmmPoolActions {
  // ============ Events: Liquidity ============

  /// @notice Liquidity was minted into one or more bins for a single position key.
  /// @dev Arrays are parallel: `binIdxs[i]`, `binBalanceDeltas[i]`, and `shares[i]` describe the same bin. Emitted after balances and position shares are updated; indexers can reconcile bins from `binBalanceDeltas` (scaled) separately from callback token flows (native).
  /// @param provider `owner` leg of the position key; indexed for position-scoped subscriptions.
  /// @param salt `salt` leg of the position key; indexed with `provider` to disambiguate positions.
  /// @param binIdxs Bin index per touched row (pool-configured range).
  /// @param binBalanceDeltas Scaled token0/token1 balance change inside each bin (`BinBalanceDelta`); not wallet transfer amounts.
  /// @param shares Liquidity shares minted per touched bin for this position.
  event LiquidityAdded(
    address indexed provider,
    uint80 indexed salt,
    int256[] binIdxs,
    BinBalanceDelta[] binBalanceDeltas,
    uint256[] shares
  );

  /// @notice Liquidity was burned from one or more bins for a single position key.
  /// @dev Same parallel-array layout as `LiquidityAdded`. `removeLiquidity` requires `msg.sender == owner`, so the position key always matches the caller for this event.
  /// @param provider Position owner (equals `msg.sender` for the removing call).
  /// @param salt Position salt with `provider` in the key.
  /// @param binIdxs Bin index per touched row.
  /// @param binBalanceDeltas Scaled balance change per bin (signs reflect token leaving or entering the bin on burn).
  /// @param shares Shares burned per touched bin.
  event LiquidityRemoved(
    address indexed provider,
    uint80 indexed salt,
    int256[] binIdxs,
    BinBalanceDelta[] binBalanceDeltas,
    uint256[] shares
  );

  // ============ Events: Swap ============

  /// @notice One step of routing updated a bin during `swap` (may emit multiple times per call).
  /// @dev Refer to types/Packed.sol to decode the packed values.
  /// @param binIdx Bin touched in this step.
  /// @param binDeltas Change in THAT BIN's scaled balances, packed: `high` = token0, `low` = token1.
  /// @param fees This step's two fee legs, packed: `high` = LP leg (stays in the bin), `low` = platform leg (protocol + admin, withheld).
  event BinSwapped(int256 binIdx, Packed2Int128 binDeltas, Packed2Uint128 fees);

  /// @notice Terminal summary after a successful `swap`.
  /// @dev Refer to types/Packed.sol to decode the packed values.
  /// @param sender `msg.sender` of `swap` (the account that may receive swap callback).
  /// @param recipient Address that received the output token leg.
  /// @param details Swap mode and resulting bin position packed into one word: `exactInput()`,
  ///        `binIdx()` (signed), `posInBin()`. Check details in PackedSwapDetailsLib.
  /// @param amountDeltas Net native-token flows for the whole call, packed: `high` = token0, `low` = token1 (positive = the pool gained that token).
  /// @param platformFees Platform (protocol + admin) fee for this swap on the input-token leg, packed: `high` = SPREAD leg, `low` = NOTIONAL leg.
  event Swap(
    address indexed sender,
    address indexed recipient,
    PackedSwapDetails details,
    Packed2Int128 amountDeltas,
    Packed2Uint128 platformFees
  );

  // ============ Errors: Liquidity ============

  /// @notice Add or remove share delta is below the pool operational floor.
  /// @dev Raised when non-zero `sharesToAdd` / `sharesToRemove` is `< MINIMAL_OPERATIONAL_LIQUIDITY`.
  /// @param binIdx Bin where the offending delta was applied.
  /// @param sharesDelta Offending share delta.
  /// @param minimalRequired Pool immutable `MINIMAL_OPERATIONAL_LIQUIDITY`.
  error SharesDeltaSmallerThanMinimalOperationalLiquidity(int256 binIdx, uint256 sharesDelta, uint256 minimalRequired);

  /// @notice Remove would leave a non-zero position below the pool operational floor.
  /// @dev Raised when leftover shares are `> 0` and `< MINIMAL_OPERATIONAL_LIQUIDITY`; remove more or exit to zero.
  /// @param binIdx Bin where the leftover would remain.
  /// @param leftovers Remaining shares after the attempted remove.
  /// @param minimalRequired Pool immutable `MINIMAL_OPERATIONAL_LIQUIDITY`.
  error LeftoversSmallerThanMinimalOperationalLiquidity(int256 binIdx, uint256 leftovers, uint256 minimalRequired);

  /// @notice Burn asked for more shares than exist for that position in a bin.
  /// @param requested `deltas.shares[i]` for the offending bin.
  /// @param available Shares recorded for `owner`+`salt` in that bin before the call.
  error InsufficientLiquidity(uint256 requested, uint256 available);

  /// @notice The modify-liquidity callback sent fewer tokens than the pool debt for this add.
  /// @dev Fires after the pool computed required `amount0`/`amount1` and invoked `msg.sender`; safe for retry once the callback actually pays.
  error InsufficientTokenBalance();

  /// @notice `removeLiquidity` caller is not the position owner.
  /// @dev Only `owner` may burn; `addLiquidity` may use a different `msg.sender` when `owner` is supplied, but removal is stricter.
  error NotPositionOwner();

  /// @notice Deposit allowlist rejected this `owner` for `addLiquidity`.
  /// @dev Never reverted by the pool itself; gating extensions raise it from the add-liquidity extension points.
  error NotAllowedToDeposit();

  /// @notice `LiquidityDelta` arrays are not the same length.
  /// @dev Checked before touching state; fix the payload and resubmit.
  error LiquidityDeltaLengthMismatch();

  /// @notice A bin index in `deltas.binIdxs` is outside this pool’s `[LOWEST_BIN, HIGHEST_BIN]`.
  /// @param binIdx First failing index from the caller payload.
  error InvalidBinIndex(int256 binIdx);

  /// @notice The amount od shares would trigger an overflow in the scaled balance calculation.
  error SharesAmountTooLarge();

  // ============ Errors: Swap ============

  /// @notice Swap callback paid the wrong token amount vs what the pool requested.
  /// @dev Distinct from `InsufficientTokenBalance` (liquidity path); the swap callback left the pool balance short of the input amount the pool requested.
  error IncorrectDelta();

  /// @notice Swap allowlist rejected `msg.sender`.
  /// @dev Never reverted by the pool itself; gating extensions raise it from `beforeSwap`, which `swap` and `simulateSwapAndRevert` run identically.
  error NotAllowedToSwap();

  /// @notice `amountSpecified == 0` on `swap` / `simulateSwapAndRevert`.
  error InvalidAmount();

  /// @notice Swap math settled with a zero input or output delta (native units).
  /// @dev After `_executeSwap`, either `amount0Delta` or `amount1Delta` is zero — e.g. price limit blocks all progress or amounts round away.
  error FinalAmountIsZero();

  /// @notice An intermediate scaled swap quantity did not fit in `uint128`.
  /// @dev Surfaces overflow-style failures in swap math before silent wrap; typically extreme size or price inputs.
  error AmountScaledExceedsMax();

  /// @notice A swap would write a bin's scaled token balance above `type(uint104).max`.
  /// @dev Happens when price × outflow would grow the incoming-side balance past the packed `BinState` width.
  ///      The cursor cannot advance past that bin until liquidity is reduced; prefer smaller bins / less dense liquidity.
  /// @param attemptedScaledBalance The balance that would have been stored (internal scaled units).
  error OverflowedOnFittingBinBalances(uint256 attemptedScaledBalance);

  /// @notice Swaps are disabled while the pool pause level is non-zero.
  /// @dev Pause level is factory-controlled; liquidity mutators are intentionally not blocked by the same check.
  error PoolPaused();

  /// @notice Bid price is not strictly below ask (`bidPriceX64 >= askPriceX64`).
  /// @dev On `swap`, comes from the live `IPriceProvider` quote; on `simulateSwapAndRevert`, from the arguments you passed.
  error BidGreaterThanAsk();

  /// @notice Bid price was zero, so mid/spread cannot be formed.
  /// @dev On `swap`, from the live provider; on `simulateSwapAndRevert`, from `bidPriceX64` you passed.
  error BidIsZero();

  /// @notice Reference price was not within `[bidPriceX64, askPriceX64]`, or was zero.
  /// @dev On `swap`, from the live provider; on `simulateSwapAndRevert`, from `referencePriceX64` you passed.
  error ReferencePriceOutOfRange();

  /// @notice Bid/ask returns about the reference are too asymmetric for the pool's `bidAskRefAsymmetryX8` bound.
  /// @dev With `r1 = reference/bid - 1`, `r2 = ask/reference - 1`, and `M = 1 + m` (`m` stored in X8), requires
  ///      `1/M <= r1/r2 <= M`. Skipped when `bidAskRefAsymmetryX8 == type(uint16).max`. A reference on bid/ask reverts.
  error BidAskRefAsymmetryOutOfBounds();

  /// @notice External call to the active `IPriceProvider` reverted or bubbled a failure.
  /// @param reason Opaque revert data from the provider (decode off-chain if the provider documents errors).
  error PriceProviderFailed(bytes reason);

  /// @notice Deliberate revert carrying simulated swap deltas; no callbacks and no token transfers.
  /// @dev Runs the same swap math and extension path as `swap` (with caller-supplied bid/ask instead of the live oracle) then always `revert SimulateSwap(...)`, rolling back any transient storage writes, so committed chain state is unchanged. Omits the `whenNotPaused` check present on `swap`, so a simulation can succeed while the pool is paused. Decode `SimulateSwap` from the revert data (`eth_call` / `try/catch`); ABI return values are unused.
  /// @param amount0Delta Net token0 the swap would move into (`>0`) or out of (`<0`) the pool (native decimals).
  /// @param amount1Delta Net token1 the swap would move into or out of the pool (native decimals).
  error SimulateSwap(int256 amount0Delta, int256 amount1Delta);

  // ============ Mutating: Liquidity ============

  /// @notice Mint shares across bins for `(owner, salt)`; pulls tokens via `IMetricOmmModifyLiquidityCallback` on `msg.sender`.
  /// @dev Callback receives native token amounts the pool expects; underpay reverts `InsufficientTokenBalance`. `msg.sender` pays but need not equal `owner` (operator pattern).
  /// @param owner Position owner encoded in the pool’s position key.
  /// @param salt Caller-chosen second leg of the position key.
  /// @param deltas Parallel `binIdxs` / `shares` arrays (see `LiquidityDelta`).
  /// @param callbackData Opaque bytes forwarded unmodified to the modify-liquidity callback.
  /// @param extensionData Opaque bytes forwarded to liquidity extensions (beforeAddLiquidity / afterAddLiquidity).
  /// @return amount0Added Total token0 actually pulled from the callback into the pool (native).
  /// @return amount1Added Total token1 actually pulled from the callback into the pool (native).
  /// @dev Reverts `LiquidityDeltaLengthMismatch` when `binIdxs` and `shares` lengths differ.
  function addLiquidity(
    address owner,
    uint80 salt,
    LiquidityDelta calldata deltas,
    bytes calldata callbackData,
    bytes calldata extensionData
  ) external returns (uint256 amount0Added, uint256 amount1Added);

  /// @notice Burn shares across bins for `(owner, salt)` and send underlying tokens to `owner`.
  /// @dev Requires `msg.sender == owner` (`NotPositionOwner` otherwise). No callback: tokens are transferred out directly.
  /// @param owner Must equal `msg.sender`.
  /// @param salt Position salt with `owner`.
  /// @param deltas Parallel arrays of bins and share burns.
  /// @param extensionData Opaque bytes forwarded to liquidity extensions (beforeRemoveLiquidity / afterRemoveLiquidity).
  /// @return amount0Removed Total token0 sent from the pool to `owner` (native).
  /// @return amount1Removed Total token1 sent from the pool to `owner` (native).
  function removeLiquidity(address owner, uint80 salt, LiquidityDelta calldata deltas, bytes calldata extensionData)
    external
    returns (uint256 amount0Removed, uint256 amount1Removed);

  // ============ Mutating: Swap ============

  /// @notice Execute a spot swap against pool liquidity using live oracle prices.
  /// @dev Pulls input from `msg.sender` through `IMetricOmmSwapCallback`;
  /// @param recipient Address that receives the output token (subject to callback flow settling the input first).
  /// @param zeroForOne `true` sells token0 for token1 along the pool’s ordering.
  /// @param amountSpecified Exact input if `>0`, exact output magnitude if `<0`, in native units of that leg.
  /// @param priceLimitX64 Q64.64 bound on the trader's realized price along the swap direction (for very small traded amounts may be significantly breached by roundings).
  /// @param callbackData Opaque bytes forwarded to the swap callback.
  /// @param extensionData Opaque bytes forwarded to swap extension point functions (beforeSwap / afterSwap).
  /// @return amount0Delta Net token0 change for the pool (signed, native).
  /// @return amount1Delta Net token1 change for the pool (signed, native).
  function swap(
    address recipient,
    bool zeroForOne,
    int128 amountSpecified,
    uint128 priceLimitX64,
    bytes calldata callbackData,
    bytes calldata extensionData
  ) external returns (int128 amount0Delta, int128 amount1Delta);

  /// @notice Run swap math with caller-supplied bid/ask; always reverts with `SimulateSwap` carrying the net deltas.
  /// @dev Does not use the pool’s live oracle prices for the mid—use for quotes/off-chain routing. Invokes the same swap extension point functions as `swap` when enabled; still enforces `priceLimitX64` and path logic; no ERC20 transfers or swap callback. Typical usage: `eth_call` or `try/catch` decoding `SimulateSwap`. `sender` is forwarded to the extension points as-is instead of `msg.sender`, so you can simulate as an arbitrary address (e.g. checking a sender-gated extension for a specific user) — safe only because the call always reverts and nothing persists.
  /// @param sender Address forwarded to swap extension point functions in place of `msg.sender`; has no other effect since the call always reverts.
  /// @param recipient Same as `swap` (forwarded to swap extension point functions).
  /// @param zeroForOne Same as `swap`.
  /// @param amountSpecified Same sign convention as `swap`.
  /// @param priceLimitX64 Same encoding as `swap`.
  /// @param bidPriceX64 Bid used for extension context and swap math in this simulation (Q64.64).
  /// @param askPriceX64 Ask used for extension context and swap math in this simulation (Q64.64).
  /// @param referencePriceX64 Reference price used as the mid/price-path anchor and for fee calculation in this simulation (Q64.64).
  /// @param extensionData Opaque bytes forwarded to swap extension point functions (beforeSwap / afterSwap).
  /// @return amount0Delta Unused in practice; values appear only on the reverting `SimulateSwap` error.
  /// @return amount1Delta Unused in practice; values appear only on the reverting `SimulateSwap` error.
  function simulateSwapAndRevert(
    address sender,
    address recipient,
    bool zeroForOne,
    int128 amountSpecified,
    uint128 priceLimitX64,
    uint128 bidPriceX64,
    uint128 askPriceX64,
    uint128 referencePriceX64,
    bytes calldata extensionData
  ) external returns (int128 amount0Delta, int128 amount1Delta);
}

lib/metric-core/contracts/interfaces/IMetricOmmPool/IMetricOmmPoolCollectFees.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

/// @title IMetricOmmPoolCollectFees
/// @notice Allocate and distribute protocol and admin fee balances held on the pool.
/// @dev Collection is factory-only. Unpaid allocations retain their split
///      and are retried using the latest destinations. `ProtocolFeesCollected` reports amounts actually transferred.
interface IMetricOmmPoolCollectFees {
  // ============ Events ============

  event FeeTransferFailed(address indexed token, address indexed destination, uint256 amount);

  /// @notice Emitted after a successful fee collection pass.
  /// @param amount0ToProtocol Token0 amount sent to `protocolFeeDestination` (native).
  /// @param amount1ToProtocol Token1 amount sent to `protocolFeeDestination` (native).
  /// @param amount0ToAdmin Token0 amount sent to `adminFeeDestination` (native).
  /// @param amount1ToAdmin Token1 amount sent to `adminFeeDestination` (native).
  event ProtocolFeesCollected(
    uint256 amount0ToProtocol, uint256 amount1ToProtocol, uint256 amount0ToAdmin, uint256 amount1ToAdmin
  );

  // ============ Mutating ============

  /// @notice Allocate accrued fees using supplied rates, then attempt payouts including previously unpaid fees.
  /// @dev Pending balances retain scaled rounding remainders; transfer failures do not revert allocation.
  ///      Supported tokens must not move funds when reporting a failed transfer.
  /// @param protocolSpreadFeeE6 Protocol spread component in E6 at collection time (must match factory policy).
  /// @param adminSpreadFeeE6 Admin spread component in E6 at collection time.
  /// @param protocolNotionalFeeE8 Protocol notional component in E8 at collection time.
  /// @param adminNotionalFeeE8 Admin notional component in E8 at collection time.
  /// @param adminFeeDestination Recipient for the admin share of collected tokens (per factory configuration).
  /// @param protocolFeeDestination Recipient for the protocol share (the factory's `feeReceiver`).
  function collectFees(
    uint256 protocolSpreadFeeE6,
    uint256 adminSpreadFeeE6,
    uint256 protocolNotionalFeeE8,
    uint256 adminNotionalFeeE8,
    address adminFeeDestination,
    address protocolFeeDestination
  ) external;
}

lib/metric-core/contracts/interfaces/IMetricOmmPool/IMetricOmmPoolFactoryActions.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

/// @title IMetricOmmPoolFactoryActions
/// @notice Entrypoints on `MetricOmmPool` that only the pool factory may call (`msg.sender == FACTORY`).
/// @dev Integrators must use `MetricOmmPoolFactory` (owner or pool admin flows); calling these on the pool directly reverts with `OnlyFactory` unless `msg.sender` is the factory contract address.
interface IMetricOmmPoolFactoryActions {
  // ============ Events ============

  /// @notice Emitted when total spread fee on the pool is updated.
  /// @param spreadFeeE6 New aggregate spread fee in E6 (`1e6 = 100%`).
  event SpreadFeeUpdated(uint24 spreadFeeE6);

  /// @notice Emitted when total notional fee on the pool is updated.
  /// @param notionalFeeE8 New aggregate notional fee in E8 (`1e8 = 100%`).
  event NotionalFeeUpdated(uint24 notionalFeeE8);

  /// @notice Emitted when pause level changes.
  /// @param previousLevel Prior pause level (`0` active, `1` admin pause, `2` protocol pause).
  /// @param newLevel New pause level after the update.
  event PauseLevelUpdated(uint8 previousLevel, uint8 newLevel);

  /// @notice Emitted when the mutable price provider address stored on the pool is updated.
  /// @param newPriceProvider New active `IPriceProvider` (immutable pools never emit this from rotation).
  event PriceProviderUpdated(address indexed newPriceProvider);

  /// @notice Emitted when per-bin additional spread fees are set.
  /// @param bin Bin index whose overrides were updated.
  /// @param addFeeBuyE6 Additional buy-side spread fee in E6 on top of base spread.
  /// @param addFeeSellE6 Additional sell-side spread fee in E6 on top of base spread.
  event BinAdditionalFeesUpdated(int16 indexed bin, uint16 addFeeBuyE6, uint16 addFeeSellE6);

  /// @notice Emitted when bid/ask/ref asymmetry slack `m` in X8 is updated (`M = 1 + m`).
  /// @param bidAskRefAsymmetryX8 New asymmetry bound; `type(uint16).max` disables the check.
  event BidAskRefAsymmetryUpdated(uint16 bidAskRefAsymmetryX8);

  // ============ Errors ============

  /// @notice Thrown when `msg.sender` is not the pool factory.
  error OnlyFactory();

  /// @notice Thrown when `setPause` is called with a level outside `0..2`.
  error InvalidPauseLevel();

  // ============ Mutating ============

  /// @notice Set aggregate pool spread and notional fee rates (sum of protocol + admin components).
  /// @param newSpreadFeeE6 Total spread fee in E6 (`1e6 = 100%`).
  /// @param newNotionalFeeE8 Total notional fee in E8 (`1e8 = 100%`).
  function setPoolFees(uint24 newSpreadFeeE6, uint24 newNotionalFeeE8) external;

  /// @notice Update bid/ask/reference asymmetry bound `m` in X8 (`type(uint16).max` disables the check).
  function setBidAskRefAsymmetryX8(uint16 newBidAskRefAsymmetryX8) external;

  /// @notice Set pool pause level (`0` active, `1` admin paused, `2` protocol paused).
  /// @param newLevel Pause level enforced by the pool; must be at most `2`.
  function setPause(uint8 newLevel) external;

  /// @notice Set per-bin additional buy and sell spread fees in E6 on top of base spread.
  /// @param bin Bin index within the pool configured bin range.
  /// @param addFeeBuyE6 Additional fee on buys into the bin (E6).
  /// @param addFeeSellE6 Additional fee on sells out of the bin (E6).
  function setBinAdditionalFees(int16 bin, uint16 addFeeBuyE6, uint16 addFeeSellE6) external;

  /// @notice Update the pool active price provider (only for pools created with a mutable provider).
  /// @param newPriceProvider New provider contract; the factory validates its `token0`/`token1`, the pool stores it as given.
  function setPriceProvider(address newPriceProvider) external;
}

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-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-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-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-core/contracts/types/Packed.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;

/// @notice Two `uint128` values in one word: `high` in the top 128 bits, `low` in the bottom.
/// @dev Used to keep event payloads to a single word where two quantities always travel together.
///      What `high` and `low` mean is documented at each use site, not here.
///      `pack` takes `uint128` halves so narrowing -- and the choice of a checked or unchecked cast --
///      is the caller's, made visibly at the call site.
type Packed2Uint128 is uint256;

using Packed2Uint128Lib for Packed2Uint128 global;

/// @dev Implemented in assembly. Inline assembly reads the raw stack slot, which Solidity does not
///      guarantee to be free of dirty high-order bits, so every half is masked to 128 bits before use.
///      The masks are load-bearing, not defensive: see `test/Packed.t.sol`.
library Packed2Uint128Lib {
  uint256 private constant MASK = 0xffffffffffffffffffffffffffffffff;

  function pack(uint128 high_, uint128 low_) internal pure returns (Packed2Uint128 packed) {
    assembly ("memory-safe") {
      packed := or(shl(128, and(high_, MASK)), and(low_, MASK))
    }
  }

  /// @notice Add to BOTH halves at once.
  /// @dev One word, one ADD -- valid because a running total can never reach 2^128 and so cannot carry
  ///      out of the low half into the high one. Callers relying on this must keep both halves bounded.
  function addBoth(Packed2Uint128 acc, uint128 high_, uint128 low_) internal pure returns (Packed2Uint128 packed) {
    assembly ("memory-safe") {
      packed := add(acc, or(shl(128, and(high_, MASK)), and(low_, MASK)))
    }
  }

  function high(Packed2Uint128 packed) internal pure returns (uint256 value) {
    assembly ("memory-safe") {
      value := shr(128, packed)
    }
  }

  function low(Packed2Uint128 packed) internal pure returns (uint256 value) {
    assembly ("memory-safe") {
      value := and(packed, MASK)
    }
  }

  function sum(Packed2Uint128 packed) internal pure returns (uint256 value) {
    assembly ("memory-safe") {
      value := add(shr(128, packed), and(packed, MASK))
    }
  }
}

/// @notice Two `int128` values in one word: `high` in the top 128 bits, `low` in the bottom.
/// @dev Two's-complement halves. Same contract as `Packed2Uint128`: meaning is documented at the use
///      site, and `pack` takes `int128` halves so the narrowing happens visibly in the caller.
type Packed2Int128 is uint256;

using Packed2Int128Lib for Packed2Int128 global;

/// @dev Implemented in assembly. The `low_` mask in `pack` is ESSENTIAL, not defensive: a negative
///      `int128` is sign-extended on the stack, so without it the all-ones upper half would be OR'd
///      straight over `high_` and destroy it. Reading back uses `SIGNEXTEND`, which is exactly the
///      `int256(int128(uint128(...)))` cast chain in one opcode.
library Packed2Int128Lib {
  uint256 private constant MASK = 0xffffffffffffffffffffffffffffffff;
  /// @dev Byte index for `SIGNEXTEND` on a 16-byte (128-bit) value.
  uint256 private constant SIGN_BYTE = 15;

  function pack(int128 high_, int128 low_) internal pure returns (Packed2Int128 packed) {
    assembly ("memory-safe") {
      packed := or(shl(128, and(high_, MASK)), and(low_, MASK))
    }
  }

  function high(Packed2Int128 packed) internal pure returns (int256 value) {
    assembly ("memory-safe") {
      value := signextend(SIGN_BYTE, shr(128, packed))
    }
  }

  function low(Packed2Int128 packed) internal pure returns (int256 value) {
    assembly ("memory-safe") {
      value := signextend(SIGN_BYTE, packed)
    }
  }
}

/// @notice A swap's mode flag and resulting bin position in one word.
/// @dev Purpose-built (unlike the two generic pairs above) because the three fields are heterogeneous
///      and always travel together on `Swap`. Layout, low bits first:
///
///        bits   0..103 : posInBin   (uint104)
///        bits 104..119 : binIdx     (int16, two's complement)
///        bit       120 : exactInput (1 = the caller specified an exact input)
///
///      121 bits total, so the three fit one word with room to spare and cost one log word instead of
///      three. `binIdx` is signed, so reads sign-extend it -- see `test/Packed.t.sol`.
///
///      Each field is exactly as wide as its parameter, so nothing a caller can construct is ever
///      truncated.
type PackedSwapDetails is uint256;

using PackedSwapDetailsLib for PackedSwapDetails global;

library PackedSwapDetailsLib {
  uint256 private constant POS_MASK = 0xffffffffffffffffffffffffff;
  uint256 private constant BIN_IDX_MASK = 0xffff;
  uint256 private constant BIN_IDX_SHIFT = 104;
  uint256 private constant EXACT_INPUT_SHIFT = 120;
  /// @dev Byte index for `SIGNEXTEND` on a 2-byte (16-bit) value.
  uint256 private constant SIGN_BYTE = 1;

  /// @dev The `binIdx_` mask is load-bearing: a negative index is sign-extended and would otherwise
  ///      smear over the flag, which `test/Packed.t.sol` pins.
  ///
  ///      The `posInBin_` mask is NOT reachable and no test covers it: a `uint104` cannot hold a value
  ///      above the field, and Solidity cleans the parameter at this boundary. It is kept only because
  ///      the optimizer elides it (measured: zero bytes) and it would matter if the field or the
  ///      parameter ever diverged. Do not read it as verified behaviour.
  function pack(bool exactInput_, int16 binIdx_, uint104 posInBin_) internal pure returns (PackedSwapDetails packed) {
    assembly ("memory-safe") {
      packed := or(
        or(shl(EXACT_INPUT_SHIFT, and(exactInput_, 1)), shl(BIN_IDX_SHIFT, and(binIdx_, BIN_IDX_MASK))),
        and(posInBin_, POS_MASK)
      )
    }
  }

  /// @notice Whether `amountSpecified` was treated as an exact input.
  function exactInput(PackedSwapDetails packed) internal pure returns (bool value) {
    assembly ("memory-safe") {
      value := and(shr(EXACT_INPUT_SHIFT, packed), 1)
    }
  }

  /// @notice Active bin index after the swap. Signed, so this sign-extends.
  function binIdx(PackedSwapDetails packed) internal pure returns (int256 value) {
    assembly ("memory-safe") {
      value := signextend(SIGN_BYTE, shr(BIN_IDX_SHIFT, packed))
    }
  }

  /// @notice Position within `binIdx` after the swap.
  function posInBin(PackedSwapDetails packed) internal pure returns (uint256 value) {
    assembly ("memory-safe") {
      value := and(packed, POS_MASK)
    }
  }
}

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-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;
}

lib/smart-contracts-poc/contracts/AnchoredPriceProvider.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import {IOffchainOracle} from "./interfaces/IOffchainOracle.sol";
import {IPricedOracle} from "./interfaces/IPricedOracle.sol";
import {IAnchorSource} from "./interfaces/IAnchorSource.sol";
import {IPriceProvider} from "./interfaces/IPriceProvider.sol";
import {IAnchoredProviderFactory} from "./interfaces/IAnchoredProviderFactory.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/// @notice Anchored Price Provider (APP) — the one standard provider for public pools. Every quote is
///         clamped to the reference band derived from the anchor oracle's own uncertainty:
///
///             bid = min(refBid, custom_bid)
///             ask = max(refAsk, custom_ask)
///
///         Single-feed reference: mid ± mid·(multiplied spread + minMargin). Synthetic reference:
///         base low / quote high and base high / quote low, with an additive mid·minMargin per side.
///
///         Two modes, one contract:
///         - Reference mode (source = 0, default): quotes the reference interval directly.
///         - Source mode: an arbitrary curator contract supplies bid/ask, clipped into the band.
///           The reference bounds how TIGHT it may quote — a source can never quote inside the
///           oracle's own uncertainty to extract LP value. Widening is NOT bounded: the pool will
///           quote arbitrarily far outside the band if the source says so. That is reachable with
///           nobody malicious — an honest source reading a venue an outsider can move hands that
///           outsider the pool's price. Accepted deliberately: the outward side is the OPERATOR's
///           due diligence, so treat a source as trusted and the clamp as protection in ONE
///           direction only.
///
///         The third output, referencePrice, is the anchor's own mid and is NOT shapeable: no source,
///         confidence, marginStep or spread multiplier touches it. Consumers charge their fee from
///         that value out to whichever edge executes, so widening a quote only worsens the widener's
///         own execution — it cannot inflate the fee base. That is what keeps an instant source swap
///         economically harmless; see _computeBidAsk.
///
///         Clamp parameters (minMargin, MAX_REF_STALENESS) and the reference binding are immutable;
///         the source pointer is instantly swappable (no timelock needed: any source is clamp-bounded
///         at all times). No proxies — upgrades are new deployments.
///
///         Two deployment variants, selected by the immutable MUTABLE_PARAMS flag:
///         - Immutable (false): nothing is tunable except the source pointer.
///         - Customizable (true): the curator may additionally tune confidenceParam; a fixed marginStep
///           bias is set at construction (immutable). For the SHAPED quote — and unlike the source
///           path above, which is bounded on both edges — the guarantee is one-directional: the final
///           quote is never TIGHTER than the multiplied reference interval plus minMargin, and nothing caps
///           how far it may widen. Note the multiplied spread: a sub-1× per-leg multiplier tightens
///           that term, so minMargin (required positive) is the only part no live knob can move.
///           Confidence is clipped to the band edge on the tight side, but a LARGE confidence widens
///           the shaped quote past the band and the clamp lets that through (see
///           testConfidenceMaxWidensBeyondBand) — "confidence only ever tightens" is false. A positive
///           marginStep likewise widens BEYOND the band. That asymmetry is deliberate: both shaping
///           inputs are factory-bounded values chosen by the provider owner, whereas a source is
///           arbitrary external code. With confidence 0 and marginStep 0 the shaped quote degenerates
///           to the band edges — behaviorally identical to the immutable variant.
///
///         Reads go through the access-gated providers oracle (Pyth / Chainlink), exclusively via
///         the attributed, non-view `price(feedId, pool)` path: the pool marks itself in-swap with
///         this provider and calls `getQuote()` (no args); this provider forwards the pool
///         (its `msg.sender`) to the oracle, which binds the read via `pool.inSwap() == provider`.
contract AnchoredPriceProvider is IPriceProvider {
    string public constant version = "1.1.0";

    // ── Constants ────────────────────────────────────────────────────────
    uint256 internal constant Q64 = 1 << 64;

    uint256 internal constant ORACLE_DECIMALS = 1e8;
    uint256 public constant BPS_BASE_U = 1e18;
    int256 public constant BPS_BASE = int256(BPS_BASE_U);
    uint16 internal constant ORACLE_BPS = 10_000;
    /// @dev Pyth/Chainlink saturate at 65534; the true uncertainty is then unknown. Reject that
    ///      value and the 65535 stall sentinel on EACH leg, before any spread multiplier is applied.
    ///      This also rejects an honest spread rounded to exactly 65534, conservatively.
    uint16 internal constant SATURATED_SPREAD = type(uint16).max - 1;
    /// @dev Oracle spread0 is in 0.01-bps units (fraction × 1e6),
    ///      matching the priced oracles (Pyth/Chainlink) and the compressed codebook. `minMargin` is
    ///      BPS_BASE_U-scale. One spread unit (0.01 bps) = 1e12 in BPS_BASE_U (1e18) scale.
    uint256 internal constant ONE_SPREAD_UNIT_E18 = 1e12;

    uint256 public constant CONFIDENCE_COOLDOWN = 1 minutes;
    uint256 public constant CONFIDENCE_MAX = 1_000_000; // 100x multiplier
    uint256 internal constant CONFIDENCE_BASE = 1e10; // 1e6 (0.01 bps) × 10_000 (multiplier base)

    /// @dev Gas forwarded to the source staticcall — bounds gas-griefing; OOG fails closed.
    uint256 public constant SOURCE_GAS_LIMIT = 500_000;

    // ── Immutables ──────────────────────────────────────────────────────
    IOffchainOracle public immutable offchainOracle;
    bytes32 public immutable baseFeedId;
    /// @notice Optional second feed for synthetic ratio quoting; zero = single-feed (no conversion).
    ///         Synthetic mid = price(baseFeedId) / price(quoteFeedId), e.g. BTC/USD ÷ ETH/USD = BTC/ETH.
    bytes32 public immutable quoteFeedId;
    /// @dev anchor factory (governs setSource), NOT the AMM pool factory passed at read.
    address public immutable factory;

    /// @notice Per-side minimum margin on top of the reference spread, BPS_BASE_U scale (1 bps = 1e14).
    uint256 public immutable minMargin;
    /// @notice Reference older than this (seconds) halts quoting — never clamp to a stale anchor.
    ///         Zero means the reference must be in the current block (refTime == block.timestamp).
    uint256 public immutable MAX_REF_STALENESS;
    /// @notice Hard ceiling for the per-leg spread multipliers (BPS_BASE_U scale, 1e18 = 1.0×).
    ///         Bounds how far a live multiplier can WIDEN the band. >= BPS_BASE_U so the 1.0×
    ///         default is always in range. A band whose upper relative deviation reaches 100% fails closed at
    ///         read time (upper relative deviation plus minMargin >= 100%), not at construction.
    uint256 public immutable maxSpreadMult;

    address public immutable baseToken;
    address public immutable quoteToken;

    /// @notice Variant flag: false = fully immutable (source swap only), true = the quote-shaping
    ///         knobs below are tunable through the factory. The band params stay immutable either way.
    bool public immutable MUTABLE_PARAMS;

    // ── Storage ─────────────────────────────────────────────────────────
    /// @notice Custom quote source; zero = reference mode.
    address public source;

    // ── Knobs (tunable only when MUTABLE_PARAMS; the immutable variant keeps the construction
    //    defaults forever AND never SLOADs them — the reads are gated behind MUTABLE_PARAMS). ─
    uint256 public confidenceParam;
    uint256 public lastConfidenceUpdate;

    /// @notice Per-leg reference staleness (seconds): the base and quote feeds each have their own
    ///         freshness bound. Default = MAX_REF_STALENESS (identical to the single-bound behavior
    ///         until tuned); a setter may only tighten them to <= MAX_REF_STALENESS (the hard cap).
    uint256 public baseMaxStaleness;
    uint256 public quoteMaxStaleness;
    uint256 public lastStalenessUpdate;

    /// @notice Per-leg spread multiplier (BPS_BASE_U scale, 1e18 = 1.0×): scales each leg's oracle
    ///         spread when forming the reference band. Default = 1.0×. May tighten (< 1×) or widen
    ///         (up to maxSpreadMult) the band. The immutable minMargin remains the absolute
    ///         half-width floor, so the band can never fully collapse regardless of these.
    uint256 public baseSpreadMult;
    uint256 public quoteSpreadMult;
    uint256 public lastSpreadMultUpdate;

    /// @dev marginStep bias and its derived step factors for the shaped reference quote — all set once
    ///      at construction (immutable). Effective only in the customizable variant (the immutable variant
    ///      quotes the band directly). marginStep can widen OR — for negative values — tighten/invert the
    ///      PRE-clamp shaped quote; what keeps the FINAL quote no tighter than the audited band, for ANY
    ///      marginStep sign, is the load-bearing band clamp in _computeBidAsk (min/max vs refBid/refAsk)
    ///      plus the bidOut>=askOut halt and Floor/Ceil rounding — NOT any monotonicity of marginStep.
    ///      That clamp is why marginStep needs no factory envelope bound; it must never be removed.
    int256 public immutable marginStep;
    uint256 internal immutable stepBidFactor; // BPS_BASE_U - marginStep
    uint256 internal immutable stepAskFactor; // BPS_BASE_U + marginStep

    // ── Events / Errors ─────────────────────────────────────────────────
    event SourceSet(address indexed source);
    event ConfidenceParamSet(uint256 indexed newValue);
    event MaxStalenessSet(uint256 baseMaxStaleness, uint256 quoteMaxStaleness);
    event SpreadMultipliersSet(uint256 baseSpreadMult, uint256 quoteSpreadMult);

    error OnlyFactory();
    error FeedStalled();
    error MaxRefStalenessOutOfBounds();
    error MaxSpreadMultOutOfBounds();
    error MinMarginZero();
    error ImmutableProvider();
    error ConfidenceParamOutOfBounds();
    error SpreadMultOutOfBounds();
    error StalenessOutOfBounds();
    error MarginStepOutOfBounds();
    error CooldownNotElapsed();

    // ── Constructor ─────────────────────────────────────────────────────
    constructor(
        address _factory,
        address _oracle,
        bytes32 _baseFeedId,
        bytes32 _quoteFeedId,
        uint256 _minMargin,
        uint256 _maxRefStaleness,
        uint256 _maxSpreadMult,
        bool _mutableParams,
        int256 _marginStep,
        address _baseToken,
        address _quoteToken,
        IAnchoredProviderFactory.InitialConfig memory _init
    ) {
        require(_factory != address(0));
        factory = _factory;

        offchainOracle = IOffchainOracle(_oracle);
        baseFeedId = _baseFeedId;
        quoteFeedId = _quoteFeedId;

        // Tokens live ONLY here (the oracles are token-free): the pair is an explicit,
        // mandatory input — including the synthetic (two-feed) mode, where the factory
        // knows the pair when it creates the pool.
        require(_baseToken != address(0) && _quoteToken != address(0) && _baseToken != _quoteToken);
        baseToken = _baseToken;
        quoteToken = _quoteToken;

        if (_maxRefStaleness > 7 days) revert MaxRefStalenessOutOfBounds(); // 0 allowed = same-block reference
        MAX_REF_STALENESS = _maxRefStaleness;

        // Spread-multiplier ceiling. Must be >= 1.0× so the 1.0× default is in range (a multiplier
        // may tighten below 1× at runtime, but the CEILING bounds how far it can WIDEN the band).
        if (_maxSpreadMult < BPS_BASE_U) revert MaxSpreadMultOutOfBounds();
        maxSpreadMult = _maxSpreadMult;

        // minMargin must be strictly positive. The `refBid >= refAsk` halt in _computeBidAsk is not
        // a sufficient safety net on its own: it only fires on an EXACTLY collapsed band, and with
        // minMargin == 0 and spreadBps == 1 the band is ~0.0001% wide, passes every guard, and the
        // provider still reports `isProvider() == true` — the audited "never tighter than
        // mid ± (spreadBps + minMargin)" floor would be satisfiable by a band of essentially zero
        // width. A positive minMargin is the only term that does not depend on the oracle's spread.
        if (_minMargin == 0) revert MinMarginZero();
        // Band-width checks run at read time: reject saturated legs, nonpositive interval edges,
        // and an upper relative deviation plus minMargin reaching 100%.
        minMargin = _minMargin;

        // Initial config (source + per-leg staleness + per-leg multipliers), applied through the SAME
        // internal helpers the post-deploy setters use — one validated path (StalenessOutOfBounds /
        // SpreadMultOutOfBounds against the immutables set just above). Applies to BOTH variants: for
        // the immutable variant these become the permanent values (no setters); pass
        // {source:0, maxRefStaleness, maxRefStaleness, 1e18, 1e18} for the plain 1.0×/shared-staleness default.
        _applySource(_init.source);
        _applyStaleness(_init.baseMaxStaleness, _init.quoteMaxStaleness);
        _applySpreadMultipliers(_init.baseSpreadMult, _init.quoteSpreadMult);

        MUTABLE_PARAMS = _mutableParams;
        // marginStep bias + derived step factors (immutable). The customizable variant shapes the quote
        // with confidence then this fixed bias; the load-bearing band clamp in _computeBidAsk keeps the
        // final quote no tighter than the band edge for ANY marginStep sign (a negative value tightens or
        // inverts the pre-clamp quote; the clamp neutralizes it). The immutable variant ignores them.
        if (_marginStep <= -BPS_BASE || _marginStep >= BPS_BASE) revert MarginStepOutOfBounds();
        marginStep = _marginStep;
        stepBidFactor = uint256(BPS_BASE - _marginStep);
        stepAskFactor = uint256(BPS_BASE + _marginStep);
    }

    // ── Factory ──────────────────────────────────────────────────────────

    /// @notice Swap the custom source (zero → reference mode). Instant: the band bounds any source
    ///         at all times, so no timelock is needed inside the APP.
    function setSource(address newSource) external {
        require(msg.sender == factory, OnlyFactory());
        _applySource(newSource);
    }

    // ── Shared apply logic (constructor + the factory-gated setters call these) ─────────
    // Validate + store + emit; no access/cooldown gates here — the public setters add those.

    function _applySource(address newSource) internal {
        source = newSource;
        emit SourceSet(newSource);
    }

    function _applyStaleness(uint256 newBase, uint256 newQuote) internal {
        // Each leg's bound may only be <= MAX_REF_STALENESS (the immutable, envelope-bound hard cap):
        // no knob — construction or live — can accept a staler reference than the audited ceiling.
        if (newBase > MAX_REF_STALENESS || newQuote > MAX_REF_STALENESS) revert StalenessOutOfBounds();
        baseMaxStaleness = newBase;
        quoteMaxStaleness = newQuote;
        emit MaxStalenessSet(newBase, newQuote);
    }

    function _applySpreadMultipliers(uint256 newBase, uint256 newQuote) internal {
        // Each may be < 1× (tighten) or up to maxSpreadMult (widen). Saturation is checked on the
        // raw spread before multiplication; nonpositive or oversized reference intervals halt.
        if (newBase > maxSpreadMult || newQuote > maxSpreadMult) revert SpreadMultOutOfBounds();
        baseSpreadMult = newBase;
        quoteSpreadMult = newQuote;
        emit SpreadMultipliersSet(newBase, newQuote);
    }

    // ── Factory: quote-shaping knobs (customizable variant only) ─────────

    function setConfidenceParam(uint256 newValue) external override {
        require(msg.sender == factory, OnlyFactory());
        if (!MUTABLE_PARAMS) revert ImmutableProvider();
        if (newValue > CONFIDENCE_MAX) {
            revert ConfidenceParamOutOfBounds();
        }
        if (block.timestamp < lastConfidenceUpdate + CONFIDENCE_COOLDOWN) {
            revert CooldownNotElapsed();
        }

        confidenceParam = newValue;
        lastConfidenceUpdate = block.timestamp;
        emit ConfidenceParamSet(newValue);
    }

    /// @notice Set the per-leg reference staleness bounds (seconds). Each may only be TIGHTENED to
    ///         <= MAX_REF_STALENESS (the immutable, envelope-bound hard cap) — a live knob can never
    ///         accept a staler reference than the audited ceiling. Cooldown-rate-limited.
    function setMaxStaleness(uint256 newBase, uint256 newQuote) external {
        require(msg.sender == factory, OnlyFactory());
        if (!MUTABLE_PARAMS) revert ImmutableProvider();
        if (block.timestamp < lastStalenessUpdate + CONFIDENCE_COOLDOWN) revert CooldownNotElapsed();

        _applyStaleness(newBase, newQuote);
        lastStalenessUpdate = block.timestamp;
    }

    /// @notice Set the per-leg spread multipliers (BPS_BASE_U scale, 1e18 = 1.0×). Each may be below
    ///         1× (tighten) or up to maxSpreadMult (widen). Saturation remains a raw per-leg check;
    ///         invalid resulting reference intervals halt at read time. Cooldown-limited.
    function setSpreadMultipliers(uint256 newBase, uint256 newQuote) external {
        require(msg.sender == factory, OnlyFactory());
        if (!MUTABLE_PARAMS) revert ImmutableProvider();
        if (block.timestamp < lastSpreadMultUpdate + CONFIDENCE_COOLDOWN) revert CooldownNotElapsed();

        _applySpreadMultipliers(newBase, newQuote);
        lastSpreadMultUpdate = block.timestamp;
    }

    // ── External reads ───────────────────────────────────────────────────
    function token0() external view override returns (address) {
        return baseToken;
    }

    function token1() external view override returns (address) {
        return quoteToken;
    }

    /// @notice Attributed swap-time read. Called (no args) by the pool, which has marked itself in-swap
    ///         with this provider. Forwards the pool (`msg.sender`) to `oracle.price(feedId, pool)` so
    ///         the read is attributed to the pool and recorded by the oracle's event.
    /// @dev    `referencePrice` is the ANCHOR's own mid — see _computeBidAsk. It is never taken from a
    ///         source, so `bid <= referencePrice <= ask` holds by construction and no source swap can
    ///         move the fee base the consumer charges against.
    function getQuote() external override returns (uint128 bid, uint128 ask, uint128 referencePrice) {
        (bid, ask, referencePrice) = _getQuote();
        if (bid == 0 || ask == type(uint128).max) revert FeedStalled();
    }

    // ── Staleness ───────────────────────────────────────────────────────

    /// @dev Pure staleness check. Any future refTime is stale.
    function _isStale(uint256 refTime, uint256 nowTs, uint256 maxDelta) internal pure returns (bool) {
        if (refTime == 0) return true;
        if (refTime > nowTs) return true;
        return (nowTs - refTime) > maxDelta;
    }

    // ── Core math ───────────────────────────────────────────────────────

    /// @dev Applies the band edge factor to a mid expressed as the exact ratio `num / den`, converting
    ///      to Q64 in a single division. The synthetic cross is NEVER materialised as an 8-decimal
    ///      integer (which would floor away most of a low cross ratio); it is carried as (num, den) and
    ///      divided out only here, so the sole rounding is the ~2⁻⁶⁴ Q64 quantisation.
    ///
    ///      Single-feed: (num, den) = (mid, ORACLE_DECIMALS) → den·BPS_BASE_U = ORACLE_DECIMALS·BPS_BASE_U,
    ///      i.e. the original 8-decimal→Q64 conversion, byte-identical.
    ///      Synthetic: (num, den) = (mid1, mid2) → exact cross with no intermediate truncation.
    ///
    ///      Numerator upper bounds: Q64 ≈ 1.8e19, edgeFactor < 2e18 → max ≈ 3.6e37, fits uint256; the
    ///      512-bit product with `num` is handled by Math.mulDiv. `den` is always > 0 (mid2 == 0 halts
    ///      the read; ORACLE_DECIMALS is a nonzero constant).
    ///
    ///      `den` bound, by caller: from _computeBidAsk it is a raw mid, so den·BPS_BASE_U ≲ 1.8e37
    ///      (uint64 mid). From _shapedQuote it is `den · CONFIDENCE_BASE` (1e10), i.e. up to ~1.8e47 —
    ///      still far inside uint256, and the denominator argument of mulDiv never overflows since it
    ///      is a plain multiplication of two bounded uint256 values.
    ///
    /// @param  num        Mid numerator (base 8-decimal price)
    /// @param  den        Mid denominator (ORACLE_DECIMALS single-feed, quote 8-decimal price synthetic)
    /// @param  edgeFactor BPS_BASE_U − half (bid edge) or BPS_BASE_U + half (ask edge)
    /// @param  rounding   Floor for bid (down), Ceil for ask (up)
    function _bandEdge(uint256 num, uint256 den, uint256 edgeFactor, Math.Rounding rounding)
        internal
        pure
        returns (uint256)
    {
        return Math.mulDiv(num, Q64 * edgeFactor, den * BPS_BASE_U, rounding);
    }

    // ── Price internals ─────────────────────────────────────────────────

    /// @dev Reads via the oracle's non-view, attributed `price(feedId, pool)` (emits PriceRead),
    ///      forwarding `msg.sender` (the pool). Single-feed: the anchor mid directly. Synthetic
    ///      (quoteFeedId set): the ratio price(baseFeedId)/price(quoteFeedId) — the shared quote
    ///      cancels (e.g. BTC/USD ÷ ETH/USD = BTC/ETH). Reference edges divide the opposing leg
    ///      interval bounds; the raw spread sum is retained only for the optional shaped quote.
    function _getQuote() internal returns (uint128, uint128, uint128) {
        // Per-leg knobs (staleness + multiplier) are read from storage for BOTH variants: they are
        // set at construction, so the immutable variant may hold custom FIXED values too (not
        // just the 1.0×/shared default). A few extra SLOADs on top of the two external oracle reads
        // per leg is negligible.
        (uint256 mid, uint256 spreadBps,, bool ok) = _readLeg(baseFeedId, baseMaxStaleness);
        if (!ok) return (0, type(uint128).max, 0);

        // Band half-width contribution (BPS_BASE_U scale): the leg's oracle spread scaled by its
        // multiplier. Ceil so rounding only ever WIDENS the band (conservative).
        uint256 baseHalf = _scaledHalf(spreadBps, baseSpreadMult);
        uint256 quoteHalf;

        // Mid as the exact ratio midNum / midDen. Single-feed: den = ORACLE_DECIMALS (mid is the
        // 8-decimal anchor). Synthetic: den = mid2, so the cross mid1/mid2 is carried at full precision
        // and divided out only inside the band edge — never floored to an 8-decimal integer (which would
        // wipe out most of a low cross ratio, e.g. a cheap base token quoted in an expensive one).
        uint256 midNum = mid;
        uint256 midDen = ORACLE_DECIMALS;

        bytes32 _quote = quoteFeedId;
        if (_quote != bytes32(0)) {
            (uint256 mid2, uint256 spreadBps2,, bool ok2) = _readLeg(_quote, quoteMaxStaleness);
            if (!ok2 || mid2 == 0) return (0, type(uint128).max, 0);
            // Synthetic ratio: keep the two relative uncertainties separate for interval division.
            //
            // The quote currencies cancelling is an ASSUMPTION, enforced nowhere on-chain. Nothing
            // here, in the factory (whose envelope is keyed on baseFeedId alone), or in the pool checks
            // that the two legs share a denominator — so a misconfigured pair such as BTC/USD ÷ EUR/USD
            // produces a confident, tightly-banded, completely meaningless cross that passes every
            // guard in this contract. Choosing two legs that actually share a quote currency is the
            // deployer's responsibility and part of the LP's diligence before depositing; there is no
            // on-chain backstop for getting it wrong.
            midDen = mid2;
            spreadBps += spreadBps2;
            quoteHalf = _scaledHalf(spreadBps2, quoteSpreadMult);
        }

        return _computeBidAsk(midNum, midDen, spreadBps, baseHalf, quoteHalf, _quote != bytes32(0));
    }

    /// @dev One leg's band half-width contribution: `legSpreadBps · ONE_SPREAD_UNIT_E18 · mult / BPS_BASE_U`,
    ///      rounded UP (a larger band is the safe direction).
    function _scaledHalf(uint256 legSpreadBps, uint256 mult) internal pure returns (uint256) {
        return Math.mulDiv(legSpreadBps * ONE_SPREAD_UNIT_E18, mult, BPS_BASE_U, Math.Rounding.Ceil);
    }

    /// @dev Reads one feed and runs its per-leg guards. ok=false (→ caller halts, fail closed) on:
    ///      stale reference, mid == 0, saturated/stalled spread, or a priceGuard violation.
    ///      Each leg is read through the attributed path independently.
    function _readLeg(bytes32 feedId, uint256 maxStaleness)
        internal
        returns (uint256 mid, uint256 spreadBps, uint256 refTime, bool ok)
    {
        (mid, spreadBps,, refTime) = IPricedOracle(address(offchainOracle)).price(feedId, msg.sender);

        // Stale reference → not ok (per-leg bound). Clamping to a stale anchor is the one false-safety case.
        if (_isStale(refTime, block.timestamp, maxStaleness)) return (mid, spreadBps, refTime, false);

        // Saturation loses the upstream uncertainty. A zero or sub-unit multiplier must not turn
        // this unknown interval back into a live quote. Values above uint16 are rejected as well.
        if (mid == 0 || spreadBps >= SATURATED_SPREAD) return (mid, spreadBps, refTime, false);

        // Per-leg price guard.
        (uint128 guardMin, uint128 guardMax) = offchainOracle.priceGuard(feedId);
        guardMax = guardMax == 0 ? type(uint128).max : guardMax;
        if (mid < guardMin || mid > guardMax) return (mid, spreadBps, refTime, false);

        ok = true;
    }

    /// @dev Anchored band + optional source clamp over an already-validated leg read.
    ///      `spreadBps` is the raw spread sum, used only by the optional shaped quote;
    ///      `baseHalf` and `quoteHalf` are multiplied per-leg uncertainties (BPS_BASE_U scale).
    ///      Returns the (0, max, 0) sentinel on any failure — fail closed, withdrawals unaffected.
    ///
    ///      The third return is the reported referencePrice: the ANCHOR's own mid, carried at full
    ///      precision as `midNum / midDen` and divided out once here. It is deliberately independent
    ///      of every quote-shaping input — source, confidence, marginStep, spread multipliers — because
    ///      the consumer charges its fee from this value to the edge being executed. A source that
    ///      widens its quote therefore worsens its own execution price without moving the fee base,
    ///      and `setSource` (instant, by design) cannot touch it at all.
    function _computeBidAsk(
        uint256 midNum,
        uint256 midDen,
        uint256 spreadBps,
        uint256 baseHalf,
        uint256 quoteHalf,
        bool synthetic
    ) internal view returns (uint128, uint128, uint128) {
        // Check each term before adding/subtracting: even arbitrarily large configured multipliers
        // or margins must halt without arithmetic overflow or a nonpositive denominator.
        if (baseHalf >= BPS_BASE_U || quoteHalf >= BPS_BASE_U || minMargin >= BPS_BASE_U) {
            return (0, type(uint128).max, 0);
        }

        // For a ratio, the upper relative deviation is (baseHalf + quoteHalf)/(1 - quoteHalf).
        // Preserve the 100% upper-band guard using the actual interval, rather than its linear sum.
        uint256 askHalf = synthetic
            ? Math.mulDiv(baseHalf + quoteHalf, BPS_BASE_U, BPS_BASE_U - quoteHalf, Math.Rounding.Ceil)
            : baseHalf;
        if (askHalf >= BPS_BASE_U - minMargin) return (0, type(uint128).max, 0);

        uint256 refBid;
        uint256 refAsk;
        if (synthetic) {
            // Divide opposing interval edges, including each E8 mid's [mid, mid+1) quantum.
            // Products are bounded by uint64 mids and factors < 2e18; denominators are positive.
            refBid = Math.mulDiv(midNum, Q64 * (BPS_BASE_U - baseHalf), (midDen + 1) * (BPS_BASE_U + quoteHalf));
            refAsk = Math.mulDiv(
                midNum + 1, Q64 * (BPS_BASE_U + baseHalf), midDen * (BPS_BASE_U - quoteHalf), Math.Rounding.Ceil
            );
            // minMargin is additive relative to the anchor mid, once per side. Round its Q64
            // amount up so subtraction lowers the bid and addition raises the ask conservatively.
            uint256 margin = _bandEdge(midNum, midDen, minMargin, Math.Rounding.Ceil);
            if (refBid <= margin) return (0, type(uint128).max, 0);
            refBid -= margin;
            refAsk += margin;
        } else {
            uint256 half = baseHalf + minMargin;
            refBid = _bandEdge(midNum, midDen, BPS_BASE_U - half, Math.Rounding.Floor);
            refAsk = _bandEdge(midNum, midDen, BPS_BASE_U + half, Math.Rounding.Ceil);
        }
        // The reported reference: the anchor's own mid, `midNum / midDen` floored onto Q64. NOT the
        // geometric mean of the band edges, which depends on uncertainty and margin.
        uint256 refMid = _bandEdge(midNum, midDen, BPS_BASE_U, Math.Rounding.Floor);
        // Degenerate/zero band halts BEFORE the quantum cover — fail closed on a fully-collapsed band
        // (minMargin 0 AND spread 0), exactly as before; the cover must not resurrect it into a quote.
        if (refBid == 0 || refAsk > type(uint128).max || refBid >= refAsk) {
            return (0, type(uint128).max, 0);
        }

        // Single-feed E8 cover. The stored mid is floored onto the 8-decimal grid, so the true mid T
        // obeys mid <= T < mid + 1 and the upstream interval's upper edge is (mid + 1)·(1 + u). Apply
        // the uncertainty AND the margin to `midNum + 1` so quantization and uncertainty compound,
        // exactly as the synthetic edges above already do. Taking the wider of mid·(1 + u + m) and a
        // bare (mid + 1) instead undercovers whenever mid·m < 1 + u — a cheap feed with a sub-quantum
        // margin (a $0.000001 token at 1% uncertainty and 1 bps margin quoted ~0.9% under the
        // upstream ask). The result is never below the pre-cover edge, so refBid <= refMid < refAsk
        // holds in either mode and the clamp preserves this bracket.
        if (!synthetic) {
            refAsk = _bandEdge(midNum + 1, midDen, BPS_BASE_U + baseHalf + minMargin, Math.Rounding.Ceil);
        }
        if (refAsk > type(uint128).max) {
            return (0, type(uint128).max, 0);
        }

        // Custom quote: source (both variants) or shaped reference quote (customizable variant).
        //    Immutable reference mode quotes the band directly — zero knob SLOADs.
        address _source = source;
        uint256 cBid;
        uint256 cAsk;
        if (_source != address(0)) {
            // 7a. Source mode: any failure (revert, OOG, garbage, zero, inverted) halts — fail
            //     closed. Knobs do NOT post-process the source output (the source shapes itself).
            bool ok;
            (ok, cBid, cAsk) = _readSource(_source);
            if (!ok) {
                return (0, type(uint128).max, 0);
            }
            // NB: the source's own reference is validated in _readSource and then dropped — the
            //     reference this provider reports is always the anchor's.
        } else if (MUTABLE_PARAMS) {
            // 7b. Shaped reference quote: mid ± mid·spreadBps·confidence, then the marginStep step
            //     factors — PriceProvider semantics, clamped into the band below.
            bool ok;
            (ok, cBid, cAsk) = _shapedQuote(midNum, midDen, spreadBps);
            if (!ok) {
                return (0, type(uint128).max, 0);
            }
        } else {
            return (uint128(refBid), uint128(refAsk), uint128(refMid));
        }

        // 8. Clamp: out-of-band custom quotes are clipped silently to the band edge.
        //    bid ≤ refBid < refAsk ≤ ask, so bid < ask holds by construction.
        uint256 bidOut = Math.min(refBid, cBid);
        uint256 askOut = Math.max(refAsk, cAsk);

        if (bidOut == 0 || bidOut >= askOut) {
            return (0, type(uint128).max, 0);
        }

        return (uint128(bidOut), uint128(askOut), uint128(refMid));
    }

    /// @dev Shaped reference quote (customizable variant, reference mode). The pre-clamp quote is
    ///      mid·(1 ∓ spreadBps·confidence) scaled by the marginStep step factors. Like the reference
    ///      band, the mid is carried as the exact ratio `num / den` (den·CONFIDENCE_BASE folds the
    ///      confidence scaling into the single band-edge division), so the synthetic cross is never
    ///      floored to an 8-decimal integer. With confidenceParam == 0 the CONFIDENCE_BASE factor
    ///      cancels exactly and this reduces to the marginStep-only band edge.
    ///
    ///      Deliberately NO `sBid >= sAsk` pre-clamp halt: with knobs at 0 (confidence 0, marginStep 0)
    ///      and a round mid, floor == ceil gives sBid == sAsk, and the band clamp restores ordering —
    ///      that is exactly the immutable-variant identity. The `sAsk > uint128.max` check MUST stay
    ///      pre-clamp (mirrors `_readSource`'s srcAsk guard): truncating later would let an
    ///      overflowing ask wrap to a sub-band quote.
    function _shapedQuote(uint256 num, uint256 den, uint256 spreadBps)
        internal
        view
        returns (bool ok, uint256 sBid, uint256 sAsk)
    {
        // N = spreadBps·confidence (0.01-bps × multiplier units); the shaped mid is num·(CB ∓ N)/(den·CB).
        uint256 n = spreadBps * confidenceParam;
        uint256 shapedDen = den * CONFIDENCE_BASE;
        uint256 bidNum = n >= CONFIDENCE_BASE ? 0 : num * (CONFIDENCE_BASE - n);
        uint256 askNum = num * (CONFIDENCE_BASE + n);

        sBid = _bandEdge(bidNum, shapedDen, stepBidFactor, Math.Rounding.Floor);
        sAsk = _bandEdge(askNum, shapedDen, stepAskFactor, Math.Rounding.Ceil);
        if (sBid == 0 || sAsk > type(uint128).max) return (false, 0, 0);

        return (true, sBid, sAsk);
    }

    /// @dev Gas-bounded staticcall to the source. Tolerates any source behavior without reverting:
    ///      revert, out-of-gas, wrong returndata size, dirty words and uint128 overflow all report
    ///      failure instead. A pre-referencePrice source returning two words is a wrong size and so
    ///      halts — sources are versioned with the provider, not independently.
    ///
    ///      Uses a raw assembly staticcall into a fixed 96-byte buffer. A high-level
    ///      `(bool, bytes memory)` call would `returndatacopy` the source's ENTIRE returndata into
    ///      caller memory before any length check, charging the pool's swap for the copy + memory
    ///      expansion — a returndata bomb costs ~2× SOURCE_GAS_LIMIT on the caller side. Capping the
    ///      output at 96 bytes makes the caller-side cost O(96) regardless of returndatasize, so
    ///      SOURCE_GAS_LIMIT is the true griefing bound. returndatasize() is still read in full for
    ///      the exact-96 check (the bomb's extra bytes are discarded, not copied).
    function _readSource(address _source) internal view returns (bool ok, uint256 srcBid, uint256 srcAsk) {
        bytes4 sel = IAnchorSource.getQuote.selector;
        bool success;
        uint256 retSize;
        uint256 b;
        uint256 a;
        uint256 r;
        assembly ("memory-safe") {
            // Scratch beyond the free-memory pointer; never updated, so this is memory-safe.
            let ptr := mload(0x40)
            mstore(ptr, sel) // 4-byte selector, left-aligned
            // Input is consumed before output is written, so in/out may share ptr. Output is capped
            // at 0x60 bytes: a larger returndata is NOT copied (only returndatasize() reports it).
            success := staticcall(SOURCE_GAS_LIMIT, _source, ptr, 0x04, ptr, 0x60)
            retSize := returndatasize()
            b := mload(ptr)
            a := mload(add(ptr, 0x20))
            r := mload(add(ptr, 0x40))
        }
        if (!success || retSize != 96) return (false, 0, 0);

        srcBid = b;
        srcAsk = a;
        // The source's reference is required and range-checked — a source that cannot place its own
        // fair value inside its own quote is malformed, and this is the only place we can say so — but
        // the value is then DROPPED: the reference this provider reports is the anchor's mid, which is
        // what keeps an instant source swap away from the consumer's fee base.
        if (srcBid == 0 || srcBid >= srcAsk || srcAsk > type(uint128).max || r < srcBid || r > srcAsk) {
            return (false, 0, 0);
        }

        return (true, srcBid, srcAsk);
    }
}

lib/smart-contracts-poc/contracts/AnchoredProviderFactory.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {Multicall} from "@openzeppelin/contracts/utils/Multicall.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {AnchoredPriceProvider} from "./AnchoredPriceProvider.sol";
import {IAnchoredProviderFactory} from "./interfaces/IAnchoredProviderFactory.sol";

/// @notice Anchor Factory: deploys AnchoredPriceProviders against an ADMIN-curated allow-list of
///         reference oracles, with clamp parameters validated against multisig-tuned pair-class
///         envelopes. createAnchoredProvider names which allow-listed oracle to anchor to; public-pool
///         eligibility is then the machine-checkable predicate `recognizedFactory.isProvider(p)`.
///         The allow-list starts EMPTY at construction and is populated/curated via addOracle /
///         removeOracle (admin) — removal only blocks NEW providers; already-deployed providers keep
///         their immutable oracle and stay isProvider()==true.
contract AnchoredProviderFactory is AccessControl, Multicall, IAnchoredProviderFactory {
    using EnumerableSet for EnumerableSet.AddressSet;

    string public constant version = "1.1.0";

    // ── Roles ───────────────────────────────────────────────────────────
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");

    /// @notice Fallback envelope class for feeds with no explicit class (feedClass == 0). Admins
    ///         configure it via setEnvelope(DEFAULT_CLASS, ...); until then, unassigned feeds revert
    ///         EnvelopeNotFound(DEFAULT_CLASS) at create — the audit-once bound is never bypassed.
    bytes32 public constant DEFAULT_CLASS = keccak256("AnchoredProviderFactory.DEFAULT_CLASS");

    // ── AnchoredPriceProvider hard bounds (mirrored for envelope validation) ──
    // Must match the constructor checks in AnchoredPriceProvider; an envelope outside these would
    // advertise parameter ranges that always revert at create() with a provider-level error.
    uint256 internal constant BPS_BASE_U = 1e18;
    uint256 internal constant MAX_STALENESS = 7 days;

    // ── Storage ─────────────────────────────────────────────────────────
    /// @notice Admin-curated allow-list of reference oracles a provider may be anchored to.
    EnumerableSet.AddressSet private _oracles;

    mapping(bytes32 classId => Envelope) public envelopes;
    mapping(bytes32 feedId => bytes32 classId) public feedClass;

    EnumerableSet.AddressSet private _providers;
    mapping(address creator => EnumerableSet.AddressSet) private _providersByCreator;
    mapping(address provider => address) public providerOwner;
    mapping(address provider => mapping(address updater => bool)) public isUpdater;

    // ── Constructor ─────────────────────────────────────────────────────
    constructor(address _admin) {
        // No oracle is seeded here — the allow-list starts empty and is populated via addOracle (admin).
        _grantRole(ADMIN_ROLE, _admin);
        _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
    }

    // ── Modifiers ─────────────────────────────────────────────────────
    modifier onlyProviderOwner(address provider) {
        if (msg.sender != providerOwner[provider]) revert NotProviderOwner();
        _;
    }

    function _requireUpdater(address provider) internal view {
        if (msg.sender != providerOwner[provider] && !isUpdater[provider][msg.sender]) {
            revert NotProviderUpdater();
        }
    }

    // ── Oracle allow-list (admin) ─────────────────────────────────────
    // The reference oracles createAnchoredProvider may anchor to. Removing one only blocks NEW
    // providers; existing providers keep their immutable oracle and stay isProvider()==true.

    function addOracle(address oracle) external override onlyRole(ADMIN_ROLE) {
        require(oracle != address(0), ZeroOracle());
        require(_oracles.add(oracle), OracleAlreadyAllowed(oracle));
        emit OracleAdded(oracle);
    }

    function removeOracle(address oracle) external override onlyRole(ADMIN_ROLE) {
        require(_oracles.remove(oracle), OracleNotFound(oracle));
        emit OracleRemoved(oracle);
    }

    function isOracle(address oracle) external view override returns (bool) {
        return _oracles.contains(oracle);
    }

    function oracleCount() external view override returns (uint256) {
        return _oracles.length();
    }

    function getOracles(uint256 start, uint256 end) external view override returns (address[] memory) {
        return _oracles.values(start, end);
    }

    // ── Envelope administration (admin/multisig) ──────────────────────

    function setEnvelope(bytes32 classId, Envelope calldata envelope) external override onlyRole(ADMIN_ROLE) {
        // Reject empty class and inverted ranges, AND any corner that the provider constructor would
        // reject — so every point inside an accepted envelope is constructor-valid and create() can
        // only fail with ParamsOutOfEnvelope, never a confusing provider revert.
        //
        // There is no band-width corner: the provider has no construction-time band bound to
        // mirror. Saturated feeds and an upper interval deviation plus margin reaching 100%
        // fail closed at read time instead.
        if (
            classId == bytes32(0) || envelope.minMarginMin == 0 // the provider rejects minMargin 0
                || envelope.minMarginMin > envelope.minMarginMax || envelope.stalenessMax > MAX_STALENESS
                || envelope.stalenessMin > envelope.stalenessMax || envelope.spreadMultMax < BPS_BASE_U // must admit the 1.0× default
        ) revert BadEnvelope();

        envelopes[classId] = envelope;
        envelopes[classId].exists = true;

        emit EnvelopeSet(
            classId,
            envelope.minMarginMin,
            envelope.minMarginMax,
            envelope.stalenessMin,
            envelope.stalenessMax,
            envelope.spreadMultMax
        );
    }

    function removeEnvelope(bytes32 classId) external override onlyRole(ADMIN_ROLE) {
        if (!envelopes[classId].exists) revert EnvelopeNotFound(classId);
        delete envelopes[classId];
        emit EnvelopeRemoved(classId);
    }

    /// @notice Assign a feed to a pair class (zero classId unassigns the feed).
    function setFeedClass(bytes32 feedId, bytes32 classId) external override onlyRole(ADMIN_ROLE) {
        if (classId != bytes32(0) && !envelopes[classId].exists) revert EnvelopeNotFound(classId);
        feedClass[feedId] = classId;
        emit FeedClassSet(feedId, classId);
    }

    // ── Deploy (permissionless, envelope-bound) ───────────────────────

    /// @param oracle the reference oracle to anchor to; must be in the allow-list (addOracle), else
    ///        reverts OracleNotAllowed. baseFeedId is NOT validated against the oracle at creation
    ///        (the constructor never reads it): a feed with no data halts provider reads until its
    ///        first update lands — feed classes/envelopes are keyed on feedId independently of the
    ///        oracle.
    /// @param mutableParams false → fully immutable variant (source swap only); true → the curator
    ///        may tune confidenceParam through this factory. The band params are envelope-validated and
    ///        immutable either way (the knobs never quote TIGHTER than the band — confidence is clipped to
    ///        it, marginStep may only widen beyond it), so mutability is a free curator choice.
    /// @param marginStep fixed shaping bias for the customizable variant, applied to the step factors at
    ///        construction. NOT envelope-bound: regardless of its sign, the provider's load-bearing band
    ///        clamp keeps the final quote no tighter than the audited band, so it cannot breach the
    ///        audit-once guarantee. (Construction still reverts if |marginStep| >= BPS_BASE.)
    /// @param quoteFeedId optional second feed for synthetic ratio quoting (zero = single-feed). The
    ///        envelope is keyed on `baseFeedId` (the provider's class); the ref feed only contributes its
    ///        uncertainty and is not validated for existence at construction (reads halt until it has data).
    function createAnchoredProvider(
        address oracle,
        bytes32 baseFeedId,
        bytes32 quoteFeedId,
        uint256 minMargin,
        uint256 maxRefStaleness,
        uint256 maxSpreadMult,
        bool mutableParams,
        int256 marginStep,
        address baseToken,
        address quoteToken,
        InitialConfig calldata init
    ) external override returns (address provider) {
        if (!_oracles.contains(oracle)) revert OracleNotAllowed(oracle);

        // Feeds without an explicit class fall back to the admin-configured DEFAULT_CLASS envelope.
        bytes32 classId = feedClass[baseFeedId];
        if (classId == bytes32(0)) classId = DEFAULT_CLASS;

        Envelope storage env = envelopes[classId];
        if (!env.exists) revert EnvelopeNotFound(classId);
        if (
            minMargin < env.minMarginMin || minMargin > env.minMarginMax || maxRefStaleness < env.stalenessMin
                || maxRefStaleness > env.stalenessMax
                // The multiplier ceiling: at least 1.0× (so the default is valid), at most the envelope's.
                || maxSpreadMult < BPS_BASE_U || maxSpreadMult > env.spreadMultMax
        ) revert ParamsOutOfEnvelope();

        AnchoredPriceProvider p = new AnchoredPriceProvider(
            address(this),
            oracle,
            baseFeedId,
            quoteFeedId,
            minMargin,
            maxRefStaleness,
            maxSpreadMult,
            mutableParams,
            marginStep,
            baseToken,
            quoteToken,
            init
        );

        provider = address(p);
        address creator = msg.sender;

        _providers.add(provider);
        _providersByCreator[creator].add(provider);
        providerOwner[provider] = creator;

        emit ProviderDeployed(
            provider,
            creator,
            baseFeedId,
            quoteFeedId,
            classId,
            p.baseToken(),
            p.quoteToken(),
            minMargin,
            maxRefStaleness,
            maxSpreadMult,
            mutableParams,
            marginStep,
            oracle
        );
    }

    // ── Curator controls ──────────────────────────────────────────────

    /// @notice Swap a provider's source (zero → reference mode). The curator's only knob — instant,
    ///         no timelock. The clamp bounds a source INWARD only (never tighter than the live band);
    ///         nothing bounds how far outward it may quote, so this is not a bounded action — vetting
    ///         the source is the operator's due diligence. See IAnchorSource.
    function setSource(address provider, address newSource) external override onlyProviderOwner(provider) {
        require(_providers.contains(provider), ProviderNotTracked());
        AnchoredPriceProvider(provider).setSource(newSource);
        emit SourceSet(provider, newSource);
    }

    function transferProviderOwnership(address provider, address newOwner)
        external
        override
        onlyProviderOwner(provider)
    {
        require(_providers.contains(provider), ProviderNotTracked());
        require(newOwner != address(0));
        address previousOwner = providerOwner[provider];

        providerOwner[provider] = newOwner;
        _providersByCreator[previousOwner].remove(provider);
        _providersByCreator[newOwner].add(provider);

        emit ProviderOwnershipTransferred(provider, previousOwner, newOwner);
    }

    // ── Updater management ────────────────────────────────────────────
    // Updaters may tune the quote-shaping knobs of customizable providers (batch setters below)
    // but can NOT swap sources — setSource stays owner-only.

    function grantUpdater(address provider, address updater) external override onlyProviderOwner(provider) {
        require(_providers.contains(provider), ProviderNotTracked());
        isUpdater[provider][updater] = true;
        emit UpdaterGranted(provider, updater);
    }

    function revokeUpdater(address provider, address updater) external override onlyProviderOwner(provider) {
        require(_providers.contains(provider), ProviderNotTracked());
        isUpdater[provider][updater] = false;
        emit UpdaterRevoked(provider, updater);
    }

    // ── Batch knob setters (customizable providers; owner or updater) ──
    // Atomic: an immutable provider anywhere in the batch reverts the whole call with
    // ImmutableProvider (as does any out-of-bounds value or an active confidence cooldown).

    function setConfidence(address[] calldata providers, uint256[] calldata values) external override {
        uint256 l = providers.length;
        if (l != values.length) revert LengthMismatch();

        for (uint256 i; i < l; ++i) {
            require(_providers.contains(providers[i]), ProviderNotTracked());
            _requireUpdater(providers[i]);
            AnchoredPriceProvider(providers[i]).setConfidenceParam(values[i]);
        }
    }

    function setSpreadMultipliers(
        address[] calldata providers,
        uint256[] calldata baseMults,
        uint256[] calldata quoteMults
    ) external override {
        uint256 l = providers.length;
        if (l != baseMults.length || l != quoteMults.length) revert LengthMismatch();

        for (uint256 i; i < l; ++i) {
            require(_providers.contains(providers[i]), ProviderNotTracked());
            _requireUpdater(providers[i]);
            AnchoredPriceProvider(providers[i]).setSpreadMultipliers(baseMults[i], quoteMults[i]);
        }
    }

    function setMaxStaleness(
        address[] calldata providers,
        uint256[] calldata baseStaleness,
        uint256[] calldata quoteStaleness
    ) external override {
        uint256 l = providers.length;
        if (l != baseStaleness.length || l != quoteStaleness.length) revert LengthMismatch();

        for (uint256 i; i < l; ++i) {
            require(_providers.contains(providers[i]), ProviderNotTracked());
            _requireUpdater(providers[i]);
            AnchoredPriceProvider(providers[i]).setMaxStaleness(baseStaleness[i], quoteStaleness[i]);
        }
    }

    // ── Views ───────────────────────────────────────────────────────────

    /// @notice Provenance predicate: this provider was deployed by this factory with parameters that
    ///         were inside their class envelope AT DEPLOY TIME. Deliberately narrower than "safe to
    ///         list": the envelope covers 4 of the constructor's inputs, and live per-leg spread
    ///         multipliers may still be tightened below 1× by the provider owner or a delegated
    ///         updater, and the source-mode clamp bounds only tightness — a source can quote
    ///         arbitrarily far outward and is the operator's to vet. Treat a `true` here as "worth
    ///         diligence", not as a completed audit.
    function isProvider(address provider) external view returns (bool) {
        return _providers.contains(provider);
    }

    function providerCount() external view returns (uint256) {
        return _providers.length();
    }

    function providerAt(uint256 index) external view returns (address) {
        return _providers.at(index);
    }

    function providerCountByCreator(address creator) external view returns (uint256) {
        return _providersByCreator[creator].length();
    }

    /// @notice Paginated provider list filtered by creator.
    function getProviders(address creator, uint256 offset, uint256 limit)
        external
        view
        returns (address[] memory providers, uint256 total)
    {
        return _paginate(_providersByCreator[creator], offset, limit);
    }

    /// @notice Paginated list of ALL providers.
    function getAllProviders(uint256 offset, uint256 limit)
        external
        view
        returns (address[] memory providers, uint256 total)
    {
        return _paginate(_providers, offset, limit);
    }

    function _paginate(EnumerableSet.AddressSet storage set, uint256 offset, uint256 limit)
        private
        view
        returns (address[] memory providers, uint256 total)
    {
        total = set.length();

        if (offset >= total) {
            return (new address[](0), total);
        }

        uint256 remaining = total - offset;
        uint256 count = limit < remaining ? limit : remaining;

        providers = new address[](count);
        for (uint256 i; i < count; ++i) {
            providers[i] = set.at(offset + i);
        }
    }
}

lib/smart-contracts-poc/contracts/interfaces/IAnchorSource.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

/// @notice Custom quote source for an AnchoredPriceProvider (source mode). Any contract — open or
///         opaque, deployed by anyone — may implement it; the provider clamps its quotes into the
///         reference band, so source code is never reviewed.
///
///         READ THIS BEFORE WRITING A SOURCE. The clamp is ONE-DIRECTIONAL: it bounds only how TIGHT
///         your quote may be (never inside the anchor's own uncertainty) and places NO bound on how
///         WIDE it may be. A quote far outside the reference band is passed through unchanged, so the
///         band does not make an arbitrary source safe.
///
///         In particular, if your source derives its quote from a venue whose price an outsider can
///         move, that outsider moves your quote with it and the anchor will not stop them — nobody
///         has to be malicious, and the victim is whoever trades while the quote is dislocated.
///
///         This is a deliberate position, not an oversight: bounding the outward side is the
///         OPERATOR's due diligence. Point a source only at a venue whose price you would be willing
///         to quote directly, and treat swapping the source as a change to the pool's pricing rather
///         than a bounded, reversible knob.
///
///         What widening CANNOT do is inflate fees. The provider derives the referencePrice it
///         reports from the ANCHOR's own mid, never from this call — your reference is validated to
///         sit in `[bid, ask]` and is then discarded. So a wide quote costs whoever trades against
///         it the wide execution price, but it cannot move the fee base the pool charges against.
/// @dev    Q64 quotes, same convention (and same selector) as IPriceProvider.getQuote — any
///         view provider qualifies as a source. The provider calls this via a gas-bounded staticcall
///         and fails closed on revert, out-of-gas, malformed returndata (anything other than exactly
///         three words — a two-word source without a referencePrice does not
///         qualify), zero bid, bid >= ask, or a reference outside [bid, ask].
interface IAnchorSource {
    function getQuote() external view returns (uint128 bid, uint128 ask, uint128 referencePrice);
}

lib/smart-contracts-poc/contracts/interfaces/IAnchoredProviderFactory.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

interface IAnchoredProviderFactory {
    // ── Types ───────────────────────────────────────────────────────────

    /// @notice Pair-class parameter envelope (multisig-tuned). Providers can only be created with
    ///         clamp parameters inside the envelope of the class their feed is assigned to.
    /// @notice Initial provider config applied AT CONSTRUCTION through the same validation the
    ///         post-deploy setters use (source swap + per-leg staleness + per-leg multipliers), so a
    ///         provider can be born fully configured in one tx. For the immutable variant these become
    ///         the permanent values (no setters); for the customizable variant they are the starting
    ///         point. Bounds: each staleness <= maxRefStaleness, each multiplier <= maxSpreadMult.
    struct InitialConfig {
        address source; // custom quote source (0 = reference mode)
        uint256 baseMaxStaleness; // per-leg reference staleness (seconds)
        uint256 quoteMaxStaleness;
        uint256 baseSpreadMult; // per-leg spread multiplier (BPS_BASE_U scale, 1e18 = 1.0×)
        uint256 quoteSpreadMult;
    }

    /// @dev No configurable spread cap: APP rejects each raw spread >= 65534 at read time.
    ///      Invalid interval bounds and an upper relative deviation plus margin reaching 100%
    ///      also halt at read time; envelopes only constrain the configuration below.
    struct Envelope {
        uint256 minMarginMin; // BPS_BASE_U scale (1 bps = 1e14)
        uint256 minMarginMax;
        uint256 stalenessMin; // seconds
        uint256 stalenessMax;
        uint256 spreadMultMax; // BPS_BASE_U scale (1e18 = 1.0×); ceiling for maxSpreadMult, >= 1e18
        bool exists;
    }

    // ── Events ──────────────────────────────────────────────────────────
    event ProviderDeployed(
        address indexed provider,
        address indexed creator,
        bytes32 indexed baseFeedId,
        bytes32 quoteFeedId,
        bytes32 classId,
        address base,
        address quote,
        uint256 minMargin,
        uint256 maxRefStaleness,
        uint256 maxSpreadMult,
        bool mutableParams,
        int256 marginStep,
        address oracle
    );

    event EnvelopeSet(
        bytes32 indexed classId,
        uint256 minMarginMin,
        uint256 minMarginMax,
        uint256 stalenessMin,
        uint256 stalenessMax,
        uint256 spreadMultMax
    );
    event EnvelopeRemoved(bytes32 indexed classId);
    event FeedClassSet(bytes32 indexed feedId, bytes32 indexed classId);

    event SourceSet(address indexed provider, address indexed source);
    event ProviderOwnershipTransferred(
        address indexed provider, address indexed previousOwner, address indexed newOwner
    );
    event UpdaterGranted(address indexed provider, address indexed updater);
    event UpdaterRevoked(address indexed provider, address indexed updater);
    event OracleAdded(address indexed oracle);
    event OracleRemoved(address indexed oracle);

    // ── Errors ──────────────────────────────────────────────────────────
    error BadEnvelope();
    error EnvelopeNotFound(bytes32 classId);
    error ParamsOutOfEnvelope();
    error ProviderNotTracked();
    error NotProviderOwner();
    error NotProviderUpdater();
    error LengthMismatch();
    error ZeroOracle();
    error OracleNotAllowed(address oracle);
    error OracleAlreadyAllowed(address oracle);
    error OracleNotFound(address oracle);

    // ── Envelope administration ─────────────────────────────────────────
    function setEnvelope(bytes32 classId, Envelope calldata envelope) external;
    function removeEnvelope(bytes32 classId) external;
    function setFeedClass(bytes32 feedId, bytes32 classId) external;

    // ── Oracle allow-list (admin) ───────────────────────────────────────
    function addOracle(address oracle) external;
    function removeOracle(address oracle) external;
    function isOracle(address oracle) external view returns (bool);
    function oracleCount() external view returns (uint256);
    function getOracles(uint256 start, uint256 end) external view returns (address[] memory);

    // ── Deploy (permissionless, envelope-bound) ─────────────────────────
    function createAnchoredProvider(
        address oracle,
        bytes32 baseFeedId,
        bytes32 quoteFeedId,
        uint256 minMargin,
        uint256 maxRefStaleness,
        uint256 maxSpreadMult,
        bool mutableParams,
        int256 marginStep,
        address baseToken,
        address quoteToken,
        InitialConfig calldata init
    ) external returns (address provider);

    // ── Curator controls ────────────────────────────────────────────────
    function setSource(address provider, address newSource) external;
    function transferProviderOwnership(address provider, address newOwner) external;
    function grantUpdater(address provider, address updater) external;
    function revokeUpdater(address provider, address updater) external;

    // ── Batch knob setters (customizable providers; owner or updater) ──
    function setConfidence(address[] calldata providers, uint256[] calldata values) external;
    /// @notice Set per-leg spread multipliers (BPS_BASE_U scale) on customizable providers.
    function setSpreadMultipliers(
        address[] calldata providers,
        uint256[] calldata baseMults,
        uint256[] calldata quoteMults
    ) external;
    /// @notice Set per-leg reference staleness bounds (seconds) on customizable providers.
    function setMaxStaleness(
        address[] calldata providers,
        uint256[] calldata baseStaleness,
        uint256[] calldata quoteStaleness
    ) external;
}

lib/smart-contracts-poc/contracts/interfaces/IOffchainOracle.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

import {TimeMs} from "../oracles/utils/TimeMs.sol";

interface IOffchainOracle {
    struct PriceGuard {
        uint128 min;
        uint128 max;
    } // 128+128 = 256

    /// @param price      Mid, 8 decimals.
    /// @param spread0    Bid/ask spread in 0.01-bps units (fraction × 1e6): 100 = 1 bp, 10_000 = 1%.
    ///                   `type(uint16).max` (65_535) is the reserved STALL sentinel — feed inactive
    ///                   (RWA market closed, compressed 0xFF/0xFF marker). Pyth/Chainlink saturate at
    ///                   65_534, losing the original uncertainty; consumers must halt at that value
    ///                   too. APP rejects spread0 >= 65_534; the plain provider has a lower 5% cap.
    /// @param spread1    ⚠️ NOT uniform across oracle families, and no in-repo provider reads it.
    ///                   `CompressedOracleV1` returns a second, independently decoded spread (the
    ///                   slot packs two codebook indices per feed). `ChainlinkOracle` and the Pyth
    ///                   Lazer path hardcode `0xFFFF` here to mean "unused" — which is bit-identical
    ///                   to the stall sentinel. An integrator reading `spread1` through
    ///                   `integratorPrice` must therefore branch on the oracle's `kind`, or it will
    ///                   read a permanent stall on two of the three lanes and 6.5535% of phantom
    ///                   uncertainty on the third. Prefer `spread0`.
    /// @param timestampMs Observation time in milliseconds; `price()` returns it in SECONDS.
    struct OracleData {
        uint64 price;
        uint16 spread0;
        uint16 spread1;
        TimeMs timestampMs;
    } // 64+16+16+56=152

    function getOracleData(bytes32 feedId) external view returns (OracleData memory data);
    function getOracleDataBulk(bytes32[] calldata feedId) external view returns (OracleData[] memory data);

    function priceGuard(bytes32 feedId) external view returns (uint128 min, uint128 max);

    event PriceGuardUpdated(bytes32 indexed feedId, uint128 minPrice, uint128 maxPrice);
    event StateGuardUpdated(bytes32 indexed feedId, address indexed stateGuard);
    event StateGuardPending(bytes32 indexed feedId, address indexed stateGuard);
    event PendingStateGuardDeleted(bytes32 indexed feedId);
    event StateGuardDeleted(bytes32 indexed feedId);

    /// @notice Emitted once per feed whose stored price is ACTUALLY advanced by an accepted update. A
    ///         monotonic-rejected (older-or-equal) push writes nothing and emits nothing. This is the
    ///         quote-side key of the off-chain builder's (oracle, feed) join: FeedUpdated(feedId)
    ///         sequences the maker update ahead of a matching PriceRead(pool, feedId) on the same
    ///         oracle. Only feedId is load-bearing for the join, so the event carries nothing else —
    ///         a consumer that wants the maker's quote reads it via the price path. Emitted by every
    ///         oracle family on write.
    event FeedUpdated(bytes32 indexed feedId);

    /// @notice Emitted when a single feed inside a multi-feed push is skipped because its timestamp
    ///         is further ahead of block time than the oracle's drift tolerance. The rest of the
    ///         batch still stores: a signed packet cannot be repackaged by the relayer, so one
    ///         publisher with a fast clock must not be able to halt fresh updates for every feed it
    ///         shares a packet with. Emitted instead of reverting, so the skip stays observable —
    ///         a push that silently writes nothing is indistinguishable from a successful one.
    event FeedSkippedFutureTimestamp(bytes32 indexed feedId);

    // Read-access control
    event PriceRead(address indexed reader, bytes32 indexed feedId);
    event PoolRegistered(bytes32 indexed feedId, address indexed pool, address indexed payer, uint256 fee);
    event RegistrationFeeUpdated(uint256 oldFee, uint256 newFee);
    event ApprovedFactoryAdded(address indexed factory);
    event ApprovedFactoryRemoved(address indexed factory);
    event BlacklistUpdated(address indexed account, bool blacklisted);
    event IntegratorUpdated(address indexed integrator, bool approved);
    event EthWithdrawn(address indexed to, uint256 amount);

    error BadCalldataLength();
    error DeadlineExceeded();
    error FeedNotFound(bytes32 feedId);
    error InvalidAuthority(address authority);
    error InvalidGuard(address guard);

    // Read-access control
    error Blacklisted(address account);
    error InsufficientFee(uint256 sent, uint256 required);
    error NotAPool(address pool);
    error NotRegistered(bytes32 feedId, address pool);
    error FactoryNotApproved(address factory);
    error FactoryAlreadyApproved(address factory);
    error InvalidInSwap();
    error NotWhitelisted(address account);
    error AlreadyIntegrator(address integrator);
    error NotIntegrator(address integrator);
}

lib/smart-contracts-poc/contracts/interfaces/IPriceProvider.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

interface IPriceProvider {
    function setConfidenceParam(uint256 newValue) external;

    function token0() external view returns (address baseToken);
    function token1() external view returns (address quoteToken);

    /// @notice The provider's quote: the two executable edges plus the fair value the consumer
    ///         charges its fee against.
    /// @dev Mutable: the attributed providers read through the oracle's non-view
    ///      `price(feedId, pool)` path. View-only providers may implement it as `view`. Reverts on a
    ///      stalled feed.
    /// @return bidPrice Executable bid (Q64.64) — the price the pool buys token0 at.
    /// @return askPrice Executable ask (Q64.64) — the price the pool sells token0 at.
    /// @return referencePrice Provider's fair-value estimate used for fees, aggregation, and price
    ///         discovery (Q64.64). Must satisfy `bidPrice <= referencePrice && referencePrice <=
    ///         askPrice`; otherwise the consumer reverts. The fee each side pays is measured from
    ///         this value to the edge it executes at, so placing it off-centre splits the spread
    ///         asymmetrically between buys and sells.
    /// @custom:security Detected misreporting will result in pool deprioritization or blacklisting.
    function getQuote() external returns (uint128 bidPrice, uint128 askPrice, uint128 referencePrice);
}

lib/smart-contracts-poc/contracts/interfaces/IPricedOracle.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

/// @notice Attributed on-chain price read on the providers oracle (Pyth/Chainlink): non-view, emits
///         PriceRead and enforces the read-access gates. Declared separately from IOffchainOracle
///         so existing IOffchainOracle implementers (compressed oracle, mocks) are not forced to
///         implement it.
interface IPricedOracle {
    /// @param pool the calling pool (forwarded by its price provider); the oracle binds the read via
    ///        `IPool(pool).inSwap() == msg.sender` and attributes the logged read to it.
    function price(bytes32 feedId, address pool)
        external
        returns (uint256 mid, uint256 spread, uint16 spread1, uint256 refTime);
}

lib/smart-contracts-poc/contracts/oracles/utils/TimeMs.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

type TimeMs is uint56;

error TimeMsOverflow(uint256 value);
error FutureTimestamp();
error ZeroTimestamp();

using {isAfter, revertIfAfterBlockTimeWithDrift, toSeconds, isZero, revertIfZero} for TimeMs global;

function toTimeMs(uint256 value) pure returns (TimeMs) {
    if (value > type(uint56).max) {
        revert TimeMsOverflow(value);
    }
    // forge-lint: disable-next-line(unsafe-typecast)
    return TimeMs.wrap(uint56(value));
}

function toSeconds(TimeMs t) pure returns (uint56) {
    return TimeMs.unwrap(t) / 1000;
}

function isAfter(TimeMs t0, TimeMs t1) pure returns (bool) {
    return TimeMs.unwrap(t0) > TimeMs.unwrap(t1);
}

function revertIfAfterBlockTimeWithDrift(TimeMs t0, uint256 drift) view {
    require(t0.toSeconds() <= block.timestamp + drift, FutureTimestamp());
}

function isZero(TimeMs t) pure returns (bool) {
    return TimeMs.unwrap(t) == 0;
}

function revertIfZero(TimeMs t) pure {
    require(!t.isZero(), ZeroTimestamp());
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/access/AccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, bytes memory returndata) = recipient.call{value: amount}("");
        if (!success) {
            _revert(returndata);
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                revert(add(returndata, 0x20), mload(returndata))
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/Arrays.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.

pragma solidity ^0.8.20;

import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";

/**
 * @dev Collection of functions related to array types.
 */
library Arrays {
    using SlotDerivation for bytes32;
    using StorageSlot for bytes32;

    /**
     * @dev Sort an array of uint256 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        uint256[] memory array,
        function(uint256, uint256) pure returns (bool) comp
    ) internal pure returns (uint256[] memory) {
        _quickSort(_begin(array), _end(array), comp);
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of uint256 in increasing order.
     */
    function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
        sort(array, Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of address (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        address[] memory array,
        function(address, address) pure returns (bool) comp
    ) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of address in increasing order.
     */
    function sort(address[] memory array) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of bytes32 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        bytes32[] memory array,
        function(bytes32, bytes32) pure returns (bool) comp
    ) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
     */
    function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
     * at end (exclusive). Sorting follows the `comp` comparator.
     *
     * Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
     *
     * IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
     * be used only if the limits are within a memory array.
     */
    function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
        unchecked {
            if (end - begin < 0x40) return;

            // Use first element as pivot
            uint256 pivot = _mload(begin);
            // Position where the pivot should be at the end of the loop
            uint256 pos = begin;

            for (uint256 it = begin + 0x20; it < end; it += 0x20) {
                if (comp(_mload(it), pivot)) {
                    // If the value stored at the iterator's position comes before the pivot, we increment the
                    // position of the pivot and move the value there.
                    pos += 0x20;
                    _swap(pos, it);
                }
            }

            _swap(begin, pos); // Swap pivot into place
            _quickSort(begin, pos, comp); // Sort the left side of the pivot
            _quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
        }
    }

    /**
     * @dev Pointer to the memory location of the first element of `array`.
     */
    function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
        assembly ("memory-safe") {
            ptr := add(array, 0x20)
        }
    }

    /**
     * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
     * that comes just after the last element of the array.
     */
    function _end(uint256[] memory array) private pure returns (uint256 ptr) {
        unchecked {
            return _begin(array) + array.length * 0x20;
        }
    }

    /**
     * @dev Load memory word (as a uint256) at location `ptr`.
     */
    function _mload(uint256 ptr) private pure returns (uint256 value) {
        assembly {
            value := mload(ptr)
        }
    }

    /**
     * @dev Swaps the elements memory location `ptr1` and `ptr2`.
     */
    function _swap(uint256 ptr1, uint256 ptr2) private pure {
        assembly {
            let value1 := mload(ptr1)
            let value2 := mload(ptr2)
            mstore(ptr1, value2)
            mstore(ptr2, value1)
        }
    }

    /// @dev Helper: low level cast address memory array to uint256 memory array
    function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 memory array to uint256 memory array
    function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast address comp function to uint256 comp function
    function _castToUint256Comp(
        function(address, address) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 comp function to uint256 comp function
    function _castToUint256Comp(
        function(bytes32, bytes32) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /**
     * @dev Searches a sorted `array` and returns the first index that contains
     * a value greater or equal to `element`. If no such index exists (i.e. all
     * values in the array are strictly less than `element`), the array length is
     * returned. Time complexity O(log n).
     *
     * NOTE: The `array` is expected to be sorted in ascending order, and to
     * contain no repeated elements.
     *
     * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
     * support for repeated elements in the array. The {lowerBound} function should
     * be used instead.
     */
    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
        if (low > 0 && unsafeAccess(array, low - 1).value == element) {
            return low - 1;
        } else {
            return low;
        }
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value greater or equal than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
     */
    function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value strictly greater than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
     */
    function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Same as {lowerBound}, but with an array in memory.
     */
    function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Same as {upperBound}, but with an array in memory.
     */
    function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getAddressSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytes32Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getUint256Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytesSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getStringSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(address[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(uint256[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(bytes[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(string[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/Comparators.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides a set of functions to compare values.
 *
 * _Available since v5.1._
 */
library Comparators {
    function lt(uint256 a, uint256 b) internal pure returns (bool) {
        return a < b;
    }

    function gt(uint256 a, uint256 b) internal pure returns (bool) {
        return a > b;
    }
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/Errors.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/Multicall.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Multicall.sol)

pragma solidity ^0.8.20;

import {Address} from "./Address.sol";
import {Context} from "./Context.sol";

/**
 * @dev Provides a function to batch together multiple calls in a single external call.
 *
 * Consider any assumption about calldata validation performed by the sender may be violated if it's not especially
 * careful about sending transactions invoking {multicall}. For example, a relay address that filters function
 * selectors won't filter calls nested within a {multicall} operation.
 *
 * NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {Context-_msgSender}).
 * If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data`
 * to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of
 * {Context-_msgSender} are not propagated to subcalls.
 */
abstract contract Multicall is Context {
    /**
     * @dev Receives and executes a batch of function calls on this contract.
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
        bytes memory context = msg.sender == _msgSender()
            ? new bytes(0)
            : msg.data[msg.data.length - _contextSuffixLength():];

        results = new bytes[](data.length);
        for (uint256 i = 0; i < data.length; i++) {
            results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context));
        }
        return results;
    }
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/Panic.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/SlotDerivation.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
 * corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
 * the solidity language / compiler.
 *
 * See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
 *
 * Example usage:
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using StorageSlot for bytes32;
 *     using SlotDerivation for bytes32;
 *
 *     // Declare a namespace
 *     string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
 *
 *     function setValueInNamespace(uint256 key, address newValue) internal {
 *         _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
 *     }
 *
 *     function getValueInNamespace(uint256 key) internal view returns (address) {
 *         return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {StorageSlot}.
 *
 * NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
 * upgrade safety will ignore the slots accessed through this library.
 *
 * _Available since v5.1._
 */
library SlotDerivation {
    /**
     * @dev Derive an ERC-7201 slot from a string (namespace).
     */
    function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
        assembly ("memory-safe") {
            mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
            slot := and(keccak256(0x00, 0x20), not(0xff))
        }
    }

    /**
     * @dev Add an offset to a slot to get the n-th element of a structure or an array.
     */
    function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
        unchecked {
            return bytes32(uint256(slot) + pos);
        }
    }

    /**
     * @dev Derive the location of the first element in an array from the slot where the length is stored.
     */
    function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, slot)
            result := keccak256(0x00, 0x20)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, and(key, shr(96, not(0))))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, iszero(iszero(key)))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(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.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * 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 {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 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 low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, 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 ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            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⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // 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²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev 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) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @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 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @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;
    }
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

import {Arrays} from "../Arrays.sol";
import {Math} from "../math/Math.sol";

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 * - Set can be cleared (all elements removed) in O(n).
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * The following types are supported:
 *
 * - `bytes32` (`Bytes32Set`) since v3.3.0
 * - `address` (`AddressSet`) since v3.3.0
 * - `uint256` (`UintSet`) since v3.3.0
 * - `string` (`StringSet`) since v5.4.0
 * - `bytes` (`BytesSet`) since v5.4.0
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: This function has an unbounded cost that scales with set size. Developers should keep in mind that
     * using it may render the function uncallable if the set grows to the point where clearing it consumes too much
     * gas to fit in a block.
     */
    function _clear(Set storage set) private {
        uint256 len = _length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set, uint256 start, uint256 end) private view returns (bytes32[] memory) {
        unchecked {
            end = Math.min(end, _length(set));
            start = Math.min(start, end);

            uint256 len = end - start;
            bytes32[] memory result = new bytes32[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(Bytes32Set storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set, uint256 start, uint256 end) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(AddressSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set, uint256 start, uint256 end) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(UintSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set, uint256 start, uint256 end) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner, start, end);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    struct StringSet {
        // Storage of set values
        string[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(string value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(StringSet storage set, string memory value) internal returns (bool) {
        if (!contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(StringSet storage set, string memory value) internal returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                string memory lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(StringSet storage set) internal {
        uint256 len = length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(StringSet storage set, string memory value) internal view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(StringSet storage set) internal view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(StringSet storage set, uint256 index) internal view returns (string memory) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(StringSet storage set) internal view returns (string[] memory) {
        return set._values;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(StringSet storage set, uint256 start, uint256 end) internal view returns (string[] memory) {
        unchecked {
            end = Math.min(end, length(set));
            start = Math.min(start, end);

            uint256 len = end - start;
            string[] memory result = new string[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }

    struct BytesSet {
        // Storage of set values
        bytes[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(BytesSet storage set, bytes memory value) internal returns (bool) {
        if (!contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(BytesSet storage set, bytes memory value) internal returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes memory lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(BytesSet storage set) internal {
        uint256 len = length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(BytesSet storage set, bytes memory value) internal view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(BytesSet storage set) internal view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(BytesSet storage set, uint256 index) internal view returns (bytes memory) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(BytesSet storage set) internal view returns (bytes[] memory) {
        return set._values;
    }

    /**
     * @dev Return a slice of the set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(BytesSet storage set, uint256 start, uint256 end) internal view returns (bytes[] memory) {
        unchecked {
            end = Math.min(end, length(set));
            start = Math.min(start, end);

            uint256 len = end - start;
            bytes[] memory result = new bytes[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 99999,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "cancun",
  "remappings": [
    "@metric-core/=lib/metric-core/contracts/",
    "@smart-contracts-poc/=lib/smart-contracts-poc/contracts/",
    "forge-std/=lib/metric-core/lib/forge-std/src/",
    "solmate/=lib/solmate/src/",
    "lib/metric-core/:@openzeppelin/contracts/=lib/metric-core/lib/openzeppelin-contracts/contracts/",
    "lib/metric-core/:@openzeppelin/contracts/=lib/metric-core/lib/openzeppelin-contracts/contracts/",
    "lib/smart-contracts-poc/:@openzeppelin/contracts/=lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/",
    "lib/smart-contracts-poc/:@openzeppelin/contracts/=lib/smart-contracts-poc/lib/openzeppelin-contracts/contracts/",
    "lib/smart-contracts-poc/:@openzeppelin/contracts-upgradeable/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/contracts/",
    "lib/smart-contracts-poc/:@openzeppelin/contracts-upgradeable/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/metric-core/lib/openzeppelin-contracts/contracts/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/openzeppelin-contracts/:erc4626-tests/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/openzeppelin-contracts/:erc4626-tests/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/solady/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/solady/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/solady/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/solady/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/:openzeppelin-contracts/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/openzeppelin-contracts/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/:openzeppelin-contracts/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/openzeppelin-contracts/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/:erc4626-tests/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/:erc4626-tests/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/:openzeppelin-contracts-upgradeable/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/:openzeppelin-contracts-upgradeable/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-contracts-upgradeable/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/:openzeppelin-contracts-upgradeable/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/:openzeppelin-contracts-upgradeable/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts-upgradeable/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/:openzeppelin-contracts/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/",
    "lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/:openzeppelin-contracts/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/openzeppelin-contracts/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/forge-std/:ds-test/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/metric-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/metric-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/metric-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/metric-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/metric-core/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/metric-core/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/metric-core/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/metric-core/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts/:erc4626-tests/=lib/smart-contracts-poc/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts/:erc4626-tests/=lib/smart-contracts-poc/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/smart-contracts-poc/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/smart-contracts-poc/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/solmate/lib/weird-erc20/:ds-test/=lib/solmate/lib/weird-erc20/lib/ds-test/src/",
    "lib/solmate/lib/weird-erc20/:ds-test/=lib/solmate/lib/weird-erc20/lib/ds-test/src/",
    "lib/metric-core/:openzeppelin-contracts/=lib/metric-core/lib/openzeppelin-contracts/",
    "lib/metric-core/:openzeppelin-contracts/=lib/metric-core/lib/openzeppelin-contracts/",
    "lib/smart-contracts-poc/:openzeppelin-contracts-upgradeable/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/",
    "lib/smart-contracts-poc/:openzeppelin-contracts-upgradeable/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/",
    "lib/smart-contracts-poc/:openzeppelin-contracts/=lib/smart-contracts-poc/lib/openzeppelin-contracts/",
    "lib/smart-contracts-poc/:openzeppelin-contracts/=lib/smart-contracts-poc/lib/openzeppelin-contracts/",
    "lib/solmate/:ds-test/=lib/solmate/lib/ds-test/src/",
    "lib/solmate/:ds-test/=lib/solmate/lib/ds-test/src/",
    "@openzeppelin/=lib/smart-contracts-poc/lib/openzeppelin-contracts/",
    "createx/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/src/",
    "ds-test/=lib/solmate/lib/ds-test/src/",
    "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-upgradeable/=lib/smart-contracts-poc/lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/metric-core/lib/openzeppelin-contracts/",
    "openzeppelin-foundry-upgrades/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-foundry-upgrades/src/",
    "pyth-crosschain/=lib/smart-contracts-poc/lib/pyth-crosschain/",
    "pyth-lazer-sdk/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/src/",
    "smart-contracts-poc/=lib/smart-contracts-poc/",
    "solady/=lib/smart-contracts-poc/lib/pyth-crosschain/lazer/contracts/evm/lib/createx/lib/solady/",
    "solidity-stringutils/=lib/smart-contracts-poc/lib/pyth-crosschain/target_chains/ethereum/sdk/stylus/pyth-mock-solidity/lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/",
    "weird-erc20/=lib/solmate/lib/weird-erc20/src/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.