Skip to content
Verified contractPartialBUSL-1.1

MultiVehicle

Address0x9e98c7d5ddf212def9cecd3c9b4607b95c3b18f6
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.34

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
EVM version
prague
Via IR
yes
License
BUSL-1.1
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,882,860
Creation transaction
0xc8ebaa4167…c16185ea0e

79 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/vehicles/multi/MultiVehicle.sol

// SPDX-License-Identifier: BUSL-1.1
//
//                        ░██░██                          ░██
//                           ░██                          ░██
//    ░██░████  ░██████   ░██░██ ░████████   ░███████  ░████████
//    ░███           ░██  ░██░██ ░██    ░██ ░██    ░██    ░██
//    ░██       ░███████  ░██░██ ░██    ░██ ░█████████    ░██
//    ░██      ░██   ░██  ░██░██ ░██    ░██ ░██           ░██
//    ░██       ░█████░██ ░██░██ ░██    ░██  ░███████      ░████
//
//    =========🚂🚃🚃🚃=========================================
//
pragma solidity >=0.8.33;

// Railnet imports
import {Query, Asset, State, Id} from "src/steam/Query.sol";

// External dependencies
import {IERC20} from "@openzeppelin-contracts/token/ERC20/IERC20.sol";
import {Math} from "@openzeppelin-contracts/utils/math/Math.sol";
import {ERC20Upgradeable} from "@openzeppelin-contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
// Internal imports - Libraries
import {ErrorLib} from "src/libs/Error.sol";
import {MultiVehicleLib} from "src/vehicles/multi/libs/MultiVehicleLib.sol";

// Internal imports - Base Vehicle
import {
    BaseVehicle,
    IBaseVehicle,
    BaseVehicleQueryStateGetter,
    BaseVehicleStore
} from "src/vehicles/base/BaseVehicle.sol";
import {FeeManager} from "src/vehicles/base/FeeManager.sol";
import {ICreateFacet} from "src/vehicles/base/interfaces/facets/ICreateFacet.sol";
import {IInitializeFacet} from "src/vehicles/base/interfaces/facets/IInitializeFacet.sol";
import {IRecoverFacet} from "src/vehicles/base/interfaces/facets/IRecoverFacet.sol";
import {IResumeFacet} from "src/vehicles/base/interfaces/facets/IResumeFacet.sol";
import {IUnlockFacet} from "src/vehicles/base/interfaces/facets/IUnlockFacet.sol";
// Internal imports - Multi Vehicle
import {MultiVehicleErrors} from "src/vehicles/multi/abstracts/MultiVehicleErrors.sol";
import {MultiVehicleFacets} from "src/vehicles/multi/facets/MultiVehicleFacets.sol";
import {ISectorAccountingEngine} from "src/vehicles/multi/interfaces/ISectorAccountingEngine.sol";
import {IVehicleManager} from "src/vehicles/multi/interfaces/IVehicleManager.sol";
import {IMultiVehicleGateway} from "src/vehicles/multi/interfaces/IMultiVehicleGateway.sol";
import {MultiVehicleStore} from "src/vehicles/multi/libs/MultiVehicleStore.sol";
import {MultiVehicleStructs} from "src/vehicles/multi/libs/MultiVehicleStructs.sol";

/// @title Multi Vehicle
/// @notice STEAM-compliant meta-vehicle aggregating multiple underlying STEAM vehicles. Users deposit
///         base assets for MultiVehicle shares representing proportional ownership of a diversified
///         portfolio across authorized sub-vehicles.
/// @dev 5-component architecture:
///        1. MultiVehicle: Main STEAM interface for user interactions
///        2. SectorAccountingEngine: Central accounting and asset management
///        3. QueueStrategyEngine: Strategy logic for allocation/unallocation decisions
///        4. SubQueryEngine: Manages sub-queries and ephemeral accounting
///        5. QueryRedeemQueue: Async redemption queue with demand/fulfillment matching
///
///      Exchange rate: shares = assets * totalSupply / totalAssets (ERC4626-style)
///      totalAssets = AVAILABLE sector + RESERVED sector + all sub-vehicle positions (converted via exchange rates)
///
///      Deposit flow: synchronous to user (always returns UNLOCKING immediately)
///       - Assets transferred to SectorAccountingEngine -> shares minted to vehicle -> UNLOCKING
///       - Auto-allocation to sub-vehicles happens asynchronously in the background
///
///      Redeem flow: synchronous or asynchronous depending on available liquidity
///      - Sync: withdrawable >= requested -> withdraw immediately -> UNLOCKING -> SETTLED
///      - Async: insufficient liquidity -> creates demand in QueryRedeemQueue
///        - Full async: all queued -> PROCESSING -> (when fulfilled) -> UNLOCKING -> SETTLED
///        - Partial async: withdraw available + queue remainder -> UNLOCKING (partial unlockable immediately)
///        - Cyclic transitions: UNLOCKING <-> PROCESSING until demand fully fulfilled
///      - Queue is position-based FIFO: earlier demands fulfilled before later ones
contract MultiVehicle is BaseVehicle, MultiVehicleErrors, IMultiVehicleGateway {
    /// @notice Address of Multi Vehicle facets (deployed in the constructor).
    MultiVehicleFacets internal immutable FACETS;

    /// @dev Restricts access to the VehicleManager contract.
    modifier onlyManager() {
        _onlyManager();
        _;
    }

    /* ------------------------------------------------------------------------------------------------------------------------ */
    /*                                                      INITIALIZATION                                                      */
    /* ------------------------------------------------------------------------------------------------------------------------ */

    /// @notice Initializes the contract. Callable once.
    /// @param params The initialization parameters.
    function initialize(MultiVehicleStructs.InitParams calldata params) external initializer {
        _initialize(abi.encode(params));
    }

    constructor() {
        FACETS = new MultiVehicleFacets();
        _disableInitializers();
    }

    /// @inheritdoc IBaseVehicle
    function recover(Query calldata) external virtual override returns (State, Asset memory) {
        revert ErrorLib.Unimplemented();
    }

    /// @inheritdoc BaseVehicle
    function resume(Query calldata) external virtual override returns (State) {
        revert ErrorLib.Unimplemented();
    }

    /* ------------------------------------------------------------------------------------------------------------------------ */
    /*                                                    MANAGER GATEWAYS                                                      */
    /* ------------------------------------------------------------------------------------------------------------------------ */

    /// @notice Starts ongoing fee handling and returns current supply/assets.
    /// @dev Callable only by VehicleManager. Does NOT have nonReentrant.
    /// @return supply_ The current total supply after fee minting.
    /// @return assets_ The current total assets.
    function startOngoingFeeHandling() external onlyManager returns (uint256 supply_, uint256 assets_) {
        return _handleOngoingFees(Id.wrap(bytes32(0)), BaseVehicleStore.getStorage().feeManager, true);
    }

    /// @notice Finishes ongoing fee handling by updating post-fee checkpoints.
    /// @dev Callable only by VehicleManager. Does NOT have nonReentrant.
    function finishOngoingFeeHandling() external onlyManager {
        _updatePostFeeCheckpoints();
    }

    /// @notice Burns shares held by the caller.
    /// @dev Callable only by VehicleManager. Does NOT have nonReentrant.
    function burnShares(uint256 amount) external onlyManager {
        _burn(msg.sender, amount);
    }

    /// @notice Returns the VehicleManager managing this MultiVehicle.
    function manager() external view returns (IVehicleManager) {
        return MultiVehicleStore.getStorage().manager;
    }

    /// @notice View-only fee-adjusted (totalSupply, totalAssets): the pair the FeeManager would see
    ///         right after `onOperations` mints accrued performance and management fee shares. Read by
    ///         `VehicleManager.exitSupplies` and off-chain consumers needing settled-supply rates
    ///         without mutating state.
    /// @dev Must execute in MultiVehicle's context: `FeeManager.previewOnOperations` reads
    ///      `cache[msg.sender]`, and only the MultiVehicle has a populated cache (written by
    ///      `onOperations` during `create()`). Any other context reads a zero-initialised cache and
    ///      computes fees as if accruing since epoch.
    /// @return totalSupply_ Current totalSupply plus the pending fee shares the FeeManager would mint
    ///         on the next `onOperations` call (0 added when no FeeManager is configured).
    /// @return totalAssets_ Current totalAssets, unchanged by the fee preview.
    function feeAdjustedSupplies() external view returns (uint256 totalSupply_, uint256 totalAssets_) {
        totalSupply_ = totalSupply();
        totalAssets_ = totalAssets();
        FeeManager _feeManager = BaseVehicleStore.getStorage().feeManager;
        if (address(_feeManager) != address(0)) {
            totalSupply_ += _feeManager.previewOnOperations(totalSupply_, totalAssets_, decimals(), _assetDecimals());
        }
    }

    /* ------------------------------------------------------------------------------------------------------------------------ */
    /*                                                      EXTERNAL VIEW                                                       */
    /* ------------------------------------------------------------------------------------------------------------------------ */

    /// @notice Returns the demand ID associated with a query.
    /// @dev 0 means no associated demand. Queries settled via the async queue path may return a
    ///      non-zero (stale) value after settlement: the value must stay set during the
    ///      registry.transition() callback so _state() returns UNLOCKING for the two-leg transition.
    ///      Post-settlement the stale value is harmless -- callers should check the registry state first.
    /// @param query The query to retrieve the demand ID for.
    /// @return The demand ID associated with the query.
    function demand(Query calldata query) external view returns (uint256) {
        return MultiVehicleStore.getStorage().values[query.toId(address(this))].demandId;
    }

    /// @inheritdoc IMultiVehicleGateway
    function totalSupply() public view override(ERC20Upgradeable, IERC20, IMultiVehicleGateway) returns (uint256) {
        return super.totalSupply();
    }

    /// @inheritdoc IMultiVehicleGateway
    function totalAssets() public view override(BaseVehicle, IMultiVehicleGateway) returns (uint256) {
        return super.totalAssets();
    }

    /// @notice Checks if the MultiVehicle and all authorized vehicles are ready for operations.
    /// @dev Overrides BaseVehicle.ready() to require this vehicle enabled (_ready()) AND every
    ///      authorized sub-vehicle ready (via SectorAccountingEngine), enabling cyclical dependency
    ///      detection when vehicles authorize each other.
    /// @return True if vehicle is enabled AND all authorized vehicles are ready.
    function ready() public view override returns (bool) {
        return _ready() && MultiVehicleStore.getStorage().accountingEngine.ready();
    }

    /// @inheritdoc BaseVehicle
    function _asset() internal view override returns (address) {
        return MultiVehicleStore.getStorage().accountingEngine.asset();
    }

    /* ------------------------------------------------------------------------------------------------------------------------ */
    /*                                                    VEHICLE INTERNALS                                                     */
    /* ------------------------------------------------------------------------------------------------------------------------ */

    /// @inheritdoc BaseVehicle
    /// @dev SectorAccountingEngine aggregate: AVAILABLE + RESERVED + all sub-vehicle positions
    ///      (ALLOCATION shares, per-vehicle sector shares/assets, and ephemeral PROCESSING-query
    ///      expected outputs).
    function _totalAssets() internal view override returns (uint256) {
        MultiVehicleStore.Storage storage $ = MultiVehicleStore.getStorage();
        return $.accountingEngine.totalAssets();
    }

    /// @inheritdoc BaseVehicle
    /// @dev Capacity is the account balance clamped to the remaining maxTotalAssets headroom, so
    ///      the advertised amount is always accepted by the post-deposit cap check in
    ///      _createDeposit (a deposit grows totalAssets by at most its input). Without the clamp,
    ///      integrators sizing deposits off maxDeposit (e.g. a parent MultiVehicle allocating
    ///      into this one) dispatch amounts the cap check then reverts.
    function _maxDeposit(address account, uint256, uint256 totalAssets_)
        internal
        view
        override
        returns (Asset memory maxAsset)
    {
        address _depositAsset = asset();
        uint256 _maxTotalAssets = MultiVehicleStore.getStorage().manager.maxTotalAssets();
        uint256 _headroom = _maxTotalAssets > totalAssets_ ? _maxTotalAssets - totalAssets_ : 0;
        maxAsset = Asset({asset: _depositAsset, value: Math.min(_headroom, IERC20(_depositAsset).balanceOf(account))});
    }

    /// @inheritdoc BaseVehicle
    function _maxRedeem(address account, uint256, uint256) internal view override returns (Asset memory maxShares) {
        maxShares = Asset({asset: address(this), value: balanceOf(account)});
    }

    /// @inheritdoc BaseVehicleQueryStateGetter
    function _state(Query calldata query) internal view override returns (State currentState) {
        MultiVehicleStore.Storage storage $ = MultiVehicleStore.getStorage();
        Id _qid = query.toId(address(this));

        currentState = super._state(query);

        // While PROCESSING with a demand, surface UNLOCKING once the demand can settle.
        if (currentState == State.PROCESSING) {
            uint256 _demandId = $.values[_qid].demandId;
            if (_demandId > 0) {
                // redeemable(): fulfillments available, demand not yet consumed.
                // pending() == 0: demand fully consumed by redeem() but storage not yet cleared
                //   (cleared only after the registry commits the terminal state).
                if ($.redeemQueue.redeemable(_demandId) || $.redeemQueue.pending(_demandId) == 0) {
                    return State.UNLOCKING;
                }
            }
        }
    }

    /// @inheritdoc BaseVehicle
    function _assetDecimals() internal view override returns (uint8) {
        return MultiVehicleStore.getStorage().accountingEngine.assetDecimals();
    }

    /// @dev Reverts if the caller is not the VehicleManager.
    function _onlyManager() internal view {
        if (msg.sender != address(MultiVehicleStore.getStorage().manager)) revert OnlyManager();
    }

    /// @inheritdoc BaseVehicle
    function _getFacets()
        internal
        view
        override
        returns (ICreateFacet, IResumeFacet, IUnlockFacet, IRecoverFacet, IInitializeFacet)
    {
        return (FACETS, IResumeFacet(address(0)), FACETS, IRecoverFacet(address(0)), FACETS);
    }

    /// @inheritdoc BaseVehicle
    /// @dev Delegates to MultiVehicleLib.previewRedeem using SectorAccountingEngine's asset and cached
    ///      decimals for the exchange rate.
    function _convertToAssets(Asset memory shares, uint256 totalSupply_, uint256 totalAssets_, bool roundUp)
        internal
        view
        override
        returns (Asset memory converted)
    {
        MultiVehicleStore.Storage storage $ = MultiVehicleStore.getStorage();
        ISectorAccountingEngine _accountingEngine = $.accountingEngine;
        Math.Rounding _rounding = roundUp ? Math.Rounding.Ceil : Math.Rounding.Floor;

        converted = Asset({
            asset: _accountingEngine.asset(),
            value: MultiVehicleLib.previewRedeem(
                shares.value, _accountingEngine.assetDecimals(), totalSupply_, totalAssets_, _rounding
            )
        });
    }

    /// @inheritdoc BaseVehicle
    /// @dev Delegates to MultiVehicleLib.previewDeposit using SectorAccountingEngine's asset and cached
    ///      decimals for the exchange rate.
    function _convertToShares(Asset memory asset_, uint256 totalSupply_, uint256 totalAssets_, bool roundUp)
        internal
        view
        override
        returns (Asset memory shares)
    {
        MultiVehicleStore.Storage storage $ = MultiVehicleStore.getStorage();
        ISectorAccountingEngine _accountingEngine = $.accountingEngine;
        Math.Rounding _rounding = roundUp ? Math.Rounding.Ceil : Math.Rounding.Floor;

        shares = Asset({
            asset: address(this),
            value: MultiVehicleLib.previewDeposit(
                asset_.value, _accountingEngine.assetDecimals(), totalSupply_, totalAssets_, _rounding
            )
        });
    }

    /// @inheritdoc BaseVehicle
    function _previewDeposit(
        uint256 assetsToDeposit,
        uint256 totalSupply_,
        uint256 totalAssets_,
        Math.Rounding rounding
    ) internal view override returns (uint256 sharesToMint) {
        return MultiVehicleLib.previewDeposit(
            assetsToDeposit,
            MultiVehicleStore.getStorage().accountingEngine.assetDecimals(),
            totalSupply_,
            totalAssets_,
            rounding
        );
    }

    /// @inheritdoc BaseVehicle
    function _previewRedeem(uint256 sharesToRedeem, uint256 totalSupply_, uint256 totalAssets_, Math.Rounding rounding)
        internal
        view
        override
        returns (uint256 assetsToWithdraw)
    {
        return MultiVehicleLib.previewRedeem(
            sharesToRedeem,
            MultiVehicleStore.getStorage().accountingEngine.assetDecimals(),
            totalSupply_,
            totalAssets_,
            rounding
        );
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "script/=script/",
    "src/=src/",
    "test/=test/",
    "@forge-deploy/=lib/forge-deploy/contracts/",
    "@forge-std/=lib/forge-std/src/",
    "@openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@morpho/=lib/morpho-blue/src/",
    "@createx/=lib/createx/src/",
    "@deploy-sol/=lib/deploy-sol/src/",
    "@halmos-cheatcodes/=lib/halmos-cheatcodes/src/",
    "@aave-v3-libs/=lib/aave-v3/src/contracts/protocol/libraries/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "aave-v3/=lib/aave-v3/",
    "createx/=lib/createx/src/",
    "ds-test/=lib/aave-v3/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/halmos-cheatcodes/src/",
    "morpho-blue/=lib/morpho-blue/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/createx/lib/openzeppelin-contracts/contracts/",
    "solady/=lib/createx/lib/solady/",
    "solidity-utils/=lib/aave-v3/lib/solidity-utils/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.