Skip to content
Verified contractPartialBUSL-1.1

StakeWiseV3ExitQueueAssistant

Address0xc020e93ca7bfb23e63adee13b2bb97abc78db13d
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,341,853
Creation transaction
0x033df94062…0b4136fb33
Libraries
src/nav/NAVRegistryLib.sol:NAVRegistryLib0x3d53…75934dsrc/prices/PriceFeedLib.sol:PriceFeedLib0x0f91…fafcf2

src/balances/AssistedBalanceAdapters/assistants/StakeWiseV3ExitQueueAssistant.sol

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

import {BalanceAdapterAssistant} from "src/balances/AssistedBalanceAdapters/assistants/BalanceAdapterAssistant.sol";

/// @title StakeWise V3 Exit-Queue Assistant
/// @author KPK
/// @notice Delegatecall-only action a depositor Safe delegatecalls to enter / exit the StakeWise V3 exit queue and, in
///         the same transaction, register / deregister the resulting `positionTicket` on
///         {StakeWiseV3ExitQueueAssistedBalanceAdapter} so the queued value stays visible to NAV. StakeWise keys
///         `claimExitedAssets` on `msg.sender` and vault shares are non-transferable, so the Safe must be both the
///         `receiver` and the claimer — exactly what delegatecall gives: the assistant's code runs in the Safe's context,
///         so `address(this)` is the Safe, the vault sees `msg.sender = Safe`, and the exit position is owned by (and
///         claimed to) the Safe. No custody, no asset-forwarding.
/// @dev Extends {BalanceAdapterAssistant} for the `SELF` / {onlyDelegateCall} guard and immutable `ADAPTER`. No token
///      approval is needed (shares live in the vault). The adapter is permissionless and self-scopes by `msg.sender`,
///      so the assistant's call (carrying `msg.sender = the Safe`) tracks exactly the Safe's own positions. See
///      [ADR 0018](../../../../docs/decisions/0018-assistant-fed-assisted-balance-adapters.md).
contract StakeWiseV3ExitQueueAssistant is BalanceAdapterAssistant {
    /// @notice Emitted (in the Safe's context) when the Safe enters the exit queue and the ticket is registered.
    event ExitQueueEntered(address indexed account, address indexed vault, uint256 positionTicket, uint256 timestamp);
    /// @notice Emitted (in the Safe's context) when the Safe claims and the ticket is deregistered.
    event ExitedAssetsClaimed(
        address indexed account, address indexed vault, uint256 positionTicket, uint256 timestamp
    );
    /// @notice Emitted (in the Safe's context) when the vault was not collateralized: StakeWise redeemed the shares
    ///         immediately (assets paid, no exit request), so there is no ticket to register.
    event RedeemedImmediately(address indexed account, address indexed vault, uint256 shares);
    /// @notice Emitted (in the Safe's context) when a partial claim re-queued the remainder under `newPositionTicket`
    ///         (same `timestamp`) and the assistant registered it — `tracked = false` if registering it failed (the claim
    ///         still went through; the keeper can file the remainder with `submitFor` while the account is below the
    ///         keeper limit; if the cache was full, the owner frees a slot with `evict` / `clearAccount` and `submit`s it).
    event RemainderRequeued(
        address indexed account,
        address indexed vault,
        uint256 positionTicket,
        uint256 newPositionTicket,
        uint256 timestamp,
        bool tracked
    );

    /// @param adapter_ The {StakeWiseV3ExitQueueAssistedBalanceAdapter} to feed. Must be a contract.
    constructor(address adapter_) BalanceAdapterAssistant(adapter_) {}

    /// @notice Enter the StakeWise V3 exit queue for `vault` and register the resulting ticket on the adapter. Mirrors
    ///         the vault's `enterExitQueue(shares, receiver)`, with `vault` prepended and `receiver` forced to the
    ///         executing Safe (`address(this)`). **Delegatecall-only.**
    /// @param vault  StakeWise V3 vault.
    /// @param shares Vault shares to move into the exit queue (burned from the Safe).
    /// @return positionTicket The ticket assigned by the vault, now tracked on the adapter for the Safe.
    function enterExitQueue(address vault, uint256 shares) external onlyDelegateCall returns (uint256 positionTicket) {
        positionTicket = IStakeWiseVaultEnterExit(vault).enterExitQueue(shares, address(this));
        // An uncollateralized vault redeems on the spot and returns type(uint256).max instead of a ticket — nothing is
        // queued, so registering it would revert (CoordinateNotOwned) and block the Safe's only allow-listed exit path.
        if (positionTicket == type(uint256).max) {
            emit RedeemedImmediately(address(this), vault, shares);
            return positionTicket;
        }
        IStakeWiseV3ExitQueueAssistedBalanceAdapter(ADAPTER).submit(vault, positionTicket, block.timestamp);
        emit ExitQueueEntered(address(this), vault, positionTicket, block.timestamp);
    }

    /// @notice Claim exited assets for a queue position, deregister its ticket, and — on a PARTIAL claim — register
    ///         the remainder. StakeWise deletes the request under `positionTicket` on every claim and, when more than one
    ///         ticket is left, re-queues the remainder under `positionTicket + exitedTickets` with the SAME `timestamp`;
    ///         registering that new ticket here keeps the unclaimed rest in the NAV without waiting for a keeper. Mirrors
    ///         the vault's `claimExitedAssets(positionTicket, timestamp, exitQueueIndex)`, with `vault` prepended.
    ///         **Delegatecall-only** (StakeWise keys the claim on `msg.sender = Safe`).
    /// @param vault          StakeWise V3 vault.
    /// @param positionTicket The exit position's ticket.
    /// @param timestamp      Entry timestamp (part of the exit-request key; the same value registered on enter).
    /// @param exitQueueIndex Checkpoint index for the position (from `getExitQueueIndex`).
    function claimExitedAssets(address vault, uint256 positionTicket, uint256 timestamp, uint256 exitQueueIndex)
        external
        onlyDelegateCall
    {
        // Same call, same state, same tx as the vault's own claim math → the exact split the claim will apply.
        (uint256 leftTickets, uint256 exitedTickets,) = IStakeWiseVaultEnterExit(vault)
            .calculateExitedAssets(address(this), positionTicket, timestamp, exitQueueIndex);
        IStakeWiseVaultEnterExit(vault).claimExitedAssets(positionTicket, timestamp, exitQueueIndex);
        // Best-effort deregister — never block the claim itself. The claim deleted the request under this ticket, so the
        // adapter normally removes it; an untracked ticket reverts `CoordinateNotCached` (nothing to untrack).
        // {_bubbleUnlessCacheRevert} swallows the cache reverts and re-throws anything else.
        try IStakeWiseV3ExitQueueAssistedBalanceAdapter(ADAPTER).remove(vault, positionTicket, timestamp) {}
        catch (bytes memory reason) {
            _bubbleUnlessCacheRevert(reason);
        }
        emit ExitedAssetsClaimed(address(this), vault, positionTicket, timestamp);
        // StakeWise re-queues only when MORE than one ticket is left (a single leftover ticket is a rounding error it
        // drops), mirroring `claimExitedAssets`'s own `leftTickets > 1` test on the values just read.
        if (leftTickets > 1 && exitedTickets > 0) {
            uint256 newPositionTicket = positionTicket + exitedTickets;
            bool tracked;
            // Never block the claim: a failed registration is reported (tracked = false). The keeper can file it with
            // `submitFor` below its limit; after a full-cache failure the owner frees a slot and `submit`s it itself.
            try IStakeWiseV3ExitQueueAssistedBalanceAdapter(ADAPTER).submit(vault, newPositionTicket, timestamp) {
                tracked = true;
            } catch {}
            emit RemainderRequeued(address(this), vault, positionTicket, newPositionTicket, timestamp, tracked);
        }
    }
}

/// @notice Minimal interface for a StakeWise V3 vault's exit-queue mutators.
interface IStakeWiseVaultEnterExit {
    /// @notice Locks `shares` into the exit queue for `receiver`; returns the position ticket.
    function enterExitQueue(uint256 shares, address receiver) external returns (uint256 positionTicket);

    /// @notice Claims assets that were withdrawn by the vault. Callable only by the `receiver` from `enterExitQueue`.
    function claimExitedAssets(uint256 positionTicket, uint256 timestamp, uint256 exitQueueIndex) external;

    /// @notice For the request keyed by `(receiver, timestamp, positionTicket)`: tickets still queued, tickets exited, and
    ///         the assets those exited tickets are worth.
    function calculateExitedAssets(address receiver, uint256 positionTicket, uint256 timestamp, uint256 exitQueueIndex)
        external
        view
        returns (uint256 leftTickets, uint256 exitedTickets, uint256 exitedAssets);
}

/// @notice Minimal interface for the assistant-fed balance adapter's tracking mutators (self-scoped to `msg.sender`).
interface IStakeWiseV3ExitQueueAssistedBalanceAdapter {
    function submit(address vault, uint256 positionTicket, uint256 timestamp) external;
    function remove(address vault, uint256 positionTicket, uint256 timestamp) external;
}

src/balances/AssistedBalanceAdapters/assistants/BalanceAdapterAssistant.sol

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

import {IBalanceAdapterAssistant} from "src/balances/AssistedBalanceAdapters/assistants/IBalanceAdapterAssistant.sol";
import {AddressCheckLib} from "src/utils/AddressCheckLib.sol";
// forge-lint: disable-next-line(unaliased-plain-import)
import "src/errors.sol";

/// @title BalanceAdapterAssistant
/// @author KPK
/// @notice Abstract base for the delegatecall-action assistants that feed the assistant-fed assisted
///         balance adapters. It contributes the pieces every such assistant shares: the immutable `ADAPTER` reference,
///         this module's own `SELF` address pinned at construction, and the {onlyDelegateCall} guard. Concrete assistants
///         add the protocol-target immutables and the forward-then-`submit`/`remove` entrypoints.
/// @dev Because entrypoints run under `delegatecall` (from the owner Safe), `address(this)` is the Safe throughout, yet
///      the immutables (`SELF`, `ADAPTER`, and any the concrete adds) remain readable — they live in the assistant's
///      bytecode. That is what lets an entrypoint both act as the Safe against the protocol and reach the adapter with
///      `msg.sender = Safe`. A *direct* call to a delegatecall-only entrypoint has `address(this) == SELF` and is
///      rejected by {onlyDelegateCall} (fail loud, canonical {NotDelegateCall}), rather than letting the protocol
///      revert obscurely. The base holds no roles, no custody, and no mutable state (delegatecall-storage-collision
///      safe): access to *which* Safe may run an assistant is governed at the Safe/Zodiac layer, not here.
abstract contract BalanceAdapterAssistant is IBalanceAdapterAssistant {
    /// @inheritdoc IBalanceAdapterAssistant
    address public immutable override SELF;

    /// @inheritdoc IBalanceAdapterAssistant
    address public immutable override ADAPTER;

    /// @param adapter_ The assistant-fed assisted balance adapter this assistant feeds. Must be a contract.
    constructor(address adapter_) {
        if (adapter_ == address(0)) revert InvalidArguments();
        AddressCheckLib.requireContract(adapter_, "adapter");
        SELF = address(this);
        ADAPTER = adapter_;
    }

    /// @notice Reverts unless the current call is a `delegatecall` (running in the caller Safe's context, not the
    ///         singleton's). Under `delegatecall` `address(this)` is the Safe; on a direct call it is this deployment
    ///         (`== SELF`). Delegatecall-only entrypoints rely on running as the Safe, so a direct call is always a
    ///         mistake — fail loud here.
    modifier onlyDelegateCall() {
        if (address(this) == SELF) revert NotDelegateCall();
        _;
    }

    /// @notice Sanity check for the assistants whose forwarded protocol call mirrors a signature with an explicit
    ///         `receiver`/`owner`/`destination` account: it MUST be the executing context (`address(this)` — the
    ///         delegatecalling Safe), so the created position is owned by, and tracked for, that same Safe. Reverts
    ///         `AssistantAccountMismatch` otherwise. Assistants that instead force the receiver to `address(this)` in the
    ///         forwarded call have no argument to check and need not call this.
    function _requireSelf(address account) internal view {
        if (account != address(this)) revert AssistantAccountMismatch(address(this), account);
    }

    /// @notice Best-effort untrack helper for the `withdraw`/`claim` entrypoints: given the raw revert `reason` from a
    ///         failed `ADAPTER.remove(...)`, swallow the two expected cache-state reverts and re-throw anything else.
    ///         `CoordinateNotCached` = the id was never tracked (cleared via `clearAccount` / `evict`, or acquired outside the
    ///         assistant) — nothing to untrack. `CoordinateStillLive` = the position is still live after a partial
    ///         withdraw/claim — keep it tracked. Both are safe to ignore because the adapter re-verifies ownership and
    ///         re-values live on every read: a coordinate left cached only ever **under-reports** (a fully-consumed or
    ///         no-longer-owned one resolves to 0), never over-reports. Any other revert is a real fault and is
    ///         re-thrown verbatim so the op fails loud rather than silently continuing.
    function _bubbleUnlessCacheRevert(bytes memory reason) internal pure {
        bytes4 sel = bytes4(reason);
        if (sel != CoordinateStillLive.selector && sel != CoordinateNotCached.selector) {
            assembly {
                revert(add(reason, 0x20), mload(reason))
            }
        }
    }
}

src/balances/AssistedBalanceAdapters/assistants/IBalanceAdapterAssistant.sol

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

/// @title IBalanceAdapterAssistant
/// @author KPK
/// @notice Marker interface for the **delegatecall-action assistants** that feed the assistant-fed assisted
///         balance adapters ({IAssistedBalanceAdapter}). An assistant is a stateless logic module a depositor Safe
///         `delegatecall`s: in the same transaction it enters/exits a protocol (deposit, withdrawal-request, exit-queue
///         entry, claim), it pushes/pops the resulting position **coordinate** onto its paired adapter. Running under
///         `delegatecall` makes `address(this)` the Safe, so the protocol sees `msg.sender = Safe` (the position owner)
///         and the adapter's `msg.sender`-keyed cache records against that same Safe — no roles, no custody, no
///         asset-forwarding.
/// @dev Concrete assistants extend {BalanceAdapterAssistant} (which provides the `SELF` / `onlyDelegateCall` guard and the
///      immutable `ADAPTER` reference) and add the protocol-specific forward-then-`submit`/`remove` entrypoints. Their
///      signatures are per-protocol, so this interface only exposes the two immutables common to all of them.
interface IBalanceAdapterAssistant {
    /// @notice The assistant-fed assisted balance adapter this assistant feeds.
    function ADAPTER() external view returns (address);

    /// @notice This assistant's own deployed address, pinned at construction — the delegatecall-guard anchor (under
    ///         `delegatecall` `address(this)` is the calling Safe, `!= SELF`; on a direct call `address(this) == SELF`).
    function SELF() external view returns (address);
}

src/errors.sol

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

error InvalidArguments();
error InvalidArgumentsWithContext(string context);
/// @notice A constructor argument expected to be a deployed contract has no code. `name` is the dependency label.
error NotAContract(string name);
error NotAuthorized();
error NotChainlinkOracle();
/// @notice Thrown when an assistant entrypoint that must be delegatecalled is called directly on the singleton
///         (`address(this) == SELF`). Canonical delegatecall-guard error for the assistant-fed family (`BalanceAdapterAssistant`).
error NotDelegateCall();
/// @notice An assistant entrypoint was told to track/act for an account other than the executing context
///         (`address(this)`, i.e. the delegatecalling Safe). Canonical assistant self-scope check (`_requireSelf`).
error AssistantAccountMismatch(address expected, address provided);

// Permissionless assistant-fed assisted balance-adapter family (ADR 0018) — shared coordinate-cache errors, used by the
// single {AssistedCoordCache} base (every coordinate is an `abi.encode`d blob). The coordinate is identified by `id`
// (a tokenId / requestId / positionTicket, from `_coordId`); the full tuple, where richer, rides in the cache's events.
/// @notice `submit` was given a coordinate not currently owned by the caller (`msg.sender`).
error CoordinateNotOwned(address account, uint256 id);
/// @notice `submit` would grow the caller's cache past its per-account cap.
error CoordinateCacheFull(address account, uint256 maxCoordinates);
/// @notice `remove` targeted a coordinate not in the caller's cache.
error CoordinateNotCached(address account, uint256 id);
/// @notice `remove` targeted a coordinate the caller still owns (a live position) — refused so a live position is never
///         dropped (would under-report the caller's own NAV). Only a claimed/consumed coordinate may be removed.
error CoordinateStillLive(address account, uint256 id);
/// @notice `submit` was given a coordinate that failed the adapter's write-time protocol validation (e.g. an
///         unregistered target). Distinct from {CoordinateNotOwned} (ownership) — this is a malformed/invalid coordinate.
error InvalidCoordinate(address account, uint256 id);

// Bridge-specific errors
error AlreadyInitialized();
error InvoiceNotFound();
error InvoiceAlreadyExists();
error InvalidInvoiceStatus();
error InvalidInvoice();
error TransferFailed();
error InsufficientBalance(address asset, uint256 required, uint256 available);
error InvalidChainId();
error InvalidNonce();
error InvalidCompletionData();
error InvalidChecksum(bytes32 invoiceId, bytes24 provided, bytes24 calculated);
error InvalidTimestamp(uint64 provided, uint64 current);
error AssetHasActiveInvoices(string symbol);
error AssetNotRegistered(string symbol);

// NAV Calculator / registry errors
error PriceFeedNotSet(address asset);
error AssetNotFound();
error OnlyNAVCalculator();
error ArrayLengthMismatch();
error InvalidAssetDecimals();
error InvalidDecimalExponent();

src/utils/AddressCheckLib.sol

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

import {NotAContract} from "src/errors.sol";

/// @title AddressCheckLib
/// @author KPK
/// @notice Constructor-argument helper for the balance-adapter layer: asserts a dependency address actually points
///         to a deployed contract, reverting with the {NotAContract} custom error carrying the dependency label.
/// @dev Centralises the `addr.code.length > 0` dependency check that every adapter pins its immutables with. The
///      price-feed layer has its own equivalent (`OracleArgumentChecks`); this is the balance-side analogue. `name`
///      is the dependency's human label (e.g. "NAVCalculator"), surfaced in the {NotAContract} error.
library AddressCheckLib {
    /// @notice Reverts {NotAContract}(`name`) unless `addr` has non-empty code.
    /// @param addr The dependency address to validate.
    /// @param name The dependency's display name (carried in the revert).
    function requireContract(address addr, string memory name) internal view {
        if (addr.code.length == 0) revert NotAContract(name);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "src/nav/NAVRegistryLib.sol": {
      "NAVRegistryLib": "0x3D5369B0b2044d62a8f643bf9a2b8CC03775934D"
    },
    "src/prices/PriceFeedLib.sol": {
      "PriceFeedLib": "0x0f913658d70BB19b7B42eF9926c3df7c70fafCf2"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
    "@chainlink/=lib/chainlink-brownie-contracts/contracts/",
    "chainlink-brownie-contracts/=lib/chainlink-brownie-contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "morpho-blue/=lib/morpho-blue/",
    "ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.