Skip to content
Verified contractExactMIT

DualAssetConcLiqWrapper

Address0x043cc0531991d0bfb46b62b3f0bb07c2b41030b9
Balance

0 ETH

 

Transactions

8

 

Compiler

solc 0.8.28

 

Same code

4 more contracts

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,139,876
Creation transaction
0xc48b0c33c6…98de70f5db

contracts/vaults/dual-asset-conc-liq/DualAssetConcLiqWrapper.sol

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

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

import { WadzWrapperBase } from "../shared/WadzWrapperBase.sol";
import { IWadzVaultCore } from "../shared/IWadzVaultCore.sol";
import { IDualAssetConcLiqVault } from "./IDualAssetConcLiqVault.sol";
import { IDualAssetLpVaultAdapter } from "./adapters/lp-vault/IDualAssetLpVaultAdapter.sol";
import { IValuationOracle } from "../../platform/oracle/IValuationOracle.sol";
import { SignedAction, WadzActionType } from "../../platform/authorizer/IWadzActionAuthorizer.sol";
import { IWadzRewardsVault, ProtocolSplitShare } from "../../platform/rewards/IWadzRewardsVault.sol";
import { VaultKind, PositionStatus, Position } from "../../platform/types/WadzTypes.sol";

/// @title DualAssetConcLiqWrapper
/// @notice WADZ Dual-Asset Concentrated-Liquidity Wrapper. Custodies VaultConcLiq
///         provider shares on behalf of users, who hold only non-transferable WADZ
///         positions. All accounting is in USDC; normal actions are authorized by
///         backend EIP-712 signatures; emergency exit is signature-free and
///         principal-only.
///
///         This wrapper is protocol-agnostic with respect to the LP provider: all
///         provider interaction is delegated to `DualAssetLpVaultAdapter`, which
///         translates wrapper calls into VaultConcLiq operations. Provider shares
///         (ERC-20) are held EXCLUSIVELY by this wrapper — never exposed to users.
///
///         Fee-only accounting: the wrapper holds a per-position
///         `FeeAccrual` struct that snapshots the strategy's `cumulativeFeePerShare`
///         index and accumulates raw-token fees attributable to each position.
///         `availableProfitUsdc` returns `min(feeOnlyUsdc, netGainUsdc)`. The
///         withdrawal fee cap is `FeeExceedsFeeOnlyProfit` — the backend-signed
///         `protocolAmount` must not exceed the fee-only figure. Harvest lag is
///         acceptable: unharvested fees are not attributable until the next harvest.
///
///         Adapter wiring: the adapter's constructor requires the wrapper address, so
///         the wrapper is deployed FIRST (without the adapter address), then the
///         adapter is deployed, then `setAdapter` is called by the deployer (typically
///         the factory) to complete wiring atomically in the same transaction.
///         `_deployer` is captured as an immutable at construction; no governance role
///         is required. This breaks the deploy-order circular dependency at the cost of
///         a one-time mutable `_adapter` slot that becomes effectively immutable after
///         the first `setAdapter` call (enforced by the `AdapterAlreadySet` guard).
///         No deposits or withdrawals are possible before `setAdapter` is called.
///
///         Access model: per-contract `Ownable`/`governance` pattern inherited from
///         `WadzWrapperBase`, matching the other wrappers on this branch. The
///         central `WadzAccessController` / `WadzRoles` pattern is parked on a
///         separate branch and is NOT applied here.
///
///         Upgradeability decision: NON-UPGRADEABLE (constructor + immutables +
///         one-time adapter wiring), mirroring `SASWVault` / `WadzWrapperBase`.
///         Per-vault deployment, custody limited to provider receipts, and an
///         always-available emergency exit make a redeploy-and-migrate model safer
///         than live proxy upgrades.
contract DualAssetConcLiqWrapper is WadzWrapperBase, IDualAssetConcLiqVault {
    using SafeERC20 for IERC20;

    // ─── Constants ───────────────────────────────────────────────────────

    /// @notice Precision denominator for fee-index arithmetic (matches the strategy's PRECISION).
    /// @dev    Must equal the PRECISION used by `StrategyPassiveManagerUniswapV3` (1e36).
    ///         Mismatch would silently corrupt all fee attribution.
    uint256 private constant PRECISION = 1e36;

    // ─── Structs ─────────────────────────────────────────────────────────

    /// @dev Internal result of the adapter deposit + dust accounting step.
    struct DepositResult {
        uint256 shares;
        uint256 consumed0;
        uint256 consumed1;
        uint256 principalUsdc;
    }

    /// @dev Internal planning result for a single withdrawal, populated by
    ///      `_planWithdraw` before any external interaction.
    struct WithdrawPlan {
        uint256 sharesToRedeem;
        uint256 principalUsdcOfWithdrawn;
        uint256 positionValueUsdcBeforeRedeem;
        bool closing;
        uint256 feeOnlyUsdcOfWithdrawn;
    }

    /// @notice Per-position fee accrual tracking for fee-only LP accounting.
    /// @dev    Stored in a PARALLEL mapping keyed by positionId; the base `Position`
    ///         struct is NOT modified. All amounts are in raw token units (not USDC).
    ///         `feeIndex0Start` / `feeIndex1Start` are snapshots of the strategy's
    ///         cumulative-per-share index at the last settle point (open or top-up).
    ///         `accruedFee0` / `accruedFee1` accumulate fees earned before the last
    ///         top-up (so that increasing share balances don't erase prior attribution).
    struct FeeAccrual {
        uint256 feeIndex0Start;
        uint256 feeIndex1Start;
        uint256 accruedFee0;
        uint256 accruedFee1;
    }

    // ─── Immutables ──────────────────────────────────────────────────────

    /// @dev Deployer address authorized to perform the one-time `setAdapter` wiring.
    ///      Set to `msg.sender` in the constructor (typically the factory).
    address private immutable _deployer;

    /// @inheritdoc IDualAssetConcLiqVault
    address public immutable override depositToken0;

    /// @inheritdoc IDualAssetConcLiqVault
    address public immutable override depositToken1;

    /// @inheritdoc IDualAssetConcLiqVault
    address public immutable override oracle;

    // ─── Storage ─────────────────────────────────────────────────────────

    /// @notice Wired adapter instance. Settable once via `setAdapter`; zero until set.
    /// @dev    Declared as a storage variable (not immutable) because of the deploy-
    ///         order constraint: the adapter requires the wrapper address in its
    ///         constructor, so the wrapper must be deployed first. The `AdapterAlreadySet`
    ///         guard makes this effectively immutable after first assignment.
    address private _adapter;

    /// @notice Authoritative provider share balance per position.
    /// @dev    `Position.receiptAmount` mirrors this for
    ///         base-struct consistency, but `positionShares` is the source of truth on
    ///         all withdrawal paths to avoid rounding divergence when partial withdrawals
    ///         progressively reduce shares. Both are updated in lockstep.
    mapping(uint256 positionId => uint256 shares) public positionShares;

    /// @notice Per-position fee accrual tracking.
    /// @dev    Parallel to `positionShares`; keyed by positionId. Holds the fee-index
    ///         snapshot and accumulated raw-token fees for each open position. Deleted
    ///         when a position is fully closed or emergency-redeemed.
    mapping(uint256 positionId => FeeAccrual) private _feeAccrual;

    /// @notice Block timestamp of each position's most recent contribution (deposit or
    ///         top-up).
    /// @dev    Same-block anti-sandwich guard for `emergencyRedeem`. The provider's
    ///         global `lastDeposit` gate is bypassed on the emergency path (so a
    ///         permissionless third-party provider deposit cannot DoS WADZ emergency
    ///         exits); this per-position stamp restores the protection precisely where
    ///         it matters — a position that contributed in the current block must not
    ///         emergency-exit while the pool is non-calm.
    mapping(uint256 positionId => uint256 timestamp) public lastContributionAt;

    // ─── Constructor ─────────────────────────────────────────────────────

    /// @param _accountingAsset USDC address used for all WADZ accounting.
    /// @param _vaultId         Registry key for this vault.
    /// @param _authorizer      EIP-712 action authorizer.
    /// @param _treasury        Protocol/treasury destination.
    /// @param _governance      Address allowed to change lifecycle state and wire adapter.
    /// @param _depositToken0   First token of the LP pair.
    /// @param _depositToken1   Second token of the LP pair.
    /// @param _oracle          Dual-asset valuation oracle (`IValuationOracle` with
    ///                         `dualValueInUsdc`). Must not be address(0).
    constructor(
        address _accountingAsset,
        uint256 _vaultId,
        address _authorizer,
        address _treasury,
        address _governance,
        address _depositToken0,
        address _depositToken1,
        address _oracle
    ) WadzWrapperBase(_accountingAsset, _vaultId, _authorizer, _treasury, _governance) {
        if (_depositToken0 == address(0) || _depositToken1 == address(0) || _oracle == address(0)) {
            revert ZeroAddress();
        }
        if (_depositToken0 == _depositToken1) revert TokensIdentical();

        _deployer = msg.sender;
        depositToken0 = _depositToken0;
        depositToken1 = _depositToken1;
        oracle = _oracle;
    }

    // ─── Adapter wiring ──────────────────────────────────────────────────

    /// @inheritdoc IDualAssetConcLiqVault
    function setAdapter(address _adapterAddress) external override {
        if (msg.sender != _deployer) revert NotDeployer(msg.sender);
        if (_adapter != address(0)) revert AdapterAlreadySet();
        if (_adapterAddress == address(0)) revert ZeroAddress();
        _adapter = _adapterAddress;
        emit AdapterSet(_adapterAddress);
    }

    /// @inheritdoc IDualAssetConcLiqVault
    function adapter() external view override returns (address) {
        return _adapter;
    }

    // ─── User flows ──────────────────────────────────────────────────────

    /// @inheritdoc IDualAssetConcLiqVault
    function deposit(
        SignedAction calldata _action,
        bytes calldata _sig,
        uint256 _amount0,
        uint256 _amount1,
        uint256 _minShares
    ) external override nonReentrant whenAcceptingDeposits returns (uint256 positionId) {
        address adapterAddress = _requireAdapter();

        _authorizeAction(_action, _sig, WadzActionType.Deposit);

        // Deposit actions do not route funds. Their amount field instead commits to
        // the exact dual-token calldata authorized by the backend signer.
        if (
            _action.positionId != 0 ||
            _action.userAmount != 0 ||
            _action.protocolAmount != 0 ||
            _action.protocolSplitHash != bytes32(0)
        ) {
            revert InvalidDepositAction();
        }
        // `_minShares` is inside the commitment: it is the caller's only defence against a
        // permissionless share-price manipulation (the provider's `deposit` is public and
        // prices shares off `strategy.balances()`, so a third party can donate to the
        // strategy to dilute this deposit). Leaving it as free calldata would let a
        // compromised or buggy client zero it out while still presenting a valid backend
        // signature. Binding it costs nothing on-chain and makes the floor the backend's
        // decision, consistent with `_amount0`/`_amount1` already being committed.
        uint256 calldataCommitment = uint256(keccak256(abi.encode(_amount0, _amount1, _minShares)));
        if (_action.amount != calldataCommitment) {
            revert DepositAmountsMismatch(_action.amount, calldataCommitment);
        }
        if (_amount0 == 0 && _amount1 == 0) revert ZeroAmount();
        // A committed floor of zero is no floor. Reject it here so a lazy signing policy
        // cannot silently opt out of dilution protection.
        if (_minShares == 0) revert ZeroMinShares();
        if (!IDualAssetLpVaultAdapter(adapterAddress).isCalm()) revert NotCalm();

        // Cache fields from calldata before calling helpers (reduces stack pressure).
        uint256 licenseId = _action.licenseId;
        address referrer = _action.referrer;

        // Pull tokens, deposit via adapter, account for dust, compute principalUsdc.
        DepositResult memory result = _executeDeposit(adapterAddress, _amount0, _amount1, _minShares);

        // Resolve create-vs-topup and store the position.
        positionId = _resolvePosition(adapterAddress, licenseId, result.shares, result.principalUsdc);

        emit Deposited(
            positionId,
            msg.sender,
            licenseId,
            _amount0,
            _amount1,
            result.principalUsdc,
            result.shares,
            referrer
        );
    }

    /// @dev Pull `_amount0`/`_amount1` from `msg.sender`, send to adapter, deposit
    ///      into VaultConcLiq. Returns minted shares, consumed amounts, and principalUsdc.
    ///      Dust returned by the adapter is forwarded to `msg.sender`.
    ///      Separated to reduce stack depth in the `deposit` entry-point.
    /// @param _adapterAddress Wired dual-asset adapter used for the provider deposit.
    /// @param _amount0        Raw amount of `depositToken0` supplied by the caller.
    /// @param _amount1        Raw amount of `depositToken1` supplied by the caller.
    /// @param _minShares      Minimum provider shares accepted from the deposit.
    /// @return result         Minted shares, consumed token amounts, and USDC principal.
    function _executeDeposit(
        address _adapterAddress,
        uint256 _amount0,
        uint256 _amount1,
        uint256 _minShares
    ) internal returns (DepositResult memory result) {
        if (_amount0 > 0) IERC20(depositToken0).safeTransferFrom(msg.sender, _adapterAddress, _amount0);
        if (_amount1 > 0) IERC20(depositToken1).safeTransferFrom(msg.sender, _adapterAddress, _amount1);

        uint256 consumed0;
        uint256 consumed1;
        (result.shares, consumed0, consumed1) = IDualAssetLpVaultAdapter(_adapterAddress).deposit(
            _amount0,
            _amount1,
            _minShares
        );
        if (result.shares == 0) revert ZeroShares();

        uint256 dust0 = _amount0 - consumed0;
        uint256 dust1 = _amount1 - consumed1;
        result.consumed0 = consumed0;
        result.consumed1 = consumed1;

        // Return dust to the caller.
        if (dust0 > 0) IERC20(depositToken0).safeTransfer(msg.sender, dust0);
        if (dust1 > 0) IERC20(depositToken1).safeTransfer(msg.sender, dust1);

        // Fix principalUsdc via the oracle. Reverts on stale/unconfigured data.
        result.principalUsdc = IValuationOracle(oracle).dualValueInUsdc(
            depositToken0,
            result.consumed0,
            depositToken1,
            result.consumed1
        );
    }

    /// @dev Resolve create-vs-topup for `(msg.sender, _licenseId)`, update the
    ///      position store, `positionShares`, and fee accrual, and return the resolved
    ///      `positionId`. Separated to reduce stack depth in the `deposit` entry-point.
    ///
    ///      `_adapterAddress` is the already-resolved adapter (avoids a second SLOAD
    ///      of `_adapter` inside this function).
    ///
    ///      Fee accrual invariants:
    ///      - New position: snapshot the current fee index as the start; accrued = 0.
    ///      - Top-up: FIRST settle fees earned on the existing shares at the current
    ///        index (rolling pending into `accruedFee*`), THEN reset the start index
    ///        to now. Net effect: fees earned before the top-up are preserved in
    ///        `accruedFee*`; the LARGER post-top-up share balance accrues from now.
    /// @param _adapterAddress Wired adapter used to snapshot fee indexes.
    /// @param _licenseId      Off-chain license reference from the signed deposit.
    /// @param _shares         Newly minted provider shares to assign to the position.
    /// @param _principalUsdc  USDC cost basis of the consumed deposit tokens.
    /// @return positionId     Resolved position id, either existing open position or new id.
    function _resolvePosition(
        address _adapterAddress,
        uint256 _licenseId,
        uint256 _shares,
        uint256 _principalUsdc
    ) internal returns (uint256 positionId) {
        positionId = _openByUserLicense[msg.sender][_licenseId];
        if (positionId == 0) {
            positionId = _createPosition(msg.sender, _licenseId, _shares, _principalUsdc);
            positionShares[positionId] = _shares;
            // New position: snapshot index now; nothing earned yet.
            // Uses the already-resolved adapter address — no second storage read.
            (uint256 idx0, uint256 idx1) = IDualAssetLpVaultAdapter(_adapterAddress).feeIndexes();
            _feeAccrual[positionId] = FeeAccrual({
                feeIndex0Start: idx0,
                feeIndex1Start: idx1,
                accruedFee0: 0,
                accruedFee1: 0
            });
        } else {
            // Top-up: settle fees first to preserve attribution on existing shares,
            // then add new shares and reset the index snapshot.
            _settleFees(positionId);
            Position storage p = _positions[positionId];
            p.receiptAmount += _shares;
            p.principalUsdc += _principalUsdc;
            positionShares[positionId] += _shares;
            // openedAt and claimedProfitUsdc are intentionally unchanged.
        }
        // Stamp the contribution block for the emergency same-block guard. Applies to
        // both a fresh position and a top-up, since either adds provider liquidity.
        lastContributionAt[positionId] = block.timestamp;
    }

    /// @inheritdoc IDualAssetConcLiqVault
    function withdraw(
        SignedAction calldata _action,
        bytes calldata _sig,
        ProtocolSplitShare[] calldata _breakdown,
        uint256 _minAmount0,
        uint256 _minAmount1
    ) external override nonReentrant {
        address adapterAddress = _requireAdapter();
        _authorizeAction(_action, _sig, WadzActionType.Withdraw);
        if (!IDualAssetLpVaultAdapter(adapterAddress).isCalm()) revert NotCalm();

        // Plan: checks + effects before any external call (CEI).
        WithdrawPlan memory plan = _planWithdraw(_action, adapterAddress);

        // `_minAmount0`/`_minAmount1` are the caller's own slippage floors, enforced inside
        // the provider. No additional on-chain bound is derived here: normal withdraw already
        // carries two independent price bounds — the `isCalm()` check above (spot within
        // `maxTickDeviation` of TWAP) and the oracle floor inside `_routeInKind`
        // (`realizedValueUsdc >= userAmount + protocolAmount`).

        // Interaction: redeem provider shares and route the proceeds in-kind.
        (uint256 toTreasury0, uint256 toTreasury1) = _executeWithdrawAndRoute(
            _action,
            adapterAddress,
            plan,
            _minAmount0,
            _minAmount1
        );

        // Record the routed fee as per-recipient entitlements in the RewardsVault
        // (== treasury). Done at this (shallow) frame to keep the routing helpers under
        // the stack limit; the funds are already at the treasury.
        _creditProtocolFee(_action.protocolSplitHash, _breakdown, toTreasury0, toTreasury1);
    }

    /// @dev Execute the provider redeem and in-kind routing for a planned withdrawal.
    ///      Separated from `withdraw` to reduce stack depth in the outer function.
    ///      Called only after `_planWithdraw` has applied all position effects.
    /// @param _action         Signed withdraw action containing the USDC routing split.
    /// @param _adapterAddress Wired adapter used to redeem provider shares.
    /// @param _plan           Withdrawal plan returned by `_planWithdraw`.
    /// @param _minAmount0     Minimum token0 amount accepted from the provider redeem.
    /// @param _minAmount1     Minimum token1 amount accepted from the provider redeem.
    function _executeWithdrawAndRoute(
        SignedAction calldata _action,
        address _adapterAddress,
        WithdrawPlan memory _plan,
        uint256 _minAmount0,
        uint256 _minAmount1
    ) internal returns (uint256 toTreasury0, uint256 toTreasury1) {
        // Transfer shares to the adapter and redeem from the provider.
        IERC20(IDualAssetLpVaultAdapter(_adapterAddress).vault()).safeTransfer(_adapterAddress, _plan.sharesToRedeem);
        (uint256 got0, uint256 got1) = IDualAssetLpVaultAdapter(_adapterAddress).withdraw(
            _plan.sharesToRedeem,
            _minAmount0,
            _minAmount1
        );

        // Route in-kind proportionally to the signed USDC split; return the treasury
        // legs so the caller can credit them to the RewardsVault.
        (toTreasury0, toTreasury1) = _transferRouted(_action, got0, got1, _plan.closing);
    }

    /// @dev Compute and execute the in-kind token transfers for a signed withdraw.
    ///      Separated to reduce stack depth. Emits `Withdrawn`.
    ///      Computes the REALIZED `totalValueUsdc` from the actual `got0`/`got1` and
    ///      passes it into `_routeInKind` — this is distinct from the PREVIEW value used
    ///      in `_planWithdraw` for the guards. The two values serve different purposes:
    ///      preview (pre-redeem) gates the fee; realized (post-redeem) settles the split.
    /// @param _action  Signed withdraw action containing `userAmount`/`protocolAmount`.
    /// @param _got0    Actual amount of `depositToken0` received from the provider.
    /// @param _got1    Actual amount of `depositToken1` received from the provider.
    /// @param _closing Whether the withdrawal closed the position.
    function _transferRouted(
        SignedAction calldata _action,
        uint256 _got0,
        uint256 _got1,
        bool _closing
    ) internal returns (uint256 toTreasury0, uint256 toTreasury1) {
        uint256 protocolAmount = _action.protocolAmount;
        // Compute the realized total USDC value of the redeemed tokens to pass into
        // _routeInKind. Oracle revert here is expected behavior for normal withdrawals
        // (stale oracle blocks normal ops — correct); only emergency bypasses this.
        uint256 realizedValueUsdc = IValuationOracle(oracle).dualValueInUsdc(
            depositToken0,
            _got0,
            depositToken1,
            _got1
        );
        uint256 toUser0;
        uint256 toUser1;
        (toUser0, toUser1, toTreasury0, toTreasury1) = _routeInKind(
            _got0,
            _got1,
            realizedValueUsdc,
            _action.userAmount + protocolAmount,
            protocolAmount
        );
        if (toTreasury0 > 0) IERC20(depositToken0).safeTransfer(treasury, toTreasury0);
        if (toTreasury1 > 0) IERC20(depositToken1).safeTransfer(treasury, toTreasury1);
        if (toUser0 > 0) IERC20(depositToken0).safeTransfer(msg.sender, toUser0);
        if (toUser1 > 0) IERC20(depositToken1).safeTransfer(msg.sender, toUser1);

        emit Withdrawn(
            _action.positionId,
            msg.sender,
            _action.userAmount,
            protocolAmount,
            toUser0,
            toUser1,
            toTreasury0,
            toTreasury1,
            _closing
        );
    }

    /// @dev Forward the routed protocol fee to the RewardsVault (== `treasury`) so it
    ///      records per-recipient entitlements. Called once per token with the ACTUAL
    ///      in-kind amounts that were just transferred to `treasury`; the RewardsVault
    ///      validates the breakdown against `_splitHash` and splits by bps. No-ops when
    ///      there is no signed breakdown (`_splitHash == 0`) — then the fee stays in the
    ///      treasury as unassigned balance (sweepable by governance).
    /// @param _splitHash   Backend commitment to `_breakdown` (from the signed action).
    /// @param _breakdown   Per-recipient, per-token shares (bps) for both pool tokens.
    /// @param _toTreasury0 token0 amount just routed to the treasury.
    /// @param _toTreasury1 token1 amount just routed to the treasury.
    function _creditProtocolFee(
        bytes32 _splitHash,
        ProtocolSplitShare[] calldata _breakdown,
        uint256 _toTreasury0,
        uint256 _toTreasury1
    ) internal {
        if (_splitHash == bytes32(0)) return;
        if (_toTreasury0 > 0) {
            IWadzRewardsVault(treasury).credit(_splitHash, _breakdown, depositToken0, _toTreasury0);
        }
        if (_toTreasury1 > 0) {
            IWadzRewardsVault(treasury).credit(_splitHash, _breakdown, depositToken1, _toTreasury1);
        }
    }

    /// @inheritdoc IDualAssetConcLiqVault
    /// @dev The surplus above principal that is routed to treasury is NAV-based
    ///      (total redeemed value − principal) and may include token price
    ///      appreciation that a normal fee-only withdrawal would have returned
    ///      to the user. This is the accepted cost of the no-backend,
    ///      principal-only escape path — exit safety takes precedence over
    ///      fee-only profit attribution.
    function emergencyRedeem(uint256 _positionId, uint256 _minOut0, uint256 _minOut1) external override nonReentrant {
        address adapterAddress = _requireAdapter();

        // Anti-sandwich guard: both zeros are rejected. The caller must supply at
        // least one non-zero floor.
        //
        // A stronger on-chain floor was evaluated and deliberately REJECTED: requiring each
        // leg to cover a fraction of `previewWithdraw` cannot be both non-blocking and
        // meaningful here. Manipulation shifts the composition BETWEEN legs, not just the
        // total, so a caller exiting mid-manipulation must pick a floor relative to a pool
        // state that does not exist yet — too low and the on-chain gate rejects it, too high
        // and the provider's own slippage check rejects it, with no reliably safe choice.
        // Since this is the one path that must never be blockable, the floor stays the
        // caller's own absolute `_minOut`, enforced inside the provider. A TWAP-derived
        // floor (not manipulable within a block, so it CAN be precomputed off-chain) is the
        // real fix and remains a future enhancement.
        if (_minOut0 == 0 && _minOut1 == 0) revert ZeroMinOut();

        Position storage position = _positions[_positionId];
        if (position.owner != msg.sender) revert NotPositionOwner(_positionId, msg.sender);
        if (position.status != PositionStatus.Active) revert PositionNotActive(_positionId);

        // Emergency does NOT check isCalm() in the general case — it must be available
        // even when the pool is not calm or when normal operations are paused. Fail-open.
        //
        // The ONLY exception is the per-position same-block anti-sandwich guard: if this
        // position contributed (deposit/top-up) in the CURRENT block, require calm.
        // This replaces the provider's global `lastDeposit` gate (which the emergency
        // path bypasses so third-party provider deposits cannot DoS the exit) with a
        // check scoped to the exiting position, blocking a deposit→manipulate→emergency
        // sandwich by the redeemer while leaving old positions fully fail-open.
        if (lastContributionAt[_positionId] == block.timestamp && !IDualAssetLpVaultAdapter(adapterAddress).isCalm()) {
            revert NotCalm();
        }

        uint256 shares = positionShares[_positionId];
        uint256 principalUsdc = position.principalUsdc;

        // ── Effects before interactions (CEI) ───────────────────────────────

        position.receiptAmount = 0;
        position.principalUsdc = 0;
        position.status = PositionStatus.EmergencyClosed;
        positionShares[_positionId] = 0;
        // Clear fee accrual state. Emergency does NOT recognize or charge fees;
        // it is fee-agnostic and must not depend on the fee index or oracle.
        delete _feeAccrual[_positionId];
        _clearOpenPosition(position.owner, position.licenseId);

        // ── Interactions ─────────────────────────────────────────────────────

        IERC20(IDualAssetLpVaultAdapter(adapterAddress).vault()).safeTransfer(adapterAddress, shares);
        // Emergency uses the adapter's `emergencyWithdraw`, which routes through the
        // provider's same-block-gate-skipping path (see the guard above for the scoped
        // anti-sandwich protection that replaces it).
        (uint256 got0, uint256 got1) = IDualAssetLpVaultAdapter(adapterAddress).emergencyWithdraw(
            shares,
            _minOut0,
            _minOut1
        );

        // Principal-only routing — BEST-EFFORT oracle, FAIL-OPEN.
        //
        // The oracle call is the ONLY step that can revert after the provider
        // redeem. Wrapping it in try/catch ensures the user can always exit
        // regardless of oracle staleness, configuration, or downtime.
        //
        // try  — oracle responds: compute surplus, route proportionally (treasury
        //         gets its slice of any gain above principal; user gets the rest).
        // catch — oracle reverts: send ALL redeemed tokens to the owner; treasury
        //         surplus is forgone. Exit safety dominates over surplus collection.
        //
        // ONLY the oracle call is in the try block. All other logic (position
        // effects, provider redeem) has already completed before this point.
        // Normal `withdraw` does NOT use try/catch — oracle revert there is the
        // correct failure mode and must propagate.
        uint256 toUser0;
        uint256 toUser1;
        uint256 toTreasury0;
        uint256 toTreasury1;

        try IValuationOracle(oracle).dualValueInUsdc(depositToken0, got0, depositToken1, got1) returns (
            uint256 totalValueUsdc
        ) {
            uint256 surplusUsdc = totalValueUsdc > principalUsdc ? totalValueUsdc - principalUsdc : 0;
            (toUser0, toUser1, toTreasury0, toTreasury1) = _routeInKind(
                got0,
                got1,
                totalValueUsdc,
                totalValueUsdc, // signedOwedUsdc == totalValueUsdc → slippage floor trivially satisfied
                surplusUsdc
            );
        } catch {
            // Oracle unavailable — fail-open: all tokens to the user.
            toUser0 = got0;
            toUser1 = got1;
            // toTreasury0 and toTreasury1 remain 0.
        }

        if (toTreasury0 > 0) IERC20(depositToken0).safeTransfer(treasury, toTreasury0);
        if (toTreasury1 > 0) IERC20(depositToken1).safeTransfer(treasury, toTreasury1);
        if (toUser0 > 0) IERC20(depositToken0).safeTransfer(msg.sender, toUser0);
        if (toUser1 > 0) IERC20(depositToken1).safeTransfer(msg.sender, toUser1);

        emit EmergencyRedeemed(_positionId, msg.sender, toUser0, toUser1, toTreasury0, toTreasury1);
    }

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

    /// @inheritdoc WadzWrapperBase
    function vaultKind() public pure override(IWadzVaultCore, WadzWrapperBase) returns (VaultKind) {
        return VaultKind.DUAL_ASSET_CONCENTRATED_LIQUIDITY;
    }

    /// @inheritdoc IDualAssetConcLiqVault
    function isCalm() external view override returns (bool) {
        address adapterAddress = _adapter;
        if (adapterAddress == address(0)) return false;
        return IDualAssetLpVaultAdapter(adapterAddress).isCalm();
    }

    /// @inheritdoc IDualAssetConcLiqVault
    function previewWithdraw(uint256 _shares) external view override returns (uint256 amount0, uint256 amount1) {
        address adapterAddress = _adapter;
        if (adapterAddress == address(0)) revert AdapterNotSet();
        return IDualAssetLpVaultAdapter(adapterAddress).previewWithdraw(_shares);
    }

    /// @inheritdoc WadzWrapperBase
    /// @dev Returns the oracle USDC value of the position's share balance via
    ///      `adapter.previewWithdraw`. Reverts on stale oracle (propagated from the
    ///      oracle; staleness must not silently miscount value).
    function positionValueUsdc(
        uint256 _positionId
    ) external view override(IWadzVaultCore, WadzWrapperBase) returns (uint256) {
        Position storage position = _positions[_positionId];
        if (position.owner == address(0)) revert UnknownPosition(_positionId);
        address adapterAddress = _adapter;
        if (adapterAddress == address(0)) revert AdapterNotSet();
        (uint256 a0, uint256 a1) = IDualAssetLpVaultAdapter(adapterAddress).previewWithdraw(
            positionShares[_positionId]
        );
        return IValuationOracle(oracle).dualValueInUsdc(depositToken0, a0, depositToken1, a1);
    }

    /// @inheritdoc WadzWrapperBase
    /// @dev For dual-asset LP this returns the FEE-ONLY protocol-fee **cap** (the maximum
    ///      `protocolAmount` a withdraw may charge, in USDC), NOT the user's realizable
    ///      profit — the user's take is the value of their shares (`previewWithdraw`).
    ///      The base-interface name `availableProfitUsdc` is kept for cross-vault-kind
    ///      compatibility; integrations should prefer the clearer `maxProtocolFeeUsdc`,
    ///      which returns the same value. See `_maxProtocolFeeUsdc` for the formula.
    function availableProfitUsdc(
        uint256 _positionId
    ) external view override(IWadzVaultCore, WadzWrapperBase) returns (uint256) {
        return _maxProtocolFeeUsdc(_positionId);
    }

    /// @inheritdoc IDualAssetConcLiqVault
    function maxProtocolFeeUsdc(uint256 _positionId) external view override returns (uint256) {
        return _maxProtocolFeeUsdc(_positionId);
    }

    /// @notice Fee-only protocol-fee cap for this position, capped by NAV net gain.
    /// @dev    The ceiling on `protocolAmount` a withdraw may
    ///         charge (in USDC), NOT the user's profit. Returns `min(feeOnlyUsdc, netGainUsdc)`:
    ///           - `feeOnlyUsdc` = USDC value of pending fees (`_pendingFees` on the
    ///             full position shares), attributed via the cumulative per-share index.
    ///           - `netGainUsdc` = max(0, positionValueUsdc − principalUsdc).
    ///         Capping by net gain prevents recognizing fees that are not realizable
    ///         due to IL (the LP fee-only rule).
    ///         `feeOnlyUsdc` is an approximate on-chain ceiling, not the authoritative
    ///         fee amount to sign. The provider index advances at harvest rather than
    ///         every fee claim, so supply changes between claim and harvest can shift
    ///         attribution. The backend must reconstruct attributable LP fees off-chain
    ///         and sign that amount; this contract additionally caps it by `netGainUsdc`.
    ///         Exact trustless attribution requires a future provider-accounting change.
    function _maxProtocolFeeUsdc(uint256 _positionId) internal view returns (uint256) {
        Position storage position = _positions[_positionId];
        if (position.owner == address(0)) revert UnknownPosition(_positionId);
        address adapterAddress = _adapter;
        // No position can exist before setAdapter is called (deposit requires a wired
        // adapter via _requireAdapter). If this path is somehow reached, revert
        // consistently with positionValueUsdc rather than silently returning zero.
        if (adapterAddress == address(0)) revert AdapterNotSet();

        uint256 shares = positionShares[_positionId];

        // Net gain: position value minus principal (zero if underwater).
        (uint256 a0, uint256 a1) = IDualAssetLpVaultAdapter(adapterAddress).previewWithdraw(shares);
        uint256 posVal = IValuationOracle(oracle).dualValueInUsdc(depositToken0, a0, depositToken1, a1);
        uint256 netGainUsdc = posVal > position.principalUsdc ? posVal - position.principalUsdc : 0;

        if (netGainUsdc == 0) return 0;

        // Fee-only USDC: oracle value of pending raw-token fees.
        (uint256 fee0, uint256 fee1) = _pendingFees(_positionId, shares, adapterAddress);
        if (fee0 == 0 && fee1 == 0) return 0;
        uint256 feeOnlyUsdc = IValuationOracle(oracle).dualValueInUsdc(depositToken0, fee0, depositToken1, fee1);

        // Return the lesser of fee-only and net gain (conservative, never over-attribute).
        return feeOnlyUsdc < netGainUsdc ? feeOnlyUsdc : netGainUsdc;
    }

    // ─── Internals ───────────────────────────────────────────────────────

    /// @dev Execute all checks and effects for a single signed withdrawal, applying
    ///      position state changes BEFORE any external interaction (CEI). Returns a
    ///      `WithdrawPlan` that the caller uses to drive the provider redeem.
    ///      Does NOT call the adapter or transfer tokens.
    ///
    ///      Specifically:
    ///      - validates `_action.positionId` position (owner, status, licenseId);
    ///      - resolves shares (partial vs. full-close sentinel);
    ///      - computes pro-rata principal of the withdrawn portion;
    ///      - previews the USDC value of those shares via the oracle;
    ///      - applies the net-negative guard (`FeeOnLoss`) and fee-only cap
    ///        (`FeeExceedsFeeOnlyProfit`: protocolAmount must not exceed
    ///        min(pendingFeeUsdc, netGainUsdc) for the withdrawn portion);
    ///      - mutates position state (receiptAmount, principalUsdc, positionShares,
    ///        status, claimedProfitUsdc, `_clearOpenPosition` on close).
    ///
    /// @param _action        Signed `Withdraw` action (nonce already consumed by caller).
    /// @param _adapterAddress Wired adapter address (already validated non-zero by caller).
    /// @return plan          Planning result for the interaction phase.
    function _planWithdraw(
        SignedAction calldata _action,
        address _adapterAddress
    ) internal returns (WithdrawPlan memory plan) {
        uint256 positionId = _action.positionId;
        Position storage position = _positions[positionId];
        _requireActionablePosition(position, positionId, _action.licenseId);

        // Force the breakdown: a protocol cut MUST carry a signed split so it is always
        // credited to recipients (no un-attributed lump). Only a backend bug hits this.
        if (_action.protocolAmount > 0 && _action.protocolSplitHash == bytes32(0)) revert MissingProtocolSplit();

        uint256 totalPositionShares = positionShares[positionId];

        // Resolve shares: type(uint256).max sentinel means full close.
        if (_action.amount == type(uint256).max) {
            plan.closing = true;
            plan.sharesToRedeem = totalPositionShares;
        } else {
            if (_action.amount == 0) revert ZeroAmount();
            plan.sharesToRedeem = _action.amount;
            if (plan.sharesToRedeem >= totalPositionShares) {
                plan.sharesToRedeem = totalPositionShares;
                plan.closing = true;
            }
        }

        // Pro-rata principal of the withdrawn portion.
        if (plan.closing) {
            plan.principalUsdcOfWithdrawn = position.principalUsdc;
        } else {
            plan.principalUsdcOfWithdrawn = Math.mulDiv(
                position.principalUsdc,
                plan.sharesToRedeem,
                totalPositionShares
            );
        }

        // Preview USDC value BEFORE any state mutation (needed for guard checks).
        {
            (uint256 preview0, uint256 preview1) = IDualAssetLpVaultAdapter(_adapterAddress).previewWithdraw(
                plan.sharesToRedeem
            );
            plan.positionValueUsdcBeforeRedeem = IValuationOracle(oracle).dualValueInUsdc(
                depositToken0,
                preview0,
                depositToken1,
                preview1
            );
        }

        // ── Guards ────────────────────────────────────────────────────────────
        uint256 protocolAmount = _action.protocolAmount;

        // Net-negative guard: no fee if the withdrawn portion is not in net profit.
        if (plan.positionValueUsdcBeforeRedeem <= plan.principalUsdcOfWithdrawn) {
            if (protocolAmount > 0) revert FeeOnLoss();
        }

        // Approximate fee-only cap: fee bounded by
        // min(pendingFeeOnlyUsdc, netGainUsdc) for the withdrawn portion, pro-rated
        // by shares. The backend remains responsible for signing off-chain
        // reconstructed attributable fees because claim-to-harvest supply changes
        // can shift this provider index.
        {
            uint256 netGain = plan.positionValueUsdcBeforeRedeem > plan.principalUsdcOfWithdrawn
                ? plan.positionValueUsdcBeforeRedeem - plan.principalUsdcOfWithdrawn
                : 0;

            // Compute pending raw fees for the entire position, then pro-rate to the
            // withdrawn portion. Round DOWN (conservative — never over-attribute fees).
            (uint256 totalFee0, uint256 totalFee1) = _pendingFees(positionId, totalPositionShares, _adapterAddress);
            uint256 withdrawnFee0;
            uint256 withdrawnFee1;
            if (plan.closing) {
                withdrawnFee0 = totalFee0;
                withdrawnFee1 = totalFee1;
            } else {
                withdrawnFee0 = Math.mulDiv(totalFee0, plan.sharesToRedeem, totalPositionShares);
                withdrawnFee1 = Math.mulDiv(totalFee1, plan.sharesToRedeem, totalPositionShares);
            }

            uint256 feeOnlyUsdc = 0;
            if (withdrawnFee0 > 0 || withdrawnFee1 > 0) {
                feeOnlyUsdc = IValuationOracle(oracle).dualValueInUsdc(
                    depositToken0,
                    withdrawnFee0,
                    depositToken1,
                    withdrawnFee1
                );
            }
            // Cap: min(feeOnly, netGain)
            plan.feeOnlyUsdcOfWithdrawn = feeOnlyUsdc < netGain ? feeOnlyUsdc : netGain;

            if (protocolAmount > plan.feeOnlyUsdcOfWithdrawn) {
                revert FeeExceedsFeeOnlyProfit(protocolAmount, plan.feeOnlyUsdcOfWithdrawn);
            }
        }

        // ── Effects ───────────────────────────────────────────────────────────

        // Settle pending fees on the current (pre-change) share count before mutating positionShares.
        _settleFees(positionId);

        if (plan.closing) {
            position.receiptAmount = 0;
            position.principalUsdc = 0;
            position.status = PositionStatus.Closed;
            positionShares[positionId] = 0;
            delete _feeAccrual[positionId];
            _clearOpenPosition(position.owner, position.licenseId);
        } else {
            position.receiptAmount -= plan.sharesToRedeem;
            position.principalUsdc -= plan.principalUsdcOfWithdrawn;
            positionShares[positionId] -= plan.sharesToRedeem;
            // Pro-rate the accrued raw fees to remove the withdrawn share's portion.
            // After _settleFees, pending = 0 and all attribution is in accruedFee*.
            FeeAccrual storage fa = _feeAccrual[positionId];
            if (fa.accruedFee0 > 0 && totalPositionShares > 0) {
                fa.accruedFee0 = Math.mulDiv(
                    fa.accruedFee0,
                    totalPositionShares - plan.sharesToRedeem,
                    totalPositionShares
                );
            }
            if (fa.accruedFee1 > 0 && totalPositionShares > 0) {
                fa.accruedFee1 = Math.mulDiv(
                    fa.accruedFee1,
                    totalPositionShares - plan.sharesToRedeem,
                    totalPositionShares
                );
            }
            if (plan.positionValueUsdcBeforeRedeem > plan.principalUsdcOfWithdrawn) {
                position.claimedProfitUsdc += plan.positionValueUsdcBeforeRedeem - plan.principalUsdcOfWithdrawn;
            }
        }
    }

    /// @dev Require the position to be Active, owned by `msg.sender`, and matching
    ///      the signed `_licenseId`.
    /// @param _position   Storage pointer to the position being checked.
    /// @param _positionId Position id used for contextual reverts.
    /// @param _licenseId  License id carried by the signed action.
    function _requireActionablePosition(
        Position storage _position,
        uint256 _positionId,
        uint256 _licenseId
    ) internal view {
        if (_position.owner != msg.sender) revert NotPositionOwner(_positionId, msg.sender);
        if (_position.status != PositionStatus.Active) revert PositionNotActive(_positionId);
        if (_position.licenseId != _licenseId) revert LicenseMismatch(_licenseId, _position.licenseId);
    }

    /// @dev Revert if the adapter has not been wired. Returns the adapter address to
    ///      avoid a second storage read in the calling function.
    /// @return adapterAddress Wired adapter address.
    function _requireAdapter() internal view returns (address adapterAddress) {
        adapterAddress = _adapter;
        if (adapterAddress == address(0)) revert AdapterNotSet();
    }

    /// @dev Compute the pending raw-token fees attributable to a position based on the
    ///      current cumulative fee index delta since the position's last settle point.
    ///      Rounds DOWN at every mulDiv — conservative, never over-attributes fees.
    ///
    ///      `pendingFee = accruedFee + mulDiv(positionShares, idx_now - idx_start, PRECISION)`
    ///
    ///      Unharvested fees (not yet reflected in the index) are NOT included — this is
    ///      intentional. Harvest is permissionless; the attribution only covers fees that
    ///      have been collected and indexed on-chain.
    ///
    /// @param _positionId    Position to query.
    /// @param _positionShares Current share count for the position (passed to avoid re-read).
    /// @param _adapterAddress Wired adapter (non-zero, pre-validated by caller).
    /// @return fee0  Attributable token0 fees (raw token amount, rounded down).
    /// @return fee1  Attributable token1 fees (raw token amount, rounded down).
    function _pendingFees(
        uint256 _positionId,
        uint256 _positionShares,
        address _adapterAddress
    ) internal view returns (uint256 fee0, uint256 fee1) {
        FeeAccrual storage fa = _feeAccrual[_positionId];
        (uint256 idx0Now, uint256 idx1Now) = IDualAssetLpVaultAdapter(_adapterAddress).feeIndexes();

        // Delta: how much index has grown since the last settle. Underflow impossible
        // because the cumulative index is monotonically increasing.
        uint256 delta0 = idx0Now - fa.feeIndex0Start;
        uint256 delta1 = idx1Now - fa.feeIndex1Start;

        // Round DOWN — Math.mulDiv default rounds towards zero (floor).
        fee0 = fa.accruedFee0 + Math.mulDiv(_positionShares, delta0, PRECISION);
        fee1 = fa.accruedFee1 + Math.mulDiv(_positionShares, delta1, PRECISION);
    }

    /// @dev Roll the current pending fees into `accruedFee*` and reset the index
    ///      snapshots to now. Must be called BEFORE any change to `positionShares`
    ///      to ensure the correct share count is used for the current-interval pending.
    ///
    ///      After this call: `accruedFee0/1` = prior accrued + interval fees;
    ///      `feeIndex0Start/1Start` = current index. Next `_pendingFees` call starts
    ///      a fresh interval.
    ///
    /// @param _positionId Position to settle.
    function _settleFees(uint256 _positionId) internal {
        // _settleFees is called only from _resolvePosition (deposit top-up) and
        // _planWithdraw, both of which are guarded by _requireAdapter() in their
        // callers. The adapter is therefore guaranteed non-zero here; no guard needed.
        address adapterAddress = _adapter;

        uint256 shares = positionShares[_positionId];
        FeeAccrual storage fa = _feeAccrual[_positionId];
        (uint256 idx0Now, uint256 idx1Now) = IDualAssetLpVaultAdapter(adapterAddress).feeIndexes();

        uint256 delta0 = idx0Now - fa.feeIndex0Start;
        uint256 delta1 = idx1Now - fa.feeIndex1Start;

        if (delta0 > 0) {
            fa.accruedFee0 += Math.mulDiv(shares, delta0, PRECISION);
        }
        if (delta1 > 0) {
            fa.accruedFee1 += Math.mulDiv(shares, delta1, PRECISION);
        }

        fa.feeIndex0Start = idx0Now;
        fa.feeIndex1Start = idx1Now;
    }

    /// @dev In-kind proportional routing. Splits `_got0`/`_got1` so that treasury
    ///      receives the fraction proportional to `_targetTreasuryUsdc` out of
    ///      `_totalValueUsdc`. Rounds DOWN for treasury (conservative — never
    ///      overpay the protocol). User receives the remainder, which includes any
    ///      surplus above the signed split.
    ///
    ///      Does NOT call the oracle. The caller is responsible for computing
    ///      `_totalValueUsdc` and passing it in. This design has two benefits:
    ///      (a) no double oracle round-trip; (b) emergency can call this helper
    ///      with an oracle-independent fallback total (all tokens to user) without
    ///      having a second oracle call inside this function.
    ///
    ///      Slippage floor (normal withdraw only): reverts `InsufficientRedeemed` if
    ///      `_totalValueUsdc < _signedOwedUsdc`. This validates that the provider
    ///      returned at least the USDC equivalent of the signed routing total
    ///      (userAmount + protocolAmount). Emergency callers pass
    ///      `_signedOwedUsdc == _totalValueUsdc` so the floor is trivially satisfied.
    ///
    /// @param _got0               token0 received from the provider.
    /// @param _got1               token1 received from the provider.
    /// @param _totalValueUsdc     USDC value of `_got0`/`_got1`, pre-computed by caller.
    /// @param _signedOwedUsdc     userAmount + protocolAmount (signed routing total, USDC).
    /// @param _targetTreasuryUsdc USDC-denominated amount that should go to treasury.
    /// @return toUser0       token0 to send to the user.
    /// @return toUser1       token1 to send to the user.
    /// @return toTreasury0   token0 to send to treasury.
    /// @return toTreasury1   token1 to send to treasury.
    function _routeInKind(
        uint256 _got0,
        uint256 _got1,
        uint256 _totalValueUsdc,
        uint256 _signedOwedUsdc,
        uint256 _targetTreasuryUsdc
    ) internal pure returns (uint256 toUser0, uint256 toUser1, uint256 toTreasury0, uint256 toTreasury1) {
        // Slippage floor: redeemed value must cover the signed routing total.
        if (_totalValueUsdc < _signedOwedUsdc) revert InsufficientRedeemed(_totalValueUsdc, _signedOwedUsdc);

        if (_targetTreasuryUsdc == 0 || _totalValueUsdc == 0) {
            // No protocol fee or nothing to split: user gets everything.
            return (_got0, _got1, 0, 0);
        }

        // Treasury fraction = targetTreasuryUsdc / totalValueUsdc, applied per token.
        // Math.mulDiv default rounds DOWN — conservative, never overpay the protocol.
        toTreasury0 = Math.mulDiv(_got0, _targetTreasuryUsdc, _totalValueUsdc);
        toTreasury1 = Math.mulDiv(_got1, _targetTreasuryUsdc, _totalValueUsdc);

        // User receives the remainder (includes surplus above the signed split).
        toUser0 = _got0 - toTreasury0;
        toUser1 = _got1 - toTreasury1;
    }
}

@openzeppelin/contracts/interfaces/IERC1363.sol

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

pragma solidity >=0.6.2;

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.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

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

@openzeppelin/contracts/interfaces/IERC20.sol

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

pragma solidity >=0.4.16;

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

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

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

pragma solidity >=0.4.16;

/**
 * @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.5.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.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 {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @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 {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 relies 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 relies 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}.
     * Oppositely, 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 `token.transfer(to, value)` call, 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 to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

@openzeppelin/contracts/utils/Panic.sol

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

pragma solidity ^0.8.20;

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

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

@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol

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

pragma solidity ^0.8.24;

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

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        _reentrancyGuardStorageSlot().asBoolean().tstore(false);
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _reentrancyGuardStorageSlot().asBoolean().tload();
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

@openzeppelin/contracts/utils/TransientSlot.sol

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

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represents a slot holding an address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

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

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

pragma solidity >=0.4.16;

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

@openzeppelin/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

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

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

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

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

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

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

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

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

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

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

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

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory buffer) private pure returns (bool) {
        uint256 chunk;
        for (uint256 i = 0; i < buffer.length; i += 0x20) {
            // See _unsafeReadBytesOffset from utils/Bytes.sol
            assembly ("memory-safe") {
                chunk := mload(add(add(buffer, 0x20), i))
            }
            if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
                return false;
            }
        }
        return true;
    }

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

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

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

    /**
     * @dev Counts the number of leading zero bits in a uint256.
     */
    function clz(uint256 x) internal pure returns (uint256) {
        return ternary(x == 0, 256, 255 - log2(x));
    }
}

@openzeppelin/contracts/utils/math/SafeCast.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

contracts/platform/authorizer/IWadzActionAuthorizer.sol

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

// ─── Enums ───────────────────────────────────────────────────────────

/// @notice Normal user actions that require a backend EIP-712 authorization.
/// @dev    `emergencyRedeem` is intentionally absent: it is signature-free and
///         must remain callable without backend authorization.
enum WadzActionType {
    Deposit,
    Claim,
    Withdraw
}

// ─── Structs ─────────────────────────────────────────────────────────

/// @notice Canonical signed-action payload. Mirrors the EIP-712 typed-data the
///         backend signs to authorize a single normal operation.
/// @dev    `chainId` and `verifyingContract` are NOT fields here: they are bound
///         by the EIP-712 domain separator inside the authorizer, so replay
///         across chains or verifier contracts is rejected at signature recovery.
///         `userAmount`/`protocolAmount` are the exact signed routing the wrapper
///         must execute on claim/withdraw; the wrapper never invents the split.
///         Units of `amount`/`userAmount`/`protocolAmount` are the wrapper's
///         transfer token (depositAsset for SINGLE_ASSET_SYNC).
struct SignedAction {
    // Action being authorized: Deposit, Claim, or Withdraw.
    WadzActionType action;
    // Wallet that must execute the tx (the wrapper enforces msg.sender == user).
    address user;
    // Target vault id (binds the signature to one vault).
    uint256 vaultId;
    // Off-chain license reference (policy lives in the backend).
    uint256 licenseId;
    // Target position id; 0 when opening a new position (deposit).
    uint256 positionId;
    // Action-specific magnitude. For a dual-asset Deposit this is
    // uint256(keccak256(abi.encode(amount0, amount1))); for other actions it keeps
    // the wrapper-defined unit (for example provider shares on a dual withdraw).
    uint256 amount;
    // Portion of `amount` routed to the user (signed split; 0 on deposit).
    uint256 userAmount;
    // Portion of `amount` routed to treasury (signed split; 0 on deposit).
    uint256 protocolAmount;
    // keccak256 commitment to the off-chain breakdown of `protocolAmount` into
    // per-recipient, per-token entitlements credited in the rewards/treasury
    // contract (referrers + protocol). `bytes32(0)` means "no breakdown": the
    // action carries no split and `protocolAmount` is routed to treasury as a
    // lump (deposits and non-referral claims/withdraws). The wrapper only records
    // a breakdown when this is non-zero and it matches the provided calldata.
    bytes32 protocolSplitHash;
    // L1 referrer for attribution, or address(0) if none.
    address referrer;
    // Unix timestamp after which the signature is no longer valid.
    uint256 deadline;
    // Single-use nonce per user (anti-replay).
    uint256 nonce;
}

/// @title IWadzActionAuthorizer
/// @notice Boundary for the EIP-712 verifier that authorizes normal wrapper
///         operations on behalf of the WADZ backend.
/// @dev    Wrappers call `verifyAndConsume` and then bind the call to the signed
///         payload (msg.sender == user, vaultId, action) themselves.
interface IWadzActionAuthorizer {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice Recovered signer is not an authorized backend signer.
    error UnauthorizedSigner(address signer);

    /// @notice Signed deadline has passed.
    error SignatureExpired(uint256 deadline);

    /// @notice Nonce has already been consumed for this user.
    error NonceAlreadyUsed(address user, uint256 nonce);

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted after a signed action is verified and its nonce consumed.
    event ActionAuthorized(address indexed user, WadzActionType indexed action, uint256 indexed vaultId, uint256 nonce);

    // ─── Functions ─────────────────────────────────────────────────────────

    /// @notice Authorize or revoke a backend signer.
    /// @dev Callable only by `SIGNER_ADMIN_ROLE` on the concrete authorizer.
    function setSigner(address _signer, bool _authorized) external;

    /// @notice Authorize or revoke a wrapper caller for a vault id.
    /// @dev Callable only by `CALLER_REGISTRAR_ROLE` on the concrete authorizer.
    function setCaller(address _caller, uint256 _vaultId, bool _authorized) external;

    /// @notice Verify a signed action and consume its nonce in the same call.
    /// @dev    Reverts unless: the caller is an authorized caller (the verifier may
    ///         restrict this to governance-registered WADZ wrappers); the recovered
    ///         signer is authorized; the EIP-712 signature is valid for the exact
    ///         typed data (domain binds `block.chainid` and this contract as
    ///         `verifyingContract`); the deadline has not expired; and the nonce was
    ///         unused. Consumes the nonce on success. Does NOT check `msg.sender ==
    ///         user`: the calling wrapper binds that.
    /// @param _action    The signed action payload.
    /// @param _signature The backend signature over `_action`.
    function verifyAndConsume(SignedAction calldata _action, bytes calldata _signature) external;

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

    /// @notice Returns true if `_signer` is an authorized backend signer.
    function isAuthorizedSigner(address _signer) external view returns (bool);

    /// @notice Returns true if `_nonce` has already been consumed for `_user`.
    function isNonceUsed(address _user, uint256 _nonce) external view returns (bool);

    /// @notice Role permitted to authorize or revoke backend EIP-712 signers.
    function SIGNER_ADMIN_ROLE() external view returns (bytes32);

    /// @notice Role permitted to authorize or revoke wrapper callers.
    function CALLER_REGISTRAR_ROLE() external view returns (bytes32);

    /// @notice Returns true if `_caller` may call `verifyAndConsume`.
    function isAuthorizedCaller(address _caller) external view returns (bool);

    /// @notice Returns the vault id `_caller` is authorized to serve (0 = unauthorized).
    function callerVaultId(address _caller) external view returns (uint256);

    /// @notice Returns the domain-separated EIP-712 digest for `_action` — the value
    ///         the backend signs and that `verifyAndConsume` recovers against
    ///         (for off-chain signing/testing).
    function hashAction(SignedAction calldata _action) external view returns (bytes32);
}

contracts/platform/oracle/IValuationOracle.sol

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

/// @title IValuationOracle
/// @notice Converts asset amounts to USDC-equivalent values for WADZ accounting.
/// @dev    Used by wrappers to compute `principalUsdc` at deposit and
///         `positionValueUsdc` at claim/withdraw. Implementations (trivial USDC,
///         Chainlink peg with staleness, dual-asset) satisfy this boundary; the
///         wrapper picks the oracle per vault at deploy time.
///         Valuation paths MUST revert on stale/unsafe data so profit is never
///         silently miscounted.
interface IValuationOracle {
    // ─── Views ───────────────────────────────────────────────────────────

    /// @notice Convert a single asset amount to its USDC-equivalent value.
    /// @dev    Reverts if the oracle data is stale or deviates beyond the
    ///         implementation's safety threshold.
    /// @param _asset  The asset to value.
    /// @param _amount Amount of `_asset` in its native decimals.
    /// @return usdcValue USDC-equivalent value (6 decimals).
    function valueInUsdc(address _asset, uint256 _amount) external view returns (uint256 usdcValue);

    /// @notice Convert two asset amounts to their combined USDC-equivalent value.
    /// @dev    Used by dual-asset wrappers. Reverts if either feed is stale.
    function dualValueInUsdc(
        address _token0,
        uint256 _amount0,
        address _token1,
        uint256 _amount1
    ) external view returns (uint256 usdcValue);

    /// @notice Last update timestamp for an asset's oracle feed.
    function lastUpdated(address _asset) external view returns (uint256 timestamp);
}

contracts/platform/rewards/IWadzRewardsVault.sol

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

// ─── Structs ─────────────────────────────────────────────────────────

/// @notice One share of a wrapper's protocol cut: `bps` (out of 10_000) of a given
///         `token`, owed to `recipient`.
/// @dev    Shares are PERCENTAGES, not absolute amounts, so a single breakdown works
///         for both single-asset (one token, exact amount known) and dual-asset (the
///         protocol cut is a proportional slice of BOTH tokens whose exact per-token
///         amounts are only known at redeem time). Per token, the `bps` of all entries
///         must sum to 10_000. The abi-encoding of a `ProtocolSplitShare[]` is what the
///         backend commits to via `SignedAction.protocolSplitHash`.
struct ProtocolSplitShare {
    // Referrer or protocol address entitled to the share.
    address recipient;
    // Token the share applies to (in-kind; no swaps).
    address token;
    // Share of that token's routed protocol amount, out of 10_000.
    uint16 bps;
}

/// @title IWadzRewardsVault
/// @notice Boundary for the WADZ rewards/treasury contract: a multi-token
///         pull-payment ledger that receives each vault's protocol cut and records
///         per-recipient (referrer + protocol) entitlements, which recipients later
///         claim WITHOUT a backend signature.
/// @dev    Wrappers call `credit` when routing a protocol cut; recipients call
///         `claim`. The split is decided off-chain by the backend and committed in
///         `SignedAction.protocolSplitHash`; all split validation lives in `credit`
///         (not in the wrappers) so every vault kind only has to forward.
interface IWadzRewardsVault {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice A zero address was supplied where a non-zero one is required.
    error ZeroAddress();

    /// @notice `credit` caller is not a registered WADZ wrapper.
    error NotAuthorizedWrapper(address caller);

    /// @notice The provided breakdown does not match the signed `splitHash`.
    error SplitHashMismatch();

    /// @notice The `bps` of the breakdown entries for a token do not sum to 10_000.
    error InvalidBpsSum(address token, uint256 bpsSum);

    /// @notice The vault does not hold enough of the token to back the credit.
    /// @dev    `required` = existing `totalOwed` + this credit; `available` = balance.
    error InsufficientBacking(address token, uint256 required, uint256 available);

    /// @notice The caller has no claimable balance for the token.
    error NothingToClaim(address recipient, address token);

    /// @notice A sweep tried to take more than the unassigned (non-credited) balance.
    error ExceedsUnassigned(uint256 requested, uint256 available);

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted when a wrapper is allowlisted or revoked as a `credit` caller.
    event WrapperSet(address indexed wrapper, bool allowed);

    /// @notice Emitted for each recipient credited by a `credit` call.
    /// @param recipient Address whose entitlement grew.
    /// @param token     Token credited.
    /// @param amount    Amount credited to `recipient` for `token`.
    /// @param splitHash Backend commitment the credit was validated against.
    event Credited(address indexed recipient, address indexed token, uint256 amount, bytes32 indexed splitHash);

    /// @notice Emitted when a recipient claims their entitlement for a token.
    event Claimed(address indexed recipient, address indexed token, uint256 amount);

    /// @notice Emitted when governance sweeps unassigned (non-credited) balance.
    event SweptUnassigned(address indexed token, address indexed to, uint256 amount);

    // ─── Wrapper registry (admin) ─────────────────────────────────────────

    /// @notice Allowlist or revoke a WADZ wrapper as an authorized `credit` caller.
    /// @dev    Gated by `WRAPPER_REGISTRAR_ROLE` (held by the factory for atomic
    ///         registration at vault deployment; governance retains it for repair).
    /// @param _wrapper Wrapper address.
    /// @param _allowed Whether it may call `credit`.
    function setWrapper(address _wrapper, bool _allowed) external;

    // ─── Credit (wrappers) ────────────────────────────────────────────────

    /// @notice Record entitlements for `amount` of `token` just routed by a wrapper,
    ///         split among recipients per the signed `breakdown`.
    /// @dev    Callable only by registered WADZ wrappers, which MUST have transferred
    ///         `amount` of `token` to this contract in the same transaction (so
    ///         recorded entitlements are always fully backed). Verifies
    ///         `keccak256(abi.encode(breakdown)) == splitHash` and that the `bps` of the
    ///         entries whose `token` matches sum to 10_000, then applies
    ///         `owed[recipient][token] += bps * amount / 10_000` to each (the last
    ///         matching entry absorbs the rounding remainder so credits sum exactly to
    ///         `amount`). A dual-asset wrapper calls this once per token with the same
    ///         `splitHash`/`breakdown`.
    /// @param _splitHash Backend commitment to `_breakdown` (from the signed action).
    /// @param _breakdown Per-recipient, per-token shares (bps).
    /// @param _token     Token being credited.
    /// @param _amount    Amount of `_token` routed for this action.
    function credit(
        bytes32 _splitHash,
        ProtocolSplitShare[] calldata _breakdown,
        address _token,
        uint256 _amount
    ) external;

    // ─── Claim (recipients) ───────────────────────────────────────────────

    /// @notice Claim the caller's full entitlement for a token, sent to the caller.
    /// @dev    Signature-free: entitlements were already authorized when credited.
    /// @param _token Token to claim.
    /// @return amount Amount transferred to the caller.
    function claim(address _token) external returns (uint256 amount);

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

    /// @notice Whether `_wrapper` may call `credit`.
    function isWrapper(address _wrapper) external view returns (bool);

    /// @notice Claimable balance of `_recipient` for `_token`.
    function owed(address _recipient, address _token) external view returns (uint256);

    /// @notice Total credited-but-unclaimed balance for `_token` (sum of all `owed`).
    /// @dev    The vault balance minus this is the unassigned amount governance may sweep.
    function totalOwed(address _token) external view returns (uint256);

    // ─── Sweep unassigned (admin) ─────────────────────────────────────────

    /// @notice Sweep unassigned (non-credited) balance of a token to `_to`.
    /// @dev    Gated by `DEFAULT_ADMIN_ROLE`. Can only move `balanceOf(this) - totalOwed`
    ///         — protocol revenue that arrived without a per-recipient split (emergency
    ///         surplus, dust, legacy lump). Credited entitlements are never touchable.
    /// @param _token  Token to sweep.
    /// @param _to     Destination (protocol treasury).
    /// @param _amount Amount to sweep (≤ unassigned balance).
    function sweep(address _token, address _to, uint256 _amount) external;
}

contracts/platform/types/WadzTypes.sol

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

// ─── Enums ───────────────────────────────────────────────────────────

/// @notice Vault kind taxonomy. A new kind is required when deposit shape,
///         withdrawal lifecycle, valuation model, or emergency behavior differs.
/// @dev    `SINGLE_ASSET_ASYNC` is reserved for a future asynchronous withdrawal
///         lifecycle so the shared type encoding remains stable.
enum VaultKind {
    SINGLE_ASSET_SYNC, // generic ERC4626 wrapper
    DUAL_ASSET_CONCENTRATED_LIQUIDITY, // concentrated-liquidity LP wrapper
    SINGLE_ASSET_ASYNC // out of MVP scope; reserved
}

/// @notice Lifecycle state of a deployed vault instance.
/// @dev    Paused blocks new deposits; withdraw/claim/emergency remain available.
///         Deprecated blocks new deposits permanently; existing positions can exit.
enum VaultState {
    Active,
    Paused,
    Deprecated
}

/// @notice Lifecycle state of a single user position inside a wrapper.
/// @dev    WithdrawPending only applies to the async kind (out of MVP scope).
enum PositionStatus {
    Active,
    WithdrawPending,
    Closed,
    EmergencyClosed
}

// ─── Structs ─────────────────────────────────────────────────────────

/// @notice Canonical position record. Stored inside each wrapper, never in a
///         shared registry, because `receiptAmount` semantics are kind-specific
///         and only the wrapper can convert it to a USDC value.
/// @dev    For SINGLE_ASSET_SYNC, `receiptAmount` is the provider ERC4626 share
///         balance held by the wrapper. `principalUsdc` is fixed at deposit time
///         via the valuation oracle. `adapterMetadata` is empty for sync kinds.
///         Profit recognized through claims and partial withdrawals.
///         dev Does not include profit implicit in a full close. Reconstruct the
///         complete history off-chain from wrapper events and ERC-20 transfers.
struct Position {
    uint256 positionId;
    address owner;
    uint256 licenseId;
    uint256 vaultId;
    VaultKind vaultKind;
    uint256 receiptAmount;
    uint256 principalUsdc;
    uint256 claimedProfitUsdc;
    uint64 openedAt;
    PositionStatus status;
    bytes adapterMetadata;
}

contracts/vaults/dual-asset-conc-liq/IDualAssetConcLiqVault.sol

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

import { IWadzVaultCore } from "../shared/IWadzVaultCore.sol";
import { SignedAction } from "../../platform/authorizer/IWadzActionAuthorizer.sol";
import { ProtocolSplitShare } from "../../platform/rewards/IWadzRewardsVault.sol";

/// @title IDualAssetConcLiqVault
/// @notice Vault-kind interface for DUAL_ASSET_CONCENTRATED_LIQUIDITY. Adds the
///         dual-token action surface to `IWadzVaultCore`. Backed by a
///         `DualAssetLpVaultAdapter` that proxies `VaultConcLiq` calls; the wrapper
///         custodies VaultConcLiq ERC-20 shares internally — users receive only a
///         non-transferable WADZ `positionId`, never the LP shares directly.
///
///         There is NO `claim()` on this interface (profit is recognized only at
///         withdrawal in MVP). There are NO single-asset deposit/withdraw/
///         emergencyRedeem overloads — only the dual-token forms below.
///
/// @dev    Policy checks are off-chain: the backend authorizes each action via
///         an EIP-712 `SignedAction`.
///         `licenseId`, `referrer`, `positionId`, and the `userAmount`/
///         `protocolAmount` routing split all arrive INSIDE the signed payload
///         and are bound by the wrapper AFTER `verifyAndConsume`.
///
///         Partial and full withdraws share one entrypoint: `_action.amount ==
///         type(uint256).max` means full close; any other value is the share count
///         to redeem. This eliminates a redundant ABI entry with identical
///         semantics.
///
///         `withdrawMany` is NOT present: the dual-asset routing model (in-kind,
///         two-token, proportional) makes aggregation non-trivial.
interface IDualAssetConcLiqVault is IWadzVaultCore {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice Deposit signed action had a non-zero `positionId` or non-zero split
    ///         fields (`userAmount`/`protocolAmount`). Deposit actions do not route
    ///         funds — the split is computed at withdrawal.
    error InvalidDepositAction();

    /// @notice Signed dual-deposit amount commitment does not match calldata amounts.
    /// @param signedCommitment Commitment supplied in `SignedAction.amount`.
    /// @param calldataCommitment Commitment derived from the actual `_amount0` and `_amount1`.
    error DepositAmountsMismatch(uint256 signedCommitment, uint256 calldataCommitment);

    /// @notice A withdraw with a protocol cut (`protocolAmount > 0`) carried no signed
    ///         split (`protocolSplitHash == 0`); every cut must be attributable.
    error MissingProtocolSplit();

    /// @notice Caller is not the owner of the target position.
    error NotPositionOwner(uint256 positionId, address caller);

    /// @notice Target position is not in the required `Active` status.
    error PositionNotActive(uint256 positionId);

    /// @notice Provided amount is zero where a positive amount is required.
    error ZeroAmount();

    /// @notice Deposit minted zero provider shares (e.g. dust amounts rounded down).
    error ZeroShares();

    /// @notice The signed `licenseId` does not match the position's stored license.
    ///         Licenses are fixed at deposit and cannot change for a position.
    error LicenseMismatch(uint256 provided, uint256 expected);

    /// @notice Signed routing is inconsistent: the USDC split does not cover the
    ///         redeemed value (totalValueUsdc < userAmount + protocolAmount).
    error InsufficientRedeemed(uint256 totalValueUsdc, uint256 owed);

    /// @notice The signed `protocolAmount` is non-zero but the withdrawn portion is
    ///         net-negative (current value <= recorded principal). Charging a fee on
    ///         a loss is forbidden.
    error FeeOnLoss();

    /// @notice The signed `protocolAmount` exceeds the fee-only attributable profit of
    ///         the withdrawn portion, capped by net gain.
    ///         `feeOnlyUsdc` = min(pendingFeeUsdc, netGainUsdc) for the withdrawn portion.
    error FeeExceedsFeeOnlyProfit(uint256 protocolAmount, uint256 feeOnlyUsdc);

    /// @notice Both `_minOut0` and `_minOut1` were zero on an emergency redeem.
    ///         At least one non-zero floor is required as an anti-sandwich guard.
    ///         A TWAP-based auto-floor may be added later.
    error ZeroMinOut();

    /// @notice The signed deposit committed a zero `minShares`, i.e. no dilution floor.
    error ZeroMinShares();

    /// @notice Normal operations (deposit/withdraw) require the pool to be calm.
    ///         Emergency redeem intentionally does NOT check this.
    error NotCalm();

    /// @notice The adapter has not been wired yet (address is zero).
    error AdapterNotSet();

    /// @notice An attempt was made to set the adapter after it was already configured.
    error AdapterAlreadySet();

    /// @notice Caller is not the deployer that is authorized to perform one-time adapter wiring.
    /// @dev    `setAdapter` is deployer-gated (captured in the constructor as an immutable)
    ///         so the factory — which deploys the wrapper and then calls `setAdapter` in the
    ///         same transaction — can perform atomic wiring without holding a governance role.
    error NotDeployer(address caller);

    /// @notice The two deposit tokens supplied to the constructor are identical.
    error TokensIdentical();

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted when a new dual-asset position is opened or topped up.
    /// @param positionId    Resolved position identifier (new or existing open position).
    /// @param user          Position owner.
    /// @param licenseId     Off-chain license reference from the signed action.
    /// @param amount0       token0 supplied by the caller before dust return.
    /// @param amount1       token1 supplied by the caller before dust return.
    /// @param principalUsdc USDC-equivalent cost basis recorded for this deposit.
    /// @param shares        Provider (VaultConcLiq) shares minted and held by the wrapper.
    /// @param referrer      L1 referrer from the signed action, or address(0).
    event Deposited(
        uint256 indexed positionId,
        address indexed user,
        uint256 indexed licenseId,
        uint256 amount0,
        uint256 amount1,
        uint256 principalUsdc,
        uint256 shares,
        address referrer
    );

    /// @notice Emitted on a signed withdrawal (partial or full).
    /// @param positionId    The position affected.
    /// @param user          Position owner (msg.sender).
    /// @param userAmountUsdc   Signed USDC-equivalent amount routed to the user.
    /// @param protocolAmountUsdc Signed USDC-equivalent amount routed to treasury.
    /// @param amount0ToUser token0 transferred to the user.
    /// @param amount1ToUser token1 transferred to the user.
    /// @param amount0ToTreasury token0 transferred to treasury.
    /// @param amount1ToTreasury token1 transferred to treasury.
    /// @param closed        True if the position was fully closed.
    event Withdrawn(
        uint256 indexed positionId,
        address indexed user,
        uint256 userAmountUsdc,
        uint256 protocolAmountUsdc,
        uint256 amount0ToUser,
        uint256 amount1ToUser,
        uint256 amount0ToTreasury,
        uint256 amount1ToTreasury,
        bool closed
    );

    /// @notice Emitted on a signature-free, principal-only emergency exit.
    /// @param positionId         The position affected.
    /// @param user               Position owner (msg.sender).
    /// @param amount0ToUser      token0 returned to the user (principal-equivalent).
    /// @param amount1ToUser      token1 returned to the user (principal-equivalent).
    /// @param amount0ToTreasury  token0 surplus above principal forwarded to treasury.
    /// @param amount1ToTreasury  token1 surplus above principal forwarded to treasury.
    event EmergencyRedeemed(
        uint256 indexed positionId,
        address indexed user,
        uint256 amount0ToUser,
        uint256 amount1ToUser,
        uint256 amount0ToTreasury,
        uint256 amount1ToTreasury
    );

    /// @notice Emitted when the adapter is wired to the wrapper (one-time operation).
    event AdapterSet(address indexed adapter);

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

    /// @notice First deposit token of the pair. Immutable after deployment.
    function depositToken0() external view returns (address);

    /// @notice Second deposit token of the pair. Immutable after deployment.
    function depositToken1() external view returns (address);

    /// @notice The `IDualAssetLpVaultAdapter` instance wired to this wrapper.
    ///         Set via `setAdapter` after deployment (one-time, deployer-gated).
    function adapter() external view returns (address);

    /// @notice The dual-asset valuation oracle. Immutable after deployment.
    function oracle() external view returns (address);

    /// @notice Preview token amounts returned for a given share count.
    /// @dev    Forwards to `adapter.previewWithdraw`. Accurate only during calm.
    /// @param _shares  Provider (VaultConcLiq) share count.
    /// @return amount0 Expected token0 returned.
    /// @return amount1 Expected token1 returned.
    function previewWithdraw(uint256 _shares) external view returns (uint256 amount0, uint256 amount1);

    /// @notice Max USDC protocol fee chargeable on a withdraw of this position (fee-only cap).
    /// @dev    Clearer alias of `availableProfitUsdc` for dual-asset: it is the CEILING on
    ///         the signed `protocolAmount`, NOT the user's profit. Equals
    ///         `min(pending fee-only USDC, net gain USDC)`. The user's take is the value
    ///         of their shares (`previewWithdraw`), separate from this cap.
    /// @param _positionId Position to query.
    /// @return maxFeeUsdc Maximum `protocolAmount` (USDC) a withdraw may charge.
    function maxProtocolFeeUsdc(uint256 _positionId) external view returns (uint256 maxFeeUsdc);

    /// @notice Whether the underlying VaultConcLiq pool is currently calm.
    function isCalm() external view returns (bool);

    // ─── Functions ─────────────────────────────────────────────────────────

    /// @notice Wire the adapter to this wrapper. One-time; deployer-gated.
    /// @dev    Separate from the constructor to break the circular deploy dependency:
    ///         the adapter's constructor requires the wrapper address, so the wrapper
    ///         must be deployed first without knowing the adapter address.
    ///         Callable only by the address that deployed the wrapper (captured as an
    ///         immutable `_deployer` in the constructor) — typically the factory, which
    ///         calls this atomically in the same deploy transaction (no front-run window).
    ///         Manual (non-factory) deployments must call `setAdapter` in the same tx
    ///         or script as deployment.
    ///         Reverts `NotDeployer` if `msg.sender != _deployer`.
    ///         Reverts `AdapterAlreadySet` if called again.
    ///         Reverts `ZeroAddress` if `_adapter` is the zero address.
    /// @param _adapterAddress The `IDualAssetLpVaultAdapter` instance wired to this wrapper.
    function setAdapter(address _adapterAddress) external;

    /// @notice Create or top up the caller's open position for a backend-authorized
    ///         dual-asset deposit.
    /// @dev    Requires a valid `SignedAction` of type `Deposit` with
    ///         `positionId == 0`, `userAmount == 0`, `protocolAmount == 0`, and
    ///         `amount == uint256(keccak256(abi.encode(_amount0, _amount1, _minShares)))`.
    ///         The amount field is a commitment, not a token or USDC value; the
    ///         backend signer must compute it from the exact authorized deposit pair
    ///         AND share floor.
    ///         The signed `licenseId` and `referrer` are extracted from the payload.
    ///         Pulls `_amount0` token0 and `_amount1` token1 from `msg.sender`,
    ///         forwards them to the adapter (which deposits into VaultConcLiq and
    ///         returns provider shares + any unspent dust). Dust is forwarded back
    ///         to `msg.sender`. `principalUsdc` is fixed as the USDC value of
    ///         consumed tokens via the dual oracle. If an open position already
    ///         exists for `(msg.sender, licenseId)`, the deposit tops it up
    ///         (additive shares + principalUsdc; `openedAt` unchanged). Otherwise
    ///         a fresh position is created.
    ///         Reverts `NotCalm` if the pool is not in a calm state.
    ///         Reverts `ZeroShares` if the provider mints zero shares.
    ///         Reverts `InvalidDepositAction` if routing fields are non-zero where
    ///         they must be zero for a deposit. Reverts `DepositAmountsMismatch` if
    ///         either calldata token amount or `_minShares` differs from the signed
    ///         commitment. Reverts `ZeroMinShares` if the committed floor is zero.
    /// @param _action    Signed deposit authorization (type `Deposit`).
    /// @param _sig       Backend signature over `_action`.
    /// @param _amount0   token0 to deposit.
    /// @param _amount1   token1 to deposit.
    /// @param _minShares Minimum provider shares to receive. Part of the signed
    ///                   commitment and must be non-zero — it is the only defence
    ///                   against permissionless share-price dilution.
    /// @return positionId Resolved position identifier (new or existing open position).
    function deposit(
        SignedAction calldata _action,
        bytes calldata _sig,
        uint256 _amount0,
        uint256 _amount1,
        uint256 _minShares
    ) external returns (uint256 positionId);

    /// @notice Partial or full withdrawal of a dual-asset position.
    /// @dev    Requires a valid `SignedAction` of type `Withdraw`. `_action.amount`
    ///         is the number of provider (VaultConcLiq) shares to redeem, or
    ///         `type(uint256).max` as a sentinel for a full close of all position
    ///         shares.
    ///         `_action.userAmount` and `_action.protocolAmount` are USDC-denominated
    ///         and represent the signed routing split. The wrapper settles in-kind
    ///         (token0 + token1) proportional to the split; it never swaps.
    ///         Guards for fee-only accounting:
    ///           - net-negative guard: reverts `FeeOnLoss` if the withdrawn portion
    ///             is not in net profit and `protocolAmount > 0`.
    ///           - fee-only cap: reverts `FeeExceedsFeeOnlyProfit` if `protocolAmount`
    ///             exceeds min(pendingFeeUsdc, netGainUsdc) for the withdrawn portion.
    ///             Unharvested fees are not yet attributable; harvest lag is acceptable.
    ///           - slippage floor: reverts `InsufficientRedeemed` if the total
    ///             redeemed USDC value < `userAmount + protocolAmount`.
    ///         Reverts `NotCalm` if the pool is not calm.
    ///         `withdrawMany` is NOT present on this interface because dual-asset
    ///         multi-position aggregation would need proportional two-token routing.
    /// @param _action     Signed withdraw authorization.
    /// @param _sig        Backend signature over `_action`.
    /// @param _breakdown  Per-recipient, per-token bps split of the protocol fee,
    ///                    committed by `_action.protocolSplitHash`. Must contain entries
    ///                    for both pool tokens (each summing to 10_000 bps) when a fee is
    ///                    charged; empty when `protocolSplitHash == 0` (no fee split).
    /// @param _minAmount0 Minimum token0 to receive from the provider (slippage guard).
    /// @param _minAmount1 Minimum token1 to receive from the provider (slippage guard).
    function withdraw(
        SignedAction calldata _action,
        bytes calldata _sig,
        ProtocolSplitShare[] calldata _breakdown,
        uint256 _minAmount0,
        uint256 _minAmount1
    ) external;

    /// @notice Emergency exit. No backend signature; returns principal only.
    /// @dev    Bypasses all off-chain policy and does NOT check `isCalm()`. The
    ///         provider permits exit while the pool remains non-calm after the
    ///         same-block deposit guard has elapsed; a deposit followed by emergency
    ///         redeem at the same timestamp can still require waiting for a later block.
    ///         Remaining provider capital may stay idle until a later deposit,
    ///         harvest, or tick-management action re-deploys it.
    ///         Redeems ALL position shares via the adapter, returns the
    ///         principal-equivalent token amounts to the caller in-kind, and routes any
    ///         surplus above recorded principal to treasury. If value <= principal, the
    ///         user receives ALL tokens and treasury receives nothing.
    ///         Reverts `ZeroMinOut` if BOTH `_minOut0 == 0 AND _minOut1 == 0`
    ///         (anti-sandwich; both-zero is rejected because the caller must supply
    ///         at least one explicit token floor).
    ///         Reverts `NotPositionOwner` if caller is not the position owner.
    ///         Reverts `PositionNotActive` if position is not active.
    /// @param _positionId Target position to emergency-exit.
    /// @param _minOut0    Minimum token0 out from the provider (slippage guard).
    /// @param _minOut1    Minimum token1 out from the provider (slippage guard).
    function emergencyRedeem(uint256 _positionId, uint256 _minOut0, uint256 _minOut1) external;
}

contracts/vaults/dual-asset-conc-liq/adapters/lp-vault/IDualAssetLpVaultAdapter.sol

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

/// @title IDualAssetLpVaultAdapter
/// @notice Adapter boundary between a WADZ dual-asset wrapper and the vendored
///         `VaultConcLiq` concentrated-liquidity provider. One stateless instance
///         is deployed per WADZ LP vault and wired 1:1 to its wrapper.
/// @dev    Custody model: the adapter is stateless and holds ZERO token0/token1/shares
///         between calls. The wrapper is the ONLY authorized caller and the custodian
///         of all provider (VaultConcLiq) shares between calls.
///
///         Because `VaultConcLiq.deposit` mints shares to `msg.sender` (no receiver
///         param), shares are minted to the ADAPTER during the deposit call. The
///         adapter immediately transfers them to the wrapper before returning. Any
///         unspent deposit dust (token0/token1 not consumed by the pool ratio) is
///         also swept back to the wrapper so the adapter leaves zero balance.
///
///         On withdraw, the wrapper first transfers the shares to the adapter. The
///         adapter calls `VaultConcLiq.withdraw` (burns the adapter's shares, sends
///         token0/token1 to the adapter), then forwards all received amounts to the
///         wrapper. The adapter again leaves zero balance.
///
///         The interface omits a `receiver` parameter on every mutating function —
///         all assets, shares, and dust flow exactly to or from the wrapper and never
///         to an arbitrary address.
interface IDualAssetLpVaultAdapter {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice Caller is not the wired wrapper.
    error OnlyWrapper(address caller);

    /// @notice A zero address was supplied where a real address is required.
    error ZeroAddress();

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted when the adapter deposits into the provider vault.
    /// @param amount0  token0 actually consumed by the provider.
    /// @param amount1  token1 actually consumed by the provider.
    /// @param shares   VaultConcLiq shares minted and forwarded to the wrapper.
    event AdapterDeposited(uint256 amount0, uint256 amount1, uint256 shares);

    /// @notice Emitted when the adapter withdraws from the provider vault.
    /// @param shares   VaultConcLiq shares burned.
    /// @param amount0  token0 forwarded to the wrapper.
    /// @param amount1  token1 forwarded to the wrapper.
    event AdapterWithdrawn(uint256 shares, uint256 amount0, uint256 amount1);

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

    /// @notice The wrapper this adapter instance serves; the only authorized
    ///         caller and the custodian of all provider shares. Immutable.
    function wrapper() external view returns (address);

    /// @notice The `VaultConcLiq` provider vault; also the ERC-20 share token.
    ///         Immutable.
    function vault() external view returns (address);

    /// @notice First token of the pair (cached from `VaultConcLiq.wants()`).
    ///         Immutable.
    function token0() external view returns (address);

    /// @notice Second token of the pair (cached from `VaultConcLiq.wants()`).
    ///         Immutable.
    function token1() external view returns (address);

    /// @notice Preview token amounts returned for a given share amount.
    /// @dev    Forwards directly to `VaultConcLiq.previewWithdraw`. Values are only
    ///         reliable while the underlying pool is calm.
    /// @param _shares  Number of provider shares.
    /// @return amount0 Expected token0 returned.
    /// @return amount1 Expected token1 returned.
    function previewWithdraw(uint256 _shares) external view returns (uint256 amount0, uint256 amount1);

    /// @notice Preview shares minted for given token amounts.
    /// @dev    Forwards directly to `VaultConcLiq.previewDeposit`. Values are only
    ///         reliable while the underlying pool is calm.
    /// @param _amount0     token0 to deposit.
    /// @param _amount1     token1 to deposit.
    /// @return shares      Expected shares minted.
    /// @return amount0Used token0 the provider will actually consume.
    /// @return amount1Used token1 the provider will actually consume.
    /// @return fee0        Swap fee charged in token0.
    /// @return fee1        Swap fee charged in token1.
    function previewDeposit(
        uint256 _amount0,
        uint256 _amount1
    ) external view returns (uint256 shares, uint256 amount0Used, uint256 amount1Used, uint256 fee0, uint256 fee1);

    /// @notice Current total token balances held by the provider strategy (across
    ///         vault + strategy contracts). Off-chain/operator view; the wrapper
    ///         values positions via `previewWithdraw`, not via this function.
    /// @return amount0 Total token0 under management.
    /// @return amount1 Total token1 under management.
    function balances() external view returns (uint256 amount0, uint256 amount1);

    /// @notice Total VaultConcLiq shares outstanding. Off-chain/operator view;
    ///         the wrapper does not use this to compute proportional position value
    ///         (it uses `previewWithdraw` directly on the position's share count).
    function totalSupply() external view returns (uint256);

    /// @notice Whether the pool is currently calm (safe for deposits). Forwards
    ///         to `VaultConcLiq.isCalm()`. The wrapper SHOULD check this before
    ///         routing a deposit; the provider enforces it internally as well.
    function isCalm() external view returns (bool);

    /// @notice Current cumulative per-share fee indexes from the provider strategy.
    /// @dev    Reads `cumulativeFee0PerShare` and `cumulativeFee1PerShare` from
    ///         the provider strategy through the vault's `strategy()` reference.
    ///         The indexes are 1e36-scaled monotonically increasing sums of
    ///         net-to-LP fees per share at each harvest.
    ///         The wrapper uses the delta from a position's snapshot index to
    ///         compute fee-only attributable profit without importing provider
    ///         contracts directly.
    /// @return cumulativeFee0PerShare  Cumulative token0 fees per share (1e36 precision).
    /// @return cumulativeFee1PerShare  Cumulative token1 fees per share (1e36 precision).
    function feeIndexes() external view returns (uint256 cumulativeFee0PerShare, uint256 cumulativeFee1PerShare);

    // ─── Functions ───────────────────────────────────────────────────────

    /// @notice Deposit token0/token1 into the provider vault.
    /// @dev    Pre-condition: the wrapper has already transferred `_amount0` of
    ///         token0 AND `_amount1` of token1 to this adapter before calling.
    ///         The adapter `forceApprove`s the provider and calls
    ///         `VaultConcLiq.deposit(_amount0, _amount1, _minShares)`.
    ///         Because `VaultConcLiq` mints shares to `msg.sender`, shares land
    ///         on the adapter; the adapter immediately transfers them to the wrapper.
    ///         Any unspent token0/token1 dust is swept back to the wrapper.
    ///         Approvals are reset to zero after the call. The adapter holds zero
    ///         balance on return.
    ///
    ///         NOTE: the provider may consume less than `_amount0`/`_amount1`
    ///         depending on the current pool ratio; dust is always returned to
    ///         the wrapper. This diverges from the ERC4626 adapter, where the
    ///         provider always consumes the full asset amount.
    /// @param _amount0   token0 transferred to the adapter by the wrapper.
    /// @param _amount1   token1 transferred to the adapter by the wrapper.
    /// @param _minShares Slippage guard; `VaultConcLiq` reverts if shares < `_minShares`.
    /// @return shares    VaultConcLiq shares minted and forwarded to the wrapper.
    /// @return consumed0 token0 actually consumed by the provider.
    /// @return consumed1 token1 actually consumed by the provider.
    function deposit(
        uint256 _amount0,
        uint256 _amount1,
        uint256 _minShares
    ) external returns (uint256 shares, uint256 consumed0, uint256 consumed1);

    /// @notice Withdraw token0/token1 from the provider vault by burning shares.
    /// @dev    Pre-condition: the wrapper has already transferred `_shares` of the
    ///         VaultConcLiq share token to this adapter before calling.
    ///         The adapter calls `VaultConcLiq.withdraw(_shares, _minAmount0,
    ///         _minAmount1)`, which burns the adapter's shares and sends token0/token1
    ///         back to the adapter. The adapter then forwards ALL received amounts to
    ///         the wrapper. The adapter holds zero balance on return.
    ///
    ///         NOTE: per-token min-out slippage is enforced by the provider itself via
    ///         the explicit `_minAmount0`/`_minAmount1` parameters. WADZ single-asset
    ///         ERC4626 redeems use the same explicit min-out pattern at the adapter
    ///         boundary, so no separate bps-based max-loss config is needed.
    /// @param _shares      VaultConcLiq shares transferred to the adapter by the wrapper.
    /// @param _minAmount0  Minimum token0 to receive; passed through to the provider.
    /// @param _minAmount1  Minimum token1 to receive; passed through to the provider.
    /// @return amount0     token0 forwarded to the wrapper.
    /// @return amount1     token1 forwarded to the wrapper.
    function withdraw(
        uint256 _shares,
        uint256 _minAmount0,
        uint256 _minAmount1
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Emergency variant of `withdraw` used only by the wrapper's
    ///         principal-only `emergencyRedeem`.
    /// @dev    Identical custody flow to `withdraw` (burns the adapter's shares,
    ///         forwards token0/token1 to the wrapper) but routes through
    ///         `VaultConcLiq.emergencyWithdraw`, which skips the provider's same-block
    ///         `lastDeposit` calm gate. The vault must have the adapter registered as
    ///         its `emergencyCaller`. The wrapper enforces the per-position same-block
    ///         anti-sandwich guard before calling this.
    /// @param _shares      VaultConcLiq shares transferred to the adapter by the wrapper.
    /// @param _minAmount0  Minimum token0 to receive; passed through to the provider.
    /// @param _minAmount1  Minimum token1 to receive; passed through to the provider.
    /// @return amount0     token0 forwarded to the wrapper.
    /// @return amount1     token1 forwarded to the wrapper.
    function emergencyWithdraw(
        uint256 _shares,
        uint256 _minAmount0,
        uint256 _minAmount1
    ) external returns (uint256 amount0, uint256 amount1);
}

contracts/vaults/shared/IWadzVaultCore.sol

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

import { VaultKind, VaultState, Position } from "../../platform/types/WadzTypes.sol";

/// @title IWadzVaultCore
/// @notice Kind-agnostic interface every WADZ wrapper implements. Carries only
///         metadata, USDC-denominated valuation, and position queries — the
///         surface that is common regardless of vault kind.
/// @dev    User action methods (deposit/claim/withdraw/emergencyRedeem) are NOT
///         here; they live on the kind-specific interfaces because their
///         signatures and life cycles differ.
interface IWadzVaultCore {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice The prospective rewards treasury does not recognize this wrapper.
    error WrapperNotRegistered(address wrapper, address treasury);

    // ─── Events ──────────────────────────────────────────────────────────

    /// @notice Emitted when governance changes the vault lifecycle state.
    event VaultStateChanged(VaultState previousState, VaultState newState);

    /// @notice Emitted when governance changes the protocol treasury destination.
    /// @param previousTreasury Previous protocol treasury destination.
    /// @param newTreasury New protocol treasury destination.
    event TreasurySet(address indexed previousTreasury, address indexed newTreasury);

    // ─── Governance ──────────────────────────────────────────────────────

    /// @notice Change the protocol treasury destination for future routing.
    /// @dev    Callable only by the wrapper governance address. The wrapper must
    ///         already be registered on the prospective `WadzRewardsVault`.
    ///         An EOA or contract without the rewards-vault interface may revert
    ///         directly during interface decoding rather than with
    ///         `WrapperNotRegistered`.
    /// @param _treasury New protocol treasury destination.
    function setTreasury(address _treasury) external;

    // ─── Views: metadata ───────────────────────────────────────────────────

    /// @notice Returns the vault kind. Immutable after deployment.
    function vaultKind() external view returns (VaultKind);

    /// @notice The asset used for all WADZ accounting (always USDC in the MVP).
    function accountingAsset() external view returns (address);

    /// @notice Destination for protocol routing and emergency surplus.
    function treasury() external view returns (address);

    /// @notice Returns the current vault lifecycle state.
    function vaultState() external view returns (VaultState);

    // ─── Views: valuation (USDC-denominated) ─────────────────────────────────

    /// @notice Current total value of a position in USDC. Reverts on stale oracle.
    function positionValueUsdc(uint256 _positionId) external view returns (uint256);

    /// @notice Recognizable profit in USDC for a position, net of claimed profit.
    /// @dev    For single-asset vaults this is share-price appreciation in USDC.
    ///         For dual-asset vaults it MUST be fee-only, not NAV change.
    function availableProfitUsdc(uint256 _positionId) external view returns (uint256);

    // ─── Views: position queries ─────────────────────────────────────────────

    /// @notice Returns the full position record.
    function getPosition(uint256 _positionId) external view returns (Position memory);

    /// @notice Returns all position ids owned by `_wallet`.
    function walletPositions(address _wallet) external view returns (uint256[] memory);

    /// @notice Returns all position ids associated with `_licenseId`.
    function licensePositions(uint256 _licenseId) external view returns (uint256[] memory);

    /// @notice Returns the currently open position for `_wallet` and `_licenseId`.
    /// @dev Returns 0 when the pair has no open position in this vault.
    function openPositionOf(address _wallet, uint256 _licenseId) external view returns (uint256 positionId);
}

contracts/vaults/shared/WadzWrapperBase.sol

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

import { ReentrancyGuardTransient } from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";

import { IWadzVaultCore } from "./IWadzVaultCore.sol";
import { IWadzActionAuthorizer, SignedAction, WadzActionType } from "../../platform/authorizer/IWadzActionAuthorizer.sol";
import { IWadzRewardsVault } from "../../platform/rewards/IWadzRewardsVault.sol";
import { VaultKind, VaultState, PositionStatus, Position } from "../../platform/types/WadzTypes.sol";

/// @title WadzWrapperBase
/// @notice Shared, kind-agnostic base for all WADZ wrappers. Owns the position
///         store and indexes, the EIP-712 authorization gate, the vault lifecycle
///         state, and the common `IWadzVaultCore` query surface.
/// @dev    Justified shared base: position storage/indexing, the signed-action
///         gate (verify + bind), and lifecycle/governance are identical across the
///         single-asset sync, dual-asset LP, and async wrapper kinds, so this base
///         removes real duplication rather than introducing speculative
///         abstraction. Kind-specific custody, valuation, and routing live in the
///         concrete wrappers, which implement `vaultKind`, `positionValueUsdc`, and
///         `availableProfitUsdc`.
///
///         Upgradeability decision: NON-UPGRADEABLE. Wrappers are deployed per
///         vault by the factory, hold custody only of provider receipts (never
///         user-transferable), and are always exitable via the signature-free
///         emergency path, so a buggy or deprecated wrapper can be retired by
///         deploying a fresh vault rather than proxy-upgrading live custody. Core
///         wiring is set in the constructor as immutables; `treasury` is the only
///         mutable routing destination so governance can migrate to a rewards/claim
///         contract without redeploying vaults. There is no initializer and no
///         namespaced storage.
abstract contract WadzWrapperBase is IWadzVaultCore, ReentrancyGuardTransient {
    // ─── Errors ──────────────────────────────────────────────────────────

    /// @notice A constructor argument was the zero address.
    error ZeroAddress();

    /// @notice Caller is not the configured governance address.
    error NotGovernance(address caller);

    /// @notice Deposits are not accepted in the current vault state.
    error DepositsNotAccepted(VaultState state);

    /// @notice Referenced position does not exist.
    error UnknownPosition(uint256 positionId);

    /// @notice Signed action type does not match the called entrypoint.
    error ActionMismatch(uint8 provided, uint8 expected);

    /// @notice `msg.sender` is not the signed action's `user`.
    error CallerNotUser(address caller, address user);

    /// @notice Signed `vaultId` does not match this vault.
    error VaultMismatch(uint256 provided, uint256 expected);

    /// @notice Deprecated vaults are terminal; they cannot return to Active or Paused.
    error DeprecatedStateIsFinal();

    // ─── Immutables ──────────────────────────────────────────────────────

    /// @notice The asset used for all WADZ accounting (USDC).
    address public immutable override accountingAsset;

    /// @notice Registry key for this vault.
    uint256 public immutable vaultId;

    /// @notice EIP-712 verifier for backend-authorized actions.
    IWadzActionAuthorizer public immutable authorizer;

    /// @notice Address allowed to change the vault lifecycle state.
    address public immutable governance;

    // ─── Storage ─────────────────────────────────────────────────────────

    /// @notice Destination for protocol/treasury routing and emergency surplus.
    address public override treasury;

    /// @dev Position records keyed by positionId.
    mapping(uint256 positionId => Position) internal _positions;

    /// @dev Position ids owned by each wallet.
    mapping(address wallet => uint256[]) internal _walletPositionIds;

    /// @dev Position ids associated with each (off-chain) licenseId.
    mapping(uint256 licenseId => uint256[]) internal _licensePositionIds;

    /// @dev The single open positionId for a (user, licenseId) pair within this vault.
    ///      Zero means no open position exists. Set on creation, cleared on every close
    ///      path (withdraw-to-close, emergency). Top-up deposits resolve through this
    ///      index instead of creating a duplicate position.
    mapping(address user => mapping(uint256 licenseId => uint256 openPositionId)) internal _openByUserLicense;

    /// @dev Monotonic position id counter; ids start at 1.
    uint256 internal _nextPositionId;

    /// @dev Current vault lifecycle state.
    VaultState internal _vaultState;

    // ─── Modifiers ───────────────────────────────────────────────────────

    modifier onlyGovernance() {
        if (msg.sender != governance) revert NotGovernance(msg.sender);
        _;
    }

    modifier whenAcceptingDeposits() {
        if (_vaultState != VaultState.Active) revert DepositsNotAccepted(_vaultState);
        _;
    }

    // ─── Constructor ─────────────────────────────────────────────────────

    /// @param _accountingAsset USDC address used for all WADZ accounting.
    /// @param _vaultId         Registry key for this vault.
    /// @param _authorizer      EIP-712 action authorizer.
    /// @param _treasury        Protocol/treasury destination.
    /// @param _governance      Address allowed to change lifecycle state.
    constructor(
        address _accountingAsset,
        uint256 _vaultId,
        address _authorizer,
        address _treasury,
        address _governance
    ) {
        if (
            _accountingAsset == address(0) ||
            _authorizer == address(0) ||
            _treasury == address(0) ||
            _governance == address(0)
        ) {
            revert ZeroAddress();
        }

        accountingAsset = _accountingAsset;
        vaultId = _vaultId;
        authorizer = IWadzActionAuthorizer(_authorizer);
        treasury = _treasury;
        governance = _governance;
        _vaultState = VaultState.Active;
    }

    // ─── Governance ──────────────────────────────────────────────────────

    /// @inheritdoc IWadzVaultCore
    function setTreasury(address _treasury) external override onlyGovernance {
        if (_treasury == address(0)) revert ZeroAddress();
        if (!IWadzRewardsVault(_treasury).isWrapper(address(this))) {
            revert WrapperNotRegistered(address(this), _treasury);
        }
        address previousTreasury = treasury;
        treasury = _treasury;
        emit TreasurySet(previousTreasury, _treasury);
    }

    /// @notice Set the vault lifecycle state. Paused/Deprecated block new deposits
    ///         while leaving withdraw, claim, and emergency exit available.
    /// @dev    Deprecated is terminal by product decision: once a vault is deprecated,
    ///         governance cannot move it back to Active or Paused.
    function setVaultState(VaultState _newState) external onlyGovernance {
        VaultState previous = _vaultState;
        if (previous == VaultState.Deprecated && _newState != VaultState.Deprecated) {
            revert DeprecatedStateIsFinal();
        }
        _vaultState = _newState;
        emit VaultStateChanged(previous, _newState);
    }

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

    /// @inheritdoc IWadzVaultCore
    function vaultState() external view override returns (VaultState) {
        return _vaultState;
    }

    /// @inheritdoc IWadzVaultCore
    function getPosition(uint256 _positionId) external view override returns (Position memory) {
        Position memory position = _positions[_positionId];
        if (position.owner == address(0)) revert UnknownPosition(_positionId);
        return position;
    }

    /// @inheritdoc IWadzVaultCore
    function walletPositions(address _wallet) external view override returns (uint256[] memory) {
        return _walletPositionIds[_wallet];
    }

    /// @inheritdoc IWadzVaultCore
    function licensePositions(uint256 _licenseId) external view override returns (uint256[] memory) {
        return _licensePositionIds[_licenseId];
    }

    /// @inheritdoc IWadzVaultCore
    function openPositionOf(address _wallet, uint256 _licenseId) external view override returns (uint256 positionId) {
        return _openByUserLicense[_wallet][_licenseId];
    }

    // ─── Internals ───────────────────────────────────────────────────────

    /// @dev Verify a signed action and bind it to this call: action type,
    ///      `msg.sender == user`, and `vaultId`. Delegates signature, signer,
    ///      deadline, nonce, chainId, and verifyingContract checks to the
    ///      authorizer, which consumes the nonce.
    /// @param _action    Signed action payload supplied to the wrapper entrypoint.
    /// @param _signature Backend signature over `_action`.
    /// @param _expected  Action type required by the calling wrapper function.
    function _authorizeAction(
        SignedAction calldata _action,
        bytes calldata _signature,
        WadzActionType _expected
    ) internal {
        if (_action.action != _expected) revert ActionMismatch(uint8(_action.action), uint8(_expected));
        if (_action.user != msg.sender) revert CallerNotUser(msg.sender, _action.user);
        if (_action.vaultId != vaultId) revert VaultMismatch(_action.vaultId, vaultId);
        authorizer.verifyAndConsume(_action, _signature);
    }

    /// @dev Create, store, and index a new position. Fills kind-agnostic fields;
    ///      `vaultKind()` is resolved from the concrete wrapper. Also registers this
    ///      position as the open position for `(_owner, _licenseId)` in
    ///      `_openByUserLicense`; the concrete wrapper must call `_clearOpenPosition`
    ///      on every close path so the invariant "non-zero index implies Active" holds.
    /// @param _owner         Wallet that owns the new WADZ position.
    /// @param _licenseId     Off-chain license reference attached to the position.
    /// @param _receiptAmount Provider receipt/share amount held by the wrapper.
    /// @param _principalUsdc USDC cost basis fixed at deposit time.
    /// @return positionId    Newly assigned WADZ position id.
    function _createPosition(
        address _owner,
        uint256 _licenseId,
        uint256 _receiptAmount,
        uint256 _principalUsdc
    ) internal returns (uint256 positionId) {
        positionId = ++_nextPositionId;

        _positions[positionId] = Position({
            positionId: positionId,
            owner: _owner,
            licenseId: _licenseId,
            vaultId: vaultId,
            vaultKind: vaultKind(),
            receiptAmount: _receiptAmount,
            principalUsdc: _principalUsdc,
            claimedProfitUsdc: 0,
            openedAt: uint64(block.timestamp),
            status: PositionStatus.Active,
            adapterMetadata: ""
        });

        _walletPositionIds[_owner].push(positionId);
        _licensePositionIds[_licenseId].push(positionId);
        _openByUserLicense[_owner][_licenseId] = positionId;
    }

    /// @dev Clear the open-position index for a `(_owner, _licenseId)` pair.
    ///      Must be called from every close path (withdraw-to-close, emergency) so
    ///      a subsequent deposit with the same licenseId creates a fresh position
    ///      rather than top-upping a closed one.
    /// @param _owner     Wallet whose open-position index is being cleared.
    /// @param _licenseId License bucket whose open position is being cleared.
    function _clearOpenPosition(address _owner, uint256 _licenseId) internal {
        _openByUserLicense[_owner][_licenseId] = 0;
    }

    // ─── Abstract (kind-specific) ────────────────────────────────────────

    /// @inheritdoc IWadzVaultCore
    function vaultKind() public view virtual override returns (VaultKind);

    /// @inheritdoc IWadzVaultCore
    function positionValueUsdc(uint256 _positionId) external view virtual override returns (uint256);

    /// @inheritdoc IWadzVaultCore
    function availableProfitUsdc(uint256 _positionId) external view virtual override returns (uint256);
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.