Skip to content
Verified contractPartialBUSL-1.1

AaveV3Vehicle

Address0x8273d7e6c50fe7acf3c2ea0224c8220e988e4e10
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,752
Creation transaction
0x1e2c909674…684e02927f

77 files

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

src/vehicles/aave_v3/AaveV3Vehicle.sol

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

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

// External dependencies
import {IERC20} from "@openzeppelin-contracts/interfaces/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin-contracts/interfaces/IERC20Metadata.sol";
import {Math} from "@openzeppelin-contracts/utils/math/Math.sol";
import {TokenMath} from "@aave-v3-libs/helpers/TokenMath.sol";
import {PercentageMath} from "@aave-v3-libs/math/PercentageMath.sol";
import {WadRayMath} from "@aave-v3-libs/math/WadRayMath.sol";

import {ErrorLib} from "src/libs/Error.sol";
import {SharesLib} from "src/libs/Shares.sol";

// Internal imports - Base Vehicle Constants
import {BaseVehicleConstants} from "src/vehicles/base/libs/BaseVehicleConstants.sol";

// Internal imports - Base Vehicle
import {BaseVehicle, IBaseVehicle} from "src/vehicles/base/BaseVehicle.sol";
import {ICreateFacet} from "src/vehicles/base/interfaces/facets/ICreateFacet.sol";
import {IResumeFacet} from "src/vehicles/base/interfaces/facets/IResumeFacet.sol";
import {IUnlockFacet} from "src/vehicles/base/interfaces/facets/IUnlockFacet.sol";
import {IRecoverFacet} from "src/vehicles/base/interfaces/facets/IRecoverFacet.sol";
import {IInitializeFacet} from "src/vehicles/base/interfaces/facets/IInitializeFacet.sol";

// Internal imports - Aave V3
import {IScaledBalanceToken} from "./interfaces/IScaledBalanceToken.sol";
import {AaveV3VehicleFacets} from "./facets/AaveV3VehicleFacets.sol";
import {AaveV3VehicleSharedInternal} from "src/vehicles/aave_v3/abstracts/AaveV3VehicleSharedInternal.sol";
import {AaveV3VehicleStore} from "./libs/AaveV3VehicleStore.sol";
import {AaveV3VehicleStructs} from "./libs/AaveV3VehicleStructs.sol";

/// @title Aave V3 Vehicle
/// @notice Implements the STEAM standard over Aave V3 lending markets.
///         Users deposit assets into Aave V3 pools to earn yield, receiving vehicle shares that
///         represent a proportional claim on the growing aToken balance.
/// @dev Architecture: Single ERC20 asset input, single asset output (shares for deposits, assets for redeems).
///      Yield source is Aave V3 lending pool interest accrual on aTokens.
///      Operations are synchronous - create immediately transitions to unlocking state.
///      Uses facet pattern for initialization to stay under bytecode limits.
contract AaveV3Vehicle is BaseVehicle, AaveV3VehicleSharedInternal {
    using TokenMath for uint256;
    using WadRayMath for uint256;
    using PercentageMath for uint256;

    /* ------------------------------------------------------------------------------------------------------------------------ */
    /*                                                        IMMUTABLES                                                         */
    /* ------------------------------------------------------------------------------------------------------------------------ */

    /// @notice Address of Aave V3 Vehicle facets (deployed in the constructor).
    AaveV3VehicleFacets internal immutable FACETS;

    /* ------------------------------------------------------------------------------------------------------------------------ */
    /*                                                       CONSTRUCTOR                                                         */
    /* ------------------------------------------------------------------------------------------------------------------------ */

    /// @dev Disable initializers on implementation contract deployment.
    constructor() {
        FACETS = new AaveV3VehicleFacets();
        _disableInitializers();
    }

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

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

    /// @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();
    }

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

    /// @inheritdoc BaseVehicle
    /// @dev totalAssets_ is unused -- internal accounting uses _totalUnderlyingShares() (Aave scaled balance).
    function _previewDeposit(uint256 assetsToDeposit, uint256 totalSupply_, uint256, Math.Rounding rounding)
        internal
        view
        virtual
        override
        returns (uint256 sharesToMint)
    {
        return AaveV3VehicleSharedInternal._previewDeposit(assetsToDeposit, totalSupply_, rounding);
    }

    /// @inheritdoc BaseVehicle
    function _previewRedeem(uint256 sharesToRedeem, uint256 totalSupply_, uint256, Math.Rounding rounding)
        internal
        view
        virtual
        override(BaseVehicle)
        returns (uint256 assetsToWithdraw)
    {
        return AaveV3VehicleSharedInternal._previewRedeem(sharesToRedeem, totalSupply_, rounding);
    }

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

    /// @inheritdoc BaseVehicle
    /// @dev Total assets under management: _totalUnderlyingShares() (donation-resistant scaled balance)
    ///      converted via the liquidity index.
    function _totalAssets() internal view override returns (uint256) {
        AaveV3VehicleStore.Storage storage $ = AaveV3VehicleStore.getStorage();
        uint256 _nextLiquidityIndex = $.aavePool.getReserveNormalizedIncome($.asset);
        return _totalUnderlyingShares().getATokenBalance(_nextLiquidityIndex);
    }

    /// @inheritdoc BaseVehicle
    /// @dev Maximum deposit for an account under Aave constraints (reserve status, supply cap, user balance).
    ///      1. Fail closed (zero) if the reserve is not active, frozen, or paused.
    ///      2. No supply cap configured -> deposit limited only by user balance.
    ///      3. Scale the raw supply cap to asset decimals.
    ///      4. Simulate treasury-accrual interest since the last update so the cap check uses live totals.
    ///      5. Convert total scaled supply (plus accrued) to present-value assets.
    ///      6. Fail closed (zero) if the cap is already reached.
    ///      7. Cap the user balance by remaining capacity under the supply cap.
    function _maxDeposit(address account, uint256, uint256) internal view override returns (Asset memory maxAsset) {
        AaveV3VehicleStore.Storage storage $ = AaveV3VehicleStore.getStorage();

        maxAsset = Asset({asset: $.asset, value: IERC20($.asset).balanceOf(account)});

        // 1. Reserve must be active, not frozen, not paused.
        (,,,, uint256 _reserveFactor,,,, bool _isActive, bool _isFrozen) = _getReserveConfigurationData($.asset);
        bool _isPaused = _getPaused($.asset);

        if (!_isActive || _isFrozen || _isPaused) {
            maxAsset.value = 0;
            return maxAsset;
        }

        // 2. No supply cap -> limited only by user balance.
        (, uint256 _rawSupplyCap) = _getPoolDataProvider().getReserveCaps($.asset);
        if (_rawSupplyCap == 0) {
            return maxAsset;
        }

        // 3. Scale raw supply cap to asset decimals.
        uint256 _supplyCap = _rawSupplyCap * 10 ** IERC20Metadata($.asset).decimals();

        // 4. Simulate treasury-accrual interest since the last update.
        uint256 _scaledTotalSupply = IScaledBalanceToken($.aToken).scaledTotalSupply();

        uint256 _nextLiquidityIndex = $.aavePool.getReserveNormalizedIncome($.asset);

        (, uint256 _accruedToTreasuryScaled,,,,,,,,, uint256 _storedVariableBorrowIndex, uint40 _lastUpdateTimestamp) =
            _getPoolDataProvider().getReserveData($.asset);

        if (_lastUpdateTimestamp != block.timestamp) {
            if (_reserveFactor != 0) {
                uint256 _scaledDebtSupply = IScaledBalanceToken($.vToken).scaledTotalSupply();
                uint256 _nextVariableBorrowIndex = $.aavePool.getReserveNormalizedVariableDebt($.asset);

                uint256 _totalDebtAccrued =
                    _scaledDebtSupply.rayMulFloor(_nextVariableBorrowIndex - _storedVariableBorrowIndex);

                uint256 _amountToMint = _totalDebtAccrued.percentMul(_reserveFactor);
                if (_amountToMint != 0) {
                    _accruedToTreasuryScaled += _amountToMint.getATokenMintScaledAmount(_nextLiquidityIndex);
                }
            }
        }

        // 5. Convert total scaled supply (plus accrued) to present-value assets.
        uint256 _currentTotalAssets =
            (_scaledTotalSupply + _accruedToTreasuryScaled).getATokenBalance(_nextLiquidityIndex);

        // 6. Cap already reached -> zero.
        if (_currentTotalAssets >= _supplyCap) {
            maxAsset.value = 0;
            return maxAsset;
        }

        // 7. Cap user balance by remaining capacity.
        uint256 _availableCapacity = _supplyCap - _currentTotalAssets;
        if (maxAsset.value > _availableCapacity) {
            maxAsset.value = _availableCapacity;
        }
    }

    /// @inheritdoc BaseVehicle
    /// @dev Maximum redeemable vehicle shares constrained by Aave pool liquidity.
    ///      1. Fail closed (zero) unless the reserve is active and not paused.
    ///      2. Read available pool liquidity.
    ///      3. Convert it to scaled-balance units via the liquidity index.
    ///      4. Cap by accounted scaled balance (donation resistance).
    ///      5. Convert the redeemable scaled balance to vehicle shares.
    ///      6. Cap at the account's actual share balance.
    function _maxRedeem(address account, uint256 totalSupply_, uint256)
        internal
        view
        override
        returns (Asset memory maxAsset)
    {
        AaveV3VehicleStore.Storage storage $ = AaveV3VehicleStore.getStorage();

        maxAsset = Asset({asset: address(this), value: 0});

        // 1. Reserve must be active and not paused (else zero).
        (,,,,,,,, bool _isActive,) = _getReserveConfigurationData($.asset);
        bool _isPaused = _getPaused($.asset);

        if (_isActive && !_isPaused) {
            // 2. Read available pool liquidity.
            uint256 _availableLiquidity = $.aavePool.getVirtualUnderlyingBalance($.asset);
            // 3. Convert liquidity to scaled-balance units.
            uint256 _index = $.aavePool.getReserveNormalizedIncome($.asset);
            uint256 _maxScaledBalance = _availableLiquidity.getATokenMintScaledAmount(_index);
            // 4. Cap by accounted scaled balance (donation resistance).
            uint256 _underlyingShares = _totalUnderlyingShares();
            uint256 _redeemableScaledBalance = Math.min(_maxScaledBalance, _underlyingShares);
            // 5. Convert redeemable scaled balance to vehicle shares.
            uint256 _vehicleShares = SharesLib.convertToShares(
                _redeemableScaledBalance,
                BaseVehicleConstants.VEHICLE_SHARES_DECIMALS,
                $.aTokenDecimals,
                totalSupply_,
                _underlyingShares,
                Math.Rounding.Floor
            );

            // 6. Cap at the account's share balance.
            maxAsset.value = Math.min(_vehicleShares, balanceOf(account));
        }
    }

    /// @dev Returns reserve configuration data.
    function _getReserveConfigurationData(address asset)
        internal
        view
        returns (
            uint256 decimals,
            uint256 ltv,
            uint256 liquidationThreshold,
            uint256 liquidationBonus,
            uint256 reserveFactor,
            bool usageAsCollateralEnabled,
            bool borrowingEnabled,
            bool stableBorrowRateEnabled,
            bool isActive,
            bool isFrozen
        )
    {
        return _getPoolDataProvider().getReserveConfigurationData(asset);
    }

    /// @dev Returns the reserve paused state.
    function _getPaused(address asset) internal view returns (bool) {
        return _getPoolDataProvider().getPaused(asset);
    }

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

    /// @inheritdoc BaseVehicle
    /// @dev Resume and recover facets are zero: this vehicle is synchronous, so resume() and recover()
    ///      are unimplemented and revert.
    function _getFacets()
        internal
        view
        override
        returns (ICreateFacet, IResumeFacet, IUnlockFacet, IRecoverFacet, IInitializeFacet)
    {
        return (FACETS, IResumeFacet(address(0)), FACETS, IRecoverFacet(address(0)), FACETS);
    }
}
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.