Skip to content
Verified contractPartialMIT

UsdgOftAdapter

Address0xc4392dd00cd09070ba34565438c972441b4a136c
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 800 runs
EVM version
cancun
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,151,664
Creation transaction
0x16d4c5cdba…4e92a90d33

53 files

src/crosschain/UsdgOftAdapter.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {IBridgeAdapter} from "./interfaces/IBridgeAdapter.sol";
import {IHubAdapter} from "./interfaces/IHubAdapter.sol";
import {ICurveStableSwap} from "./interfaces/ICurveStableSwap.sol";
import {IOFT, SendParam, MessagingFee, MessagingReceipt, OFTReceipt} from "./interfaces/ILayerZero.sol";
import {LzCodec} from "./libraries/LzCodec.sol";
import {HubAdapterBase} from "./HubAdapterBase.sol";
import {CairnLinks} from "../base/CairnLinks.sol";

/// @title UsdgOftAdapter
/// @notice USDC -> USDG on Curve, then USDG -> Robinhood Chain through the Paxos USDG OFT, in one
///         call, for the BridgeHub and nobody else.
///
/// @dev Everything that decides where value goes is an immutable: the Curve pool and its coin
///      indices, the OFT, the destination endpoint id and the remote hub. No setter touches them
///      and no other function moves a token. The only `to` this contract ever puts in a
///      LayerZero message is `remoteHub`, so the keeper, the hub's only caller, chooses when to
///      bridge and the minimum within the adapter's bound, and nothing else. The numbers, the Curve
///      slippage bound, the compose gas (a base, a part per market and the most markets a batch may
///      carry) and the delivery gas (a base and a part per market), are the protocol owner's
///      settings (2026-10-05; the compose's per-market part and the cap since audit loop 10, L10-B1;
///      the delivery's since audit loop 11, L11-B1).
///
///      The compose message carries the per-market split. It is rescaled from the USDC amounts to
///      the USDG actually obtained on Curve, so the amounts the remote hub distributes sum to exactly
///      the transfer's `amountLD` and the remote hub can refuse any message where they do not.
///
///      The stock table: a basket on Ethereum lists Ethereum-side asset addresses, the mirror vault
///      buys Robinhood Chain tokens. The translation is the hub's append-only table; a basket that
///      names an asset outside it cannot be bridged (`UnmappedStock`) until the factory owner maps
///      it, and a mapped asset can never be redirected.
///
///      Options: this contract appends to the OFT's enforced options two executor options whose gas
///      grows with the batch, one for each step on Robinhood Chain.
///      - `lzReceive`, the delivery: the endpoint hashes and clears the whole message, the OFT mints
///        and re-encodes it, and the endpoint stores its compose's hash and logs the whole compose,
///        about 14.8 gas a byte on Robinhood Chain mainnet. The OFT's owner enforces a fixed figure
///        (Paxos: 200,000), which LayerZero's executor tops up a little (222,174 given): enough for
///        nine five-stock markets, not for the seventeen the cap allows (audit loop 11, L11-B1,
///        measured on a fork of Robinhood Chain mainnet with Paxos's OFT and LayerZero's executor).
///        This contract adds `receiveGasBase` plus `receiveGasPerMarket` for each market, which the
///        executor adds to the enforced gas. By default that part alone delivers the batch, so a
///        batch does not depend on the figure the OFT's owner enforces, which this contract does not
///        read.
///      - `lzCompose`, the remote hub's distribution (initializing the mirror vaults the keeper
///        predeployed, then funding them): `composeGas`, the part every batch costs, plus
///        `composeGasPerMarket` for each market, sized for a market's first batch, the heaviest (its
///        mirror vault's `initBasket`): four new five-stock markets ran a fixed 1,200,000 out of
///        gas (audit loop 10, L10-B1).
///      A fixed figure could not be right for every batch, whose size the keeper decides at each
///      pass. A batch carries at most `maxBatchMarkets` markets, which bounds its message, refused by
///      LayerZero's send library above the pathway executor's `maxMessageSize` (10,000 bytes by
///      default; a market adds at most 544 bytes, `DEFAULT_MAX_BATCH_MARKETS`), and its two options,
///      at most `MAX_BATCH_RECEIVE_GAS` and `MAX_BATCH_COMPOSE_GAS`, which Robinhood Chain's
///      per-transaction limit can execute. The keeper sends at most that many and leaves the rest
///      for its next pass. The extra gas costs little: the executor charges it at Robinhood Chain's
///      gas price. A delivery or a compose short of gas waits on the endpoint until someone runs it
///      again with more gas, which anyone may do.
contract UsdgOftAdapter is CairnLinks, HubAdapterBase {
    using SafeERC20 for IERC20;

    /// @notice Default worst USDG-per-USDC rate accepted on Curve: 10 %, the founder's figure of
    ///         2026-10-07 (decision 29), an owner setting like every number (`setSettings`, refused
    ///         only above 100 %). USDG and USDC are both six-decimal dollar stablecoins; this floor is
    ///         no longer the sandwich bound: the keeper quotes the pool for each batch and asks at least
    ///         that quote less a small tolerance (`KEEPER_BRIDGE_QUOTE_TOLERANCE_BPS`, 30 bps), and sends
    ///         less (`BridgeHub.bridgeReadyAmounts`) when the whole batch would cost more than this
    ///         floor allows, reading the floor live. Was 30 bps until then.
    uint16 public constant DEFAULT_MAX_SLIPPAGE_BPS = 1000;
    /// @notice Default compose gas per market of a batch. A market's first batch, the heaviest,
    ///         measured at about 296,500 gas for a five-stock basket on a fork of Robinhood Chain
    ///         testnet through LayerZero's endpoint (seventeen new markets 5,118,831 of their
    ///         7,000,000; 5,122,494 on a fork of mainnet), and 21,000 to 39,000 for a market already
    ///         initialized; 400,000 keeps a third above the heaviest (audit loops 10 and 11, L10-B1).
    uint128 public constant DEFAULT_COMPOSE_GAS_PER_MARKET = 400_000;
    /// @notice Default `lzReceive` gas a batch adds to the OFT's enforced figure, whatever it carries:
    ///         the delivery's fixed part, about 148,000 on a fork of Robinhood Chain mainnet (the
    ///         endpoint's checks and clearing, the OFT's credit, the compose stored), with a third to
    ///         spare, so that the option alone delivers a batch whatever the OFT's owner enforces
    ///         (audit loop 11, L11-B1).
    uint128 public constant DEFAULT_RECEIVE_GAS_BASE = 200_000;
    /// @notice Default `lzReceive` gas each market adds: a five-stock market grows the message by 544
    ///         bytes, about 8,100 gas of delivery at 14.8 a byte, measured on a fork of Robinhood Chain
    ///         mainnet (9 five-stock markets need 219,794, 17 need 283,974); 16,000 is about twice
    ///         that: seventeen markets' part alone is 472,000, and 672,000 with the 200,000 Paxos
    ///         enforces (audit loop 11, L11-B1).
    uint128 public constant DEFAULT_RECEIVE_GAS_PER_MARKET = 16_000;
    /// @notice Default most markets one batch carries: 17, set by the size of the message, not by
    ///         its gas. LayerZero's send library refuses a message above the pathway executor's
    ///         `maxMessageSize`, 10,000 bytes by default (the testnet pathway's, read on Sepolia:
    ///         `LZ_MessageLib_InvalidMessageSize` above it). The OFT's message is a 72-byte header and
    ///         the batch, whose fixed part is 320 bytes and each market at most 544 (a five-stock
    ///         basket, the factory's `MAX_BASKET_STOCKS`): 17 markets make at most 9,640 bytes, 18
    ///         make 10,184 (the verifier gate of audit loop 10, L10-B1). A pathway configured for
    ///         another size wants `setBatchGas` to match it: at most (maxMessageSize - 392) / 544
    ///         markets. The option of 17 is `composeGas` plus 6.8 million gas.
    uint16 public constant DEFAULT_MAX_BATCH_MARKETS = 17;
    /// @notice The most compose gas one batch may ask for, whatever the settings: Robinhood Chain
    ///         executes at most 32,000,000 gas in one transaction (ArbOS's `maxTxGasLimit`), which
    ///         must also hold the executor's own work. LayerZero's executor could not run an option
    ///         above it (anyone could still run the compose by hand with the gas it needs).
    uint256 public constant MAX_BATCH_COMPOSE_GAS = 24_000_000;
    /// @notice The most `lzReceive` gas one batch may add to the OFT's enforced figure, whatever the
    ///         settings: far under what Robinhood Chain executes in one transaction, the delivery of
    ///         the largest message needing about 284,000 in all.
    uint256 public constant MAX_BATCH_RECEIVE_GAS = 2_000_000;

    IERC20 public immutable usdc;
    IERC20 public immutable usdg;
    ICurveStableSwap public immutable curvePool;
    int128 public immutable curveUsdcIndex;
    int128 public immutable curveUsdgIndex;
    IOFT public immutable oft;
    uint32 public immutable dstEid;
    bytes32 public immutable remoteHub;
    /// @notice Whether the OFT pulls by allowance (a lockbox adapter) or burns the sender's tokens
    ///         by the token's own permission (the Paxos mint/burn adapter: no allowance needed).
    ///         A constant of the OFT contract, read once.
    bool public immutable oftNeedsApproval;
    /// @dev The compose gas the proxy starts with (`Config.composeGas`).
    uint128 private immutable _initialComposeGas;

    /// @notice Worst USDG-per-USDC rate accepted on Curve, in basis points. Owner setting
    ///         (2026-10-05), `DEFAULT_MAX_SLIPPAGE_BPS` to start with.
    uint16 public maxSlippageBps;
    /// @notice The part of the remote hub's `lzCompose` gas every batch needs, whatever it carries
    ///         (the endpoint's own work, the batch's checks and roles); each market adds
    ///         `composeGasPerMarket`. Owner setting (2026-10-05), the deployment's figure to start
    ///         with. Until audit loop 10 (L10-B1) it was the whole compose's gas.
    uint128 public composeGas;
    /// @notice Compose gas each market of a batch adds to `composeGas`. Owner setting (audit loop
    ///         10, L10-B1), `DEFAULT_COMPOSE_GAS_PER_MARKET` to start with; zero on a proxy
    ///         initialized before it, which bridges nothing (`BatchGasNotSet`) until it is set.
    uint128 public composeGasPerMarket;
    /// @notice Most markets one batch may carry (`BatchTooLarge` above). Owner setting (audit loop
    ///         10, L10-B1), `DEFAULT_MAX_BATCH_MARKETS` to start with; set with `composeGasPerMarket`.
    uint16 public maxBatchMarkets;
    /// @notice The `lzReceive` gas every batch adds to the OFT's enforced figure. Owner setting (audit
    ///         loop 11, L11-B1), `DEFAULT_RECEIVE_GAS_BASE` to start with.
    uint128 public receiveGasBase;
    /// @notice The `lzReceive` gas each market of a batch adds. Owner setting (audit loop 11, L11-B1),
    ///         `DEFAULT_RECEIVE_GAS_PER_MARKET` to start with; zero on a proxy initialized before it,
    ///         which bridges nothing (`BatchGasNotSet`) until `setBatchReceiveGas`.
    uint128 public receiveGasPerMarket;

    event UsdgBridged(bytes32 indexed guid, uint256 usdcIn, uint256 usdgSent, uint256 nativeFee);
    event SettingsSet(uint16 maxSlippageBps, uint128 composeGas);
    event BatchGasSet(uint128 composeGasPerMarket, uint16 maxBatchMarkets);
    event BatchReceiveGasSet(uint128 receiveGasBase, uint128 receiveGasPerMarket);

    error CurveCoinsMismatch();
    error OftTokenMismatch();
    error DustNotSupported(uint256 sent, uint256 received);
    error ZeroComposeGas();
    error InvalidSlippage(uint256 bps);
    /// @notice A batch setting is unset: the per-market compose gas and the cap on a proxy
    ///         initialized before audit loop 10, until the owner calls `setBatchGas`; the per-market
    ///         delivery gas on one initialized before audit loop 11, until `setBatchReceiveGas`. Such
    ///         a proxy bridges nothing and quotes nothing until both are set.
    error BatchGasNotSet();
    error InvalidBatchGas();
    error BatchTooLarge(uint256 markets, uint256 maxMarkets);
    error BatchGasTooHigh(uint256 gas, uint256 maxGas);
    error BatchReceiveGasTooHigh(uint256 gas, uint256 maxGas);

    struct Config {
        address usdc;
        address usdg;
        address curvePool;
        int128 curveUsdcIndex;
        int128 curveUsdgIndex;
        address oft;
        uint32 dstEid;
        bytes32 remoteHub;
        uint128 composeGas;
        address factory;
        /// @notice The BridgeHub proxy this adapter serves.
        address hub;
    }

    /// @dev Deployed against the hub's proxy, which names it (`BridgeHub.setAdapter`); a
    ///      replacement names the hub and must carry the same pins (`BridgeHub.changeAdapter`,
    ///      decision 20).
    constructor(Config memory c) HubAdapterBase(c.factory, c.hub) {
        if (c.usdc == address(0) || c.usdg == address(0) || c.curvePool == address(0) || c.oft == address(0)) {
            revert ZeroAddress();
        }
        if (c.remoteHub == bytes32(0)) revert ZeroAddress();
        if (c.composeGas == 0) revert ZeroComposeGas();
        ICurveStableSwap pool = ICurveStableSwap(c.curvePool);
        if (
            pool.coins(uint256(uint128(c.curveUsdcIndex))) != c.usdc
                || pool.coins(uint256(uint128(c.curveUsdgIndex))) != c.usdg
        ) revert CurveCoinsMismatch();
        if (IOFT(c.oft).token() != c.usdg) revert OftTokenMismatch();

        usdc = IERC20(c.usdc);
        usdg = IERC20(c.usdg);
        curvePool = pool;
        curveUsdcIndex = c.curveUsdcIndex;
        curveUsdgIndex = c.curveUsdgIndex;
        oft = IOFT(c.oft);
        dstEid = c.dstEid;
        remoteHub = c.remoteHub;
        _initialComposeGas = c.composeGas;
        oftNeedsApproval = IOFT(c.oft).approvalRequired();
    }

    /// @notice Sets up the proxy, once: the default slippage bound, the deployment's compose gas,
    ///         the default per-market compose gas and batch cap, and the default delivery gas.
    function initialize() external initializer {
        _setSettings(DEFAULT_MAX_SLIPPAGE_BPS, _initialComposeGas);
        _setBatchGas(DEFAULT_COMPOSE_GAS_PER_MARKET, DEFAULT_MAX_BATCH_MARKETS);
        _setBatchReceiveGas(DEFAULT_RECEIVE_GAS_BASE, DEFAULT_RECEIVE_GAS_PER_MARKET);
    }

    /// @notice Sets the Curve slippage bound and the compose gas every batch needs, for every
    ///         bridge from now on. Protocol owner only.
    function setSettings(uint16 maxSlippageBps_, uint128 composeGas_) external {
        if (msg.sender != _upgrader()) revert NotProtocolOwner();
        _setSettings(maxSlippageBps_, composeGas_);
    }

    /// @notice Sets the compose gas each market of a batch adds and the most markets a batch may
    ///         carry, for every bridge from now on. Protocol owner only. The largest batch's compose
    ///         option, `composeGas + maxMarkets * perMarket`, must be at most `MAX_BATCH_COMPOSE_GAS`
    ///         (`BatchGasTooHigh`), its delivery part, `receiveGasBase + maxMarkets *
    ///         receiveGasPerMarket`, at most `MAX_BATCH_RECEIVE_GAS` (`BatchReceiveGasTooHigh`), and its
    ///         message at most the pathway's `maxMessageSize`, which this contract does not read: with
    ///         five-stock baskets, at most (maxMessageSize - 392) / 544 markets
    ///         (`DEFAULT_MAX_BATCH_MARKETS`).
    function setBatchGas(uint128 perMarket, uint16 maxMarkets) external {
        if (msg.sender != _upgrader()) revert NotProtocolOwner();
        _setBatchGas(perMarket, maxMarkets);
    }

    /// @notice Sets the `lzReceive` gas every batch adds to the OFT's enforced figure and the gas
    ///         each market adds, for every bridge from now on. Protocol owner only. The largest
    ///         batch's part, `base + maxBatchMarkets * perMarket`, must be at most
    ///         `MAX_BATCH_RECEIVE_GAS`. Size it to cover the delivery alone (on Robinhood Chain
    ///         mainnet about 148,000, plus 14.8 gas a byte of message): the OFT's owner may change the
    ///         figure it enforces, which this contract does not read, and the executor adds the two.
    function setBatchReceiveGas(uint128 base, uint128 perMarket) external {
        if (msg.sender != _upgrader()) revert NotProtocolOwner();
        _setBatchReceiveGas(base, perMarket);
    }

    function _setSettings(uint16 maxSlippageBps_, uint128 composeGas_) private {
        if (maxSlippageBps_ > BPS) revert InvalidSlippage(maxSlippageBps_);
        if (composeGas_ == 0) revert ZeroComposeGas();
        _checkBatchCeiling(composeGas_, composeGasPerMarket, maxBatchMarkets);
        maxSlippageBps = maxSlippageBps_;
        composeGas = composeGas_;
        emit SettingsSet(maxSlippageBps_, composeGas_);
    }

    function _setBatchGas(uint128 perMarket, uint16 maxMarkets) private {
        if (perMarket == 0 || maxMarkets == 0) revert InvalidBatchGas();
        _checkBatchCeiling(composeGas, perMarket, maxMarkets);
        _checkReceiveCeiling(receiveGasBase, receiveGasPerMarket, maxMarkets);
        composeGasPerMarket = perMarket;
        maxBatchMarkets = maxMarkets;
        emit BatchGasSet(perMarket, maxMarkets);
    }

    function _setBatchReceiveGas(uint128 base, uint128 perMarket) private {
        if (perMarket == 0) revert InvalidBatchGas();
        _checkReceiveCeiling(base, perMarket, maxBatchMarkets);
        receiveGasBase = base;
        receiveGasPerMarket = perMarket;
        emit BatchReceiveGasSet(base, perMarket);
    }

    /// @dev The largest batch's delivery part must stay within its ceiling.
    function _checkReceiveCeiling(uint128 base, uint128 perMarket, uint16 maxMarkets) private pure {
        uint256 gas = uint256(base) + uint256(perMarket) * maxMarkets;
        if (gas > MAX_BATCH_RECEIVE_GAS) revert BatchReceiveGasTooHigh(gas, MAX_BATCH_RECEIVE_GAS);
    }

    /// @dev The largest batch's option must be one Robinhood Chain can execute.
    function _checkBatchCeiling(uint128 base, uint128 perMarket, uint16 maxMarkets) private pure {
        uint256 gas = uint256(base) + uint256(perMarket) * maxMarkets;
        if (gas > MAX_BATCH_COMPOSE_GAS) revert BatchGasTooHigh(gas, MAX_BATCH_COMPOSE_GAS);
    }

    /// @inheritdoc IBridgeAdapter
    /// @dev Builds the batch from the factory: current keeper, each market's basket translated to
    ///      remote addresses. The hub only aggregates USDC, which it transfers here before the call
    ///      (no allowance round trip).
    function bridge(uint256 usdcAmount, uint256[] calldata marketIds, uint256[] calldata amounts, uint256 minUsdgOut)
        external
        payable
        onlyHub
        returns (uint256 usdgSent)
    {
        _checkBatch(usdcAmount, marketIds.length, amounts);
        // Before anything moves: a batch the settings cannot pay for, or one larger than the cap,
        // is refused whole (`BatchGasNotSet`, `BatchTooLarge`).
        extraOptionsFor(marketIds.length);
        usdgSent = _swapOnCurve(usdcAmount, minUsdgOut);
        _dispatch(marketIds, amounts, usdcAmount, usdgSent);
    }

    function _dispatch(uint256[] calldata marketIds, uint256[] calldata amounts, uint256 usdcAmount, uint256 usdgSent)
        private
    {
        uint256[] memory usdgAmounts = _rescale(amounts, usdcAmount, usdgSent);
        bytes memory composeMsg = _batchFor(marketIds, usdgAmounts);
        bytes32 guid = _send(usdgSent, composeMsg, marketIds.length);
        _recordGuid(guid);
        emit UsdgBridged(guid, usdcAmount, usdgSent, msg.value);
    }

    /// @inheritdoc IBridgeAdapter
    function quoteBridge(uint256 usdgAmount) external view returns (uint256 nativeFee) {
        // The fee depends on the options and the payload size, not on the payload's content; quote
        // with a payload of a representative shape.
        MessagingFee memory fee = oft.quoteSend(_sendParam(usdgAmount, _representativeBatch(), 1), false);
        return fee.nativeFee;
    }

    /// @inheritdoc IBridgeAdapter
    /// @dev The executor fee has a per-byte component and pays the delivery's and the compose's gas,
    ///      both growing with the batch: quoted on the payload and the options this batch produces.
    ///      Reverts as `bridge` would on a batch the settings refuse.
    function quoteBridgeFor(uint256[] calldata marketIds) public view returns (uint256 nativeFee) {
        (bytes memory payload, uint256 total) = _quotePayload(marketIds);
        return oft.quoteSend(_sendParam(total, payload, marketIds.length), false).nativeFee;
    }

    /// @inheritdoc IBridgeAdapter
    /// @dev LayerZero's fee does not depend on the Ethereum base fee.
    function quoteBridgeAt(uint256[] calldata marketIds, uint256) external view returns (uint256 nativeFee) {
        return quoteBridgeFor(marketIds);
    }

    /// @inheritdoc IHubAdapter
    function pins() external view returns (IHubAdapter.Pins memory) {
        return IHubAdapter.Pins({
            hub: hub,
            factory: address(factory),
            usdc: address(usdc),
            usdg: address(usdg),
            remoteHub: remoteHub,
            remoteEid: dstEid,
            bridge: address(oft),
            gatewayRouter: address(0)
        });
    }

    /// @notice The executor options appended to a one-market batch: `extraOptionsFor(1)`.
    function extraOptions() external view returns (bytes memory) {
        return extraOptionsFor(1);
    }

    /// @notice The executor options appended to a batch of `markets` markets: an `lzReceive` option
    ///         of `receiveGasBase + markets * receiveGasPerMarket`, on top of what the OFT enforces,
    ///         and an `lzCompose` option of `composeGas + markets * composeGasPerMarket`. Reverts on a
    ///         proxy never initialized (`ZeroComposeGas`), on one whose batch settings are unset
    ///         (`BatchGasNotSet`: an adapter upgraded from before them), and on an empty batch or one
    ///         above `maxBatchMarkets` (`BatchTooLarge`).
    function extraOptionsFor(uint256 markets) public view returns (bytes memory) {
        uint128 base = composeGas;
        if (base == 0) revert ZeroComposeGas();
        (uint128 perMarket, uint16 maxMarkets) = (composeGasPerMarket, maxBatchMarkets);
        (uint128 receiveBase, uint128 receivePerMarket) = (receiveGasBase, receiveGasPerMarket);
        if (perMarket == 0 || maxMarkets == 0 || receivePerMarket == 0) revert BatchGasNotSet();
        if (markets == 0 || markets > maxMarkets) revert BatchTooLarge(markets, maxMarkets);
        // At most `MAX_BATCH_RECEIVE_GAS` and `MAX_BATCH_COMPOSE_GAS` (the two ceilings' checks), so
        // the sums fit easily.
        return LzCodec.receiveAndComposeOptions(
            receiveBase + uint128(markets) * receivePerMarket, base + uint128(markets) * perMarket
        );
    }

    /// @inheritdoc IHubAdapter
    function minUsdgOutFor(uint256 usdcIn) public view returns (uint256) {
        return (usdcIn * (BPS - maxSlippageBps)) / BPS;
    }

    function _swapOnCurve(uint256 usdcIn, uint256 minUsdgOut) private returns (uint256 usdgOut) {
        uint256 bound = minUsdgOutFor(usdcIn);
        if (minUsdgOut < bound) revert MinimumTooLoose(minUsdgOut, bound);

        uint256 before = usdg.balanceOf(address(this));
        // The hub transferred `usdcIn` here; hand it to the pool and swap what it received.
        usdc.safeTransfer(address(curvePool), usdcIn);
        curvePool.exchange_received(curveUsdcIndex, curveUsdgIndex, usdcIn, minUsdgOut);
        usdgOut = usdg.balanceOf(address(this)) - before;
        if (usdgOut < minUsdgOut) revert OutputBelowMinimum(usdgOut, minUsdgOut);
    }

    function _send(uint256 amountLD, bytes memory composeMsg, uint256 markets) private returns (bytes32 guid) {
        SendParam memory p = _sendParam(amountLD, composeMsg, markets);
        if (oftNeedsApproval) usdg.forceApprove(address(oft), amountLD);
        (MessagingReceipt memory receipt, OFTReceipt memory oftReceipt) =
            oft.send{value: msg.value}(p, MessagingFee({nativeFee: msg.value, lzTokenFee: 0}), hub);
        if (oftNeedsApproval) usdg.forceApprove(address(oft), 0);
        // USDG has six local and six shared decimals, so the OFT removes no dust; refuse anything
        // else, because the compose split was computed on the full amount.
        if (oftReceipt.amountSentLD != amountLD || oftReceipt.amountReceivedLD != amountLD) {
            revert DustNotSupported(oftReceipt.amountSentLD, oftReceipt.amountReceivedLD);
        }
        guid = receipt.guid;
    }

    function _sendParam(uint256 amountLD, bytes memory composeMsg, uint256 markets)
        private
        view
        returns (SendParam memory)
    {
        return SendParam({
            dstEid: dstEid,
            to: remoteHub,
            amountLD: amountLD,
            minAmountLD: amountLD,
            extraOptions: extraOptionsFor(markets),
            composeMsg: composeMsg,
            oftCmd: ""
        });
    }
}

lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/access/Ownable.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.20;

import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 */
library ERC1967Utils {
    // We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
    // This will be fixed in Solidity 0.8.21. At that point we should remove these events.
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.20;

import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    /**
     * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC1967-compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

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

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

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

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

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

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

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

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

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

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

lib/v4-periphery/lib/v4-core/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/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     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;
 *     }
 * }
 * ```
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 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) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

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

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

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

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            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) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            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) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

lib/v4-periphery/lib/v4-core/src/interfaces/IExtsload.sol

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

/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
    /// @notice Called by external contracts to access granular pool state
    /// @param slot Key of slot to sload
    /// @return value The value of the slot as bytes32
    function extsload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access granular pool state
    /// @param startSlot Key of slot to start sloading from
    /// @param nSlots Number of slots to load into return value
    /// @return values List of loaded values.
    function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);

    /// @notice Called by external contracts to access sparse pool state
    /// @param slots List of slots to SLOAD from.
    /// @return values List of loaded values.
    function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

lib/v4-periphery/lib/v4-core/src/interfaces/IExttload.sol

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

/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
    /// @notice Called by external contracts to access transient storage of the contract
    /// @param slot Key of slot to tload
    /// @return value The value of the slot as bytes32
    function exttload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access sparse transient pool state
    /// @param slots List of slots to tload
    /// @return values List of loaded values
    function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

lib/v4-periphery/lib/v4-core/src/interfaces/IHooks.sol

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

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";

/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
    /// @notice The hook called before the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @return bytes4 The function selector for the hook
    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);

    /// @notice The hook called after the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @param tick The current tick after the state of a pool is initialized
    /// @return bytes4 The function selector for the hook
    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
        external
        returns (bytes4);

    /// @notice The hook called before liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterAddLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
    function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
        external
        returns (bytes4, BeforeSwapDelta, uint24);

    /// @notice The hook called after a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external returns (bytes4, int128);

    /// @notice The hook called before donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);
}

lib/v4-periphery/lib/v4-core/src/interfaces/IPoolManager.sol

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

import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";

/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
    /// @notice Thrown when a currency is not netted out after the contract is unlocked
    error CurrencyNotSettled();

    /// @notice Thrown when trying to interact with a non-initialized pool
    error PoolNotInitialized();

    /// @notice Thrown when unlock is called, but the contract is already unlocked
    error AlreadyUnlocked();

    /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
    error ManagerLocked();

    /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
    error TickSpacingTooLarge(int24 tickSpacing);

    /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
    error TickSpacingTooSmall(int24 tickSpacing);

    /// @notice PoolKey must have currencies where address(currency0) < address(currency1)
    error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);

    /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
    /// or on a pool that does not have a dynamic swap fee.
    error UnauthorizedDynamicLPFeeUpdate();

    /// @notice Thrown when trying to swap amount of 0
    error SwapAmountCannotBeZero();

    ///@notice Thrown when native currency is passed to a non native settlement
    error NonzeroNativeValue();

    /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
    error MustClearExactPositiveDelta();

    /// @notice Emitted when a new pool is initialized
    /// @param id The abi encoded hash of the pool key struct for the new pool
    /// @param currency0 The first currency of the pool by address sort order
    /// @param currency1 The second currency of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param hooks The hooks contract address for the pool, or address(0) if none
    /// @param sqrtPriceX96 The price of the pool on initialization
    /// @param tick The initial tick of the pool corresponding to the initialized price
    event Initialize(
        PoolId indexed id,
        Currency indexed currency0,
        Currency indexed currency1,
        uint24 fee,
        int24 tickSpacing,
        IHooks hooks,
        uint160 sqrtPriceX96,
        int24 tick
    );

    /// @notice Emitted when a liquidity position is modified
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that modified the pool
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param liquidityDelta The amount of liquidity that was added or removed
    /// @param salt The extra data to make positions unique
    event ModifyLiquidity(
        PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
    );

    /// @notice Emitted for swaps between currency0 and currency1
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param amount0 The delta of the currency0 balance of the pool
    /// @param amount1 The delta of the currency1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of the price of the pool after the swap
    /// @param fee The swap fee in hundredths of a bip
    event Swap(
        PoolId indexed id,
        address indexed sender,
        int128 amount0,
        int128 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick,
        uint24 fee
    );

    /// @notice Emitted for donations
    /// @param id The abi encoded hash of the pool key struct for the pool that was donated to
    /// @param sender The address that initiated the donate call
    /// @param amount0 The amount donated in currency0
    /// @param amount1 The amount donated in currency1
    event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);

    /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
    /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
    /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
    /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
    /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
    function unlock(bytes calldata data) external returns (bytes memory);

    /// @notice Initialize the state for a given pool ID
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The pool key for the pool to initialize
    /// @param sqrtPriceX96 The initial square root price
    /// @return tick The initial tick of the pool
    function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);

    /// @notice Modify the liquidity for the given pool
    /// @dev Poke by calling with a zero liquidityDelta
    /// @param key The pool to modify liquidity in
    /// @param params The parameters for modifying the liquidity
    /// @param hookData The data to pass through to the add/removeLiquidity hooks
    /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
    /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
    /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
    /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
    /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);

    /// @notice Swap against the given pool
    /// @param key The pool to swap in
    /// @param params The parameters for swapping
    /// @param hookData The data to pass through to the swap hooks
    /// @return swapDelta The balance delta of the address swapping
    /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
    /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
    /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta swapDelta);

    /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
    /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
    /// Donors should keep this in mind when designing donation mechanisms.
    /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
    /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
    /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
    /// Read the comments in `Pool.swap()` for more information about this.
    /// @param key The key of the pool to donate to
    /// @param amount0 The amount of currency0 to donate
    /// @param amount1 The amount of currency1 to donate
    /// @param hookData The data to pass through to the donate hooks
    /// @return BalanceDelta The delta of the caller after the donate
    function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        external
        returns (BalanceDelta);

    /// @notice Writes the current ERC20 balance of the specified currency to transient storage
    /// This is used to checkpoint balances for the manager and derive deltas for the caller.
    /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
    /// for native tokens because the amount to settle is determined by the sent value.
    /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
    /// native funds, this function can be called with the native currency to then be able to settle the native currency
    function sync(Currency currency) external;

    /// @notice Called by the user to net out some value owed to the user
    /// @dev Will revert if the requested amount is not available, consider using `mint` instead
    /// @dev Can also be used as a mechanism for free flash loans
    /// @param currency The currency to withdraw from the pool manager
    /// @param to The address to withdraw to
    /// @param amount The amount of currency to withdraw
    function take(Currency currency, address to, uint256 amount) external;

    /// @notice Called by the user to pay what is owed
    /// @return paid The amount of currency settled
    function settle() external payable returns (uint256 paid);

    /// @notice Called by the user to pay on behalf of another address
    /// @param recipient The address to credit for the payment
    /// @return paid The amount of currency settled
    function settleFor(address recipient) external payable returns (uint256 paid);

    /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
    /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
    /// @dev This could be used to clear a balance that is considered dust.
    /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
    function clear(Currency currency, uint256 amount) external;

    /// @notice Called by the user to move value into ERC6909 balance
    /// @param to The address to mint the tokens to
    /// @param id The currency address to mint to ERC6909s, as a uint256
    /// @param amount The amount of currency to mint
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function mint(address to, uint256 id, uint256 amount) external;

    /// @notice Called by the user to move value from ERC6909 balance
    /// @param from The address to burn the tokens from
    /// @param id The currency address to burn from ERC6909s, as a uint256
    /// @param amount The amount of currency to burn
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function burn(address from, uint256 id, uint256 amount) external;

    /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The key of the pool to update dynamic LP fees for
    /// @param newDynamicLPFee The new dynamic pool LP fee
    function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}

lib/v4-periphery/lib/v4-core/src/interfaces/IProtocolFees.sol

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

import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";

/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
    /// @notice Thrown when protocol fee is set too high
    error ProtocolFeeTooLarge(uint24 fee);

    /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
    error InvalidCaller();

    /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
    error ProtocolFeeCurrencySynced();

    /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
    event ProtocolFeeControllerUpdated(address indexed protocolFeeController);

    /// @notice Emitted when the protocol fee is updated for a pool.
    event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);

    /// @notice Given a currency address, returns the protocol fees accrued in that currency
    /// @param currency The currency to check
    /// @return amount The amount of protocol fees accrued in the currency
    function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);

    /// @notice Sets the protocol fee for the given pool
    /// @param key The key of the pool to set a protocol fee for
    /// @param newProtocolFee The fee to set
    function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;

    /// @notice Sets the protocol fee controller
    /// @param controller The new protocol fee controller
    function setProtocolFeeController(address controller) external;

    /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
    /// @dev This will revert if the contract is unlocked
    /// @param recipient The address to receive the protocol fees
    /// @param currency The currency to withdraw
    /// @param amount The amount of currency to withdraw
    /// @return amountCollected The amount of currency successfully withdrawn
    function collectProtocolFees(address recipient, Currency currency, uint256 amount)
        external
        returns (uint256 amountCollected);

    /// @notice Returns the current protocol fee controller address
    /// @return address The current protocol fee controller address
    function protocolFeeController() external view returns (address);
}

lib/v4-periphery/lib/v4-core/src/interfaces/external/IERC20Minimal.sol

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

/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
    /// @notice Returns an account's balance in the token
    /// @param account The account for which to look up the number of tokens it has, i.e. its balance
    /// @return The number of tokens held by the account
    function balanceOf(address account) external view returns (uint256);

    /// @notice Transfers the amount of token from the `msg.sender` to the recipient
    /// @param recipient The account that will receive the amount transferred
    /// @param amount The number of tokens to send from the sender to the recipient
    /// @return Returns true for a successful transfer, false for an unsuccessful transfer
    function transfer(address recipient, uint256 amount) external returns (bool);

    /// @notice Returns the current allowance given to a spender by an owner
    /// @param owner The account of the token owner
    /// @param spender The account of the token spender
    /// @return The current allowance granted by `owner` to `spender`
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
    /// @param spender The account which will be allowed to spend a given amount of the owners tokens
    /// @param amount The amount of tokens allowed to be used by `spender`
    /// @return Returns true for a successful approval, false for unsuccessful
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
    /// @param sender The account from which the transfer will be initiated
    /// @param recipient The recipient of the transfer
    /// @param amount The amount of the transfer
    /// @return Returns true for a successful transfer, false for unsuccessful
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
    /// @param from The account from which the tokens were sent, i.e. the balance decreased
    /// @param to The account to which the tokens were sent, i.e. the balance increased
    /// @param value The amount of tokens that were transferred
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
    /// @param owner The account that approved spending of its tokens
    /// @param spender The account for which the spending allowance was modified
    /// @param value The new allowance from the owner to the spender
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

lib/v4-periphery/lib/v4-core/src/interfaces/external/IERC6909Claims.sol

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

/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OperatorSet(address indexed owner, address indexed operator, bool approved);

    event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);

    event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                                 FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @notice Owner balance of an id.
    /// @param owner The address of the owner.
    /// @param id The id of the token.
    /// @return amount The balance of the token.
    function balanceOf(address owner, uint256 id) external view returns (uint256 amount);

    /// @notice Spender allowance of an id.
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @return amount The allowance of the token.
    function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);

    /// @notice Checks if a spender is approved by an owner as an operator
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @return approved The approval status.
    function isOperator(address owner, address spender) external view returns (bool approved);

    /// @notice Transfers an amount of an id from the caller to a receiver.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Transfers an amount of an id from a sender to a receiver.
    /// @param sender The address of the sender.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Approves an amount of an id to a spender.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always
    function approve(address spender, uint256 id, uint256 amount) external returns (bool);

    /// @notice Sets or removes an operator for the caller.
    /// @param operator The address of the operator.
    /// @param approved The approval status.
    /// @return bool True, always
    function setOperator(address operator, bool approved) external returns (bool);
}

lib/v4-periphery/lib/v4-core/src/libraries/CustomRevert.sol

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

/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
    /// @dev ERC-7751 error for wrapping bubbled up reverts
    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);

    /// @dev Reverts with the selector of a custom error in the scratch space
    function revertWith(bytes4 selector) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            revert(0, 0x04)
        }
    }

    /// @dev Reverts with a custom error with an address argument in the scratch space
    function revertWith(bytes4 selector, address addr) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with an int24 argument in the scratch space
    function revertWith(bytes4 selector, int24 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, signextend(2, value))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with a uint160 argument in the scratch space
    function revertWith(bytes4 selector, uint160 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with two int24 arguments
    function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), signextend(2, value1))
            mstore(add(fmp, 0x24), signextend(2, value2))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two uint160 arguments
    function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two address arguments
    function revertWith(bytes4 selector, address value1, address value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
    /// @dev this method can be vulnerable to revert data bombs
    function bubbleUpAndRevertWith(
        address revertingContract,
        bytes4 revertingFunctionSelector,
        bytes4 additionalContext
    ) internal pure {
        bytes4 wrappedErrorSelector = WrappedError.selector;
        assembly ("memory-safe") {
            // Ensure the size of the revert data is a multiple of 32 bytes
            let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)

            let fmp := mload(0x40)

            // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
            mstore(fmp, wrappedErrorSelector)
            mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(
                add(fmp, 0x24),
                and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            // offset revert reason
            mstore(add(fmp, 0x44), 0x80)
            // offset additional context
            mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
            // size revert reason
            mstore(add(fmp, 0x84), returndatasize())
            // revert reason
            returndatacopy(add(fmp, 0xa4), 0, returndatasize())
            // size additional context
            mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
            // additional context
            mstore(
                add(fmp, add(0xc4, encodedDataSize)),
                and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            revert(fmp, add(0xe4, encodedDataSize))
        }
    }
}

lib/v4-periphery/lib/v4-core/src/libraries/SafeCast.sol

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

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

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    using CustomRevert for bytes4;

    error SafeCastOverflow();

    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint160
    function toUint160(uint256 x) internal pure returns (uint160 y) {
        y = uint160(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a uint128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint128
    function toUint128(uint256 x) internal pure returns (uint128 y) {
        y = uint128(x);
        if (x != y) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a int128 to a uint128, revert on overflow or underflow
    /// @param x The int128 to be casted
    /// @return y The casted integer, now type uint128
    function toUint128(int128 x) internal pure returns (uint128 y) {
        if (x < 0) SafeCastOverflow.selector.revertWith();
        y = uint128(x);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param x The int256 to be downcasted
    /// @return y The downcasted integer, now type int128
    function toInt128(int256 x) internal pure returns (int128 y) {
        y = int128(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int256, revert on overflow
    /// @param x The uint256 to be casted
    /// @return y The casted integer, now type int256
    function toInt256(uint256 x) internal pure returns (int256 y) {
        y = int256(x);
        if (y < 0) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return The downcasted integer, now type int128
    function toInt128(uint256 x) internal pure returns (int128) {
        if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
        return int128(int256(x));
    }
}

lib/v4-periphery/lib/v4-core/src/types/BalanceDelta.sol

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

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

/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;

using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;

function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
    assembly ("memory-safe") {
        balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
    }
}

function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := add(a0, b0)
        res1 := add(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := sub(a0, b0)
        res1 := sub(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}

function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}

/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
    /// @notice A BalanceDelta of 0
    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);

    function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
        assembly ("memory-safe") {
            _amount0 := sar(128, balanceDelta)
        }
    }

    function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
        assembly ("memory-safe") {
            _amount1 := signextend(15, balanceDelta)
        }
    }
}

lib/v4-periphery/lib/v4-core/src/types/BeforeSwapDelta.sol

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

// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;

// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
    pure
    returns (BeforeSwapDelta beforeSwapDelta)
{
    assembly ("memory-safe") {
        beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
    }
}

/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
    /// @notice A BeforeSwapDelta of 0
    BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);

    /// extracts int128 from the upper 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap
    function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
        assembly ("memory-safe") {
            deltaSpecified := sar(128, delta)
        }
    }

    /// extracts int128 from the lower 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap and afterSwap
    function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
        assembly ("memory-safe") {
            deltaUnspecified := signextend(15, delta)
        }
    }
}

lib/v4-periphery/lib/v4-core/src/types/Currency.sol

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

import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";

type Currency is address;

using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;

function equals(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) == Currency.unwrap(other);
}

function greaterThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) > Currency.unwrap(other);
}

function lessThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) < Currency.unwrap(other);
}

function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) >= Currency.unwrap(other);
}

/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
    /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
    error NativeTransferFailed();

    /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
    error ERC20TransferFailed();

    /// @notice A constant to represent the native currency
    Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));

    function transfer(Currency currency, address to, uint256 amount) internal {
        // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
        // modified custom error selectors

        bool success;
        if (currency.isAddressZero()) {
            assembly ("memory-safe") {
                // Transfer the ETH and revert if it fails.
                success := call(gas(), to, amount, 0, 0, 0, 0)
            }
            // revert with NativeTransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
            }
        } else {
            assembly ("memory-safe") {
                // Get a pointer to some free memory.
                let fmp := mload(0x40)

                // Write the abi-encoded calldata into memory, beginning with the function selector.
                mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

                success :=
                    and(
                        // Set success to whether the call reverted, if not we check it either
                        // returned exactly 1 (can't just be non-zero data), or had no return data.
                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                        // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                        // Counterintuitively, this call must be positioned second to the or() call in the
                        // surrounding and() call or else returndatasize() will be zero during the computation.
                        call(gas(), currency, 0, fmp, 68, 0, 32)
                    )

                // Now clean the memory we used
                mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
                mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
                mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
            }
            // revert with ERC20TransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(
                    Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
                );
            }
        }
    }

    function balanceOfSelf(Currency currency) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return address(this).balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
        }
    }

    function balanceOf(Currency currency, address owner) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return owner.balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
        }
    }

    function isAddressZero(Currency currency) internal pure returns (bool) {
        return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
    }

    function toId(Currency currency) internal pure returns (uint256) {
        return uint160(Currency.unwrap(currency));
    }

    // If the upper 12 bytes are non-zero, they will be zero-ed out
    // Therefore, fromId() and toId() are not inverses of each other
    function fromId(uint256 id) internal pure returns (Currency) {
        return Currency.wrap(address(uint160(id)));
    }
}

lib/v4-periphery/lib/v4-core/src/types/PoolId.sol

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

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

type PoolId is bytes32;

/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
    /// @notice Returns value equal to keccak256(abi.encode(poolKey))
    function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
        assembly ("memory-safe") {
            // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
            poolId := keccak256(poolKey, 0xa0)
        }
    }
}

lib/v4-periphery/lib/v4-core/src/types/PoolKey.sol

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

import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";

using PoolIdLibrary for PoolKey global;

/// @notice Returns the key for identifying a pool
struct PoolKey {
    /// @notice The lower currency of the pool, sorted numerically
    Currency currency0;
    /// @notice The higher currency of the pool, sorted numerically
    Currency currency1;
    /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
    uint24 fee;
    /// @notice Ticks that involve positions must be a multiple of tick spacing
    int24 tickSpacing;
    /// @notice The hooks of the pool
    IHooks hooks;
}

lib/v4-periphery/lib/v4-core/src/types/PoolOperation.sol

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

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";

/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
    // the lower and upper tick of the position
    int24 tickLower;
    int24 tickUpper;
    // how to modify the liquidity
    int256 liquidityDelta;
    // a value to set if you want unique liquidity positions at the same range
    bytes32 salt;
}

/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
    /// Whether to swap token0 for token1 or vice versa
    bool zeroForOne;
    /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
    int256 amountSpecified;
    /// The sqrt price at which, if reached, the swap will stop executing
    uint160 sqrtPriceLimitX96;
}

src/TreasuryOracle.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

import {AggregatorV3Interface} from "./interfaces/AggregatorV3Interface.sol";
import {UpgradeableModule} from "./base/UpgradeableModule.sol";
import {Rescuable} from "./base/Rescuable.sol";
import {CairnLinks} from "./base/CairnLinks.sol";

/// @title TreasuryOracle
/// @notice Registry of the Chainlink feeds a vault reads to compute its own price bounds.
///
/// @dev The vault never accepts a minimum output on trust: it prices the trade here first and
///      refuses any keeper minimum looser than its own, so the keeper chooses when a trade runs,
///      never the price it runs at. Whoever controls this table therefore controls the bound:
///      the feed and the decimals of an asset are written once, when the asset is registered, and
///      no setter touches them afterwards. The table is append-only: the initialization writes the
///      first assets, and the protocol owner adds a new stock with `addFeed` (2026-10-07: a basket
///      of new stocks registered without a new oracle, so every market keeps its oracle and every
///      asset already priced keeps its feed).
///
///      Upgradeable by the protocol owner like every module (doc/DECISIONS.md, 2026-10-02): an
///      ERC-1967 proxy whose authority is the factory on Ethereum and the RemoteHub on Robinhood
///      Chain, so that owner already controls the table through an upgrade, and moves out with
///      `rescue` whatever is sent here by mistake (`Rescuable`, 2026-10-05). The heartbeats, the
///      longest gap tolerated between two publications of each feed, are that owner's settings
///      (2026-10-05): `setEthUsdHeartbeat`, `setHeartbeat`. The ETH/USD feed is an immutable of the
///      implementation, its heartbeat the proxy's state from initialization on.
///
///      Two guards for Robinhood Chain (2026-10-06, launch plan, Robinhood oracles), owner settings
///      too, both off until the owner turns them on, which `DeployRemote` does and the Ethereum
///      scripts never do:
///        - the L2 sequencer uptime feed (`setSequencerUptimeFeed`): while it says the sequencer is
///          down, or came back up no longer than the grace period ago, or cannot be read, no price
///          of this oracle is usable. A fresh-looking answer is no proof of a live market while the
///          sequencer orders nothing, and right after a restart the feeds and the pools are still
///          catching up;
///        - each stock token's `oraclePaused()` (`setOraclePauseCheck`, per asset): while a stock's
///          token says its oracle is paused for a corporate action, that stock's price alone is
///          unusable. The feed then holds its last value, which can still look fresh, while the
///          token's multiplier changes under it.
///      Both are read with a bounded low-level call that copies a fixed number of bytes, so neither
///      a broken feed nor a token can make a soft read revert, and one stock's token never touches
///      another stock's price.
///
///      Every strict read reverts rather than returning a degraded value. A stale feed, a
///      non-positive answer, an unregistered asset, a sequencer down or just back, and a stock in a
///      corporate action are all states in which the correct behaviour is to not trade, and the
///      loudest way to express that on-chain is to revert.
contract TreasuryOracle is CairnLinks, Rescuable {
    struct Feed {
        AggregatorV3Interface aggregator;
        /// @notice Longest gap tolerated between two publications before the price is unusable.
        uint32 heartbeat;
        /// @notice ERC-20 decimals of the priced asset. Stored, never read from the token, because a
        ///         token frozen by its issuer can make even `decimals()` revert.
        uint8 assetDecimals;
        bool exists;
    }

    struct FeedConfig {
        address asset;
        address aggregator;
        uint32 heartbeat;
        uint8 assetDecimals;
    }

    /// @notice What the sequencer check says now (`sequencerState`). Prices are usable in `Off` and
    ///         `Up` only.
    enum SequencerState {
        /// No uptime feed is set: the check is off (the Ethereum deployment).
        Off,
        /// The feed says up, for longer than the grace period.
        Up,
        /// The feed says down.
        Down,
        /// The feed says up again, for no longer than the grace period.
        GracePeriod,
        /// The feed cannot be read, has never been initialized, or answers neither 0 nor 1.
        Unknown
    }

    /// @notice Gas forwarded to each read of the uptime feed and of a token's `oraclePaused()`: far
    ///         above what a Chainlink proxy or a stock token's beacon proxy needs (a stock token
    ///         answers in at most 13,300, cold, measured on a Robinhood Chain fork on 2026-10-06),
    ///         and a bound on what a broken one can cost the caller. Same bound as `SafeBalance`.
    uint256 public constant GUARD_READ_GAS = 100_000;
    /// @dev `oraclePaused()` of a Robinhood stock token: true while its price is not to be trusted
    ///      (docs.robinhood.com/chain/oracles-and-price-feeds, "Oracle Pauses During Corporate
    ///      Actions").
    bytes4 private constant ORACLE_PAUSED_SELECTOR = 0x7706ba52;

    /// @notice ETH/USD feed, used to bound the ETH -> USDC leg.
    AggregatorV3Interface public immutable ethUsdFeed;
    /// @dev The ETH/USD heartbeat the proxy starts with.
    uint32 private immutable _initialEthUsdHeartbeat;

    mapping(address asset => Feed) private _feeds;
    address[] private _assets;
    /// @notice Heartbeat of the ETH/USD feed. Shorter than a stock's: ETH trades 24/7. Owner setting
    ///         (2026-10-05).
    uint32 public ethUsdHeartbeat;
    /// @notice Chainlink's L2 sequencer uptime feed on this chain; zero turns the check off, which is
    ///         the Ethereum deployment's value. Owner setting (2026-10-06).
    AggregatorV3Interface public sequencerUptimeFeed;
    /// @notice How long the sequencer must have been up again before a price counts, in seconds.
    ///         Set with the feed, zero exactly when the check is off (2026-10-06).
    uint32 public sequencerGracePeriod;
    /// @notice Whether `asset`'s own `oraclePaused()` is read before its price. Owner setting, per
    ///         asset, off unless turned on (2026-10-06).
    mapping(address asset => bool) public oraclePauseCheck;

    event EthUsdHeartbeatSet(uint32 heartbeat);
    event FeedAdded(address indexed asset, address aggregator, uint32 heartbeat, uint8 assetDecimals);
    event HeartbeatSet(address indexed asset, uint32 heartbeat);
    event SequencerUptimeFeedSet(address indexed feed, uint32 gracePeriod);
    event OraclePauseCheckSet(address indexed asset, bool enabled);

    error ZeroAddress();
    error ZeroHeartbeat();
    error DuplicateFeed(address asset);
    error InvalidAssetDecimals(address asset, uint8 assetDecimals);
    error UnknownFeed(address asset);
    error StalePrice(address asset, uint256 updatedAt, uint32 heartbeat);
    error InvalidPrice(address asset, int256 answer);
    /// @notice A sequencer setting that cannot work: a feed without code or without a grace period,
    ///         or a grace period without a feed.
    error InvalidSequencerSetting(address feed, uint32 gracePeriod);
    /// @notice The uptime feed says the sequencer has been down since `since`.
    error SequencerDown(uint256 since);
    /// @notice The sequencer came back up at `upSince`, no longer than `gracePeriod` ago.
    error SequencerGracePeriod(uint256 upSince, uint32 gracePeriod);
    /// @notice The uptime feed cannot be read, has never been initialized, or answers neither 0 nor 1.
    error SequencerStatusUnknown(address feed);
    /// @notice `asset`'s token says its oracle is paused: a corporate action is in progress.
    error StockOraclePaused(address asset);

    /// @param authority The factory on Ethereum, the RemoteHub on Robinhood Chain: its protocol
    ///        owner upgrades this oracle.
    constructor(address authority, address ethUsdFeed_, uint32 ethUsdHeartbeat_) UpgradeableModule(authority) {
        if (authority == address(0) || ethUsdFeed_ == address(0) || ethUsdHeartbeat_ == 0) revert ZeroAddress();
        ethUsdFeed = AggregatorV3Interface(ethUsdFeed_);
        _initialEthUsdHeartbeat = ethUsdHeartbeat_;
    }

    /// @notice Writes the feed table, once, inside the proxy's constructor, with the deployment's
    ///         ETH/USD heartbeat. Both guards start off.
    function initialize(FeedConfig[] calldata feeds) external initializer {
        ethUsdHeartbeat = _initialEthUsdHeartbeat;
        emit EthUsdHeartbeatSet(_initialEthUsdHeartbeat);
        for (uint256 i; i < feeds.length; ++i) {
            _addFeed(feeds[i]);
        }
    }

    /// @notice Registers the feed of a new asset (a stock of a basket to come), once: the table is
    ///         append-only, an asset already registered keeps its feed and its decimals for good
    ///         (`DuplicateFeed`). The same checks as at initialization. Protocol owner only.
    /// @dev Adding never changes how an asset already registered is priced, so no market's bound
    ///      moves; until the stock is in a basket nothing reads it (2026-10-07).
    function addFeed(FeedConfig calldata feed) external {
        if (msg.sender != _upgrader()) revert NotProtocolOwner();
        _addFeed(feed);
    }

    function _addFeed(FeedConfig memory f) private {
        if (f.asset == address(0) || f.aggregator == address(0) || f.heartbeat == 0) revert ZeroAddress();
        if (_feeds[f.asset].exists) revert DuplicateFeed(f.asset);
        // Decimals scale the bound by 10^assetDecimals: an unvalidated 0 would silence the
        // price guard entirely, and anything exotic is a configuration mistake.
        if (f.assetDecimals < 6 || f.assetDecimals > 18) revert InvalidAssetDecimals(f.asset, f.assetDecimals);
        _feeds[f.asset] = Feed({
            aggregator: AggregatorV3Interface(f.aggregator),
            heartbeat: f.heartbeat,
            assetDecimals: f.assetDecimals,
            exists: true
        });
        _assets.push(f.asset);
        emit FeedAdded(f.asset, f.aggregator, f.heartbeat, f.assetDecimals);
    }

    // -----------------------------------------------------------------------------------------------
    // Settings: the heartbeats (2026-10-05) and the two guards (2026-10-06), the protocol owner's
    // -----------------------------------------------------------------------------------------------

    /// @notice Sets the longest gap tolerated between two ETH/USD publications.
    function setEthUsdHeartbeat(uint32 heartbeat) external {
        if (msg.sender != _upgrader()) revert NotProtocolOwner();
        if (heartbeat == 0) revert ZeroHeartbeat();
        ethUsdHeartbeat = heartbeat;
        emit EthUsdHeartbeatSet(heartbeat);
    }

    /// @notice Sets the longest gap tolerated between two publications of `asset`'s feed. The feed
    ///         itself stays the one registered at initialization.
    function setHeartbeat(address asset, uint32 heartbeat) external {
        if (msg.sender != _upgrader()) revert NotProtocolOwner();
        if (!_feeds[asset].exists) revert UnknownFeed(asset);
        if (heartbeat == 0) revert ZeroHeartbeat();
        _feeds[asset].heartbeat = heartbeat;
        emit HeartbeatSet(asset, heartbeat);
    }

    /// @notice Sets the L2 sequencer uptime feed and the grace period after a restart, in seconds;
    ///         `(address(0), 0)` turns the check off. A feed needs code and a grace period; no
    ///         feed, no grace period.
    /// @dev Never calls the feed, so it is always the way out of a feed that cannot be read, which
    ///      holds every price of this oracle back until the owner points this at another feed or
    ///      turns the check off.
    function setSequencerUptimeFeed(address feed, uint32 gracePeriod) external {
        if (msg.sender != _upgrader()) revert NotProtocolOwner();
        if (feed == address(0) ? gracePeriod != 0 : (gracePeriod == 0 || feed.code.length == 0)) {
            revert InvalidSequencerSetting(feed, gracePeriod);
        }
        sequencerUptimeFeed = AggregatorV3Interface(feed);
        sequencerGracePeriod = gracePeriod;
        emit SequencerUptimeFeedSet(feed, gracePeriod);
    }

    /// @notice Turns on or off, for one registered asset, the read of its token's `oraclePaused()`
    ///         before its price. Per asset, because only the Robinhood stock tokens carry the signal
    ///         (on for each one `DeployRemote` registers), and so that a token whose answer this
    ///         oracle cannot use is switched off alone, its price falling back on its feed's checks.
    function setOraclePauseCheck(address asset, bool enabled) external {
        if (msg.sender != _upgrader()) revert NotProtocolOwner();
        if (!_feeds[asset].exists) revert UnknownFeed(asset);
        oraclePauseCheck[asset] = enabled;
        emit OraclePauseCheckSet(asset, enabled);
    }

    // -----------------------------------------------------------------------------------------------
    // Strict reads. These are what the vault calls, and they revert rather than degrade.
    // -----------------------------------------------------------------------------------------------

    /// @notice Current ETH price in USD.
    /// @return price Answer as published.
    /// @return priceDecimals Decimals the answer is scaled by.
    function ethUsdPrice() external view returns (uint256 price, uint8 priceDecimals) {
        _requireSequencerUp();
        price = _read(address(0), ethUsdFeed, ethUsdHeartbeat);
        priceDecimals = ethUsdFeed.decimals();
    }

    /// @notice Current price of one whole `stock` in USD.
    /// @return price Answer as published.
    /// @return priceDecimals Decimals the answer is scaled by.
    /// @return assetDecimals ERC-20 decimals of `stock`, as registered here.
    function stockPrice(address stock) external view returns (uint256 price, uint8 priceDecimals, uint8 assetDecimals) {
        Feed memory feed = _feeds[stock];
        if (!feed.exists) revert UnknownFeed(stock);
        _requireSequencerUp();
        if (stockOraclePaused(stock)) revert StockOraclePaused(stock);
        price = _read(stock, feed.aggregator, feed.heartbeat);
        priceDecimals = feed.aggregator.decimals();
        assetDecimals = feed.assetDecimals;
    }

    // -----------------------------------------------------------------------------------------------
    // Soft reads. The keeper and the dapp use these to decide whether acting is even worth a
    // transaction; they answer "unusable" instead of reverting.
    // -----------------------------------------------------------------------------------------------

    /// @notice Non-reverting view of a stock's feed.
    /// @return price Answer as published, 0 when unusable.
    /// @return priceDecimals Decimals the answer is scaled by, 0 when unusable.
    /// @return updatedAt Timestamp of the last publication, 0 when unknown.
    /// @return usable False when the feed is unregistered, stale, or publishing a non-positive answer,
    ///         while the sequencer check holds prices back, and while the stock's token says its
    ///         oracle is paused (when its check is on).
    function peekStock(address stock)
        external
        view
        returns (uint256 price, uint8 priceDecimals, uint256 updatedAt, bool usable)
    {
        Feed memory feed = _feeds[stock];
        if (!feed.exists) return (0, 0, 0, false);
        (price, priceDecimals, updatedAt, usable) = _peek(feed.aggregator, feed.heartbeat);
        if (usable && (!_sequencerUsable() || stockOraclePaused(stock))) return (0, 0, updatedAt, false);
    }

    /// @notice Non-reverting view of the ETH/USD feed, unusable too while the sequencer check holds
    ///         prices back.
    function peekEthUsd() external view returns (uint256 price, uint8 priceDecimals, uint256 updatedAt, bool usable) {
        (price, priceDecimals, updatedAt, usable) = _peek(ethUsdFeed, ethUsdHeartbeat);
        if (usable && !_sequencerUsable()) return (0, 0, updatedAt, false);
    }

    /// @notice True when every asset in `stocks` is currently priceable: the sequencer check lets
    ///         prices through, the ETH/USD feed is fresh, and each stock is registered, fresh and not
    ///         paused by its token.
    /// @dev The keeper's third precondition, answered in one call.
    function allFresh(address[] calldata stocks) external view returns (bool) {
        if (!_sequencerUsable()) return false;
        (,,, bool ethUsable) = _peek(ethUsdFeed, ethUsdHeartbeat);
        if (!ethUsable) return false;
        for (uint256 i; i < stocks.length; ++i) {
            Feed memory feed = _feeds[stocks[i]];
            if (!feed.exists) return false;
            (,,, bool usable) = _peek(feed.aggregator, feed.heartbeat);
            if (!usable || stockOraclePaused(stocks[i])) return false;
        }
        return true;
    }

    /// @notice What the sequencer check says now: prices are usable in `Off` and `Up` only.
    /// @return state `Off` without a feed; otherwise the feed's status, `GracePeriod` while it has
    ///         been up again for no longer than `sequencerGracePeriod`, `Unknown` when it cannot be
    ///         read or answers no status.
    /// @return since When the feed's status last changed (`startedAt`), 0 for `Off` and `Unknown`.
    function sequencerState() public view returns (SequencerState state, uint256 since) {
        address feed = address(sequencerUptimeFeed);
        if (feed == address(0)) return (SequencerState.Off, 0);
        (bool readable, int256 answer, uint256 startedAt) = _sequencerRound(feed);
        // Chainlink's L2 sequencer uptime feeds answer 0 while the sequencer is up and 1 while it is
        // down, and `startedAt` is when that status last changed. It is 0 only on an Arbitrum-stack
        // feed not initialized yet (Robinhood Chain is an Arbitrum chain): no status at all, never
        // "up since forever" (docs.chain.link/data-feeds/l2-sequencer-feeds).
        if (!readable || startedAt == 0 || (answer != 0 && answer != 1)) return (SequencerState.Unknown, 0);
        if (answer == 1) return (SequencerState.Down, startedAt);
        // Up again: a price counts only once more than the grace period has passed, as in
        // Chainlink's reference consumer (`block.timestamp - startedAt <= GRACE_PERIOD_TIME`
        // refuses). A status change stamped later than this block is as recent as can be.
        if (startedAt > block.timestamp || block.timestamp - startedAt <= sequencerGracePeriod) {
            return (SequencerState.GracePeriod, startedAt);
        }
        return (SequencerState.Up, startedAt);
    }

    /// @notice True while `stock`'s token says its oracle is paused and the check is on for it.
    /// @dev An answer of at least one word whose first word is not zero counts as paused: a token
    ///      the owner turned the check on for and that answers anything but a clean `false` is not
    ///      vouching for its price. No answer counts as not paused: a token without the function,
    ///      one that reverts, runs out of its gas or answers less than a word. The flag is advisory
    ///      (Robinhood: the staleness check stays the primary guard), so a token that does not
    ///      answer leaves its price to its feed's checks instead of making it unusable for good.
    function stockOraclePaused(address stock) public view returns (bool) {
        return oraclePauseCheck[stock] && _tokenSaysPaused(stock);
    }

    // -----------------------------------------------------------------------------------------------
    // Registry views
    // -----------------------------------------------------------------------------------------------

    function hasFeed(address stock) external view returns (bool) {
        return _feeds[stock].exists;
    }

    function feedOf(address stock) external view returns (Feed memory) {
        return _feeds[stock];
    }

    /// @notice Every asset this oracle can price, in registration order.
    function registeredAssets() external view returns (address[] memory) {
        return _assets;
    }

    // -----------------------------------------------------------------------------------------------

    function _read(address asset, AggregatorV3Interface aggregator, uint32 heartbeat) private view returns (uint256) {
        (, int256 answer,, uint256 updatedAt,) = aggregator.latestRoundData();
        if (answer <= 0) revert InvalidPrice(asset, answer);
        // A feed that has never published, or published longer ago than its heartbeat allows, is a
        // feed the protocol has no opinion from. It is not a reason to trade at a guessed price.
        if (updatedAt == 0 || block.timestamp - updatedAt > heartbeat) {
            revert StalePrice(asset, updatedAt, heartbeat);
        }
        return uint256(answer);
    }

    function _peek(AggregatorV3Interface aggregator, uint32 heartbeat)
        private
        view
        returns (uint256 price, uint8 priceDecimals, uint256 updatedAt, bool usable)
    {
        try aggregator.latestRoundData() returns (uint80, int256 answer, uint256, uint256 at, uint80) {
            updatedAt = at;
            if (answer <= 0 || at == 0 || block.timestamp - at > heartbeat) return (0, 0, at, false);
            price = uint256(answer);
        } catch {
            return (0, 0, 0, false);
        }

        try aggregator.decimals() returns (uint8 d) {
            priceDecimals = d;
        } catch {
            return (0, 0, updatedAt, false);
        }
        usable = true;
    }

    /// @dev Reverts with the reason the sequencer check holds prices back, if it does.
    function _requireSequencerUp() private view {
        (SequencerState state, uint256 since) = sequencerState();
        if (state == SequencerState.Off || state == SequencerState.Up) return;
        if (state == SequencerState.Down) revert SequencerDown(since);
        if (state == SequencerState.GracePeriod) revert SequencerGracePeriod(since, sequencerGracePeriod);
        revert SequencerStatusUnknown(address(sequencerUptimeFeed));
    }

    function _sequencerUsable() private view returns (bool) {
        (SequencerState state,) = sequencerState();
        return state == SequencerState.Off || state == SequencerState.Up;
    }

    /// @dev One bounded read of the uptime feed's `latestRoundData()`. Unreadable when the feed has
    ///      no code, reverts, runs out of its gas or answers fewer than the five words of a round;
    ///      only the answer and `startedAt` are copied, so a long answer costs nothing.
    function _sequencerRound(address feed) internal view returns (bool readable, int256 answer, uint256 startedAt) {
        bytes memory callData = abi.encodeCall(AggregatorV3Interface.latestRoundData, ());
        assembly ("memory-safe") {
            let out := mload(0x40)
            readable := staticcall(GUARD_READ_GAS, feed, add(callData, 0x20), mload(callData), out, 0x60)
            readable := and(readable, gt(returndatasize(), 0x9f))
            if readable {
                answer := mload(add(out, 0x20))
                startedAt := mload(add(out, 0x40))
            }
        }
    }

    /// @dev One bounded read of `token`'s `oraclePaused()`, its first word at most copied (see
    ///      `stockOraclePaused` for what counts as paused). A read that failed with less than a
    ///      63rd of its gas left may have been starved by the caller's gas limit (EIP-150) rather
    ///      than refused by the token: it counts as paused, so no caller can buy a paused stock by
    ///      sending too little gas.
    function _tokenSaysPaused(address token) internal view returns (bool) {
        bytes memory callData = abi.encodeWithSelector(ORACLE_PAUSED_SELECTOR);
        bool answered;
        uint256 word;
        assembly ("memory-safe") {
            answered := staticcall(GUARD_READ_GAS, token, add(callData, 0x20), mload(callData), 0x00, 0x20)
            answered := and(answered, gt(returndatasize(), 0x1f))
            word := mload(0x00)
        }
        if (answered) return word != 0;
        return gasleft() < GUARD_READ_GAS / 63;
    }
}

src/TreasuryVault.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

import {IStockRouter} from "./interfaces/IStockRouter.sol";
import {ICairnFactory} from "./interfaces/ICairnFactory.sol";
import {IAirdropDistributor} from "./interfaces/IAirdropDistributor.sol";
import {TreasuryOracle} from "./TreasuryOracle.sol";
import {SafeBalance} from "./libraries/SafeBalance.sol";
import {ReentrancyGuardTransient} from "./base/ReentrancyGuardTransient.sol";
import {EmergencyGuard} from "./crosschain/EmergencyGuard.sol";
import {UpgradeableModule} from "./base/UpgradeableModule.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {CairnLinks} from "./base/CairnLinks.sol";

/// @title TreasuryVault
/// @notice Holds a market's ETH, turns it into the tokenized stocks of its basket by way of USDC,
///         and hands the stocks to the airdrop, which distributes them to the token's holders
///         (`AirdropDistributor`, doc/DECISIONS.md, 2026-10-04). Assets leave only along that
///         rail, or through the factory owner's emergency recovery, which moves them at once
///         (`EmergencyGuard`, decision 20; immediate since 2026-10-05). The creator buyback that
///         used to sell stocks back down the rail was removed on 2026-09-27.
///
/// @dev Read the list of what this contract does NOT have, it is the point of the contract:
///        - no withdraw, transfer, rescue, sweep or migrate function, for ETH, USDC or stocks: no
///          normal function takes a destination address. The only outbound calls of the rail are
///          to the pinned stock router, the bridge hub and the factory's airdrop module, which
///          only ever credits this vault's market. The one function with a destination is the
///          owner's `emergencyTransfer`
///        - no owner of its own: the emergency admin is read live from the factory, and it can
///          only move assets out or pause; the keeper can only trigger a conversion
///        - no residual ERC-20 approval: every allowance is set to the exact size of one leg and
///          reset to zero in the same transaction, so the router can never reach what is already held
///        - no cached balances: every read hits `balanceOf`, so a rebasing stock stays correct
///
///      Conversion is two steps because there is no liquid ETH/stock pool: tokenized stocks trade
///      against stablecoins. `convertEthToUsdc` runs first, `convertUsdcToStocks` second, and the two
///      are separate transactions so a stock leg that cannot fill today leaves the USDC here instead
///      of undoing a first leg that worked.
///
///      Neither step trusts the keeper's numbers. For each leg the vault prices the trade against its
///      own Chainlink feed, derives its own minimum output, and rejects any keeper-supplied minimum
///      looser than that. The keeper therefore decides *when* to convert and may ask for something
///      stricter; it never chooses what is bought, where it goes, or at what price, and what it does
///      not convert stays here.
///
///      Amounts (security audit of 2026-09-29, M-4 and M-5): each step spends an amount the keeper
///      names, so a vault that has grown past what its venue fills within the bound converts in
///      slices instead of never. The USDC is set aside per basket leg as it arrives, at the basket's
///      weights, and each leg only ever spends its own reservation: a leg the keeper skips keeps it
///      for a later call, and the keeper cannot move USDC from one stock to another.
///
///      Upgradeable, market by market (doc/DECISIONS.md, 2026-10-02): each vault is its own ERC-1967
///      proxy, initialized in its constructor by the `VaultDeployer`, and the protocol owner
///      upgrades each one on its own, with immediate effect, alongside the emergency recovery
///      above. The implementation holds only the factory; everything a vault
///      is bound to (basket, market, router, oracle, cash token, bridge hub) is the proxy's state,
///      written once by `initialize`.
contract TreasuryVault is CairnLinks, ReentrancyGuardTransient, EmergencyGuard, UpgradeableModule {
    using SafeERC20 for IERC20;

    uint256 private constant BPS = 10_000;

    /// @notice `marketId` of a vault that belongs to no registered market (the $CAIRN vault).
    uint256 public constant NO_MARKET = type(uint256).max;

    /// @notice Factory of the protocol: source of the current keeper and of the protocol owner, who
    ///         upgrades this vault. Fixed in the implementation.
    ICairnFactory public immutable factory;

    /// @notice Basket this vault is bound to, forever.
    uint8 public basketId;
    /// @dev Read once at initialization so no later call depends on the token answering.
    uint8 public usdcDecimals;
    /// @notice DEX adapter used for both legs, pinned at initialization from the factory. No
    ///         function repoints it.
    IStockRouter public router;
    /// @notice Feed registry used to bound both legs, pinned the same way.
    TreasuryOracle public oracle;
    /// @notice Stablecoin the stock legs are settled in, taken from the router.
    IERC20 public usdc;
    /// @notice BridgeHub this vault hands its USDC to, pinned at initialization from the factory.
    ///         Zero on a vault of the local rail. Non-zero means the stocks are bought and held by
    ///         this market's mirror vault on Robinhood Chain: `convertUsdcToStocks` is disabled and
    ///         `releaseUsdcToBridge` takes its place. See docs/IMPLEMENTATION_DECISIONS.md, decision 18.
    address public bridgeHub;
    /// @notice Registry id of the market this vault belongs to, `NO_MARKET` for the protocol vault.
    uint256 public marketId;

    address[] private _stocks;
    uint16[] private _weightsBps;
    /// @dev USDC set aside for each basket leg, spent by that leg only. USDC beyond the sum is not
    ///      allocated yet: the next conversion splits it by weight (`_allocatedUsdc`).
    uint256[] private _reservedUsdc;
    /// @dev Sum of `_reservedUsdc`.
    uint256 private _reservedTotal;

    /// @notice Timestamp of the last successful stock purchase, 0 if none.
    uint64 public lastConversionAt;
    /// @notice Timestamp of the last successful ETH -> USDC leg, 0 if none.
    uint64 public lastEthConversionAt;
    /// @notice Cumulative ETH this vault has turned into USDC.
    uint256 public totalEthConverted;
    /// @notice Cumulative USDC this vault has turned into stocks.
    uint256 public totalUsdcConverted;
    /// @notice Cumulative USDC released to the bridge hub (bridge rail only).
    uint256 public totalUsdcBridged;
    /// @notice Timestamp of the last hand-over of stocks to the airdrop, 0 if none.
    uint64 public lastAirdropAt;

    event FundsReceived(address indexed from, uint256 amount);
    event EthConvertedToUsdc(uint256 ethSpent, uint256 usdcReceived, uint256 oracleBound);
    event TreasuryBuyExecuted(uint256 usdcSpent, address[] stocks, uint256[] amountsReceived);
    event LegSkipped(address indexed stock, uint256 usdcSlice);
    event UsdcReleasedToBridge(uint256 amount);
    event SentToAirdrop(address indexed distributor, address[] stocks, uint256[] amounts);
    /// @notice A purchase leg failed (a router or pool that reverts, a frozen stock, an output below
    ///         the minimum): it keeps its reservation, and the other legs ran (the founder's rule of
    ///         2026-10-05: one failure never blocks the rest).
    event LegFailed(address indexed stock, uint256 usdcSlice, bytes reason);
    /// @notice A stock could not be handed to the airdrop (an issuer freeze, say): it stays here,
    ///         and the other stocks went.
    event AirdropSendFailed(address indexed stock, uint256 amount, bytes reason);

    error NotKeeper();
    error BelowThreshold(uint256 amount, uint256 required);
    error AmountExceedsBalance(uint256 amount, uint256 balance);
    /// @notice A leg asked for more USDC than is set aside for its stock.
    error AmountExceedsReservation(address stock, uint256 amount, uint256 reserved);
    /// @notice An executed leg came without a minimum. Zero never means "accept any output".
    error ZeroMinimum(address stock);
    error WrongLengths();
    error NoUsdcToConvert();
    error NothingConverted();
    error OutputBelowMinimum(address asset, uint256 received, uint256 minOut);
    /// @notice The keeper asked the vault to accept less than the vault's own oracle-derived bound.
    error MinimumTooLoose(address asset, uint256 proposed, uint256 required);
    error DeadlinePassed();
    error RouterTookWrongAmount(address stock, uint256 slice);
    /// @notice The function belongs to the other rail: this vault bridges (or does not).
    error LocalRailDisabled();
    error BridgeRailDisabled();
    error NotBridgeHub();
    error NoAirdropDistributor();
    error NotABasketStock(address stock);
    error DuplicateStock(address stock);
    error NothingToSend();
    /// @notice The stock's `balanceOf` reverted or answered nothing (an issuer freeze, say).
    error BalanceUnreadable(address stock);
    /// @notice Only this vault runs one leg or one send on its own behalf.
    error NotSelf();

    /// @param factory_ The factory every vault of this implementation belongs to.
    constructor(ICairnFactory factory_) UpgradeableModule(address(factory_)) {
        factory = factory_;
    }

    /// @notice Binds the vault, once, inside its proxy's constructor: to a basket and a market, and
    ///         to the router, oracle and bridge hub the factory names at that moment.
    function initialize(uint8 basketId_, address[] calldata stocks_, uint16[] calldata weights_, uint256 marketId_)
        external
        initializer
    {
        basketId = basketId_;
        _stocks = stocks_;
        _weightsBps = weights_;
        _reservedUsdc = new uint256[](stocks_.length);
        marketId = marketId_;
        IStockRouter router_ = factory.treasuryRouter();
        router = router_;
        oracle = factory.treasuryOracle();
        bridgeHub = factory.bridgeHub();
        address usdc_ = router_.usdc();
        usdc = IERC20(usdc_);
        usdcDecimals = IERC20Metadata(usdc_).decimals();
    }

    /// @dev The factory owner, read live: an ownership transfer on the factory moves the emergency
    ///      powers of every vault at once.
    function _emergencyAdmin() internal view override returns (address) {
        return Ownable(address(factory)).owner();
    }

    /// @dev An executed emergency that takes the USDC below the reservations voids them, as
    ///      `_allocatedUsdc` reads them, and this saves it: every leg's reservation and the total
    ///      go to zero, so what is left, and whatever arrives next, is split afresh by weight.
    ///      Before, the old reservations came back as soon as the balance recovered, and the order
    ///      of the next calls decided the basket mix (security pipeline of 2026-10-01, R2T-2).
    function _emergencyTransfer(address asset, uint256 amount, address to) internal override {
        super._emergencyTransfer(asset, amount, to);
        if (asset == address(usdc) && usdc.balanceOf(address(this)) < _reservedTotal) {
            uint256 n = _reservedUsdc.length;
            for (uint256 i; i < n; ++i) {
                _reservedUsdc[i] = 0;
            }
            _reservedTotal = 0;
        }
    }

    /// @notice Accepts the treasury share of every trade and of what the locked positions collect,
    ///         and the creation fee when the team wallet refuses it.
    receive() external payable {
        emit FundsReceived(msg.sender, msg.value);
    }

    // -----------------------------------------------------------------------------------------------
    // Step one: ETH -> USDC
    // -----------------------------------------------------------------------------------------------

    /// @notice Swaps `ethAmount` of the vault's ETH for USDC.
    /// @dev Converting inside a trade would make that trade depend on stock-market liquidity, so this
    ///      is a separate keeper-triggered transaction. A trade must never fail because of the
    ///      treasury. The bound is computed on `ethAmount`, not on the live balance, so the ETH that
    ///      every trade adds while the transaction waits cannot invalidate the keeper's minimum
    ///      (security audit of 2026-09-29, L-2).
    /// @param ethAmount ETH to convert: at least `minConversion()`, at most the balance. The keeper
    ///        sizes it to what the venue fills within the bound; the rest waits for a later call.
    /// @param minUsdcOut Minimum USDC the keeper is willing to accept. Must be at least the vault's
    ///        own bound, derived here from the Chainlink ETH/USD feed.
    /// @param deadline Unix timestamp after which the call reverts.
    /// @return usdcOut USDC actually received.
    function convertEthToUsdc(uint256 ethAmount, uint256 minUsdcOut, uint256 deadline)
        external
        nonReentrant
        whenNotPaused
        returns (uint256 usdcOut)
    {
        if (msg.sender != factory.keeper()) revert NotKeeper();
        if (block.timestamp > deadline) revert DeadlinePassed();

        uint256 minimum = minConversion();
        if (ethAmount < minimum) revert BelowThreshold(ethAmount, minimum);
        uint256 balance = address(this).balance;
        if (ethAmount > balance) revert AmountExceedsBalance(ethAmount, balance);

        uint256 bound = minUsdcOutFor(ethAmount);
        if (minUsdcOut < bound) revert MinimumTooLoose(address(usdc), minUsdcOut, bound);

        // Measured on this vault's own balance, never taken from the router's return value: a
        // router that lied about its output would otherwise pass the bound while keeping the ETH.
        uint256 usdcBefore = usdc.balanceOf(address(this));
        router.swapExactEthForUsdc{value: ethAmount}(minUsdcOut, address(this), deadline, "");
        usdcOut = usdc.balanceOf(address(this)) - usdcBefore;
        // The keeper's minimum, at least the bound, holds on what actually arrived.
        if (usdcOut < minUsdcOut) revert OutputBelowMinimum(address(usdc), usdcOut, minUsdcOut);

        lastEthConversionAt = uint64(block.timestamp);
        totalEthConverted += ethAmount;
        emit EthConvertedToUsdc(ethAmount, usdcOut, bound);
    }

    // -----------------------------------------------------------------------------------------------
    // Step two: USDC -> stocks
    // -----------------------------------------------------------------------------------------------

    /// @notice Spends USDC on the basket, each leg out of its own reservation.
    /// @dev The USDC not reserved yet is first split by the basket's fixed weights. Each leg runs on
    ///      its own (`_runLegs`): a leg that cannot fill within the vault's oracle bound, or fails in
    ///      any other way, keeps its USDC reserved here and emits `LegFailed`, and the others spend
    ///      theirs; the call reverts only when no leg executes, with the first leg's reason. The
    ///      vault has no deadline of its own, because it never sells: waiting for a better window
    ///      costs it nothing.
    /// @param amountsIn One entry per basket leg: USDC to spend on that stock, at most its
    ///        reservation (`plannedStockSlices`). Zero skips the leg, which is how the keeper steps
    ///        over a stock frozen by its issuer or one whose feed has gone quiet; the leg keeps its
    ///        reservation for a later call. Less than the reservation spends a slice of it, for a
    ///        venue that cannot fill the whole of it within the bound.
    /// @param minAmountsOut One entry per basket leg, each at least the vault's own bound for that
    ///        leg's amount. An executed leg with a zero minimum reverts: zero is never read as
    ///        "accept any output".
    /// @param legData One entry per basket leg, handed to the router untouched. Empty for a pool
    ///        router, which ignores it. The vault never reads it: whatever the router does with it,
    ///        the leg's output is still measured on the vault's own balance and held to the oracle
    ///        bound.
    /// @param deadline Unix timestamp after which the call reverts.
    function convertUsdcToStocks(
        uint256[] calldata amountsIn,
        uint256[] calldata minAmountsOut,
        bytes[] calldata legData,
        uint256 deadline
    ) external nonReentrant whenNotPaused {
        if (msg.sender != factory.keeper()) revert NotKeeper();
        if (bridgeHub != address(0)) revert LocalRailDisabled();
        if (block.timestamp > deadline) revert DeadlinePassed();

        uint256 n = _stocks.length;
        if (amountsIn.length != n || minAmountsOut.length != n || legData.length != n) revert WrongLengths();

        (uint256[] memory reserved, uint256 balance) = _allocatedUsdc();
        if (balance == 0) revert NoUsdcToConvert();

        (uint256 spent, uint256[] memory received) = _runLegs(reserved, amountsIn, minAmountsOut, legData, deadline);

        // Each executed leg took exactly its amount (`_swapLeg`), so the reservations still add up
        // to the balance.
        _reservedUsdc = reserved;
        _reservedTotal = balance - spent;

        if (spent != 0) {
            lastConversionAt = uint64(block.timestamp);
            totalUsdcConverted += spent;
            emit TreasuryBuyExecuted(spent, _stocks, received);
        }
    }

    /// @dev Runs every leg with a non-zero amount, each on its own: one that fails keeps its
    ///      reservation (`LegFailed`) and the others run. Lowers `reserved` by what executed.
    function _runLegs(
        uint256[] memory reserved,
        uint256[] calldata amountsIn,
        uint256[] calldata minAmountsOut,
        bytes[] calldata legData,
        uint256 deadline
    ) private returns (uint256 spent, uint256[] memory received) {
        received = new uint256[](reserved.length);
        bytes memory failure;
        for (uint256 i; i < reserved.length; ++i) {
            if (amountsIn[i] == 0) {
                emit LegSkipped(_stocks[i], reserved[i]);
                continue;
            }
            if (amountsIn[i] > reserved[i]) revert AmountExceedsReservation(_stocks[i], amountsIn[i], reserved[i]);
            if (minAmountsOut[i] == 0) revert ZeroMinimum(_stocks[i]);
            try this.swapLegSelf(_stocks[i], amountsIn[i], minAmountsOut[i], deadline, legData[i]) returns (uint256 out) {
                received[i] = out;
                reserved[i] -= amountsIn[i];
                spent += amountsIn[i];
            } catch (bytes memory reason) {
                emit LegFailed(_stocks[i], amountsIn[i], reason);
                if (failure.length == 0) failure = reason;
            }
        }
        // Nothing executed: the call reverts with the first leg's reason, as one leg would, or
        // `NothingConverted` when no leg was asked for.
        if (spent == 0) {
            if (failure.length != 0) _bubble(failure);
            revert NothingConverted();
        }
    }

    /// @dev Reverts with `reason`, the revert data of a call that failed.
    function _bubble(bytes memory reason) private pure {
        assembly {
            revert(add(reason, 32), mload(reason))
        }
    }

    /// @notice One purchase leg, which only this vault calls on itself (`convertUsdcToStocks`), so
    ///         that a leg that fails is undone alone.
    function swapLegSelf(address stock, uint256 slice, uint256 minOut, uint256 deadline, bytes calldata data)
        external
        returns (uint256 out)
    {
        if (msg.sender != address(this)) revert NotSelf();
        out = _swapLeg(stock, slice, minOut, deadline, data);
    }

    /// @dev The reservations once the USDC beyond them has been split by weight, and the balance
    ///      they now add up to. Shared by the conversion and by `plannedStockSlices`, so the keeper
    ///      sizes its amounts off exactly the numbers the conversion uses. The weights' rounding
    ///      remainder goes to the last leg, as in `Fees.split`. A balance below the reservations,
    ///      which only an executed emergency can cause, voids them: what is left is split afresh.
    ///      The emergency saves that void (`_emergencyTransfer`), so the branch here is a fallback.
    function _allocatedUsdc() private view returns (uint256[] memory reserved, uint256 balance) {
        uint256 n = _stocks.length;
        balance = usdc.balanceOf(address(this));
        uint256 fresh;
        if (balance < _reservedTotal) {
            reserved = new uint256[](n);
            fresh = balance;
        } else {
            reserved = _reservedUsdc;
            fresh = balance - _reservedTotal;
        }
        if (fresh == 0) return (reserved, balance);
        uint256 allocated;
        for (uint256 i; i < n; ++i) {
            uint256 share = i == n - 1 ? fresh - allocated : (fresh * _weightsBps[i]) / BPS;
            reserved[i] += share;
            allocated += share;
        }
    }

    /// @dev One bounded leg. The bound is computed here, from this vault's own feed read, on the
    ///      leg's amount; the keeper's number is only ever allowed to be stricter. The allowance is
    ///      opened for exactly this leg and closed again before returning, so the router is never
    ///      standing approved against the USDC the vault is still holding.
    function _swapLeg(address stock, uint256 slice, uint256 minOut, uint256 deadline, bytes calldata data)
        private
        returns (uint256 out)
    {
        uint256 bound = minStockOutFor(stock, slice);
        if (minOut < bound) revert MinimumTooLoose(stock, minOut, bound);

        // Measured on the vault's own balances, so a router that misreports, or a stock that takes
        // a transfer fee, is caught by the keeper's minimum (at least the oracle bound) rather than
        // trusted.
        uint256 stockBefore = IERC20(stock).balanceOf(address(this));
        uint256 usdcBefore = usdc.balanceOf(address(this));
        usdc.forceApprove(address(router), slice);
        router.swapExactUsdcForStock(stock, slice, minOut, address(this), deadline, data);
        usdc.forceApprove(address(router), 0);
        if (usdcBefore - usdc.balanceOf(address(this)) != slice) revert RouterTookWrongAmount(stock, slice);
        out = IERC20(stock).balanceOf(address(this)) - stockBefore;
        if (out < minOut) revert OutputBelowMinimum(stock, out, minOut);
    }

    // -----------------------------------------------------------------------------------------------
    // Step three, local rail: stocks -> airdrop
    // -----------------------------------------------------------------------------------------------

    /// @notice Hands the whole balance of each listed basket stock to the airdrop, credited to this
    ///         vault's market for its current cycle.
    /// @dev Keeper only: it decides when, never how much or where. The destination is the
    ///      factory's airdrop module, read live, and the amount is the vault's whole balance of the
    ///      stock. Each allowance is sized to its stock's amount and closed again before returning.
    ///      On the bridge rail the stocks are on Robinhood Chain, held by the mirror vault, which
    ///      sends them itself.
    /// @param stocks Basket stocks to send, each at most once. A stock with no balance is skipped; one
    ///        whose balance cannot be read or whose transfer is refused (an issuer freeze) stays
    ///        here with `AirdropSendFailed`, and the others go.
    /// @return amounts Amount of each listed stock handed over.
    function sendToAirdrop(address[] calldata stocks)
        external
        nonReentrant
        whenNotPaused
        returns (uint256[] memory amounts)
    {
        if (msg.sender != factory.keeper()) revert NotKeeper();
        if (bridgeHub != address(0)) revert LocalRailDisabled();
        address distributor = factory.airdropDistributor();
        if (distributor == address(0)) revert NoAirdropDistributor();

        uint256 n = stocks.length;
        amounts = new uint256[](n);
        uint256 total;
        bytes memory failure;
        for (uint256 i; i < n; ++i) {
            address stock = stocks[i];
            if (!_isBasketStock(stock)) revert NotABasketStock(stock);
            for (uint256 j; j < i; ++j) {
                if (stocks[j] == stock) revert DuplicateStock(stock);
            }
            // Each stock on its own, its balance read included: one the issuer froze stays here and
            // the others go (review of 2026-10-05, loop 5).
            (bool readable, uint256 amount) = SafeBalance.balanceOf(stock, address(this));
            if (!readable) {
                bytes memory unreadable = abi.encodeWithSelector(BalanceUnreadable.selector, stock);
                emit AirdropSendFailed(stock, 0, unreadable);
                if (failure.length == 0) failure = unreadable;
                continue;
            }
            if (amount == 0) continue;
            try this.sendStockSelf(distributor, stock, amount) {
                amounts[i] = amount;
                total += amount;
            } catch (bytes memory reason) {
                emit AirdropSendFailed(stock, amount, reason);
                if (failure.length == 0) failure = reason;
            }
        }
        if (total == 0) {
            // Nothing went: say why, as a single stock would (the distributor paused, say).
            if (failure.length != 0) _bubble(failure);
            revert NothingToSend();
        }
        lastAirdropAt = uint64(block.timestamp);
        emit SentToAirdrop(distributor, stocks, amounts);
    }

    /// @notice One stock to the airdrop, which only this vault calls on itself (`sendToAirdrop`), so
    ///         that a stock that fails is undone alone, its allowance included.
    function sendStockSelf(address distributor, address stock, uint256 amount) external {
        if (msg.sender != address(this)) revert NotSelf();
        IERC20(stock).forceApprove(distributor, amount);
        address[] memory assets = new address[](1);
        uint256[] memory amounts = new uint256[](1);
        (assets[0], amounts[0]) = (stock, amount);
        IAirdropDistributor(distributor).depositFromVault(marketId, assets, amounts);
        IERC20(stock).forceApprove(distributor, 0);
    }

    function _isBasketStock(address stock) private view returns (bool) {
        uint256 n = _stocks.length;
        for (uint256 i; i < n; ++i) {
            if (_stocks[i] == stock) return true;
        }
        return false;
    }

    // -----------------------------------------------------------------------------------------------
    // Bridge rail: USDC -> bridge hub. One way only: nothing comes back to this vault.
    // -----------------------------------------------------------------------------------------------

    /// @notice Hands the USDC waiting for a conversion to the pinned bridge hub, which forwards it
    ///         to this market's mirror vault on Robinhood Chain.
    /// @dev Only the hub may call, and the hub is the only place the USDC can go: the hub is an
    ///      immutable of this vault and the mirror vault an immutable derivation of the market id on
    ///      the hub's side.
    /// @return amount USDC moved to the hub, zero when there was nothing to move (the hub decides
    ///         whether that is an error for the batch).
    function releaseUsdcToBridge() external nonReentrant whenNotPaused returns (uint256 amount) {
        amount = _releaseUsdcToBridge(type(uint256).max);
    }

    /// @notice `releaseUsdcToBridge` for at most `maxAmount`: the founder's rule of 2026-10-07
    ///         (decision 29), a treasury too large for the Curve pool's depth leaves in slices, the
    ///         rest waiting here for the next batches. Same caller, same destination, same pause.
    /// @return amount USDC moved to the hub: the smaller of `maxAmount` and what the vault holds.
    function releaseUsdcToBridgeUpTo(uint256 maxAmount) external nonReentrant whenNotPaused returns (uint256 amount) {
        amount = _releaseUsdcToBridge(maxAmount);
    }

    function _releaseUsdcToBridge(uint256 maxAmount) private returns (uint256 amount) {
        if (bridgeHub == address(0)) revert BridgeRailDisabled();
        if (msg.sender != bridgeHub) revert NotBridgeHub();
        amount = usdc.balanceOf(address(this));
        if (amount > maxAmount) amount = maxAmount;
        if (amount == 0) return 0;
        totalUsdcBridged += amount;
        usdc.safeTransfer(bridgeHub, amount);
        emit UsdcReleasedToBridge(amount);
    }

    // -----------------------------------------------------------------------------------------------
    // The bounds, exposed so anyone can check them without simulating a conversion.
    // -----------------------------------------------------------------------------------------------

    /// @notice Smallest ETH amount the first leg converts at once: the factory's setting, read live
    ///         (an owner setting since 2026-10-05; 0.1 ETH by default).
    function minConversion() public view returns (uint256) {
        return factory.minConversion();
    }

    /// @notice Worst execution accepted against the oracle on the ETH -> USDC leg, in basis points:
    ///         the factory's setting, read live (50 by default). Beyond it the vault reverts and
    ///         waits, which costs it nothing.
    function ethUsdcMaxSlippageBps() public view returns (uint256) {
        return factory.ethUsdcMaxSlippageBps();
    }

    /// @notice Worst execution accepted against the oracle on a USDC -> stock leg, in basis points:
    ///         the factory's setting, read live (200 by default).
    function stockMaxSlippageBps() public view returns (uint256) {
        return factory.stockMaxSlippageBps();
    }

    /// @notice Least USDC this vault will accept for `ethAmount`, from the Chainlink ETH/USD feed.
    /// @dev Reverts when the feed is stale or unusable, which is also the answer to "may the keeper
    ///      act right now".
    function minUsdcOutFor(uint256 ethAmount) public view returns (uint256) {
        (uint256 price, uint8 priceDecimals) = oracle.ethUsdPrice();
        uint256 expected = Math.mulDiv(ethAmount, price * (10 ** usdcDecimals), 1e18 * (10 ** priceDecimals));
        return (expected * (BPS - ethUsdcMaxSlippageBps())) / BPS;
    }

    /// @notice Least `stock` this vault will accept for `usdcIn`, from that stock's Chainlink feed.
    /// @dev Reverts when the feed is stale, unusable or unregistered.
    function minStockOutFor(address stock, uint256 usdcIn) public view returns (uint256) {
        (uint256 price, uint8 priceDecimals, uint8 assetDecimals) = oracle.stockPrice(stock);
        uint256 expected =
            Math.mulDiv(usdcIn, (10 ** priceDecimals) * (10 ** assetDecimals), (10 ** usdcDecimals) * price);
        return (expected * (BPS - stockMaxSlippageBps())) / BPS;
    }

    // -----------------------------------------------------------------------------------------------
    // Views. Read-only, used by the dapp and the keeper.
    // -----------------------------------------------------------------------------------------------

    /// @notice Basket composition of this vault.
    function basket() external view returns (address[] memory stocks, uint16[] memory weightsBps) {
        return (_stocks, _weightsBps);
    }

    function stockCount() external view returns (uint256) {
        return _stocks.length;
    }

    /// @notice USDC each leg may spend on the next `convertUsdcToStocks`: its reservation, plus its
    ///         weight's share of the USDC not reserved yet. The slices add up to the USDC balance.
    /// @dev Exposed so the keeper sizes its amounts and minimums off the same numbers the vault will
    ///      use, rather than off its own arithmetic.
    function plannedStockSlices() external view returns (address[] memory stocks, uint256[] memory slices) {
        stocks = _stocks;
        (slices,) = _allocatedUsdc();
    }

    /// @notice Live holdings, read from each token at call time. Nothing is ever cached.
    /// @return stocks Basket assets.
    /// @return balances Balance held per asset, 0 when the asset could not be read.
    /// @return readable False for an asset that could not be read: `balanceOf` reverted (e.g. frozen
    ///         by its issuer), or the address has no code on this chain (a bridge-rail basket id).
    function holdings()
        external
        view
        returns (address[] memory stocks, uint256[] memory balances, bool[] memory readable)
    {
        uint256 n = _stocks.length;
        stocks = _stocks;
        balances = new uint256[](n);
        readable = new bool[](n);
        for (uint256 i; i < n; ++i) {
            // A stock frozen, misbehaving or absent on this chain must not break the whole panel.
            (readable[i], balances[i]) = SafeBalance.balanceOf(stocks[i], address(this));
        }
    }

    /// @notice ETH sitting in the vault waiting for its first leg.
    function pendingEth() external view returns (uint256) {
        return address(this).balance;
    }

    /// @notice USDC sitting in the vault waiting for stock liquidity.
    /// @dev A non-zero value here is a normal resting state, not a stuck conversion.
    function pendingUsdc() external view returns (uint256) {
        return usdc.balanceOf(address(this));
    }

    /// @notice True when the vault's ETH balance is at least the conversion threshold
    ///         (`minConversion()`). With the threshold set to zero it is true at a zero balance
    ///         too, where the first leg has nothing to swap and reverts in the router.
    function convertible() external view returns (bool) {
        return address(this).balance >= minConversion();
    }

    /// @notice True when the vault holds USDC for the keeper to run the second leg on the local
    ///         rail. Always false on a bridge vault, whose USDC leaves through `releaseUsdcToBridge`.
    function stockConvertible() external view returns (bool) {
        return bridgeHub == address(0) && usdc.balanceOf(address(this)) > 0;
    }

    /// @notice USDC the bridge hub would take on the next release. Zero on a local-rail vault.
    function releasableUsdc() external view returns (uint256) {
        if (bridgeHub == address(0)) return 0;
        return usdc.balanceOf(address(this));
    }
}

src/base/CairnLinks.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @title CairnLinks
/// @notice Cairn.fun's official links, readable on every production contract.
/// @dev Pure functions only: no storage, so inheriting it never moves a module's storage layout.
abstract contract CairnLinks {
    /// @notice Cairn.fun on X.
    function twitter() external pure returns (string memory) {
        return "https://x.com/Cairnfun";
    }

    /// @notice Cairn.fun's website.
    function website() external pure returns (string memory) {
        return "https://cairnfun.com/";
    }

    /// @notice Cairn.fun's documentation.
    function docs() external pure returns (string memory) {
        return "https://gitbook.cairnfun.com/";
    }
}

src/base/ReentrancyGuardTransient.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @title ReentrancyGuardTransient
/// @notice Reentrancy guard using transient storage (EIP-1153).
/// @dev Cancun-only. Cheaper than a storage slot and automatically cleared at the end of the
///      transaction, which matters here because the guard wraps calls that hand control to
///      creator-supplied and trader-supplied addresses.
abstract contract ReentrancyGuardTransient {
    // A fixed transient slot of the guard, used by nothing else (the protocol's other transient
    // slots are the keccak256 of their names). Transient: no storage layout depends on it.
    bytes32 private constant SLOT = 0x9f6c3b7c8ad2e0a29a63f1a8f4a3f0e5cb1d7bbbf6e0d1c3b8a4e0f2d6c5b7a1;

    error Reentrancy();

    modifier nonReentrant() {
        _enter();
        _;
        _exit();
    }

    function _enter() private {
        bool entered;
        assembly ("memory-safe") {
            entered := tload(SLOT)
            tstore(SLOT, 1)
        }
        if (entered) revert Reentrancy();
    }

    function _exit() private {
        assembly ("memory-safe") {
            tstore(SLOT, 0)
        }
    }
}

src/base/Rescuable.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {UpgradeableModule} from "./UpgradeableModule.sol";
import {SafeSend} from "../libraries/SafeSend.sol";

/// @title Rescuable
/// @notice The recovery lever of a module that keeps nothing of anyone's between transactions (the
///         founder's rule of 2026-10-05: whatever is stuck can be moved out): the protocol owner,
///         who upgrades the module, moves out ETH or a token sent to it by mistake or left by a
///         failed operation.
/// @dev Gated on `_upgrader()`, so it follows the module's own authority: the factory's owner on
///      Ethereum, the RemoteHub's admin on Robinhood Chain, the owner on the factory itself. No
///      storage. A module that does keep funds for others between transactions bounds what may
///      leave in `_beforeRescue`; the modules with books of their own (the vaults, the hubs, the
///      airdrop) use `EmergencyGuard` instead.
abstract contract Rescuable is UpgradeableModule {
    using SafeERC20 for IERC20;

    event Rescued(address indexed asset, address indexed to, uint256 amount);

    error RescueToZeroAddress();

    /// @notice Moves `amount` of `asset` (the zero address for ETH) from this contract to `to`.
    ///         Protocol owner only.
    function rescue(address asset, uint256 amount, address to) external {
        if (msg.sender != _upgrader()) revert NotProtocolOwner();
        if (to == address(0)) revert RescueToZeroAddress();
        _beforeRescue(asset, amount);
        emit Rescued(asset, to, amount);
        if (asset == address(0)) SafeSend.sendAllGas(to, amount);
        else IERC20(asset).safeTransfer(to, amount);
    }

    /// @dev Reverts when `amount` of `asset` is not free to leave. Everything is, by default.
    function _beforeRescue(address asset, uint256 amount) internal virtual {}
}

src/base/UpgradeableModule.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";

import {IProtocolAuthority} from "../interfaces/IProtocolAuthority.sol";

/// @title UpgradeableModule
/// @notice Base of every upgradeable Cairn module (doc/DECISIONS.md, 2026-10-02): deployed behind
///         an ERC-1967 proxy and upgraded (UUPS) by the protocol owner, with immediate effect.
///
/// @dev Who may upgrade is asked live of `upgradeAuthority`, the factory on Ethereum and the
///      RemoteHub on Robinhood Chain, so an ownership transfer moves the upgrade power of every
///      module at once. The authority is an immutable of the implementation, and an upgrade must
///      keep it: a new implementation that named another authority is refused. The factory and the
///      RemoteHub are their own authority (zero here) and override `_upgrader`.
///
///      Configuration fixed for the life of an implementation (a PoolManager, a token address)
///      stays an immutable of that implementation; state lives in the proxy and is written by an
///      `initialize` that runs once, inside the proxy's constructor. Storage is laid out
///      sequentially, so an upgrade may only append state variables, never reorder or retype them
///      (snapshots in `storage-layouts/`, checked by `script/check-storage-layouts.sh`). The
///      implementation itself can never be initialized.
abstract contract UpgradeableModule is Initializable, UUPSUpgradeable {
    /// @notice The contract whose `protocolOwner()` may upgrade this module. Zero on the factory and
    ///         the RemoteHub, which answer that question themselves.
    address public immutable upgradeAuthority;

    /// @dev The implementation contract's own address, and who deployed it. The implementation is
    ///      never used directly and its storage never initialized, so a module that keeps its admin
    ///      in storage has none there anybody holds (the RemoteHub's admin reads zero; the
    ///      factory's owner is the dead address its constructor sets): its deployer is the lever for
    ///      whatever is sent to the implementation's address by mistake (the founder's rule of
    ///      2026-10-05; review of 2026-10-05, loop 5). Never used by a proxy.
    address private immutable _self;
    address internal immutable implementationDeployer;

    error NotProtocolOwner();
    /// @notice An upgrade must keep the authority that decides the next one.
    error UpgradeAuthorityChanged(address expected, address actual);

    constructor(address upgradeAuthority_) {
        upgradeAuthority = upgradeAuthority_;
        _self = address(this);
        implementationDeployer = msg.sender;
        _disableInitializers();
    }

    /// @dev True when this code runs as the implementation contract itself, not behind a proxy.
    function _onImplementation() internal view returns (bool) {
        return address(this) == _self;
    }

    /// @dev The address allowed to upgrade this module: the protocol owner.
    function _upgrader() internal view virtual returns (address) {
        return IProtocolAuthority(upgradeAuthority).protocolOwner();
    }

    function _authorizeUpgrade(address newImplementation) internal view virtual override {
        if (msg.sender != _upgrader()) revert NotProtocolOwner();
        address next = UpgradeableModule(newImplementation).upgradeAuthority();
        if (next != upgradeAuthority) revert UpgradeAuthorityChanged(upgradeAuthority, next);
        _checkUpgrade(newImplementation);
    }

    /// @dev Hook for a module whose next implementation must keep something more (a PoolManager,
    ///      say). Does nothing by default.
    function _checkUpgrade(address newImplementation) internal view virtual {}
}

src/crosschain/EmergencyGuard.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

/// @title EmergencyGuard
/// @notice Owner emergency recovery, shared by the contracts that hold the protocol's assets:
///         `TreasuryVault`, `BridgeHub` and `AirdropDistributor` on Ethereum, `RemoteHub` and
///         `RemoteTreasuryVault` on Robinhood Chain. See docs/IMPLEMENTATION_DECISIONS.md, decision
///         20, and doc/DECISIONS.md, amendment of 2026-10-05.
///
/// @dev Two powers, both held by the emergency admin (the factory owner on Ethereum, the same
///      address mirrored through every bridge message on Robinhood Chain), and nothing else:
///
///        - an immediate transfer: `emergencyTransfer(asset, amount, to)` moves `amount` of
///          `asset` to `to` at once, without notice or delay (2026-10-05: the 48-hour schedule of
///          2026-08-29 is gone). Each transfer is logged with a sequential id.
///        - an immediate pause: `pause()` / `unpause()` stop the rail (conversions, bridging,
///          remote purchases, the airdrop's deposits) without moving anything.
///
///      Every other rule of the rail is untouched: the normal paths still have no destination
///      parameter, the keeper still only tightens bounds, the routers still hold nothing.
abstract contract EmergencyGuard {
    using SafeERC20 for IERC20;

    /// @notice Number of emergency transfers run so far: the id of the next one.
    uint256 public emergencyCount;
    bool public paused;

    event EmergencyExecuted(uint256 indexed id, address indexed asset, uint256 amount, address indexed to);
    event RailPaused(address indexed by);
    event RailUnpaused(address indexed by);

    error NotEmergencyAdmin();
    error Paused();
    error ZeroEmergency();
    error EmergencyTransferFailed();

    modifier onlyEmergencyAdmin() {
        if (msg.sender != _emergencyAdmin()) revert NotEmergencyAdmin();
        _;
    }

    modifier whenNotPaused() {
        if (paused) revert Paused();
        _;
    }

    /// @notice Address allowed to move assets out and to pause. Read live: on Ethereum the factory
    ///         owner, on Robinhood Chain the owner the last bridge message carried.
    function emergencyAdmin() external view returns (address) {
        return _emergencyAdmin();
    }

    function _emergencyAdmin() internal view virtual returns (address);

    /// @notice Moves `amount` of `asset` (`address(0)` for ETH) from this contract to `to`, at once.
    /// @return id Sequential id of the transfer, in `EmergencyExecuted`.
    function emergencyTransfer(address asset, uint256 amount, address to)
        external
        onlyEmergencyAdmin
        returns (uint256 id)
    {
        id = _executeEmergency(asset, amount, to);
    }

    /// @dev One emergency transfer, counted and logged: what `emergencyTransfer` runs, and what an
    ///      inheritor's variant that also settles its books runs after settling them.
    function _executeEmergency(address asset, uint256 amount, address to) internal returns (uint256 id) {
        if (amount == 0 || to == address(0)) revert ZeroEmergency();
        id = emergencyCount++;
        _emergencyTransfer(asset, amount, to);
        emit EmergencyExecuted(id, asset, amount, to);
    }

    /// @notice Stops the rail immediately. Moves nothing.
    function pause() external onlyEmergencyAdmin {
        paused = true;
        emit RailPaused(msg.sender);
    }

    function unpause() external onlyEmergencyAdmin {
        paused = false;
        emit RailUnpaused(msg.sender);
    }

    /// @dev Exactly `amount` of `asset` from this contract to `to`; ETH by a plain call.
    function _emergencyTransfer(address asset, uint256 amount, address to) internal virtual {
        if (asset == address(0)) {
            (bool ok,) = to.call{value: amount}("");
            if (!ok) revert EmergencyTransferFailed();
            return;
        }
        IERC20(asset).safeTransfer(to, amount);
    }
}

src/crosschain/HubAdapterBase.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

import {IHubAdapter} from "./interfaces/IHubAdapter.sol";
import {BridgeMessage} from "./libraries/BridgeMessage.sol";
import {ICairnFactory} from "../interfaces/ICairnFactory.sol";
import {TreasuryVault} from "../TreasuryVault.sol";
import {UpgradeableModule} from "../base/UpgradeableModule.sol";
import {Rescuable} from "../base/Rescuable.sol";

/// @dev What an adapter reads back from its hub: the append-only stock table (see
///      BridgeHub.addStockMapping) and the batch counter the hub increments before every send.
interface IHubReads {
    function remoteStockOf(address ethereumStock) external view returns (address);
    function batchSequence() external view returns (uint64);
}

/// @title HubAdapterBase
/// @notice What every adapter of the BridgeHub shares: the hub it answers to, the factory it reads
///         markets from, the batch it builds for the remote hub (keeper, emergency admin, per-market
///         split, basket translated through the hub's stock table), the checks on the split and
///         the transient record of the send identifier.
///
/// @dev The transport (OFT or canonical bridge) is the subclass's business; nothing here moves a
///      token but the protocol owner's `rescue` (`Rescuable`, the founder's rule of 2026-10-05). An
///      adapter keeps nothing between transactions, so whatever it holds then is a stray: sent by
///      mistake, or left by a hub that refused a fee refund. Deployed against the hub's proxy, which names it once (`BridgeHub.setAdapter`) and
///      afterwards replaces it only by an adapter with the same pins (`BridgeHub.changeAdapter`,
///      decision 20). Upgradeable by the protocol
///      owner like every module (doc/DECISIONS.md, 2026-10-02): the hub, the factory and the
///      transport's counterparties are immutables of the implementation.
abstract contract HubAdapterBase is IHubAdapter, Rescuable {
    uint256 internal constant BPS = 10_000;

    address public immutable hub;
    ICairnFactory public immutable factory;

    /// @dev Transient slot holding the identifier of the send made in this transaction, for the hub
    ///      to read back in the same call (`bridge` returns only the amount, per IBridgeAdapter).
    bytes32 private constant LAST_GUID_SLOT = keccak256("cairn.HubAdapter.lastGuid");

    error NotHub();
    error ZeroAddress();
    error WrongLengths();
    error AmountMismatch(uint256 sum, uint256 usdcAmount);
    error MinimumTooLoose(uint256 proposed, uint256 required);
    error OutputBelowMinimum(uint256 received, uint256 minOut);
    error UnmappedStock(address stock);
    error UnknownMarket(uint256 marketId);

    constructor(address factory_, address hub_) UpgradeableModule(factory_) {
        if (factory_ == address(0) || hub_ == address(0)) revert ZeroAddress();
        factory = ICairnFactory(factory_);
        hub = hub_;
    }

    modifier onlyHub() {
        if (msg.sender != hub) revert NotHub();
        _;
    }

    /// @inheritdoc IHubAdapter
    function lastGuid() external view returns (bytes32 guid) {
        bytes32 slot = LAST_GUID_SLOT;
        assembly ("memory-safe") {
            guid := tload(slot)
        }
    }

    function _recordGuid(bytes32 guid) internal {
        bytes32 slot = LAST_GUID_SLOT;
        assembly ("memory-safe") {
            tstore(slot, guid)
        }
    }

    /// @inheritdoc IHubAdapter
    function vaultOf(uint256 marketId) public view returns (address vault) {
        if (marketId == type(uint256).max) return factory.protocolVault();
        vault = factory.getMarket(marketId).vault;
        if (vault == address(0)) revert UnknownMarket(marketId);
    }

    /// @inheritdoc IHubAdapter
    function initFor(uint256 marketId) external view returns (BridgeMessage.MarketInit memory) {
        return _initFor(marketId);
    }

    function _initFor(uint256 marketId) internal view returns (BridgeMessage.MarketInit memory init) {
        address vault = vaultOf(marketId);
        if (vault == address(0)) revert UnknownMarket(marketId);
        (address[] memory stocks, uint16[] memory weights) = TreasuryVault(payable(vault)).basket();
        address[] memory remote = new address[](stocks.length);
        for (uint256 i; i < stocks.length; ++i) {
            remote[i] = IHubReads(hub).remoteStockOf(stocks[i]);
            if (remote[i] == address(0)) revert UnmappedStock(stocks[i]);
        }
        init = BridgeMessage.MarketInit({stocks: remote, weightsBps: weights});
    }

    /// @dev The batch the remote hub distributes: current keeper and factory owner, the hub's batch
    ///      sequence (incremented by the hub before this call), the markets, their remote-side
    ///      amounts and their inits.
    function _batchFor(uint256[] calldata marketIds, uint256[] memory amounts) internal view returns (bytes memory) {
        uint256 n = marketIds.length;
        BridgeMessage.MarketInit[] memory inits = new BridgeMessage.MarketInit[](n);
        for (uint256 i; i < n; ++i) {
            inits[i] = _initFor(marketIds[i]);
        }
        return BridgeMessage.encodeBatch(
            BridgeMessage.Batch({
                keeper: factory.keeper(),
                emergencyAdmin: Ownable(address(factory)).owner(),
                sequence: IHubReads(hub).batchSequence(),
                marketIds: marketIds,
                amounts: amounts,
                inits: inits
            })
        );
    }

    /// @dev The payload `bridge` would send for `marketIds` right now (each vault's releasable USDC
    ///      as its amount), and its total, for a fee quote on the real batch shape.
    function _quotePayload(uint256[] calldata marketIds) internal view returns (bytes memory payload, uint256 total) {
        uint256 n = marketIds.length;
        uint256[] memory amounts = new uint256[](n);
        for (uint256 i; i < n; ++i) {
            amounts[i] = TreasuryVault(payable(vaultOf(marketIds[i]))).releasableUsdc();
            total += amounts[i];
        }
        payload = _batchFor(marketIds, amounts);
    }

    function _checkBatch(uint256 usdcAmount, uint256 n, uint256[] calldata amounts) internal pure {
        if (n == 0 || amounts.length != n) revert WrongLengths();
        uint256 sum;
        for (uint256 i; i < n; ++i) {
            sum += amounts[i];
        }
        if (sum != usdcAmount) revert AmountMismatch(sum, usdcAmount);
    }

    /// @dev Rescales the USDC split to the amount that leaves; the rounding remainder goes to the
    ///      last entry so the parts always sum to the whole.
    function _rescale(uint256[] calldata amounts, uint256 usdcAmount, uint256 sent)
        internal
        pure
        returns (uint256[] memory out)
    {
        uint256 n = amounts.length;
        out = new uint256[](n);
        uint256 assigned;
        for (uint256 i; i < n - 1; ++i) {
            out[i] = (amounts[i] * sent) / usdcAmount;
            assigned += out[i];
        }
        out[n - 1] = sent - assigned;
    }

    /// @dev A batch of a representative shape, for fee quotes that depend on the payload size.
    function _representativeBatch() internal pure returns (bytes memory) {
        BridgeMessage.MarketInit[] memory inits = new BridgeMessage.MarketInit[](1);
        inits[0] = BridgeMessage.MarketInit({stocks: new address[](5), weightsBps: new uint16[](5)});
        return BridgeMessage.encodeBatch(
            BridgeMessage.Batch({
                keeper: address(0),
                emergencyAdmin: address(0),
                sequence: 0,
                marketIds: new uint256[](1),
                amounts: new uint256[](1),
                inits: inits
            })
        );
    }
}

src/crosschain/interfaces/IBridgeAdapter.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @title IBridgeAdapter
/// @notice The one call the Ethereum BridgeHub makes to move USDC to the mirror vaults on Robinhood
///         Chain: USDC in, USDG out on the other side, split per market.
///
/// @dev The adapter has no recipient parameter. Where the funds land is an immutable of the adapter
///      (the remote hub), and how they are split is a list of market ids the remote hub turns into
///      addresses by itself. Nothing the caller passes can direct a single unit anywhere else.
interface IBridgeAdapter {
    /// @param usdcAmount USDC the caller transferred to the adapter before the call, equal to the
    ///        sum of `amounts`.
    /// @param marketIds Markets the funds belong to, one per entry of `amounts`.
    /// @param amounts USDC per market. The adapter converts the total and rescales the split so the
    ///        per-market USDG amounts sum to exactly what was sent.
    /// @param minUsdgOut Least USDG the caller accepts for the whole batch; the adapter also applies
    ///        its own minimum and takes the stricter of the two.
    /// @return usdgSent USDG that left this chain for the remote hub.
    function bridge(uint256 usdcAmount, uint256[] calldata marketIds, uint256[] calldata amounts, uint256 minUsdgOut)
        external
        payable
        returns (uint256 usdgSent);

    /// @notice Native fee the messaging layer asks for a send of `usdgAmount` with this adapter's
    ///         options, quoted on a payload of a representative shape (one market, five stocks).
    ///         An estimate: `quoteBridgeFor` quotes the real batch.
    function quoteBridge(uint256 usdgAmount) external view returns (uint256 nativeFee);

    /// @notice Native fee for bridging exactly `marketIds` as `bridge` would send them: the payload
    ///         is built for these markets (their current releasable USDC, baskets and creator), so a
    ///         per-byte fee component is covered. The keeper reads it before `BridgeHub.bridgeReady`
    ///         and forwards it as `msg.value`.
    function quoteBridgeFor(uint256[] calldata marketIds) external view returns (uint256 nativeFee);

    /// @notice `quoteBridgeFor` at the Ethereum base fee `baseFee`, for a caller off chain: a call
    ///         made without a gas price runs at a zero base fee on most nodes, which a fee priced on
    ///         the base fee would read as free. A rail whose fee does not depend on it ignores it.
    function quoteBridgeAt(uint256[] calldata marketIds, uint256 baseFee) external view returns (uint256 nativeFee);
}

src/crosschain/interfaces/ICurveStableSwap.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @notice The functions the bridge uses on a Curve stableswap-NG pool (USDG/USDC on Ethereum).
/// @dev `exchange_received` swaps `dx` of coin `i` that the caller transferred to the pool in the
///      same transaction (the pool measures its balance against its stored one), so no allowance is
///      needed; ~30k gas cheaper than approve + `exchange` on the live pool. Not available for
///      rebasing coins, which USDG and USDC are not.
interface ICurveStableSwap {
    function coins(uint256 i) external view returns (address);
    function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256);
    function exchange(int128 i, int128 j, uint256 dx, uint256 minDy) external returns (uint256);
    function exchange_received(int128 i, int128 j, uint256 dx, uint256 minDy) external returns (uint256);
}

src/crosschain/interfaces/IHubAdapter.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import {IBridgeAdapter} from "./IBridgeAdapter.sol";
import {BridgeMessage} from "../libraries/BridgeMessage.sol";

/// @title IHubAdapter
/// @notice Everything the BridgeHub reads from its adapter besides `IBridgeAdapter.bridge`: the
///         pinned counterparties it checks before accepting a replacement, the vault lookup it
///         shares, the batch-local send identifier and the rate bound.
///
/// @dev Two implementations: `UsdgOftAdapter` (USDC -> USDG on Curve -> Paxos OFT, mainnet) and
///      `ArbitrumCanonicalAdapter` (the Orbit chain's canonical token bridge plus a retryable
///      ticket, testnet and fallback). The hub is written against this interface only.
interface IHubAdapter is IBridgeAdapter {
    /// @notice Everything that decides where a batch goes, as the hub pins it: a replacement
    ///         adapter must answer exactly what the current one answers (`BridgeHub.changeAdapter`),
    ///         so a change can only ever alter gas figures, options or, on the OFT rail, the Curve
    ///         pool.
    struct Pins {
        address hub;
        address factory;
        address usdc;
        address usdg;
        /// @notice The remote hub, as bytes32 on both rails.
        bytes32 remoteHub;
        /// @notice Destination endpoint id on the OFT rail, zero on the canonical rail.
        uint32 remoteEid;
        /// @notice The transport: the OFT, or the canonical bridge's Inbox.
        address bridge;
        /// @notice Canonical rail: the parent-chain gateway router the token is escrowed through.
        ///         Zero on the OFT rail.
        address gatewayRouter;
    }

    /// @notice The pinned counterparties of this adapter, see `Pins`.
    function pins() external view returns (Pins memory);
    /// @notice The BridgeHub this adapter serves.
    function hub() external view returns (address);
    /// @notice The token the hub hands to `bridge`.
    function usdc() external view returns (IERC20);
    /// @notice The token that arrives on the remote chain (USDG on the OFT rail, the bridged
    ///         stable itself on the canonical rail).
    function usdg() external view returns (IERC20);
    /// @notice The vault of `marketId` as the hub resolves it: the protocol vault for `NO_MARKET`.
    function vaultOf(uint256 marketId) external view returns (address);
    /// @notice Least remote-side amount this adapter accepts for `usdcIn`.
    function minUsdgOutFor(uint256 usdcIn) external view returns (uint256);
    /// @notice Identifier of the send made by `bridge` in the current transaction, zero otherwise.
    function lastGuid() external view returns (bytes32);
    /// @notice Basket of `marketId` as the remote hub will pin it.
    function initFor(uint256 marketId) external view returns (BridgeMessage.MarketInit memory);
}

src/crosschain/interfaces/ILayerZero.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @notice The subset of LayerZero v2 / OFT the bridge contracts speak. Copied from
///         `@layerzerolabs/oft-evm` and `@layerzerolabs/lz-evm-protocol-v2` rather than imported, so
///         the repo carries no LayerZero dependency for a handful of structs.

/// @dev `IOFT.SendParam`: where and how much. `to` is a bytes32 so non-EVM chains fit.
struct SendParam {
    uint32 dstEid;
    bytes32 to;
    uint256 amountLD;
    uint256 minAmountLD;
    bytes extraOptions;
    bytes composeMsg;
    bytes oftCmd;
}

struct MessagingFee {
    uint256 nativeFee;
    uint256 lzTokenFee;
}

struct MessagingReceipt {
    bytes32 guid;
    uint64 nonce;
    MessagingFee fee;
}

struct OFTReceipt {
    uint256 amountSentLD;
    uint256 amountReceivedLD;
}

struct OFTLimit {
    uint256 minAmountLD;
    uint256 maxAmountLD;
}

struct OFTFeeDetail {
    int256 feeAmountLD;
    string description;
}

interface IOFT {
    function token() external view returns (address);
    function approvalRequired() external view returns (bool);
    function quoteSend(SendParam calldata sendParam, bool payInLzToken) external view returns (MessagingFee memory);
    function quoteOFT(SendParam calldata sendParam)
        external
        view
        returns (OFTLimit memory, OFTFeeDetail[] memory, OFTReceipt memory);
    function send(SendParam calldata sendParam, MessagingFee calldata fee, address refundAddress)
        external
        payable
        returns (MessagingReceipt memory, OFTReceipt memory);
    function endpoint() external view returns (address);
}

/// @dev What the endpoint calls on the recipient of an OFT transfer that carried a `composeMsg`.
///      `_message` is `OFTComposeMsgCodec`-encoded, see `LzCodec`.
interface ILayerZeroComposer {
    function lzCompose(address from, bytes32 guid, bytes calldata message, address executor, bytes calldata extraData)
        external
        payable;
}

src/crosschain/libraries/BridgeMessage.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @title BridgeMessage
/// @notice The payload the Ethereum hub sends to the Robinhood Chain hub.
///
/// @dev One direction only (Ethereum -> Robinhood Chain): a `Batch`. The return path that carried a
///      creator buyback back to Ethereum was removed with the buyback on 2026-09-27. Every entry
///      carries its market's basket, not only the first one: the remote hub pins it the first time
///      it sees a market and ignores it afterwards, so a batch can be delivered in any order and the
///      same market can be in several in-flight messages without the remote side having to remember
///      what Ethereum told it earlier. The keeper address rides along so the Ethereum factory
///      owner's keeper rotation reaches the remote vaults through the same trusted channel, with no
///      owner on the remote chain; the emergency admin (the factory owner itself, decision 20) rides
///      along the same way, so the remote contracts' emergency powers follow an ownership transfer
///      on Ethereum with the next batch. Both roles are ordered by `sequence`, a counter the
///      Ethereum hub increments for every batch on either rail: the remote hub applies the roles
///      of a batch only if its sequence is above the last one it applied, so a message delivered
///      (or re-executed) late can never roll a rotation back, while its funds are still
///      distributed.
library BridgeMessage {
    struct MarketInit {
        /// @notice Robinhood Chain addresses of the basket's stocks, in basket order.
        address[] stocks;
        uint16[] weightsBps;
    }

    struct Batch {
        address keeper;
        /// @notice Factory owner on Ethereum at send time, the remote contracts' emergency admin.
        address emergencyAdmin;
        /// @notice Position of this batch in the Ethereum hub's send order (`BridgeHub.batchSequence`,
        ///         from 1). The remote hub applies `keeper` / `emergencyAdmin` only from a batch whose
        ///         sequence is above the last applied one.
        uint64 sequence;
        uint256[] marketIds;
        /// @notice USDG per market, summing exactly to the transfer's `amountLD`.
        uint256[] amounts;
        MarketInit[] inits;
    }

    function encodeBatch(Batch memory batch) internal pure returns (bytes memory) {
        return abi.encode(batch);
    }

    function decodeBatch(bytes calldata data) internal pure returns (Batch memory) {
        return abi.decode(data, (Batch));
    }
}

src/crosschain/libraries/LzCodec.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @title LzCodec
/// @notice Decoding of the compose message an OFT hands to `lzCompose`, and the encoding of the
///         executor options a send needs to pay for that compose (and, on the airdrop sends, for
///         the delivery's `lzReceive`).
///
/// @dev Layout of `OFTComposeMsgCodec` (LayerZero v2 oft-evm):
///        [0:8]    nonce      uint64
///        [8:12]   srcEid     uint32
///        [12:44]  amountLD   uint256
///        [44:76]  composeFrom bytes32, the `msg.sender` of `send()` on the source chain
///        [76:]    composeMsg the bytes the sender passed
///      The two hubs check `srcEid` and `composeFrom` against immutables before reading anything
///      else: the sender identity is what makes a message trustworthy, not its content.
library LzCodec {
    uint256 private constant COMPOSE_MSG_OFFSET = 76;

    /// @dev Executor worker id and option types, per `ExecutorOptions`.
    uint8 private constant WORKER_ID_EXECUTOR = 1;
    uint8 private constant OPTION_TYPE_LZRECEIVE = 1;
    uint8 private constant OPTION_TYPE_LZCOMPOSE = 3;
    uint16 private constant OPTIONS_TYPE_3 = 3;

    error ComposeMessageTooShort(uint256 length);

    function srcEid(bytes calldata message) internal pure returns (uint32) {
        if (message.length < COMPOSE_MSG_OFFSET) revert ComposeMessageTooShort(message.length);
        return uint32(bytes4(message[8:12]));
    }

    function amountLD(bytes calldata message) internal pure returns (uint256) {
        if (message.length < COMPOSE_MSG_OFFSET) revert ComposeMessageTooShort(message.length);
        return uint256(bytes32(message[12:44]));
    }

    function composeFrom(bytes calldata message) internal pure returns (bytes32) {
        if (message.length < COMPOSE_MSG_OFFSET) revert ComposeMessageTooShort(message.length);
        return bytes32(message[44:76]);
    }

    function composeMsg(bytes calldata message) internal pure returns (bytes calldata) {
        if (message.length < COMPOSE_MSG_OFFSET) revert ComposeMessageTooShort(message.length);
        return message[COMPOSE_MSG_OFFSET:];
    }

    /// @notice Encodes a compose message exactly as the OFT would. Used by the mock OFT in tests.
    function encodeCompose(uint64 nonce, uint32 srcEid_, uint256 amountLD_, bytes32 composeFrom_, bytes memory msg_)
        internal
        pure
        returns (bytes memory)
    {
        return abi.encodePacked(nonce, srcEid_, amountLD_, composeFrom_, msg_);
    }

    function addressToBytes32(address a) internal pure returns (bytes32) {
        return bytes32(uint256(uint160(a)));
    }

    function bytes32ToAddress(bytes32 b) internal pure returns (address) {
        return address(uint160(uint256(b)));
    }

    /// @notice Type-3 executor options asking the destination executor to run `lzCompose` at index
    ///         0 with `gas`. Combined by the OFT with its enforced `lzReceive` options; without it
    ///         the executor would deliver the tokens and skip the compose for lack of gas.
    function composeOptions(uint128 gas) internal pure returns (bytes memory) {
        // option = type(1) ++ index(2) ++ gas(16); worker header = workerId(1) ++ size(2)
        bytes memory option = abi.encodePacked(OPTION_TYPE_LZCOMPOSE, uint16(0), gas);
        return abi.encodePacked(OPTIONS_TYPE_3, WORKER_ID_EXECUTOR, uint16(option.length), option);
    }

    /// @notice Type-3 executor options asking the destination executor for `receiveGas` on
    ///         `lzReceive` and `composeGas` on `lzCompose` at index 0, as LayerZero's
    ///         `OptionsBuilder.newOptions().addExecutorLzReceiveOption(receiveGas, 0)
    ///         .addExecutorLzComposeOption(0, composeGas, 0)` encodes them.
    /// @dev The OFT appends them to its enforced options (`OAppOptionsType3.combineOptions`: the
    ///      enforced bytes, then these without their two-byte type), and LayerZero's executor adds up
    ///      every `lzReceive` option it is given (`ExecutorFeeLib._parseExecutorOptions`:
    ///      `lzReceiveGas += gas`; `OptionsBuilder.addExecutorLzReceiveOption`: "summed by the
    ///      executor"): the delivery gets `receiveGas` on top of what the OFT's owner enforces, and
    ///      a send whose OFT enforces nothing still carries an `lzReceive` option, without which the
    ///      executor refuses to quote it (`Executor_ZeroLzReceiveGasProvided`). Added for the airdrop
    ///      sends (2026-10-06, Glamsterdam repricing, L9-T6): an issuer's enforced gas sized for the
    ///      old prices left every delivery short at the executor.
    function receiveAndComposeOptions(uint128 receiveGas, uint128 composeGas) internal pure returns (bytes memory) {
        // Each option = workerId(1) ++ size(2) ++ type(1) ++ body, size counting the type:
        // lzReceive body = gas(16), size 17; lzCompose body = index(2) ++ gas(16), size 19.
        return abi.encodePacked(
            OPTIONS_TYPE_3,
            WORKER_ID_EXECUTOR,
            uint16(17),
            OPTION_TYPE_LZRECEIVE,
            receiveGas,
            WORKER_ID_EXECUTOR,
            uint16(19),
            OPTION_TYPE_LZCOMPOSE,
            uint16(0),
            composeGas
        );
    }
}

src/interfaces/AggregatorV3Interface.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @title AggregatorV3Interface
/// @notice The subset of the Chainlink price feed interface this protocol reads.
/// @dev Declared here rather than pulled in as a submodule: these four signatures have been stable
///      across every Chainlink feed generation, and the protocol needs nothing else from them.
///      `answer` is signed because the interface is shared with feeds that can go negative; a price
///      feed never should, and every reader here treats a non-positive answer as unusable.
interface AggregatorV3Interface {
    function decimals() external view returns (uint8);

    function description() external view returns (string memory);

    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

src/interfaces/IAirdropDistributor.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @title IAirdropDistributor
/// @notice What the treasury vaults and the dapp call on the airdrop: the stocks a market's treasury
///         bought, distributed to the market token's holders by cycle (`AirdropDistributor`).
interface IAirdropDistributor {
    /// @notice Hands the distributor stocks a market's vault on Ethereum bought (local rail). The
    ///         distributor pulls each amount, so the vault approves it first, and credits what it
    ///         actually received to the market's current cycle.
    /// @dev Only the vault the factory registers for `marketId` may call; `type(uint256).max` names
    ///      the $CAIRN market. A zero amount is skipped.
    function depositFromVault(uint256 marketId, address[] calldata assets, uint256[] calldata amounts) external;

    /// @notice Opens the cycle the market's next deposits will land in, so each of them only adds to
    ///         it. Callable by anyone; reverts when the window has no eligible holding.
    function openCycle(uint256 marketId) external returns (uint256 cycleEnd);

    /// @notice Moves what the market holds aside into the first window, after the last one found
    ///         without eligible holdings, that has some. Callable by anyone; zero when the windows
    ///         checked had none, the next call going on from there.
    function assignUnassigned(uint256 marketId) external returns (uint256 cycleEnd);

    /// @notice Pays the caller their due in `assets` (every asset of the cycle when empty) for one
    ///         cycle of one market. An asset the books are short of, or whose transfer is refused,
    ///         is deferred (`ClaimDeferred`) and stays due. Reverts when nothing is paid: nothing
    ///         due, or everything due deferred (`Underfunded`, `TransferRefused`).
    function claim(uint256 marketId, uint256 cycleEnd, address[] calldata assets) external;

    /// @notice Pays the caller their due in every asset of each listed cycle, deferring what
    ///         `claim` defers and skipping a cycle whose exclusion list names the caller. Reverts
    ///         when nothing at all is paid.
    function claimMany(uint256[] calldata marketIds, uint256[] calldata cycleEnds) external;

    /// @notice What `account` can claim now from one cycle, asset by asset.
    function claimable(uint256 marketId, uint256 cycleEnd, address account)
        external
        view
        returns (address[] memory assets, uint256[] memory amounts);

    /// @notice End of the window a deposit for `marketId` arriving now belongs to.
    function currentCycleEnd(uint256 marketId) external view returns (uint256);

    /// @notice Number of cycles a market has opened.
    function cycleCount(uint256 marketId) external view returns (uint256);

    /// @notice The `index`-th cycle a market opened, in the order they opened: by the end of their
    ///         window, except a window that held-aside stocks opened late.
    function cycleEndAt(uint256 marketId, uint256 index) external view returns (uint256);
}

src/interfaces/ICairnFactory.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

import {IStockRouter} from "./IStockRouter.sol";
import {TreasuryOracle} from "../TreasuryOracle.sol";
import {IHoldingRecorder} from "./IHoldingRecorder.sol";
import {IProtocolAuthority} from "./IProtocolAuthority.sol";
import {LaunchConfig} from "./ILiquidityLock.sol";

/// @notice Registry entry for one market.
struct MarketInfo {
    address token;
    address vault;
    address creator;
    uint8 basketId;
    uint64 createdAt;
}

/// @notice Everything a creator chooses at launch.
/// @dev Grouped into a struct rather than five flat arguments: four calldata strings plus the four
///      return values do not fit in the legacy compiler's stack.
struct MarketParams {
    string name;
    string symbol;
    string imageURI;
    string description;
    uint8 basketId;
}

/// @notice An immutable basket of tokenized stocks.
struct Basket {
    address[] stocks;
    uint16[] weightsBps;
    string name;
    bool exists;
}

interface ICairnFactory is IProtocolAuthority {
    function teamWallet() external view returns (address);
    function buybackWallet() external view returns (address);
    function keeper() external view returns (address);
    function protocolToken() external view returns (address);
    function protocolVault() external view returns (address);
    function hook() external view returns (address);
    function liquidityLock() external view returns (address);
    function treasuryRouter() external view returns (IStockRouter);
    function treasuryOracle() external view returns (TreasuryOracle);
    /// @notice The official CairnSwapRouter. Zero until set.
    function swapRouter() external view returns (address);
    /// @notice BridgeHub vaults created from now on release their USDC to. Zero for the local rail.
    function bridgeHub() external view returns (address);
    /// @notice Holding-record module of the market tokens created from now on.
    function holdingRecorder() external view returns (IHoldingRecorder);
    /// @notice Implementation behind the treasury vault of every market created from now on.
    function vaultImplementation() external view returns (address);
    /// @notice Airdrop module the vaults hand their stocks to; zero until the owner names it.
    function airdropDistributor() external view returns (address);
    /// @notice Flat fee to create a market. Owner setting.
    function creationFee() external view returns (uint256);
    /// @notice Smallest ETH amount a vault converts at once. Owner setting, read live by the vaults.
    function minConversion() external view returns (uint256);
    /// @notice Worst execution accepted against the oracle on the ETH -> USDC leg, in basis points.
    function ethUsdcMaxSlippageBps() external view returns (uint16);
    /// @notice Worst execution accepted against the oracle on a USDC -> stock leg, in basis points.
    function stockMaxSlippageBps() external view returns (uint16);
    /// @notice The shape of the markets launched from now on. Owner setting.
    function launchConfig() external view returns (LaunchConfig memory);
    /// @notice Shares of what the locked positions collect, to the vault and to the team, in basis
    ///         points. Owner settings, read live by the liquidity lock.
    function lpFeeVaultBps() external view returns (uint16);
    function lpFeeTeamBps() external view returns (uint16);

    function marketCount() external view returns (uint256);
    function marketIdOfToken(address token) external view returns (uint256 marketId, bool found);
    function getMarket(uint256 marketId) external view returns (MarketInfo memory);
    function getBasket(uint8 basketId) external view returns (Basket memory);
    function basketCount() external view returns (uint8);
}

src/interfaces/IHoldingRecorder.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @title IHoldingRecorder
/// @notice The holding record of Cairn tokens, kept outside the tokens. A token calls
///         `onTransfer` on every balance change; the record of a token is written only by that
///         token.
interface IHoldingRecorder {
    struct Checkpoint {
        uint32 timestamp;
        uint96 balance;
        uint128 cumulative;
    }

    /// @notice The recorded supply at the start of an hour in which it moved.
    struct SupplyMark {
        /// @notice Hours since the epoch: the mark stands at `hour * SUPPLY_MARK_PERIOD`.
        uint32 hour;
        /// @notice The recorded supply at the start of that hour.
        uint96 supply;
        /// @notice Its integral up to the start of that hour, in token-seconds.
        uint128 cumulative;
    }

    /// @notice Records a balance change of the calling token, after the balances moved.
    /// @param from Sender, zero on a mint.
    /// @param to Recipient, zero on a burn.
    /// @param value Amount moved.
    /// @param fromBalance `from`'s balance after the move.
    /// @param toBalance `to`'s balance after the move.
    function onTransfer(address from, address to, uint256 value, uint256 fromBalance, uint256 toBalance) external;

    /// @notice Starts the calling token's recorded supply at `supply`, the token's supply outside
    ///         the PoolManager now, when the token names this module on a live supply. Only for a
    ///         token this module has never recorded.
    function seedSupply(uint256 supply) external;

    /// @notice When this module started recording `token` on a live supply (`seedSupply`); zero for
    ///         a module that has recorded it since its mint. It knows nothing of the token before.
    function seededAt(address token) external view returns (uint256);

    function poolManager() external view returns (address);
    function cumulativeBalanceAt(address token, address account, uint256 t) external view returns (uint256);
    function averageBalance(address token, address account, uint256 start, uint256 end) external view returns (uint256);
    function recordedSupply(address token) external view returns (uint256);
    function cumulativeRecordedSupplyAt(address token, uint256 t) external view returns (uint256);
    function averageRecordedSupply(address token, uint256 start, uint256 end) external view returns (uint256);
}

src/interfaces/ILiquidityLock.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

import {PoolKey} from "v4-core/src/types/PoolKey.sol";
import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";

/// @notice The shape of a market launch: owner settings on the factory since 2026-10-05, passed to
///         the lock with each launch. Defaults in `LaunchBands`.
struct LaunchConfig {
    /// @notice Supply minted for the market, all of it deposited in the two bands.
    uint96 totalSupply;
    /// @notice Tokens in band 1, from the launch price to its top; band 2 takes the rest.
    uint96 band1Tokens;
    /// @notice Opening tick, the top edge of band 1.
    int24 launchTick;
    /// @notice Band 1 is [band1LowerTick, launchTick].
    int24 band1LowerTick;
    /// @notice Band 2 is [band2LowerTick, band1LowerTick].
    int24 band2LowerTick;
    /// @notice Tick spacing of the pool.
    int24 tickSpacing;
    /// @notice Uniswap LP fee of the pool, in hundredths of a basis point.
    uint24 lpFee;
}

interface ILiquidityLock {
    /// @notice The PoolManager holding every pool this lock creates.
    function poolManager() external view returns (IPoolManager);

    /// @notice Creates a market's v4 pool with the shape `config` gives, deposits the whole token
    ///         supply in its two locked positions, and runs the creator's optional launch buy with
    ///         `msg.value`.
    /// @dev Callable only by the factory, inside `createMarket`. The token supply must already sit
    ///      on this contract.
    /// @return key The pool key of the created pool.
    /// @return creatorTokens Tokens bought for the creator, zero without a launch buy.
    function launchMarket(
        address token,
        address vault,
        address creator,
        address[] calldata whitelist,
        LaunchConfig calldata config
    ) external payable returns (PoolKey memory key, uint256 creatorTokens);

    /// @notice Collects what the locked positions earned and distributes it. Callable by anyone.
    /// @dev With the default LP fee of zero, this only ever collects donations.
    function collectFees(PoolKey calldata key) external returns (uint256 ethCollected, uint256 tokensCollected);
}

src/interfaces/IProtocolAuthority.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @title IProtocolAuthority
/// @notice The contract that names the protocol owner on its chain: the factory on Ethereum (its
///         owner), the RemoteHub on Robinhood Chain (the owner the last bridge message carried).
///         Every upgradeable module asks it who may upgrade it.
interface IProtocolAuthority {
    function protocolOwner() external view returns (address);
}

src/interfaces/IStockRouter.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @title IStockRouter
/// @notice The swap legs a TreasuryVault needs: ETH -> USDC then USDC -> tokenized stock for a
///         conversion. The reverse legs of the creator buyback were removed with it on 2026-09-27.
///
/// @dev There is deliberately no ETH -> stock function. No liquid ETH/stock pool exists: tokenized
///      stocks trade against stablecoins, so USDC is the real path rather than a detour. Offering a
///      direct leg would also mean a second code path that skips the vault's oracle bound, which is
///      the one protection the treasury design rests on.
///
///      The router address is immutable per vault, fixed at market creation. A vault approves it for
///      the exact USDC amount of a single leg and resets that approval to zero in the same
///      transaction, so a router can never reach the stocks a vault already holds.
///
///      Every swap takes a trailing opaque `data` argument, a router-specific payload the keeper hands
///      through the vault. A pool-based router ignores it. The vault never reads `data`: the oracle
///      bound on the measured output is what protects it, whatever the router does with the bytes.
interface IStockRouter {
    error UnsupportedStock(address stock);
    error InsufficientOutput(address asset, uint256 received, uint256 minOut);

    /// @notice Stablecoin every stock leg is quoted and settled in.
    function usdc() external view returns (address);

    /// @notice True when the `quote*` functions answer from on-chain state.
    function quotesOnChain() external view returns (bool);

    /// @notice Swaps the whole `msg.value` for USDC, sending the proceeds to `recipient`.
    /// @param minAmountOut Minimum acceptable output. Must be non-zero.
    /// @param recipient Address credited with the USDC.
    /// @param deadline Unix timestamp after which the swap reverts.
    /// @param data Router-specific payload, ignored by pool routers.
    /// @return amountOut USDC actually received by `recipient`.
    function swapExactEthForUsdc(uint256 minAmountOut, address recipient, uint256 deadline, bytes calldata data)
        external
        payable
        returns (uint256 amountOut);

    /// @notice Swaps `usdcIn` for `stock`, sending the proceeds to `recipient`.
    /// @dev Pulls `usdcIn` from `msg.sender`, who must have approved this router for at least that.
    /// @param stock Tokenized stock to acquire.
    /// @param usdcIn Exact USDC to spend.
    /// @param minAmountOut Minimum acceptable output. Must be non-zero.
    /// @param recipient Address credited with the stock.
    /// @param deadline Unix timestamp after which the swap reverts.
    /// @param data Router-specific payload, ignored by pool routers.
    /// @return amountOut Stock tokens actually received by `recipient`.
    function swapExactUsdcForStock(
        address stock,
        uint256 usdcIn,
        uint256 minAmountOut,
        address recipient,
        uint256 deadline,
        bytes calldata data
    ) external returns (uint256 amountOut);

    /// @notice Off-chain quote helper for the first leg. Not an oracle, and never treated as one.
    /// @dev Non-view on purpose: v4-style quoting simulates a swap. Call it with `eth_call`.
    function quoteEthForUsdc(uint256 ethIn) external returns (uint256 amountOut);

    /// @notice Off-chain quote helper for the second leg. Not an oracle, and never treated as one.
    /// @dev Non-view on purpose: v4-style quoting simulates a swap. Call it with `eth_call`.
    ///      Reverts on a router whose quotes are off-chain (`quotesOnChain() == false`).
    function quoteUsdcForStock(address stock, uint256 usdcIn) external returns (uint256 amountOut);

    /// @notice True when the router can route USDC into `stock`.
    function supportsStock(address stock) external view returns (bool);
}

src/libraries/SafeBalance.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @title SafeBalance
/// @notice Reads an ERC-20 balance without trusting the token.
/// @dev A high-level `balanceOf` call skips the code-size check when it expects return data, so an
///      address without code "succeeds" with empty returndata and the ABI decode then reverts in the
///      caller, where `try/catch` cannot catch it. That is how a bridge-rail basket, registered with
///      Robinhood Chain addresses that have no code on Ethereum, used to revert every view listing
///      its market. Here a revert, an address without code and a short return all read as
///      unreadable with a zero balance. The call is gas-capped and copies at most 32 bytes of
///      returndata, so a hostile token cannot exhaust the caller's gas or memory.
library SafeBalance {
    /// @notice Gas forwarded to `balanceOf`. Far above what a token or a token proxy needs.
    uint256 internal constant GAS_CAP = 100_000;

    /// @return ok False when the token has no code, reverted, or returned fewer than 32 bytes.
    /// @return amount `account`'s balance, 0 when `ok` is false.
    function balanceOf(address token, address account) internal view returns (bool ok, uint256 amount) {
        if (token.code.length == 0) return (false, 0);
        bytes memory callData = abi.encodeWithSelector(0x70a08231, account); // balanceOf(address)
        assembly ("memory-safe") {
            ok := staticcall(GAS_CAP, token, add(callData, 0x20), mload(callData), 0x00, 0x20)
            ok := and(ok, gt(returndatasize(), 0x1f))
            amount := mload(0x00)
        }
        if (!ok) amount = 0;
    }
}

src/libraries/SafeSend.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Cairn.fun
// X:       https://x.com/Cairnfun
// Website: https://cairnfun.com/
// Docs:    https://gitbook.cairnfun.com/

/// @title SafeSend
/// @notice Native ETH transfers that cannot be used to grief a trade.
/// @dev Every send is capped in gas and ignores return data, so a recipient cannot burn the
///      caller's gas or blow up memory with a returndata bomb. Callers decide whether a failure
///      reverts or falls back to another recipient.
library SafeSend {
    /// @notice Gas forwarded to a recipient. Generous enough for a multisig fallback, small enough
    ///         that a hostile recipient cannot consume a meaningful share of the block.
    uint256 internal constant GAS_CAP = 100_000;

    error SendFailed(address to, uint256 amount);

    /// @notice Attempts to send `amount` to `to`. Never reverts.
    /// @return ok True when the recipient accepted the ETH.
    function trySend(address to, uint256 amount) internal returns (bool ok) {
        if (amount == 0) return true;
        assembly ("memory-safe") {
            ok := call(GAS_CAP, to, amount, 0, 0, 0, 0)
        }
    }

    /// @notice Sends `amount` to `to` or reverts. Used only for protocol-owned recipients.
    function send(address to, uint256 amount) internal {
        if (!trySend(to, amount)) revert SendFailed(to, amount);
    }

    /// @notice Sends `amount` to `to` forwarding all remaining gas, reverting on failure.
    /// @dev For user-facing payouts (claims, refunds, sale proceeds) where the recipient is the
    ///      caller itself: they cannot grief anyone but themselves, and a smart-contract wallet
    ///      may legitimately need more than the capped stipend.
    function sendAllGas(address to, uint256 amount) internal {
        if (!trySendAllGas(to, amount)) revert SendFailed(to, amount);
    }

    /// @notice Attempts to send `amount` to `to` forwarding all remaining gas. Never reverts.
    /// @dev For the retry of a debt to a protocol recipient that refused a capped push (a vault
    ///      after a broken upgrade): whoever retries pays the gas, and a failure keeps the debt.
    function trySendAllGas(address to, uint256 amount) internal returns (bool ok) {
        if (amount == 0) return true;
        assembly ("memory-safe") {
            ok := call(gas(), to, amount, 0, 0, 0, 0)
        }
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 800,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "v4-core/=lib/v4-periphery/lib/v4-core/",
    "@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
    "v4-periphery/=lib/v4-periphery/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "@openzeppelin/contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/",
    "@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
    "erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "hardhat/=lib/v4-periphery/lib/v4-core/node_modules/hardhat/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.