Skip to content
Verified contractExactMIT

ReserveHookUniswapV4

Address0xee614cd036e7c11e05007e344c94e30682a8e888
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.26

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,407,721
Creation transaction
0xc756877206…f2cc67c883

src/reserve/ReserveHookUniswapV4.sol

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IUniswapV4PoolManager.sol";
import "../interfaces/IReserveManager.sol";
import "../libraries/Errors.sol";

/// @notice A Uniswap v4 pool that sells wSPCTR for `ASSET`, one backing asset listed on the reserve
///         desk (one deployment per asset), and is funded by the buyer's own money: every buy
///         deposits the buyer's `ASSET` into the desk in the same transaction, and the wSPCTR the
///         desk issues for it is what the buyer receives. Buy-only, exact-input only.
///
/// @dev WHY A HOOK AND NOT A ONE-SIDED POSITION (I-015). A one-sided v3 or v4 position needs wSPCTR
///      sitting in the pool BEFORE anyone pays for it, which is issuance with no backing behind it
///      and breaks `reserveSum() >= netIssued()`. Here nothing is issued until a buyer's `ASSET` has
///      reached the desk, and the desk's own `deposit` does the issuing, with every one of its
///      guardrails (pause, listing, cap, mint fee).
///
/// @dev HOW A BUY SETTLES (v4 custom accounting). A buy is an exact-input `ASSET` -> wSPCTR swap, so
///      the specified currency is `ASSET` (`currency1`) and the unspecified one wSPCTR (`currency0`).
///      In `beforeSwap` this hook (1) `take`s `amountIn` `ASSET` from the PoolManager, (2) deposits it
///      into the desk with itself as recipient, (3) measures the wSPCTR issued, (4) pays exactly that
///      to the PoolManager (`sync`, transfer, `settle`), and (5) returns the delta
///      (specified +`amountIn`, unspecified -`issued`). The PoolManager then swaps `0` on the curve,
///      nets this hook's two deltas to zero, and leaves the swapper owing `amountIn` `ASSET` and owed
///      `issued` wSPCTR, both settled by the router before the lock closes. If any figure is off by
///      one wei the lock does not close and the whole transaction reverts.
///
/// @dev THE POOLMANAGER'S `ASSET` IS BORROWED FOR ONE CALL. Step (1) spends `ASSET` the PoolManager
///      holds for other pools; the swapper's own payment repays it before the lock closes, so the net
///      movement is zero. Through a router that pays after the swap, as the Universal Router does,
///      a buy larger than that balance reverts; a caller that pays first is not bounded by it. The
///      desk's `depositCap` for `ASSET`, when set, bounds every buy.
///
/// @dev WHAT A BUYER GETS: wSPCTR ON ETHEREUM. The desk bridges to native SPCTR only for an EOA
///      recipient (`ReserveManager._deliver`), and its recipient here is this contract, so the desk
///      hands over plain wSPCTR, which the router forwards to the buyer. Native SPCTR is one bridge
///      transfer away, made by the buyer.
///
/// @dev AMOUNTS ARE MEASURED, NOT TRUSTED (ADR-0024 D4): the wSPCTR passed on is the balance delta
///      across the desk call, and this contract's `ASSET` balance must end exactly where it started, so
///      a short `take`, a short pull or a donation can never be passed on or deposited.
///
/// @dev NON-UPGRADEABLE, STATELESS, UNOWNED (ADR-0009's "immutability is a deliberate property"): no
///      proxy, no `initialize`, no role, no owner, no pause, no upgrade path, no rescue, no storage.
///      Five immutables. A token donated here is stuck permanently and is never deposited.
///
/// @dev NO ETH PATH. No `receive()`, no `payable` function.
///
/// @dev FAIL CLOSED. A sell, an exact-output swap, a desk that refuses the deposit (pause, delisting,
///      cap, solvency) or a balance that does not reconcile reverts the whole transaction, and the
///      buyer's `ASSET` never moves. The PoolManager wraps a hook's revert in its `WrappedError`.
///
/// @dev NO ROLE ON THE DESK IS NEEDED. To `ReserveManager` this is an ordinary `ASSET` depositor.
///
/// @dev THE KILL SWITCH IS THE DESK'S. Nothing in this contract can be switched off. The desk's
///      `pause()` stops every buy, as do delisting `ASSET` or exhausting its `depositCap`.
///
/// @dev ONE POOL, FOREVER. The constructor creates the only pool (the PoolManager skips a hook's own
///      callbacks when the hook itself is the caller), and `beforeInitialize` rejects every other pool
///      keyed to this hook, so `beforeSwap` never sees another key and does not re-check it. It
///      would fail closed even if it did: the PoolManager settles per currency, and the lock could
///      not close. A pool keyed to this address cannot be created before this contract exists: the
///      PoolManager would call `beforeInitialize` on empty code and reject the empty reply.
///
/// @dev NO LIQUIDITY. `beforeAddLiquidity` rejects every position, so the pool has no LPs, nothing
///      can be `donate`d to it, and no LP or protocol fee can apply (the curve always swaps zero).
///
/// @dev REENTRANCY: NO GUARD. Only the PoolManager can call `beforeSwap`, the desk's `deposit` is
///      `nonReentrant`, and every frame measures its own deltas, so an inner frame can only make an
///      outer one revert. A guard would add the only storage slot to a contract that has none.
///
/// @dev INDEXERS. The PoolManager's `Swap` event for this pool carries zero amounts, because the
///      curve never moves. `HookSwap` carries the real ones, and the desk's `Deposited` event is the
///      authoritative issuance record.
///
/// @dev DEPLOYMENT. A v4 hook's permissions are read from its address, so this contract is created
///      through CREATE2 with a salt mined until the address's low 14 bits equal `HOOK_FLAGS`, and the
///      constructor rejects any other address. `test/fork/ReserveHookUniswapV4.fork.test.ts` runs the
///      deployment, a buy and every refusal against the deployed PoolManager, Universal Router,
///      PositionManager and desk; on mainnet the deploy script refuses without a rehearsal record
///      written after the last commit to the reserve sources (I-011).
contract ReserveHookUniswapV4 {
    using SafeERC20 for IERC20;

    /// @notice The permissions this hook's address must encode: `beforeInitialize` (1 << 13),
    ///         `beforeAddLiquidity` (1 << 11), `beforeSwap` (1 << 7) and `beforeSwapReturnDelta` (1 << 3).
    ///         Bit positions from v4-core `src/libraries/Hooks.sol`.
    uint160 public constant HOOK_FLAGS = 0x2888;
    /// @dev The fourteen permission bits v4 reads from a hook address (`Hooks.ALL_HOOK_MASK`).
    uint160 private constant HOOK_FLAG_MASK = 0x3FFF;
    /// @notice The pool's LP fee: zero, because the pool never has an LP.
    uint24 public constant POOL_FEE = 0;
    /// @notice The pool's tick spacing: the smallest v4 allows. The curve is never used.
    int24 public constant POOL_TICK_SPACING = 1;
    /// @dev The pool's opening price, 1:1 (`2**96` is a square-root price of 1 in Q64.96). Cosmetic:
    ///      the curve never moves, and every buy is priced by the desk.
    uint160 private constant SQRT_PRICE_1_1 = 2 ** 96;

    /// @notice The Uniswap v4 singleton PoolManager this hook is bound to.
    IUniswapV4PoolManager public immutable POOL_MANAGER;
    /// @notice The reserve desk every buy deposits into (`ReserveManager`, ADR-0024).
    IReserveManager public immutable DESK;
    /// @notice wSPCTR: the token the desk issues, `currency0` of the pool.
    IERC20 public immutable WSPCTR;
    /// @notice The listed backing asset a buyer pays with, `currency1` of the pool.
    IERC20 public immutable ASSET;
    /// @notice The v4 id of the one pool this hook serves: `keccak256(abi.encode(poolKey))`.
    bytes32 public immutable POOL_ID;

    /// @notice One buy. The standard event for a swap a hook settles off the curve (OpenZeppelin
    ///         `uniswap-hooks` `IHookEvents.HookSwap`, read 2026-11-07), so indexers see the amounts
    ///         the PoolManager's own `Swap` event shows as zero.
    /// @param poolId `POOL_ID`.
    /// @param sender The PoolManager's caller (the router), as v4 passes it to `beforeSwap`.
    /// @param amount0 wSPCTR, negative: the amount the buyer received.
    /// @param amount1 `ASSET`, positive: the amount the buyer paid.
    /// @param hookLPfeeAmount0 Always 0: this hook charges no fee. The desk's mint fee is already
    ///        out of `amount0`.
    /// @param hookLPfeeAmount1 Always 0.
    event HookSwap(
        bytes32 indexed poolId,
        address indexed sender,
        int128 amount0,
        int128 amount1,
        uint128 hookLPfeeAmount0,
        uint128 hookLPfeeAmount1
    );

    /// @param poolManager_ The Uniswap v4 PoolManager.
    /// @param desk_ `ReserveManager`.
    /// @param wspctr_ wSPCTR, the token `desk_` issues.
    /// @param asset_ The stablecoin buyers pay with. Must be listed on `desk_` (checked by the deploy
    ///        script; an unlisted asset makes every buy revert).
    ///
    /// @dev Creates the pool. wSPCTR must sort below the asset: the buy direction and the delta
    ///      encoding above are written for wSPCTR as `currency0`.
    constructor(address poolManager_, address desk_, address wspctr_, address asset_) {
        if (
            poolManager_ == address(0) || desk_ == address(0) || wspctr_ == address(0) || asset_ == address(0)
        ) {
            revert Errors.ZeroAddress();
        }
        // Each must be a deployed contract, or the first buy would revert inside it.
        if (poolManager_.code.length == 0) revert Errors.AdapterMismatch();
        if (desk_.code.length == 0) revert Errors.AdapterMismatch();
        if (wspctr_.code.length == 0) revert Errors.AdapterMismatch();
        if (asset_.code.length == 0) revert Errors.AdapterMismatch();
        if (uint160(address(this)) & HOOK_FLAG_MASK != HOOK_FLAGS) revert Errors.HookAddressMismatch();
        if (wspctr_ >= asset_) revert Errors.UnsupportedAsset();

        POOL_MANAGER = IUniswapV4PoolManager(poolManager_);
        DESK = IReserveManager(desk_);
        WSPCTR = IERC20(wspctr_);
        ASSET = IERC20(asset_);

        PoolKey memory key = PoolKey(wspctr_, asset_, POOL_FEE, POOL_TICK_SPACING, address(this));
        POOL_ID = keccak256(abi.encode(key));
        IUniswapV4PoolManager(poolManager_).initialize(key, SQRT_PRICE_1_1);
    }

    /// @notice v4 callback before a pool keyed to this hook is created. Always reverts: the
    ///         constructor's pool is the only one (the PoolManager does not call this for it).
    /// @dev The arguments (v4's `sender`, `key`, `sqrtPriceX96`) are unnamed because none is read.
    /// @return Never returns; the `bytes4` is v4's `IHooks` signature.
    function beforeInitialize(address, PoolKey calldata, uint160) external pure returns (bytes4) {
        revert Errors.PoolNotAllowed();
    }

    /// @notice v4 callback before liquidity is added. Always reverts: the pool takes no liquidity.
    /// @dev The arguments (v4's `sender`, `key`, `params`, `hookData`) are unnamed because none is read.
    /// @return Never returns; the `bytes4` is v4's `IHooks` signature.
    function beforeAddLiquidity(
        address,
        PoolKey calldata,
        ModifyLiquidityParams calldata,
        bytes calldata
    ) external pure returns (bytes4) {
        revert Errors.LiquidityNotAccepted();
    }

    /// @notice v4 callback before a swap: settles an exact-input `ASSET` -> wSPCTR buy through the desk.
    /// @dev Only the PoolManager may call it, inside a swap. Returns the v4 `BeforeSwapDelta`
    ///      (specified delta in the upper 128 bits, unspecified in the lower; v4-core
    ///      `src/types/BeforeSwapDelta.sol`) and no LP-fee override. The swap's `sqrtPriceLimitX96`
    ///      is never read, here or by the PoolManager: this hook takes the whole input, so v4 swaps
    ///      nothing on the curve and returns before its price-limit checks (v4-core
    ///      `src/libraries/Pool.sol`, `swap`). A buyer's bound is the router's minimum output.
    ///      `key` and `hookData` are unnamed because neither is read.
    /// @param sender The PoolManager's caller (the router), emitted in {HookSwap}.
    /// @param params The swap. Must be one-for-zero (`ASSET` in) and exact-input.
    /// @return The selector, as v4 requires.
    /// @return The `BeforeSwapDelta`: `+amountIn` specified (`ASSET`, owed by the swapper) and
    ///         `-issued` unspecified (wSPCTR, owed to the swapper).
    /// @return 0: no LP-fee override.
    function beforeSwap(
        address sender,
        PoolKey calldata,
        SwapParams calldata params,
        bytes calldata
    ) external returns (bytes4, int256, uint24) {
        if (msg.sender != address(POOL_MANAGER)) revert Errors.NotPoolManager();
        // A buy is `oneForZero` (`ASSET` in) and exact-input (negative `amountSpecified`).
        if (params.zeroForOne || params.amountSpecified >= 0) revert Errors.SwapNotSupported();
        // Bounded so the negation below cannot overflow and the amount fits v4's `int128` deltas.
        if (params.amountSpecified < -int256(type(int128).max)) revert Errors.AmountOverflow();
        uint256 amountIn = uint256(-params.amountSpecified);

        // Baselines BEFORE the take, so a donated balance is never counted.
        uint256 assetBefore = ASSET.balanceOf(address(this));
        uint256 wspctrBefore = WSPCTR.balanceOf(address(this));

        POOL_MANAGER.take(address(ASSET), address(this), amountIn);
        ASSET.forceApprove(address(DESK), amountIn);
        DESK.deposit(address(ASSET), amountIn, address(this));
        // Zeroed on the success path too, so no standing claim on this contract can survive.
        ASSET.forceApprove(address(DESK), 0);
        // Every unit taken must have gone into the desk. One check covers a short take, a short pull
        // and a donation spent in place of the taken `ASSET`. Selector reused from the zaps.
        if (ASSET.balanceOf(address(this)) != assetBefore) revert Errors.BalanceTooLow();

        uint256 issued = WSPCTR.balanceOf(address(this)) - wspctrBefore;
        if (issued == 0) revert Errors.ZeroAmount();
        if (issued > uint256(uint128(type(int128).max))) revert Errors.AmountOverflow();

        // Pay the PoolManager exactly what was issued. `settle` credits what arrived since `sync`,
        // and the lock only closes if that equals `issued`.
        POOL_MANAGER.sync(address(WSPCTR));
        WSPCTR.safeTransfer(address(POOL_MANAGER), issued);
        POOL_MANAGER.settle();

        // Exact: both values were bounded to the `int128` range above.
        int128 paidIn = int128(int256(amountIn));
        int128 paidOut = -int128(int256(issued));
        emit HookSwap(POOL_ID, sender, paidOut, paidIn, 0, 0);
        int256 delta = (int256(paidIn) << 128) | int256(uint256(uint128(paidOut)));
        return (ReserveHookUniswapV4.beforeSwap.selector, delta, 0);
    }
}

@openzeppelin/contracts/interfaces/IERC1363.sol

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

pragma solidity ^0.8.20;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

@openzeppelin/contracts/interfaces/IERC165.sol

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

pragma solidity ^0.8.20;

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

@openzeppelin/contracts/interfaces/IERC20.sol

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

pragma solidity ^0.8.20;

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

@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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);
}

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

@openzeppelin/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/utils/Errors.sol

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

pragma solidity ^0.8.20;

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

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

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

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

@openzeppelin/contracts/utils/introspection/IERC165.sol

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

pragma solidity ^0.8.20;

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

src/interfaces/IReserveManager.sol

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

/// @notice External surface of the SPCTR reserve + mint/redeem desk (ADR-0024 D5/D6).
/// @dev Views only expose the solvency quantities a monitor or a peripheral contract
///      needs; administration (listing, caps, fees, sweeps) is deliberately NOT part of
///      this interface — it is role-gated on the implementation.
/// @dev This is the V1 surface, and it stays frozen at it. A successor's additional user
///      doors — `redeemTo` on {ReserveManagerV2} — live OFF this interface on purpose:
///      widening it would make {ReserveManager} abstract, which no drop-in successor can
///      afford, and the peripherals that hold this interface ({ReserveZap},
///      {ReserveZapERC20}) call only `deposit`. Cross-repo consumers read the generated ABI
///      export rather than this file.
interface IReserveManager {
    /// @notice Deposit a listed backing asset and receive SPCTR 1:1 against the units
    ///         actually received, less the mint fee.
    /// @param asset A listed, 18-decimal, $1-target backing asset.
    /// @param amount Units of `asset` to pull from `msg.sender` (approval required).
    /// @param recipient Address credited with SPCTR.
    function deposit(address asset, uint256 amount, address recipient) external;

    /// @notice Return SPCTR (as wSPCTR) to the desk and take `assetOut` 1:1 out of the
    ///         reserve, less the redeem fee.
    /// @param amount wSPCTR handed back (approval required); bounded by `netIssued()`.
    /// @param assetOut A listed backing asset the redeemer chooses to be paid in.
    function redeem(uint256 amount, address assetOut) external;

    /// @notice SPCTR currently in circulation because this desk issued it.
    /// @return net `totalIssued - totalRedeemed`.
    function netIssued() external view returns (uint256 net);

    /// @notice Total backing held across every LISTED asset, valued at $1 per unit.
    /// @return total The solvency quantity of ADR-0024 D6.
    function reserveSum() external view returns (uint256 total);

    /// @notice Whether `asset` currently counts toward `reserveSum`.
    /// @param asset The asset to query.
    /// @return listed True when `asset` is an accepted backing asset.
    function isAssetListed(address asset) external view returns (bool listed);

    /// @notice Backing held in one asset: its balance net of fees accrued in it.
    /// @param asset The asset to query.
    /// @return backing Balance minus accrued fees, saturating at 0.
    function backingBalanceOf(address asset) external view returns (uint256 backing);

    /// @notice The currently listed backing assets, in no guaranteed order.
    /// @dev Read by the ops solvency monitor so the asset set is never hardcoded there
    ///      (AR-6: the monitor must be able to enumerate backing without an ABI copy).
    /// @return assets The canonical listed set.
    function listedAssets() external view returns (address[] memory assets);

    /// @notice Fees taken in `asset`. Held by the contract but EXCLUDED from backing.
    /// @param asset The asset to query.
    /// @return fees Accrued fee units, the quantity `reserveSum` subtracts.
    /// @dev Excluded from backing AND withdrawable as surplus by `DEFAULT_ADMIN_ROLE`
    ///      through `withdrawSurplus` on the implementation (ADR-0024 Amendment 3,
    ///      2026-08-25), which charges this pot FIRST. Because the pot is outside
    ///      `reserveSum`, extracting it alone moves `reserveSum` by nothing; anything
    ///      beyond it comes out of backing and is capped by the post-transfer solvency
    ///      assertion. `withdrawSurplus` itself is administration and is deliberately not
    ///      part of this interface, for the same reason listing, caps, fees and the sweeps
    ///      are not.
    function accruedFees(address asset) external view returns (uint256 fees);

    /// @notice The yield venues bound to `asset`, in current array order (not stable across removal).
    /// @param asset The backing asset to query.
    /// @return venues The ERC-4626 vaults whose positions count toward `asset`'s backing.
    /// @dev A SET since ADR-0024 Amendment 8 — the owner is never locked into one venue.
    ///      Read by the ops solvency monitor so its independent reconstruction of
    ///      `reserveSum()` sees the same positions the contract does. Without it the
    ///      monitor's own sum diverges from the chain's on every poll the moment any
    ///      backing is deployed. Binding a venue is administration and is deliberately not
    ///      on this interface, for the same reason listing and the sweeps are not.
    function venuesOf(address asset) external view returns (address[] memory venues);

    /// @notice The asset a venue address is bound to, or `address(0)` if unbound.
    /// @param venue The venue address to query.
    /// @return asset The backing asset this venue serves.
    /// @dev One venue address serves exactly one asset — the guard against counting the
    ///      same shares twice in `reserveSum`. Exposed because the monitor needs to resolve
    ///      a venue seen in an event back to its asset without replaying every binding.
    function venueAssetOf(address venue) external view returns (address asset);

    /// @notice Value of ONE venue's position, denominated in the asset's units.
    /// @param venue The venue to query.
    /// @return assets The vault's own `convertToAssets` figure, or 0 if unreadable.
    /// @dev The per-venue read the allocation dials are enforced against; `venueAssets`
    ///      sums these across an asset's set.
    function positionOf(address venue) external view returns (uint256 assets);

    /// @notice Fraction of `asset`'s BACKING that may be deployed, in bps. Launch 0.
    /// @param asset The backing asset to query.
    /// @return bps The current deployment ceiling — the risk-posture dial (Amendment 8).
    function maxDeployBps(address asset) external view returns (uint16 bps);

    /// @notice The venue exposure dial, in bps of the surplus (I-016).
    /// @return bps The current `venueExposureBps` — read by the ops monitor's check (h).
    function venueExposureBps() external view returns (uint16 bps);

    /// @notice Value of `asset`'s venue position, denominated in `asset` units.
    /// @param asset The backing asset to query.
    /// @return assets The vault's own `convertToAssets` figure, or 0 if unreadable.
    /// @dev Counted as backing (ADR-0024 Amendment 4, 2026-08-26) and therefore inside
    ///      `backingBalanceOf` and `reserveSum`. This is the first trusted external numeric
    ///      input in the design: it is published by the venue, not verified by the desk.
    ///      Not an oracle — no market price is read — so ADR-0017 stays open and untouched.
    function venueAssets(address asset) external view returns (uint256 assets);
}

src/interfaces/IUniswapV4PoolManager.sol

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

/// @notice Uniswap v4 `PoolKey`: the five fields that identify one pool. Field order and types are
///         copied from v4-core `src/types/PoolKey.sol`. v4's `Currency` and `IHooks` are both an
///         `address` in the ABI, and are written as `address` here.
struct PoolKey {
    address currency0;
    address currency1;
    uint24 fee;
    int24 tickSpacing;
    address hooks;
}

/// @notice Uniswap v4 swap arguments, as the PoolManager hands them to a hook's `beforeSwap`.
///         Copied from v4-core `src/types/PoolOperation.sol`. A NEGATIVE `amountSpecified` is an
///         exact-input swap, a positive one exact-output.
struct SwapParams {
    bool zeroForOne;
    int256 amountSpecified;
    uint160 sqrtPriceLimitX96;
}

/// @notice Uniswap v4 liquidity arguments, as the PoolManager hands them to a hook's
///         `beforeAddLiquidity`. Copied from v4-core `src/types/PoolOperation.sol`.
struct ModifyLiquidityParams {
    int24 tickLower;
    int24 tickUpper;
    int256 liquidityDelta;
    bytes32 salt;
}

/// @notice Minimal surface of the Uniswap v4 singleton PoolManager
///         (`0x000000000004444c5dc75cB358380D2e3dE08A90` on Ethereum): exactly the four calls
///         `ReserveHookUniswapV4` makes.
///
/// @dev SOURCE. Signatures copied from v4-core `src/PoolManager.sol` and `src/interfaces/IPoolManager.sol`
///      (read 2026-11-07). The ABI, and so every selector, is identical to v4's with `Currency`
///      written as `address`. `test/fork/ReserveHookUniswapV4.fork.test.ts` proves it against the
///      deployed PoolManager.
///
/// @dev DELIBERATELY NOT DECLARED: `unlock`, `swap`, `modifyLiquidity`, `donate`, `mint`, `burn`,
///      `clear`, `settleFor` and every protocol-fee call. The hook never opens a lock, never trades on
///      the curve and never provides liquidity. An interface is an attack-surface description.
///
/// @dev MUTABILITY. `settle` is `payable` on the PoolManager and NON-payable here, for the reason
///      {ICurveStableswapPool} gives: mutability is not part of the selector, and a non-payable call
///      sends exactly 0 wei. (The PoolManager also reverts a non-zero `msg.value` on an ERC-20 settle.)
interface IUniswapV4PoolManager {
    /// @notice Create the pool `key` at the price `sqrtPriceX96`. Not lock-gated: anyone may call it.
    /// @param key The pool.
    /// @param sqrtPriceX96 The starting price, as a Q64.96 square root.
    /// @return tick The pool's starting tick.
    function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);

    /// @notice Send `amount` of `currency` to `to`, debiting the caller's open delta by `amount`.
    ///         Only inside a lock.
    /// @param currency The token sent.
    /// @param to The recipient.
    /// @param amount The amount sent.
    function take(address currency, address to, uint256 amount) external;

    /// @notice Record the PoolManager's balance of `currency`, so the next `settle` can measure what arrived.
    /// @param currency The token the next `settle` measures.
    function sync(address currency) external;

    /// @notice Credit the caller with the `currency` (as last `sync`ed) that arrived since the `sync`.
    ///         Only inside a lock.
    /// @return paid The amount credited.
    function settle() external returns (uint256 paid);
}

src/libraries/Errors.sol

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

library Errors {
    error ZeroAddress();
    error ZeroAmount();
    error InvalidBps();
    error LengthMismatch();
    error InvalidSchedule();
    error ScheduleLocked();
    error RecipientNotAllowed();
    error NothingToRelease();
    error AmountExceedsAvailable();
    error AmountExceedsCap();
    error CapNotIncreasing();
    error BalanceTooLow();
    error TransferFailed();
    error DuplicateTransfer();
    error EpochLimitExceeded();
    error DailyLimitExceeded();
    error AssetNotEnabled();
    error AssetPaused();
    error UnsupportedAsset();
    error InvalidRateLimit();
    error NonProductionBridge();
    error AllocationAlreadyLinked();
    error AdapterMismatch();
    error AmountOverflow();
    error AdminAdapterCollision();
    error AdminCannotHoldBridgeOperator();
    /// @dev ADR-0024 D6 / PLAYBOOK I-015 — the reserve desk's compliance line:
    ///      `reserveSum() >= netIssued()` must hold after every state change.
    error SolvencyViolation();
    /// @dev ADR-0024 Amendment 9 — a money body reached WITHOUT its entry-point guards.
    ///      `ReserveManager._redeem` is `internal` so a successor can reuse one
    ///      implementation of the redemption path instead of copying it; the price is that
    ///      a future subclass could call it from a door missing `whenNotPaused` or
    ///      `nonReentrant`. The body asserts the reentrancy guard is engaged and reverts
    ///      this rather than trusting the next author to remember.
    error GuardNotEngaged();
    /// @dev ADR-0024 D6 / D-H — a SWEEP may never move a LISTED backing asset out of
    ///      the reserve desk. Exactly two paths may release backing, and a sweep is
    ///      neither: `redeem`, and the surplus-bounded `withdrawSurplus` (ADR-0024
    ///      Amendment 3, 2026-08-25). `deployToVenue` (Amendment 4) moves a listed asset out
    ///      of the contract without RELEASING it — the value stays in `reserveSum()` as a
    ///      venue position — so it is not a third release path either.
    error ReserveAssetNotWithdrawable();
    /// @dev ADR-0024 Amendment 4 (2026-08-26) — the yield venue bound to a backing asset
    ///      still holds shares. Re-pointing or clearing it now would strand that position:
    ///      the shares stay in the desk while their value leaves `reserveSum()`. Recall
    ///      the position to zero first, then change the binding.
    error VenuePositionOpen();

    // --- ETH collateral wing (ADR-eth-collateral-wing, PLAYBOOK I-017) -------------------

    /// @dev One position per address (the Liquity trove model, plan D-4). Close the
    ///      existing position before opening another.
    error PositionAlreadyOpen();
    error PositionNotFound();
    /// @dev Liquidation refused: the position's collateral ratio is at or above `mcrBps`
    ///      at the live oracle price. Liquidating healthy positions is theft-with-a-bonus.
    error PositionHealthy();
    /// @dev Open refused: the requested borrow would start below `mcrBps`. Positions may
    ///      FALL below the ratio afterwards (prices move; that is what liquidation is
    ///      for) — they may never START below it.
    error CollateralRatioTooLow();
    /// @dev The Chainlink answer is unusable — any of THREE modes: a non-positive answer, an
    ///      answer older than MAX_ORACLE_AGE, or a feed that reverts outright (the try/catch
    ///      folds the third in).
    ///
    ///      CORRECTED 2026-09-02. This said FOUR modes and named "undecodable return data" as
    ///      the fourth, "folded in" by the try/catch. IT IS NOT. Solidity's `try/catch` catches
    ///      a REVERT; a short/undecodable RETURN is not one — the callee returned successfully
    ///      and the ABI decode then fails in the CALLER's frame, outside the catch. Such a feed
    ///      reverts with a decoder error, NOT with this selector, so a monitor or frontend
    ///      keying on `OraclePriceStale` fails to decode that case. Measured and pinned by
    ///      `CollateralManager.test.ts` W29 against `MockShortReturnAggregator`. This repo
    ///      already stated it correctly for the desk (`ReserveManager.sol`, and the desk's own
    ///      test pins it) — only the wing's copy was wrong. The mode is unreachable at runtime
    ///      behind the wing's IMMUTABLE feed, which was verified live before being hardcoded;
    ///      it is documented rather than guarded, deliberately.
    ///
    ///      Fails CLOSED on the two price-touching paths (open, liquidate) and cannot, by
    ///      construction, block repay/close/addCollateral — those never read a price.
    error OraclePriceStale();
    /// @dev Positions below `minDebt` are unliquidatable at gas cost (plan D-8, Liquity
    ///      precedent) — refused at open and on partial repays that would leave dust.
    ///
    ///      TWO CALL SITES, and the second is NOT about dust. `CollateralManager.open` refuses
    ///      a borrow below the dial; `CollateralManager.repay` refuses BOTH a partial repay
    ///      that would leave a remainder under the dial AND an **OVERPAYMENT**
    ///      (`amount >= principal`), which is neither an open nor dust. So a caller can see
    ///      this selector for trying to repay MORE than they owe. **The remedy in that case is
    ///      `close`**, which settles the whole debt and returns the ETH in one call. Named
    ///      here 2026-09-02 because the docblock described only one of the two repay branches,
    ///      and an integrator decoding this selector on an overpayment would have no idea what
    ///      the contract wanted from them.
    error DebtBelowMinimum();
    /// @dev `minDebt` moved outside its compile-time band. The band is a TYPO GUARD, not a
    ///      safety proof: a value inside it can still be too low for a liquidator to bother
    ///      with. The real number is a MEASUREMENT, held by ADR-eth-collateral-wing §8
    ///      gate 2 (mainnet liquidation cost, measured on the fork), not a bound.
    error MinDebtOutOfBand();
    /// @dev A Uniswap v4 hook callback was called by an address other than the PoolManager.
    error NotPoolManager();
    /// @dev A Uniswap v4 hook was deployed at an address whose permission bits are not the ones it
    ///      implements. v4 reads a hook's permissions from its address, so the deployment salt is wrong.
    error HookAddressMismatch();
    /// @dev A second pool was keyed to a hook that serves exactly one.
    error PoolNotAllowed();
    /// @dev A swap the hook does not settle: a sell, or an exact-output buy.
    error SwapNotSupported();
    /// @dev Liquidity offered to a pool that takes none.
    error LiquidityNotAccepted();
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.