Skip to content
Verified contractPartialLicenseRef-BUSL

PositionManagerEngine

Address0x4be21ebee6efc3e9d81f52f04023a9e40b2a01a6
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 44,444,444 runs
EVM version
cancun
License
LicenseRef-BUSL
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,383,981
Creation transaction
0x177fa119c2…bf235a5ff3

src/config-engine/libraries/PositionManagerEngine.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

import {IPositionManagerBase} from 'src/position-manager/interfaces/IPositionManagerBase.sol';
import {IAaveV4ConfigEngine} from 'src/config-engine/interfaces/IAaveV4ConfigEngine.sol';

/// @title PositionManagerEngine
/// @author Aave Labs
/// @notice Library containing position manager logic for AaveV4ConfigEngine.
library PositionManagerEngine {
  /// @notice Registers/deregisters Spokes on position managers.
  /// @param registrations The Spoke registrations to execute.
  function executePositionManagerSpokeRegistrations(
    IAaveV4ConfigEngine.SpokeRegistration[] calldata registrations
  ) external {
    uint256 length = registrations.length;
    for (uint256 i; i < length; ++i) {
      IPositionManagerBase(registrations[i].positionManager).registerSpoke(
        registrations[i].spoke,
        registrations[i].registered
      );
    }
  }

  /// @notice Renounces position manager roles for users on Spokes.
  /// @param renouncements The role renouncements to execute.
  function executePositionManagerRoleRenouncements(
    IAaveV4ConfigEngine.PositionManagerRoleRenouncement[] calldata renouncements
  ) external {
    uint256 length = renouncements.length;
    for (uint256 i; i < length; ++i) {
      IPositionManagerBase(renouncements[i].positionManager).renouncePositionManagerRole(
        renouncements[i].spoke,
        renouncements[i].user
      );
    }
  }
}

src/config-engine/interfaces/IAaveV4ConfigEngine.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

import {IHubConfigurator} from 'src/hub/interfaces/IHubConfigurator.sol';
import {ISpokeConfigurator} from 'src/spoke/interfaces/ISpokeConfigurator.sol';
import {IHub} from 'src/hub/interfaces/IHub.sol';
import {ISpoke} from 'src/spoke/interfaces/ISpoke.sol';
import {IAssetInterestRateStrategy} from 'src/hub/interfaces/IAssetInterestRateStrategy.sol';

/// @title IAaveV4ConfigEngine
/// @author Aave Labs
/// @notice Interface for the Aave V4 Config Engine, defining all structs and engine method signatures.
/// The engine is stateless and invoked via delegatecall from payload contracts.
/// All numeric fields in config structs use uint256 so that type(uint256).max can serve as
/// the universal KEEP_CURRENT sentinel. Boolean fields use uint256 (0=false, 1=true, KEEP_CURRENT=skip).
interface IAaveV4ConfigEngine {
  /// @notice Parameters for tokenization of an asset on a Hub when listing the asset.
  /// @dev Tokenization is skipped only when all fields are unset. Otherwise `name`, `symbol` and
  /// `proxyAdminOwner` are all required; a partially set config reverts.
  /// @dev addCap The add cap for the TokenizationSpoke.
  /// @dev proxyAdminOwner The owner to set on the ProxyAdmin of the deployed TokenizationSpoke (address(0) when unset).
  /// @dev name The name for the TokenizationSpoke ('' when unset).
  /// @dev symbol The symbol for the TokenizationSpoke ('' when unset).
  struct TokenizationSpokeConfig {
    uint256 addCap;
    address proxyAdminOwner;
    string name;
    string symbol;
  }

  /// @notice Parameters for listing a new asset on a Hub.
  /// @dev hubConfigurator The HubConfigurator to use for this action.
  /// @dev hub The address of the Hub.
  /// @dev underlying The address of the underlying asset.
  /// @dev feeReceiver The address of the fee receiver Spoke.
  /// @dev liquidityFee The liquidity fee of the asset, in BPS.
  /// @dev irStrategy The address of the interest rate strategy contract.
  /// @dev irData The interest rate data to apply to the given asset.
  /// @dev tokenization The tokenization configuration for the asset.
  struct AssetListing {
    IHubConfigurator hubConfigurator;
    address hub;
    address underlying;
    address feeReceiver;
    uint256 liquidityFee;
    address irStrategy;
    IAssetInterestRateStrategy.InterestRateData irData;
    TokenizationSpokeConfig tokenization;
  }

  /// @notice Parameters for updating asset config (fee, interest rate, reinvestment) on a Hub.
  /// @dev hubConfigurator The HubConfigurator to use for this action.
  /// @dev hub The address of the Hub.
  /// @dev underlying The address of the underlying asset.
  /// @dev liquidityFee The new liquidity fee (KEEP_CURRENT to skip).
  /// @dev feeReceiver The new fee receiver (KEEP_CURRENT_ADDRESS to skip).
  /// @dev irStrategy The new interest rate strategy (KEEP_CURRENT_ADDRESS to skip strategy update).
  /// @dev irData The interest rate data. If irStrategy != KEEP_CURRENT_ADDRESS, calls updateInterestRateStrategy.
  /// Otherwise individual fields use KEEP_CURRENT_UINT16/KEEP_CURRENT_UINT32 sentinels;
  /// non-sentinel fields trigger a read-modify-write via updateInterestRateData.
  /// @dev reinvestmentController The new reinvestment controller (KEEP_CURRENT_ADDRESS to skip).
  struct AssetConfigUpdate {
    IHubConfigurator hubConfigurator;
    address hub;
    address underlying;
    uint256 liquidityFee;
    address feeReceiver;
    address irStrategy;
    IAssetInterestRateStrategy.InterestRateData irData;
    address reinvestmentController;
  }

  /// @notice Pairs an underlying asset address with its Spoke configuration.
  /// @dev underlying The address of the underlying asset.
  /// @dev config The Spoke configuration for the asset.
  struct SpokeAssetConfig {
    address underlying;
    IHub.SpokeConfig config;
  }

  /// @notice Parameters for registering a Spoke for multiple assets on a Hub.
  /// @dev hubConfigurator The HubConfigurator to use for this action.
  /// @dev hub The address of the Hub.
  /// @dev spoke The address of the Spoke.
  /// @dev assets The list of underlying assets with their Spoke configurations.
  struct SpokeToAssetsAddition {
    IHubConfigurator hubConfigurator;
    address hub;
    address spoke;
    SpokeAssetConfig[] assets;
  }

  /// @notice Parameters for updating Spoke config (caps, risk premium threshold, status) on a Hub.
  /// @dev hubConfigurator The HubConfigurator to use for this action.
  /// @dev hub The address of the Hub.
  /// @dev underlying The address of the underlying asset.
  /// @dev spoke The address of the Spoke.
  /// @dev addCap The new add cap (KEEP_CURRENT to skip).
  /// @dev drawCap The new draw cap (KEEP_CURRENT to skip).
  /// @dev riskPremiumThreshold The new risk premium threshold (KEEP_CURRENT to skip).
  /// @dev active New active flag (0=false, 1=true, KEEP_CURRENT=skip).
  /// @dev halted New halted flag (0=false, 1=true, KEEP_CURRENT=skip).
  struct SpokeConfigUpdate {
    IHubConfigurator hubConfigurator;
    address hub;
    address underlying;
    address spoke;
    uint256 addCap;
    uint256 drawCap;
    uint256 riskPremiumThreshold;
    uint256 active;
    uint256 halted;
  }

  /// @notice Parameters for halting an asset on a Hub.
  /// @dev hubConfigurator The HubConfigurator to use for this action.
  /// @dev hub The address of the Hub.
  /// @dev underlying The address of the underlying asset.
  struct AssetHalt {
    IHubConfigurator hubConfigurator;
    address hub;
    address underlying;
  }

  /// @notice Parameters for deactivating an asset on a Hub.
  /// @dev hubConfigurator The HubConfigurator to use for this action.
  /// @dev hub The address of the Hub.
  /// @dev underlying The address of the underlying asset.
  struct AssetDeactivation {
    IHubConfigurator hubConfigurator;
    address hub;
    address underlying;
  }

  /// @notice Parameters for resetting asset caps on a Hub to 0.
  /// @dev hubConfigurator The HubConfigurator to use for this action.
  /// @dev hub The address of the Hub.
  /// @dev underlying The address of the underlying asset.
  struct AssetCapsReset {
    IHubConfigurator hubConfigurator;
    address hub;
    address underlying;
  }

  /// @notice Parameters for deactivating a Spoke on a Hub.
  /// @dev hubConfigurator The HubConfigurator to use for this action.
  /// @dev hub The address of the Hub.
  /// @dev spoke The address of the Spoke.
  struct SpokeDeactivation {
    IHubConfigurator hubConfigurator;
    address hub;
    address spoke;
  }

  /// @notice Parameters for resetting Spoke caps on a Hub.
  /// @dev hubConfigurator The HubConfigurator to use for this action.
  /// @dev hub The address of the Hub.
  /// @dev spoke The address of the Spoke.
  struct SpokeCapsReset {
    IHubConfigurator hubConfigurator;
    address hub;
    address spoke;
  }

  /// @notice Parameters for listing a new reserve on a Spoke.
  /// @dev spokeConfigurator The SpokeConfigurator to use for this action.
  /// @dev spoke The address of the Spoke.
  /// @dev hub The address of the Hub.
  /// @dev underlying The address of the underlying asset.
  /// @dev priceSource The address of the price source.
  /// @dev config The configuration of the reserve.
  /// @dev dynamicConfig The dynamic configuration of the reserve.
  struct ReserveListing {
    ISpokeConfigurator spokeConfigurator;
    address spoke;
    address hub;
    address underlying;
    address priceSource;
    ISpoke.ReserveConfig config;
    ISpoke.DynamicReserveConfig dynamicConfig;
  }

  /// @notice Parameters for updating reserve config on a Spoke.
  /// @dev spokeConfigurator The SpokeConfigurator to use for this action.
  /// @dev spoke The address of the Spoke.
  /// @dev hub The address of the Hub.
  /// @dev underlying The address of the underlying asset.
  /// @dev priceSource The new price source address (KEEP_CURRENT_ADDRESS to skip).
  /// @dev collateralRisk New collateral risk (KEEP_CURRENT to skip).
  /// @dev paused New paused flag (0=false, 1=true, KEEP_CURRENT=skip).
  /// @dev frozen New frozen flag (0=false, 1=true, KEEP_CURRENT=skip).
  /// @dev borrowable New borrowable flag (0=false, 1=true, KEEP_CURRENT=skip).
  /// @dev receiveSharesEnabled New receiveSharesEnabled flag (0=false, 1=true, KEEP_CURRENT=skip).
  struct ReserveConfigUpdate {
    ISpokeConfigurator spokeConfigurator;
    address spoke;
    address hub;
    address underlying;
    address priceSource;
    uint256 collateralRisk;
    uint256 paused;
    uint256 frozen;
    uint256 borrowable;
    uint256 receiveSharesEnabled;
  }

  /// @notice Parameters for updating liquidation config on a Spoke.
  /// @dev spokeConfigurator The SpokeConfigurator to use for this action.
  /// @dev spoke The address of the Spoke.
  /// @dev targetHealthFactor The new target health factor (KEEP_CURRENT to skip).
  /// @dev healthFactorForMaxBonus The new health factor for max bonus (KEEP_CURRENT to skip).
  /// @dev liquidationBonusFactor The new liquidation bonus factor (KEEP_CURRENT to skip).
  struct LiquidationConfigUpdate {
    ISpokeConfigurator spokeConfigurator;
    address spoke;
    uint256 targetHealthFactor;
    uint256 healthFactorForMaxBonus;
    uint256 liquidationBonusFactor;
  }

  /// @notice Parameters for adding a dynamic reserve config on a Spoke.
  /// @dev spokeConfigurator The SpokeConfigurator to use for this action.
  /// @dev spoke The address of the Spoke.
  /// @dev hub The address of the Hub.
  /// @dev underlying The address of the underlying asset.
  /// @dev dynamicConfig The new dynamic config.
  struct DynamicReserveConfigAddition {
    ISpokeConfigurator spokeConfigurator;
    address spoke;
    address hub;
    address underlying;
    ISpoke.DynamicReserveConfig dynamicConfig;
  }

  /// @notice Parameters for updating a dynamic reserve config on a Spoke.
  /// @dev spokeConfigurator The SpokeConfigurator to use for this action.
  /// @dev spoke The address of the Spoke.
  /// @dev hub The address of the Hub.
  /// @dev underlying The address of the underlying asset.
  /// @dev dynamicConfigKey The key of the dynamic config to update.
  /// @dev collateralFactor New collateral factor (KEEP_CURRENT to skip).
  /// @dev maxLiquidationBonus New max liquidation bonus (KEEP_CURRENT to skip).
  /// @dev liquidationFee New liquidation fee (KEEP_CURRENT to skip).
  struct DynamicReserveConfigUpdate {
    ISpokeConfigurator spokeConfigurator;
    address spoke;
    address hub;
    address underlying;
    uint256 dynamicConfigKey;
    uint256 collateralFactor;
    uint256 maxLiquidationBonus;
    uint256 liquidationFee;
  }

  /// @notice Parameters for updating a position manager on a Spoke.
  /// @dev spokeConfigurator The SpokeConfigurator to use for this action.
  /// @dev spoke The address of the Spoke.
  /// @dev positionManager The address of the position manager.
  /// @dev active The new active flag.
  struct PositionManagerUpdate {
    ISpokeConfigurator spokeConfigurator;
    address spoke;
    address positionManager;
    bool active;
  }

  /// @notice Parameters for registering/deregistering a Spoke on a position manager.
  /// @dev positionManager The position manager address.
  /// @dev spoke The address of the Spoke.
  /// @dev registered Whether to register (true) or deregister (false) the Spoke.
  struct SpokeRegistration {
    address positionManager;
    address spoke;
    bool registered;
  }

  /// @notice Parameters for renouncing the position manager role for a user on a Spoke.
  /// @dev positionManager The position manager address.
  /// @dev spoke The address of the Spoke.
  /// @dev user The address of the user to renounce the role for.
  struct PositionManagerRoleRenouncement {
    address positionManager;
    address spoke;
    address user;
  }

  /// @notice Parameters for granting or revoking a role via AccessManager.
  /// @dev When granted=true → grantRole(roleId, account, executionDelay).
  /// @dev When granted=false → revokeRole(roleId, account). executionDelay is ignored.
  /// @dev authority The AccessManager address.
  /// @dev roleId The role identifier.
  /// @dev account The account to grant/revoke the role to/from.
  /// @dev granted Whether to grant (true) or revoke (false) the role.
  /// @dev executionDelay The execution delay for the account (only used when granted=true).
  struct RoleMembership {
    address authority;
    uint64 roleId;
    address account;
    bool granted;
    uint32 executionDelay;
  }

  /// @notice Parameters for updating role configuration via AccessManager.
  /// @dev Uses type-specific sentinels to skip fields: KEEP_CURRENT_UINT64 for admin/guardian,
  /// KEEP_CURRENT_UINT32 for grantDelay, empty string for label.
  /// @dev authority The AccessManager address.
  /// @dev roleId The role identifier.
  /// @dev admin The new admin role identifier (KEEP_CURRENT_UINT64 to skip).
  /// @dev guardian The new guardian role identifier (KEEP_CURRENT_UINT64 to skip).
  /// @dev grantDelay The new grant delay (KEEP_CURRENT_UINT32 to skip).
  /// @dev label The label string (empty string to skip).
  /// @dev labelUpdate Must be true to relabel an already-labeled role (clears the existing label first).
  struct RoleUpdate {
    address authority;
    uint64 roleId;
    uint64 admin;
    uint64 guardian;
    uint32 grantDelay;
    string label;
    bool labelUpdate;
  }

  /// @notice Parameters for setting target function roles via AccessManager.
  /// @dev authority The AccessManager address.
  /// @dev target The target contract address.
  /// @dev selectors The function selectors.
  /// @dev roleId The role identifier.
  struct TargetFunctionRoleUpdate {
    address authority;
    address target;
    bytes4[] selectors;
    uint64 roleId;
  }

  /// @notice Parameters for setting target admin delay via AccessManager.
  /// @dev authority The AccessManager address.
  /// @dev target The target contract address.
  /// @dev newDelay The new admin delay.
  struct TargetAdminDelayUpdate {
    address authority;
    address target;
    uint32 newDelay;
  }

  /// @notice Lists new assets on Hubs via the HubConfigurator.
  /// @param listings The asset listings to execute.
  function executeHubAssetListings(AssetListing[] calldata listings) external;

  /// @notice Updates asset config (fee, interest rate, reinvestment) on Hubs.
  /// @param updates The asset config updates to execute.
  function executeHubAssetConfigUpdates(AssetConfigUpdate[] calldata updates) external;

  /// @notice Registers Spokes for multiple assets on Hubs.
  /// @param additions The Spoke-to-assets additions to execute.
  function executeHubSpokeToAssetsAdditions(SpokeToAssetsAddition[] calldata additions) external;

  /// @notice Updates Spoke config (caps, risk premium threshold, status) on Hubs.
  /// @param updates The Spoke config updates to execute.
  function executeHubSpokeConfigUpdates(SpokeConfigUpdate[] calldata updates) external;

  /// @notice Halts assets on Hubs.
  /// @param halts The asset halts to execute.
  function executeHubAssetHalts(AssetHalt[] calldata halts) external;

  /// @notice Deactivates assets on Hubs.
  /// @param deactivations The asset deactivations to execute.
  function executeHubAssetDeactivations(AssetDeactivation[] calldata deactivations) external;

  /// @notice Resets asset caps on Hubs.
  /// @param resets The asset caps resets to execute.
  function executeHubAssetCapsResets(AssetCapsReset[] calldata resets) external;

  /// @notice Deactivates Spokes on Hubs.
  /// @param deactivations The Spoke deactivations to execute.
  function executeHubSpokeDeactivations(SpokeDeactivation[] calldata deactivations) external;

  /// @notice Resets Spoke caps on Hubs.
  /// @param resets The Spoke caps resets to execute.
  function executeHubSpokeCapsResets(SpokeCapsReset[] calldata resets) external;

  /// @notice Lists new reserves on Spokes.
  /// @param listings The reserve listings to execute.
  function executeSpokeReserveListings(ReserveListing[] calldata listings) external;

  /// @notice Updates reserve config on Spokes.
  /// @param updates The reserve config updates to execute.
  function executeSpokeReserveConfigUpdates(ReserveConfigUpdate[] calldata updates) external;

  /// @notice Updates liquidation config on Spokes.
  /// @param updates The liquidation config updates to execute.
  function executeSpokeLiquidationConfigUpdates(
    LiquidationConfigUpdate[] calldata updates
  ) external;

  /// @notice Adds dynamic reserve configs on Spokes.
  /// @param additions The dynamic reserve config additions to execute.
  function executeSpokeDynamicReserveConfigAdditions(
    DynamicReserveConfigAddition[] calldata additions
  ) external;

  /// @notice Updates dynamic reserve configs on Spokes.
  /// @param updates The dynamic reserve config updates to execute.
  function executeSpokeDynamicReserveConfigUpdates(
    DynamicReserveConfigUpdate[] calldata updates
  ) external;

  /// @notice Updates position managers on Spokes.
  /// @param updates The position manager updates to execute.
  function executeSpokePositionManagerUpdates(PositionManagerUpdate[] calldata updates) external;

  /// @notice Registers/deregisters Spokes on position managers.
  /// @param registrations The Spoke registrations to execute.
  function executePositionManagerSpokeRegistrations(
    SpokeRegistration[] calldata registrations
  ) external;

  /// @notice Renounces position manager roles for users on Spokes.
  /// @param renouncements The role renouncements to execute.
  function executePositionManagerRoleRenouncements(
    PositionManagerRoleRenouncement[] calldata renouncements
  ) external;

  /// @notice Grants or revokes roles via AccessManager.
  /// @param memberships The role memberships to execute.
  function executeRoleMemberships(RoleMembership[] calldata memberships) external;

  /// @notice Updates role configuration (admin, guardian, grant delay, label) via AccessManager.
  /// @dev Set labelUpdate to true to relabel an already-labeled role (the existing label is cleared
  /// first); labeling an already-labeled role with labelUpdate false reverts.
  /// Clearing a label without setting a new one requires a direct `labelRole` call.
  /// @param updates The role updates to execute.
  function executeRoleUpdates(RoleUpdate[] calldata updates) external;

  /// @notice Updates target function roles via AccessManager.
  /// @param updates The target function role updates to execute.
  function executeTargetFunctionRoleUpdates(TargetFunctionRoleUpdate[] calldata updates) external;

  /// @notice Updates target admin delays via AccessManager.
  /// @param updates The target admin delay updates to execute.
  function executeTargetAdminDelayUpdates(TargetAdminDelayUpdate[] calldata updates) external;
}

src/dependencies/openzeppelin/IAccessManaged.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/IAccessManaged.sol)

pragma solidity >=0.8.4;

interface IAccessManaged {
  /**
   * @dev Authority that manages this contract was updated.
   */
  event AuthorityUpdated(address authority);

  error AccessManagedUnauthorized(address caller);
  error AccessManagedRequiredDelay(address caller, uint32 delay);
  error AccessManagedInvalidAuthority(address authority);

  /**
   * @dev Returns the current authority.
   */
  function authority() external view returns (address);

  /**
   * @dev Transfers control to a new authority. The caller must be the current authority.
   */
  function setAuthority(address) external;

  /**
   * @dev Returns true only in the context of a delayed restricted call, at the moment that the scheduled operation is
   * being consumed. Prevents denial of service for delayed restricted calls in the case that the contract performs
   * attacker controlled calls.
   */
  function isConsumingScheduledOp() external view returns (bytes4);
}

src/hub/interfaces/IAssetInterestRateStrategy.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

import {IBasicInterestRateStrategy} from 'src/hub/interfaces/IBasicInterestRateStrategy.sol';

/// @title IAssetInterestRateStrategy
/// @author Aave Labs
/// @notice Interface of the optimal-usage-based asset interest rate strategy.
interface IAssetInterestRateStrategy is IBasicInterestRateStrategy {
  /// @notice Holds the interest rate data for a given asset.
  /// @dev optimalUsageRatio The optimal usage ratio, in BPS. Maximum and minimum values are defined by `MAX_OPTIMAL_RATIO` and `MIN_OPTIMAL_RATIO`.
  /// @dev baseDrawnRate The base drawn rate, in BPS.
  /// @dev rateGrowthBeforeOptimal The rate growth before the optimal usage ratio, in BPS.
  /// @dev rateGrowthAfterOptimal The rate growth after the optimal usage ratio, in BPS.
  struct InterestRateData {
    uint16 optimalUsageRatio;
    uint32 baseDrawnRate;
    uint32 rateGrowthBeforeOptimal;
    uint32 rateGrowthAfterOptimal;
  }

  /// @notice Emitted when interest rate data is updated for an asset.
  /// @param hub The address of the associated Hub.
  /// @param assetId The identifier of the asset whose interest rate data is updated.
  /// @param optimalUsageRatio The optimal usage ratio, in BPS.
  /// @param baseDrawnRate The base drawn rate, in BPS.
  /// @param rateGrowthBeforeOptimal The rate growth before the optimal usage ratio, in BPS.
  /// @param rateGrowthAfterOptimal The rate growth after the optimal usage ratio, in BPS.
  event UpdateInterestRateData(
    address indexed hub,
    uint256 indexed assetId,
    uint256 optimalUsageRatio,
    uint256 baseDrawnRate,
    uint256 rateGrowthBeforeOptimal,
    uint256 rateGrowthAfterOptimal
  );

  /// @notice Thrown when the given address is invalid.
  error InvalidAddress();

  /// @notice Thrown when the caller is not the Hub.
  error OnlyHub();

  /// @notice Thrown when the max possible rate is greater than `MAX_ALLOWED_DRAWN_RATE`.
  error InvalidMaxDrawnRate();

  /// @notice Thrown when the optimal usage ratio is less than `MIN_OPTIMAL_RATIO` or greater than `MAX_OPTIMAL_RATIO`.
  error InvalidOptimalUsageRatio();

  /// @notice Returns the full InterestRateData struct for the given asset.
  /// @param assetId The identifier of the asset for which to get the data.
  /// @return The InterestRateData struct for the given asset, all in BPS.
  function getInterestRateData(uint256 assetId) external view returns (InterestRateData memory);

  /// @notice Returns the optimal usage rate for the given asset.
  /// @param assetId The identifier of the asset for which to get the optimal usage ratio.
  /// @return The optimal usage ratio, in BPS.
  function getOptimalUsageRatio(uint256 assetId) external view returns (uint256);

  /// @notice Returns the base drawn rate.
  /// @param assetId The identifier of the asset for which to get the base drawn rate.
  /// @return The base drawn rate, in BPS.
  function getBaseDrawnRate(uint256 assetId) external view returns (uint256);

  /// @notice Returns the rate growth before the optimal usage ratio.
  /// @dev Applicable when usage ratio > 0 and <= OPTIMAL_USAGE_RATIO.
  /// @param assetId The identifier of the asset for which to get the rate growth before the optimal usage ratio.
  /// @return The rate growth, in BPS.
  function getRateGrowthBeforeOptimal(uint256 assetId) external view returns (uint256);

  /// @notice Returns the rate growth after the optimal usage ratio.
  /// @dev Applicable when usage ratio > OPTIMAL_USAGE_RATIO.
  /// @param assetId The identifier of the asset for which to get the rate growth after the optimal usage ratio.
  /// @return The rate growth, in BPS.
  function getRateGrowthAfterOptimal(uint256 assetId) external view returns (uint256);

  /// @notice Returns the maximum drawn rate.
  /// @param assetId The identifier of the asset for which to get the maximum drawn rate.
  /// @return The maximum drawn rate, in BPS.
  function getMaxDrawnRate(uint256 assetId) external view returns (uint256);

  /// @notice Returns the maximum allowed value for a drawn rate.
  /// @return The maximum drawn rate, in BPS.
  function MAX_ALLOWED_DRAWN_RATE() external view returns (uint256);

  /// @notice Returns the minimum optimal usage ratio.
  /// @return The minimum optimal usage ratio, expressed in BPS.
  function MIN_OPTIMAL_RATIO() external view returns (uint256);

  /// @notice Returns the maximum optimal usage ratio.
  /// @return The maximum optimal usage ratio, expressed in BPS.
  function MAX_OPTIMAL_RATIO() external view returns (uint256);

  /// @notice Returns the address of the Hub.
  function HUB() external view returns (address);
}

src/hub/interfaces/IBasicInterestRateStrategy.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

/// @title IBasicInterestRateStrategy
/// @author Aave Labs
/// @notice Basic interface for any interest rate strategy.
interface IBasicInterestRateStrategy {
  /// @notice Thrown when the interest rate data is not set for the asset.
  /// @param assetId The identifier of the asset with no interest rate data set.
  error InterestRateDataNotSet(uint256 assetId);

  /// @notice Sets the interest rate parameters for a specified asset.
  /// @param assetId The identifier of the asset.
  /// @param data The encoded parameters used to configure the interest rate of the asset.
  function setInterestRateData(uint256 assetId, bytes calldata data) external;

  /// @notice Calculates the interest rate depending on the asset's state and configurations.
  /// @param assetId The identifier of the asset.
  /// @param liquidity The current available liquidity of the asset.
  /// @param drawn The current drawn amount of the asset.
  /// @param deficit The current deficit of the asset.
  /// @param swept The current swept (reinvested) amount of the asset.
  /// @return The interest rate, expressed in RAY.
  function calculateInterestRate(
    uint256 assetId,
    uint256 liquidity,
    uint256 drawn,
    uint256 deficit,
    uint256 swept
  ) external view returns (uint256);
}

src/hub/interfaces/IHub.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

import {IAccessManaged} from 'src/dependencies/openzeppelin/IAccessManaged.sol';
import {IHubBase} from 'src/hub/interfaces/IHubBase.sol';

/// @title IHub
/// @author Aave Labs
/// @notice Full interface for the Hub.
interface IHub is IHubBase, IAccessManaged {
  /// @notice Asset position and configuration data.
  /// @dev liquidity The liquidity available to be accessed, expressed in asset units.
  /// @dev realizedFees The amount of fees realized but not yet minted, expressed in asset units.
  /// @dev decimals The number of decimals of the underlying asset.
  /// @dev addedShares The total shares added across all spokes.
  /// @dev swept The outstanding liquidity which has been invested by the reinvestment controller, expressed in asset units.
  /// @dev premiumOffsetRay The total premium offset across all spokes, used to calculate the premium, expressed in asset units and scaled by RAY.
  /// @dev drawnShares The total drawn shares across all spokes.
  /// @dev premiumShares The total premium shares across all spokes.
  /// @dev liquidityFee The protocol fee charged on drawn and premium liquidity growth, expressed in BPS.
  /// @dev drawnIndex The drawn index which monotonically increases according to the drawn rate, expressed in RAY.
  /// @dev drawnRate The rate at which drawn assets grow, expressed in RAY.
  /// @dev lastUpdateTimestamp The timestamp of the last accrual.
  /// @dev underlying The address of the underlying asset.
  /// @dev irStrategy The address of the interest rate strategy.
  /// @dev reinvestmentController The address of the reinvestment controller.
  /// @dev feeReceiver The address of the fee receiver spoke.
  /// @dev deficitRay The amount of outstanding bad debt across all spokes, expressed in asset units and scaled by RAY.
  struct Asset {
    uint120 liquidity;
    uint120 realizedFees;
    uint8 decimals;
    //
    uint120 addedShares;
    uint120 swept;
    //
    int200 premiumOffsetRay;
    //
    uint120 drawnShares;
    uint120 premiumShares;
    uint16 liquidityFee;
    //
    uint120 drawnIndex;
    uint96 drawnRate;
    uint40 lastUpdateTimestamp;
    //
    address underlying;
    //
    address irStrategy;
    //
    address reinvestmentController;
    //
    address feeReceiver;
    //
    uint200 deficitRay;
  }

  /// @notice Asset configuration. Subset of the `Asset` struct.
  struct AssetConfig {
    address feeReceiver;
    uint16 liquidityFee;
    address irStrategy;
    address reinvestmentController;
  }

  /// @notice Spoke position and configuration data.
  /// @dev drawnShares The drawn shares of a spoke for a given asset.
  /// @dev premiumShares The premium shares of a spoke for a given asset.
  /// @dev premiumOffsetRay The premium offset of a spoke for a given asset, used to calculate the premium, expressed in asset units and scaled by RAY.
  /// @dev addedShares The added shares of a spoke for a given asset.
  /// @dev addCap The maximum amount that can be added by a spoke, expressed in whole assets (not scaled by decimals). A value of `MAX_ALLOWED_SPOKE_CAP` indicates no cap.
  /// @dev drawCap The maximum amount that can be drawn by a spoke, expressed in whole assets (not scaled by decimals). A value of `MAX_ALLOWED_SPOKE_CAP` indicates no cap.
  /// @dev riskPremiumThreshold The maximum ratio of premium to drawn shares a spoke can have, expressed in BPS. A value of `MAX_RISK_PREMIUM_THRESHOLD` indicates no threshold.
  /// @dev active True if the Spoke is allowed to perform any action.
  /// @dev halted True if the Spoke is prevented from performing actions that instantly update liquidity.
  /// @dev deficitRay The deficit reported by a spoke for a given asset, expressed in asset units and scaled by RAY.
  struct SpokeData {
    uint120 drawnShares;
    uint120 premiumShares;
    //
    int200 premiumOffsetRay;
    //
    uint120 addedShares;
    uint40 addCap;
    uint40 drawCap;
    uint24 riskPremiumThreshold;
    bool active;
    bool halted;
    //
    uint200 deficitRay;
  }

  /// @notice Spoke configuration data. Subset of the `SpokeData` struct.
  struct SpokeConfig {
    uint40 addCap;
    uint40 drawCap;
    uint24 riskPremiumThreshold;
    bool active;
    bool halted;
  }

  /// @notice Emitted when an asset is added.
  /// @param assetId The identifier of the asset.
  /// @param underlying The address of the underlying asset.
  /// @param decimals The number of decimals of the asset.
  event AddAsset(uint256 indexed assetId, address indexed underlying, uint8 decimals);

  /// @notice Emitted when an asset is updated.
  /// @param assetId The identifier of the asset.
  /// @param drawnIndex The new drawn index of the asset.
  /// @param drawnRate The new drawn rate of the asset.
  /// @param accruedFees The accrued fees of the asset since the last mint.
  event UpdateAsset(
    uint256 indexed assetId,
    uint256 drawnIndex,
    uint256 drawnRate,
    uint256 accruedFees
  );

  /// @notice Emitted when an asset configuration is updated.
  /// @param assetId The identifier of the asset.
  /// @param config The new asset configuration struct.
  event UpdateAssetConfig(uint256 indexed assetId, AssetConfig config);

  /// @notice Emitted when a spoke is added.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  event AddSpoke(uint256 indexed assetId, address indexed spoke);

  /// @notice Emitted when a spoke configuration is updated.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param config The new spoke configuration struct.
  event UpdateSpokeConfig(uint256 indexed assetId, address indexed spoke, SpokeConfig config);

  /// @notice Emitted when fees are minted to the fee receiver spoke.
  /// @param assetId The identifier of the asset.
  /// @param feeReceiver The address of the current fee receiver spoke.
  /// @param shares The amount of shares minted.
  /// @param assets The amount of assets used to mint the shares.
  event MintFeeShares(
    uint256 indexed assetId,
    address indexed feeReceiver,
    uint256 shares,
    uint256 assets
  );

  /// @notice Emitted when liquidity is invested by the reinvestment controller.
  /// @param assetId The identifier of the asset.
  /// @param reinvestmentController The active asset controller.
  /// @param amount The amount invested.
  event Sweep(uint256 indexed assetId, address indexed reinvestmentController, uint256 amount);

  /// @notice Emitted when liquidity is reclaimed (from swept liquidity) by the reinvestment controller.
  /// @param assetId The identifier of the asset.
  /// @param reinvestmentController The active asset controller.
  /// @param amount The amount reclaimed.
  event Reclaim(uint256 indexed assetId, address indexed reinvestmentController, uint256 amount);

  /// @notice Emitted when a deficit is eliminated.
  /// @param assetId The identifier of the asset.
  /// @param callerSpoke The spoke that eliminated the deficit using its added shares.
  /// @param coveredSpoke The spoke for which the deficit was eliminated.
  /// @param shares The amount of shares removed.
  /// @param deficitAmountRay The amount of deficit eliminated, expressed in asset units and scaled by RAY.
  event EliminateDeficit(
    uint256 indexed assetId,
    address indexed callerSpoke,
    address indexed coveredSpoke,
    uint256 shares,
    uint256 deficitAmountRay
  );

  /// @notice Thrown when an underlying asset is already listed.
  error UnderlyingAlreadyListed();

  /// @notice Thrown when an asset is not listed.
  error AssetNotListed();

  /// @notice Thrown when the add cap is exceeded.
  /// @param addCap The current `addCap` of the asset, expressed in whole assets (not scaled by decimals).
  error AddCapExceeded(uint256 addCap);

  /// @notice Thrown when the available liquidity is insufficient.
  /// @param liquidity The current available liquidity.
  error InsufficientLiquidity(uint256 liquidity);

  /// @notice Thrown when the transferred liquidity is insufficient.
  /// @param liquidityNeeded The amount of additional liquidity needed.
  error InsufficientTransferred(uint256 liquidityNeeded);

  /// @notice Thrown when the draw cap is exceeded.
  /// @param drawCap The current `drawCap` of the asset, expressed in whole assets (not scaled by decimals).
  error DrawCapExceeded(uint256 drawCap);

  /// @notice Thrown when a surplus amount of drawn is restored.
  /// @param maxAllowedRestore The maximum allowed drawn amount to restore.
  error SurplusDrawnRestored(uint256 maxAllowedRestore);

  /// @notice Thrown when a surplus amount of premium is restored.
  /// @param maxAllowedRestoreRay The maximum allowed premium amount to restore, expressed in asset units and scaled by RAY.
  error SurplusPremiumRayRestored(uint256 maxAllowedRestoreRay);

  /// @notice Thrown when the premium change is invalid.
  error InvalidPremiumChange();

  /// @notice Thrown when a surplus amount of drawn is reported as deficit.
  /// @param maxAllowedDeficit The maximum allowed drawn to report as deficit.
  error SurplusDrawnDeficitReported(uint256 maxAllowedDeficit);

  /// @notice Thrown when a surplus amount of premium is reported as deficit.
  /// @param maxAllowedDeficitRay The maximum allowed premium to report as deficit, expressed in asset units and scaled by RAY.
  error SurplusPremiumRayDeficitReported(uint256 maxAllowedDeficitRay);

  /// @notice Thrown when a spoke is not active.
  error SpokeNotActive();

  /// @notice Thrown when a spoke is halted.
  error SpokeHalted();

  /// @notice Thrown when a new reinvestment controller is the zero address and the asset has existing swept liquidity.
  error InvalidReinvestmentController();

  /// @notice Thrown when an invalid reinvestment controller attempts to perform a `sweep` action.
  error OnlyReinvestmentController();

  /// @notice Thrown when a spoke being added is already listed.
  error SpokeAlreadyListed();

  /// @notice Thrown when a spoke being updated is not listed.
  error SpokeNotListed();

  /// @notice Thrown when the amount is invalid.
  error InvalidAmount();

  /// @notice Thrown when the shares amount is invalid.
  error InvalidShares();

  /// @notice Thrown when an input address is invalid.
  error InvalidAddress();

  /// @notice Thrown if the liquidity fee is invalid when updating an asset configuration.
  error InvalidLiquidityFee();

  /// @notice Thrown when the asset decimals exceed the maximum allowed decimals.
  error InvalidAssetDecimals();

  /// @notice Thrown if the interest rate strategy or data are invalid when updating an asset configuration.
  /// @dev The `irData` must be empty if the interest rate strategy is not updated.
  error InvalidInterestRateStrategy();

  /// @notice Adds a new asset to the Hub.
  /// @dev The same underlying asset address cannot be added as an asset multiple times.
  /// @dev The fee receiver is added as a new spoke with maximum add cap and zero draw cap.
  /// @param underlying The address of the underlying asset.
  /// @param decimals The number of decimals of `underlying`.
  /// @param feeReceiver The address of the fee receiver spoke.
  /// @param irStrategy The address of the interest rate strategy contract.
  /// @param irData The interest rate data to apply to the given asset encoded in bytes.
  /// @return The unique identifier of the added asset.
  function addAsset(
    address underlying,
    uint8 decimals,
    address feeReceiver,
    address irStrategy,
    bytes calldata irData
  ) external returns (uint256);

  /// @notice Updates the configuration of an asset.
  /// @dev If the fee receiver is updated, adds it as a new spoke with maximum add cap and zero draw cap, and sets old fee receiver caps to zero.
  /// @dev If the fee receiver is updated, accrued fees are minted as shares before the update if their value exceeds one share.
  /// @dev If the interest rate strategy is updated, it is configured with `irData`. Otherwise, `irData` must be empty.
  /// @param assetId The identifier of the asset.
  /// @param config The new configuration for the asset.
  /// @param irData The interest rate data to apply to the given asset, encoded in bytes.
  function updateAssetConfig(
    uint256 assetId,
    AssetConfig calldata config,
    bytes calldata irData
  ) external;

  /// @notice Registers a new spoke for a specific asset in the Hub.
  /// @dev Reverts with `SpokeAlreadyListed` if spoke is already listed.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke to add.
  /// @param params The configuration parameters for the Spoke.
  function addSpoke(uint256 assetId, address spoke, SpokeConfig calldata params) external;

  /// @notice Updates the configuration of a spoke for a specific asset.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke to update.
  /// @param config The new configuration for the Spoke.
  function updateSpokeConfig(uint256 assetId, address spoke, SpokeConfig calldata config) external;

  /// @notice Updates the interest rate strategy for a specified asset.
  /// @param assetId The identifier of the asset.
  /// @param irData The interest rate data to apply to the given asset, encoded in bytes.
  function setInterestRateData(uint256 assetId, bytes calldata irData) external;

  /// @notice Mints shares to the fee receiver from accrued fees.
  /// @dev No op when fees are worth less than one share.
  /// @param assetId The identifier of the asset.
  /// @return The amount of shares minted.
  function mintFeeShares(uint256 assetId) external returns (uint256);

  /// @notice Eliminates deficit by removing added shares of caller spoke.
  /// @dev Only callable by active and authorized spokes.
  /// @param assetId The identifier of the asset.
  /// @param amount The amount of deficit to eliminate.
  /// @param spoke The spoke for which the deficit is eliminated.
  /// @return The amount of added shares removed.
  /// @return The amount of deficit eliminated, expressed in asset units.
  function eliminateDeficit(
    uint256 assetId,
    uint256 amount,
    address spoke
  ) external returns (uint256, uint256);

  /// @notice Allows a spoke to transfer its added shares of an asset to another spoke.
  /// @dev Only callable by spokes.
  /// @param assetId The identifier of the asset.
  /// @param shares The amount of shares to move.
  /// @param toSpoke The address of the recipient spoke.
  function transferShares(uint256 assetId, uint256 shares, address toSpoke) external;

  /// @notice Sweeps an amount of liquidity of the corresponding asset and sends it to the configured reinvestment controller.
  /// @dev The controller handles the actual reinvestment of funds, redistribution of interest, and investment caps.
  /// @param assetId The identifier of the asset.
  /// @param amount The amount to sweep.
  function sweep(uint256 assetId, uint256 amount) external;

  /// @notice Reclaims an amount of liquidity of the corresponding asset from the configured reinvestment controller.
  /// @dev The controller can only reclaim up to swept amount. All accrued interest is distributed offchain.
  /// @dev Underlying assets must be transferred to the Hub before invocation.
  /// @dev Extra untracked underlying liquidity in the Hub can be skimmed into the Hub's liquidity accounting through this action.
  /// @param assetId The identifier of the asset.
  /// @param amount The amount to reclaim.
  function reclaim(uint256 assetId, uint256 amount) external;

  /// @notice Returns whether the underlying is listed as an asset.
  /// @param underlying The address of the underlying asset.
  /// @return True if the underlying asset is listed.
  function isUnderlyingListed(address underlying) external view returns (bool);

  /// @notice Returns the number of listed assets.
  function getAssetCount() external view returns (uint256);

  /// @notice Returns information regarding the specified asset.
  /// @dev `drawnIndex`, `drawnRate` and `lastUpdateTimestamp` can be outdated due to passage of time.
  /// @param assetId The identifier of the asset.
  /// @return The asset struct.
  function getAsset(uint256 assetId) external view returns (Asset memory);

  /// @notice Returns the asset configuration for the specified asset.
  /// @param assetId The identifier of the asset.
  /// @return The asset configuration struct.
  function getAssetConfig(uint256 assetId) external view returns (AssetConfig memory);

  /// @notice Returns the accrued fees for the asset, expressed in asset units.
  /// @dev Accrued fees are excluded from total added assets.
  /// @param assetId The identifier of the asset.
  /// @return The amount of accrued fees.
  function getAssetAccruedFees(uint256 assetId) external view returns (uint256);

  /// @notice Returns the amount of liquidity swept by the reinvestment controller for the specified asset.
  /// @param assetId The identifier of the asset.
  /// @return The amount of liquidity swept.
  function getAssetSwept(uint256 assetId) external view returns (uint256);

  /// @notice Calculates the current drawn rate for the specified asset.
  /// @param assetId The identifier of the asset.
  /// @return The current drawn rate of the asset.
  function getAssetDrawnRate(uint256 assetId) external view returns (uint256);

  /// @notice Returns the number of spokes listed for the specified asset.
  /// @param assetId The identifier of the asset.
  function getSpokeCount(uint256 assetId) external view returns (uint256);

  /// @notice Returns whether the Spoke is listed for the specified asset.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @return True if the Spoke is listed.
  function isSpokeListed(uint256 assetId, address spoke) external view returns (bool);

  /// @notice Returns the address of the Spoke for an asset at the given index.
  /// @param assetId The identifier of the asset.
  /// @param index The index of the Spoke.
  /// @return The address of the Spoke.
  function getSpokeAddress(uint256 assetId, uint256 index) external view returns (address);

  /// @notice Returns the Spoke data struct.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @return The spoke data struct.
  function getSpoke(uint256 assetId, address spoke) external view returns (SpokeData memory);

  /// @notice Returns the Spoke configuration struct.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @return The spoke configuration struct.
  function getSpokeConfig(
    uint256 assetId,
    address spoke
  ) external view returns (SpokeConfig memory);

  /// @notice Returns the maximum allowed number of decimals for the underlying asset.
  /// @return The maximum number of decimals (inclusive).
  function MAX_ALLOWED_UNDERLYING_DECIMALS() external view returns (uint8);

  /// @notice Returns the minimum allowed number of decimals for the underlying asset.
  /// @return The minimum number of decimals (inclusive).
  function MIN_ALLOWED_UNDERLYING_DECIMALS() external view returns (uint8);

  /// @notice Returns the maximum value for any spoke cap (add or draw).
  /// @dev The value is not inclusive; using the maximum value indicates no cap.
  /// @return The maximum cap value, expressed in asset units.
  function MAX_ALLOWED_SPOKE_CAP() external view returns (uint40);

  /// @notice Returns the maximum value for any spoke risk premium threshold.
  /// @dev The value is not inclusive; using the maximum value indicates no threshold.
  /// @return The maximum risk premium threshold, expressed in BPS.
  function MAX_RISK_PREMIUM_THRESHOLD() external view returns (uint24);
}

src/hub/interfaces/IHubBase.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

/// @title IHubBase
/// @author Aave Labs
/// @notice Minimal interface for Hub.
interface IHubBase {
  /// @notice Changes to premium owed accounting.
  /// @dev sharesDelta The change in premium shares.
  /// @dev offsetRayDelta The change in premium offset, expressed in asset units and scaled by RAY.
  /// @dev restoredPremiumRay The restored premium, expressed in asset units and scaled by RAY.
  struct PremiumDelta {
    int256 sharesDelta;
    int256 offsetRayDelta;
    uint256 restoredPremiumRay;
  }

  /// @notice Emitted on the `add` action.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param shares The amount of shares added.
  /// @param amount The amount of assets added.
  event Add(uint256 indexed assetId, address indexed spoke, uint256 shares, uint256 amount);

  /// @notice Emitted on the `remove` action.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param shares The amount of shares removed.
  /// @param amount The amount of assets removed.
  event Remove(uint256 indexed assetId, address indexed spoke, uint256 shares, uint256 amount);

  /// @notice Emitted on the `draw` action.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param drawnShares The amount of drawn shares.
  /// @param drawnAmount The amount of drawn assets.
  event Draw(
    uint256 indexed assetId,
    address indexed spoke,
    uint256 drawnShares,
    uint256 drawnAmount
  );

  /// @notice Emitted on the `restore` action.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param drawnShares The amount of drawn shares.
  /// @param premiumDelta The premium delta data struct.
  /// @param drawnAmount The amount of drawn assets restored.
  /// @param premiumAmount The amount of premium assets restored.
  event Restore(
    uint256 indexed assetId,
    address indexed spoke,
    uint256 drawnShares,
    PremiumDelta premiumDelta,
    uint256 drawnAmount,
    uint256 premiumAmount
  );

  /// @notice Emitted on the `refreshPremium` action.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param premiumDelta The premium delta data struct.
  event RefreshPremium(uint256 indexed assetId, address indexed spoke, PremiumDelta premiumDelta);

  /// @notice Emitted on the `reportDeficit` action.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param drawnShares The amount of drawn shares reported as deficit.
  /// @param premiumDelta The premium delta data struct.
  /// @param deficitAmountRay The amount of deficit reported, expressed in asset units and scaled by RAY.
  event ReportDeficit(
    uint256 indexed assetId,
    address indexed spoke,
    uint256 drawnShares,
    PremiumDelta premiumDelta,
    uint256 deficitAmountRay
  );

  /// @notice Emitted on the `transferShares` action.
  /// @param assetId The identifier of the asset.
  /// @param sender The address of the sender.
  /// @param receiver The address of the receiver.
  /// @param shares The amount of shares transferred.
  event TransferShares(
    uint256 indexed assetId,
    address indexed sender,
    address indexed receiver,
    uint256 shares
  );

  /// @notice Adds assets on behalf of a user.
  /// @dev Only callable by active spokes.
  /// @dev Underlying assets must be transferred to the Hub before invocation.
  /// @dev Extra untracked underlying liquidity in the Hub can be skimmed into the Hub's liquidity accounting through this action.
  /// @param assetId The identifier of the asset.
  /// @param amount The amount of asset liquidity to add.
  /// @return The amount of shares added.
  function add(uint256 assetId, uint256 amount) external returns (uint256);

  /// @notice Removes assets on behalf of a user.
  /// @dev Only callable by active spokes.
  /// @param assetId The identifier of the asset.
  /// @param amount The amount of asset liquidity to remove.
  /// @param to The address to transfer the assets to.
  /// @return The amount of shares removed.
  function remove(uint256 assetId, uint256 amount, address to) external returns (uint256);

  /// @notice Draws assets on behalf of a user.
  /// @dev Only callable by active spokes.
  /// @param assetId The identifier of the asset.
  /// @param amount The amount of assets to draw.
  /// @param to The address to transfer the underlying assets to.
  /// @return The amount of drawn shares.
  function draw(uint256 assetId, uint256 amount, address to) external returns (uint256);

  /// @notice Restores assets on behalf of a user.
  /// @dev Only callable by active spokes.
  /// @dev Interest is always paid off first from premium, then from drawn.
  /// @dev Underlying assets must be transferred to the Hub before invocation.
  /// @dev Extra untracked underlying liquidity in the Hub can be skimmed into the Hub's liquidity accounting through this action.
  /// @param assetId The identifier of the asset.
  /// @param drawnAmount The drawn amount to restore.
  /// @param premiumDelta The premium delta to apply which signals premium repayment.
  /// @return The amount of drawn shares restored.
  function restore(
    uint256 assetId,
    uint256 drawnAmount,
    PremiumDelta calldata premiumDelta
  ) external returns (uint256);

  /// @notice Reports an owed amount by the caller Spoke as a deficit.
  /// @dev Only callable by active spokes.
  /// @param assetId The identifier of the asset.
  /// @param drawnAmount The drawn amount to report as deficit.
  /// @param premiumDelta The premium delta to apply which signals premium deficit.
  /// @return The amount of drawn shares reported as deficit.
  /// @return The amount of deficit reported, expressed in asset units.
  function reportDeficit(
    uint256 assetId,
    uint256 drawnAmount,
    PremiumDelta calldata premiumDelta
  ) external returns (uint256, uint256);

  /// @notice Refreshes premium accounting.
  /// @dev Only callable by active spokes.
  /// @dev Asset and spoke premium should not decrease.
  /// @param assetId The identifier of the asset.
  /// @param premiumDelta The change in premium.
  function refreshPremium(uint256 assetId, PremiumDelta calldata premiumDelta) external;

  /// @notice Transfers an amount of added shares of the caller Spoke to the fee receiver Spoke.
  /// @dev It can be used to execute one-time payments to the fee receiver Spoke (e.g., liquidation fees).
  /// @dev Only callable by active spokes.
  /// @param assetId The identifier of the asset.
  /// @param shares The amount of shares to pay to feeReceiver.
  function payFeeShares(uint256 assetId, uint256 shares) external;

  /// @notice Converts the specified amount of assets to shares upon an `add` action.
  /// @dev Rounds down to the nearest shares amount.
  /// @dev Defaults to a 1:1 exchange rate.
  /// @param assetId The identifier of the asset.
  /// @param assets The amount of assets to convert to shares amount.
  /// @return The amount of shares converted from assets amount.
  function previewAddByAssets(uint256 assetId, uint256 assets) external view returns (uint256);

  /// @notice Converts the specified shares amount to assets amount added upon an `add` action.
  /// @dev Rounds up to the nearest assets amount.
  /// @dev Defaults to a 1:1 exchange rate.
  /// @param assetId The identifier of the asset.
  /// @param shares The amount of shares to convert to assets amount.
  /// @return The amount of assets converted from shares amount.
  function previewAddByShares(uint256 assetId, uint256 shares) external view returns (uint256);

  /// @notice Converts the specified amount of assets to shares amount removed upon a `remove` action.
  /// @dev Rounds up to the nearest shares amount.
  /// @dev Defaults to a 1:1 exchange rate.
  /// @param assetId The identifier of the asset.
  /// @param assets The amount of assets to convert to shares amount.
  /// @return The amount of shares converted from assets amount.
  function previewRemoveByAssets(uint256 assetId, uint256 assets) external view returns (uint256);

  /// @notice Converts the specified amount of shares to assets amount removed upon a `remove` action.
  /// @dev Rounds down to the nearest assets amount.
  /// @dev Defaults to a 1:1 exchange rate.
  /// @param assetId The identifier of the asset.
  /// @param shares The amount of shares to convert to assets amount.
  /// @return The amount of assets converted from shares amount.
  function previewRemoveByShares(uint256 assetId, uint256 shares) external view returns (uint256);

  /// @notice Converts the specified amount of assets to shares amount drawn upon a `draw` action.
  /// @dev Rounds up to the nearest shares amount.
  /// @param assetId The identifier of the asset.
  /// @param assets The amount of assets to convert to shares amount.
  /// @return The amount of shares converted from assets amount.
  function previewDrawByAssets(uint256 assetId, uint256 assets) external view returns (uint256);

  /// @notice Converts the specified amount of shares to assets amount drawn upon a `draw` action.
  /// @dev Rounds down to the nearest assets amount.
  /// @param assetId The identifier of the asset.
  /// @param shares The amount of shares to convert to assets amount.
  /// @return The amount of assets converted from shares amount.
  function previewDrawByShares(uint256 assetId, uint256 shares) external view returns (uint256);

  /// @notice Converts the specified amount of assets to shares amount restored upon a `restore` action.
  /// @dev Rounds down to the nearest shares amount.
  /// @param assetId The identifier of the asset.
  /// @param assets The amount of assets to convert to shares amount.
  /// @return The amount of shares converted from assets amount.
  function previewRestoreByAssets(uint256 assetId, uint256 assets) external view returns (uint256);

  /// @notice Converts the specified amount of shares to assets amount restored upon a `restore` action.
  /// @dev Rounds up to the nearest assets amount.
  /// @param assetId The identifier of the asset.
  /// @param shares The amount of drawn shares to convert to assets amount.
  /// @return The amount of assets converted from shares amount.
  function previewRestoreByShares(uint256 assetId, uint256 shares) external view returns (uint256);

  /// @notice Returns the asset identifier for the specified underlying asset.
  /// @dev Reverts with `AssetNotListed` if the underlying is not listed.
  /// @param underlying The address of the underlying asset.
  function getAssetId(address underlying) external view returns (uint256);

  /// @notice Returns the underlying address and decimals of the specified asset.
  /// @param assetId The identifier of the asset.
  /// @return The underlying address of the asset.
  /// @return The decimals of the asset.
  function getAssetUnderlyingAndDecimals(uint256 assetId) external view returns (address, uint8);

  /// @notice Calculates the current drawn index for the specified asset.
  /// @param assetId The identifier of the asset.
  /// @return The current drawn index of the asset.
  function getAssetDrawnIndex(uint256 assetId) external view returns (uint256);

  /// @notice Returns the total amount of the specified asset added to the Hub.
  /// @param assetId The identifier of the asset.
  /// @return The amount of the asset added.
  function getAddedAssets(uint256 assetId) external view returns (uint256);

  /// @notice Returns the total amount of shares of the specified asset added to the Hub.
  /// @param assetId The identifier of the asset.
  /// @return The amount of shares of the asset added.
  function getAddedShares(uint256 assetId) external view returns (uint256);

  /// @notice Returns the amount of owed drawn and premium assets for the specified asset.
  /// @param assetId The identifier of the asset.
  /// @return The amount of owed drawn assets.
  /// @return The amount of owed premium assets.
  function getAssetOwed(uint256 assetId) external view returns (uint256, uint256);

  /// @notice Returns the total amount of assets owed to the Hub.
  /// @param assetId The identifier of the asset.
  /// @return The total amount of the assets owed.
  function getAssetTotalOwed(uint256 assetId) external view returns (uint256);

  /// @notice Returns the amount of owed premium with full precision for specified asset.
  /// @param assetId The identifier of the asset.
  /// @return The amount of premium owed, expressed in asset units and scaled by RAY.
  function getAssetPremiumRay(uint256 assetId) external view returns (uint256);

  /// @notice Returns the amount of drawn shares of the specified asset.
  /// @param assetId The identifier of the asset.
  /// @return The amount of drawn shares.
  function getAssetDrawnShares(uint256 assetId) external view returns (uint256);

  /// @notice Returns the information regarding premium shares of the specified asset.
  /// @param assetId The identifier of the asset.
  /// @return The amount of premium shares owed to the asset.
  /// @return The premium offset of the asset, expressed in asset units and scaled by RAY.
  function getAssetPremiumData(uint256 assetId) external view returns (uint256, int256);

  /// @notice Returns the amount of available liquidity for the specified asset.
  /// @param assetId The identifier of the asset.
  /// @return The amount of available liquidity.
  function getAssetLiquidity(uint256 assetId) external view returns (uint256);

  /// @notice Returns the amount of deficit with full precision of the specified asset.
  /// @param assetId The identifier of the asset.
  /// @return The amount of deficit, expressed in asset units and scaled by RAY.
  function getAssetDeficitRay(uint256 assetId) external view returns (uint256);

  /// @notice Returns the total amount of the specified assets added to the Hub by the specified spoke.
  /// @dev If spoke is `asset.feeReceiver`, includes converted `unrealizedFeeShares` in return value.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @return The amount of added assets.
  function getSpokeAddedAssets(uint256 assetId, address spoke) external view returns (uint256);

  /// @notice Returns the total amount of shares of the specified asset added to the Hub by the specified spoke.
  /// @dev If spoke is `asset.feeReceiver`, includes `unrealizedFeeShares` in return value.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @return The amount of added shares.
  function getSpokeAddedShares(uint256 assetId, address spoke) external view returns (uint256);

  /// @notice Returns the amount of the specified assets owed to the Hub by the specified spoke.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @return The amount of owed drawn assets.
  /// @return The amount of owed premium assets.
  function getSpokeOwed(uint256 assetId, address spoke) external view returns (uint256, uint256);

  /// @notice Returns the total amount of the specified asset owed to the Hub by the specified spoke.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @return The total amount of the asset owed.
  function getSpokeTotalOwed(uint256 assetId, address spoke) external view returns (uint256);

  /// @notice Returns the amount of owed premium with full precision for specified asset and spoke.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @return The amount of owed premium assets, expressed in asset units and scaled by RAY.
  function getSpokePremiumRay(uint256 assetId, address spoke) external view returns (uint256);

  /// @notice Returns the amount of drawn shares of the specified asset by the specified spoke.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @return The amount of drawn shares.
  function getSpokeDrawnShares(uint256 assetId, address spoke) external view returns (uint256);

  /// @notice Returns the information regarding premium shares of the specified asset for the specified spoke.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @return The amount of premium shares.
  /// @return The premium offset, expressed in asset units and scaled by RAY.
  function getSpokePremiumData(
    uint256 assetId,
    address spoke
  ) external view returns (uint256, int256);

  /// @notice Returns the amount of a given spoke's deficit with full precision for the specified asset.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @return The amount of deficit, expressed in asset units and scaled by RAY.
  function getSpokeDeficitRay(uint256 assetId, address spoke) external view returns (uint256);
}

src/hub/interfaces/IHubConfigurator.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

import {IHub} from 'src/hub/interfaces/IHub.sol';

/// @title IHubConfigurator
/// @author Aave Labs
/// @notice Interface for HubConfigurator.
interface IHubConfigurator {
  /// @notice Thrown when an address parameter is the zero address.
  error InvalidAddress();

  /// @notice Thrown when the list of assets and spoke configs are not the same length in `addSpokeToAssets`.
  error MismatchedConfigs();

  /// @notice Adds a new asset to a specified Hub.
  /// @dev Retrieves the decimals of the underlying asset from its ERC20 contract.
  /// @dev The fee receiver is automatically added as a Spoke with maximum caps.
  /// @param hub The address of the Hub.
  /// @param underlying The address of the underlying asset.
  /// @param feeReceiver The address of the fee receiver Spoke.
  /// @param liquidityFee The liquidity fee of the asset, expressed in BPS.
  /// @param irStrategy The address of the interest rate strategy contract.
  /// @param irData The interest rate data to apply to the given asset, encoded in bytes.
  /// @return The unique identifier of the added asset.
  function addAsset(
    address hub,
    address underlying,
    address feeReceiver,
    uint256 liquidityFee,
    address irStrategy,
    bytes calldata irData
  ) external returns (uint256);

  /// @notice Adds a new asset to a specified Hub with explicit decimals.
  /// @dev The fee receiver is automatically added as a Spoke with maximum caps.
  /// @param hub The address of the Hub.
  /// @param underlying The address of the underlying asset.
  /// @param decimals The number of decimals of the asset.
  /// @param feeReceiver The address of the fee receiver Spoke.
  /// @param liquidityFee The liquidity fee of the asset, expressed in BPS.
  /// @param irStrategy The address of the interest rate strategy contract.
  /// @param irData The interest rate data to apply to the given asset, encoded in bytes.
  /// @return The unique identifier of the added asset.
  function addAssetWithDecimals(
    address hub,
    address underlying,
    uint8 decimals,
    address feeReceiver,
    uint256 liquidityFee,
    address irStrategy,
    bytes calldata irData
  ) external returns (uint256);

  /// @notice Updates the liquidity fee of an asset on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  /// @param liquidityFee The new liquidity fee.
  function updateLiquidityFee(address hub, uint256 assetId, uint256 liquidityFee) external;

  /// @notice Updates the fee receiver of an asset on a specified hub.
  /// @dev The fee receiver cannot be zero.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  /// @param feeReceiver The new fee receiver.
  function updateFeeReceiver(address hub, uint256 assetId, address feeReceiver) external;

  /// @notice Updates the liquidity fee and fee receiver of an asset on a specified Hub.
  /// @dev The fee receiver cannot be zero.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  /// @param liquidityFee The new liquidity fee.
  /// @param feeReceiver The new fee receiver.
  function updateFeeConfig(
    address hub,
    uint256 assetId,
    uint256 liquidityFee,
    address feeReceiver
  ) external;

  /// @notice Updates the interest rate strategy of an asset on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  /// @param irStrategy The new interest rate strategy.
  /// @param irData The interest rate data to apply to the given asset, encoded in bytes.
  function updateInterestRateStrategy(
    address hub,
    uint256 assetId,
    address irStrategy,
    bytes calldata irData
  ) external;

  /// @notice Updates the reinvestment controller of an asset on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  /// @param reinvestmentController The new reinvestment controller.
  function updateReinvestmentController(
    address hub,
    uint256 assetId,
    address reinvestmentController
  ) external;

  /// @notice Resets all Spokes' add and draw caps to zero for an asset on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  function resetAssetCaps(address hub, uint256 assetId) external;

  /// @notice Deactivates an asset on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  function deactivateAsset(address hub, uint256 assetId) external;

  /// @notice Halts an asset on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  function haltAsset(address hub, uint256 assetId) external;

  /// @notice Registers the Spoke for the specified asset on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param spoke The address of the Spoke.
  /// @param assetId The identifier of the asset to register the Spoke for.
  /// @param config The Spoke configuration to register.
  function addSpoke(
    address hub,
    address spoke,
    uint256 assetId,
    IHub.SpokeConfig calldata config
  ) external;

  /// @notice Registers the same Spoke for multiple assets on a specified Hub, each with their own configuration.
  /// @dev The i-th asset identifier in `assetIds` corresponds to the i-th configuration in `configs`.
  /// @param hub The address of the Hub.
  /// @param spoke The address of the Spoke.
  /// @param assetIds The list of asset identifiers to register the Spoke for.
  /// @param configs The list of Spoke configurations to register.
  function addSpokeToAssets(
    address hub,
    address spoke,
    uint256[] calldata assetIds,
    IHub.SpokeConfig[] calldata configs
  ) external;

  /// @notice Updates the active flag of an asset's Spoke on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param active The new active flag.
  function updateSpokeActive(address hub, uint256 assetId, address spoke, bool active) external;

  /// @notice Updates the halted flag of an asset's Spoke on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param halted The new halted flag.
  function updateSpokeHalted(address hub, uint256 assetId, address spoke, bool halted) external;

  /// @notice Updates the add cap of an asset's spoke on a specified hub.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param addCap The new add cap.
  function updateSpokeAddCap(address hub, uint256 assetId, address spoke, uint256 addCap) external;

  /// @notice Updates the draw cap of an asset's Spoke on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param drawCap The new draw cap.
  function updateSpokeDrawCap(
    address hub,
    uint256 assetId,
    address spoke,
    uint256 drawCap
  ) external;

  /// @notice Updates the risk premium threshold of an asset's Spoke on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param riskPremiumThreshold The new risk premium threshold.
  function updateSpokeRiskPremiumThreshold(
    address hub,
    uint256 assetId,
    address spoke,
    uint256 riskPremiumThreshold
  ) external;

  /// @notice Updates the caps of an asset's Spoke on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  /// @param spoke The address of the Spoke.
  /// @param addCap The new add cap.
  /// @param drawCap The new draw cap.
  function updateSpokeCaps(
    address hub,
    uint256 assetId,
    address spoke,
    uint256 addCap,
    uint256 drawCap
  ) external;

  /// @notice Deactivates all assets of a Spoke on a specified Hub by setting the active flag to false.
  /// @param hub The address of the Hub.
  /// @param spoke The address of the Spoke.
  function deactivateSpoke(address hub, address spoke) external;

  /// @notice Halts all assets of a Spoke on a specified Hub by setting the halted flag to true.
  /// @param hub The address of the Hub.
  /// @param spoke The address of the Spoke.
  function haltSpoke(address hub, address spoke) external;

  /// @notice Resets draw cap and add cap to zero for a Spoke on a specified Hub.
  /// @param hub The address of the Hub.
  /// @param spoke The address of the Spoke.
  function resetSpokeCaps(address hub, address spoke) external;

  /// @notice Updates the interest rate data for an asset.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset.
  /// @param irData The interest rate data to apply to the given asset, encoded in bytes.
  function updateInterestRateData(address hub, uint256 assetId, bytes calldata irData) external;
}

src/interfaces/IExtSload.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

/// @title IExtSload
/// @author Aave Labs
/// @notice Minimal interface to easily access storage of source contract externally. See https://eips.ethereum.org/EIPS/eip-2330#rationale.
interface IExtSload {
  /// @notice Returns the storage `value` of this contract at a given `slot`.
  /// @param slot Slot to SLOAD from.
  function extSload(bytes32 slot) external view returns (bytes32 value);

  /// @notice Returns the storage `values` of this contract at the given `slots`.
  /// @param slots Array of slots to SLOAD from.
  function extSloads(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

src/interfaces/IIntentConsumer.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

import {INoncesKeyed} from 'src/interfaces/INoncesKeyed.sol';

/// @title IIntentConsumer
/// @author Aave Labs
/// @notice Minimal interface for IntentConsumer.
interface IIntentConsumer is INoncesKeyed {
  /// @notice Thrown when given signature is invalid.
  error InvalidSignature();

  /// @notice Returns the EIP-712 domain separator.
  function DOMAIN_SEPARATOR() external view returns (bytes32);
}

src/interfaces/IMulticall.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

/// @title IMulticall
/// @author Aave Labs
/// @notice Minimal interface for Multicall.
interface IMulticall {
  /// @notice Call multiple functions in the current contract and return the data from each if they all succeed.
  /// @param data The encoded function data for each of the calls to make to this contract.
  /// @return results The results from each of the calls passed in via data.
  function multicall(bytes[] calldata data) external returns (bytes[] memory);
}

src/interfaces/INoncesKeyed.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

interface INoncesKeyed {
  /// @notice Thrown when nonce being consumed does not match `currentNonce` for `account`.
  error InvalidAccountNonce(address account, uint256 currentNonce);

  /// @notice Allows caller to revoke their next sequential nonce at specified `key`.
  /// @dev This does not invalidate nonce at other `key`s namespace.
  /// @param key The key which specifies namespace of the nonce.
  /// @return keyNonce The revoked key-prefixed nonce.
  function useNonce(uint192 key) external returns (uint256 keyNonce);

  /// @notice Returns the next unused nonce for an address and key. Result contains the key prefix.
  /// @param owner The address of the nonce owner.
  /// @param key The key which specifies namespace of the nonce.
  /// @return keyNonce The first 24 bytes are for the key, & the last 8 bytes for the nonce.
  function nonces(address owner, uint192 key) external view returns (uint256 keyNonce);
}

src/interfaces/IRescuable.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

/// @title IRescuable
/// @author Aave Labs
/// @notice Interface for Rescuable.
interface IRescuable {
  /// @notice Thrown when caller is not the rescue guardian.
  error OnlyRescueGuardian();

  /// @notice Recovers ERC20 tokens sent to this contract.
  /// @param token The address of the ERC20 token to rescue.
  /// @param to The address to send the rescued tokens to.
  /// @param amount Amount of tokens to rescue.
  function rescueToken(address token, address to, uint256 amount) external;

  /// @notice Recovers native assets remaining in this contract.
  /// @param to The address to send rescued native assets to.
  /// @param amount Amount of native assets to rescue.
  function rescueNative(address to, uint256 amount) external;

  /// @notice Returns the rescue guardian address.
  /// @return The address allowed to rescue funds.
  function rescueGuardian() external view returns (address);
}

src/position-manager/interfaces/IPositionManagerBase.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

import {IMulticall} from 'src/interfaces/IMulticall.sol';
import {IRescuable} from 'src/interfaces/IRescuable.sol';

/// @title IPositionManagerBase
/// @author Aave Labs
/// @notice Base interface for position managers.
/// @dev This base interface is not mandatory for position managers, it only provides optional convenience methods.
interface IPositionManagerBase is IRescuable, IMulticall {
  /// @notice Emitted when the Spoke's registration status is updated.
  event RegisterSpoke(address indexed spoke, bool registered);

  /// @notice Thrown when the specified address is invalid.
  error InvalidAddress();

  /// @notice Thrown when the specified amount is invalid.
  error InvalidAmount();

  /// @notice Thrown when trying to call an unsupported action on this position manager.
  error UnsupportedAction();

  /// @notice Thrown when the specified Spoke is not registered.
  error SpokeNotRegistered();

  /// @notice Facilitates setting this position manager as user position manager on the specified registered Spoke
  /// with a typed signature from `onBehalfOf`.
  /// @dev The signature is consumed on the specified registered Spoke.
  /// @dev The given data is passed to the Spoke for the signature to be verified.
  /// @dev Uses keyed-nonces where for each key's namespace nonce is consumed sequentially.
  /// @param spoke The address of the registered spoke.
  /// @param onBehalfOf The address of the user on whose behalf this position manager can act.
  /// @param approve True to approve the position manager, false to revoke approval.
  /// @param nonce The key-prefixed nonce for the signature.
  /// @param deadline The deadline for the intent.
  /// @param signature The EIP712-typed signed bytes for the intent.
  function setSelfAsUserPositionManagerWithSig(
    address spoke,
    address onBehalfOf,
    bool approve,
    uint256 nonce,
    uint256 deadline,
    bytes calldata signature
  ) external;

  /// @notice Facilitates consuming a permit for the given reserve's underlying asset on the specified registered Spoke.
  /// @dev The given data is passed to the underlying asset for the signature to be verified.
  /// @dev Uses keyed-nonces where for each key's namespace nonce is consumed sequentially.
  /// @dev Spender is this position manager contract.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param onBehalfOf The address of the user on whose behalf the permit is being used.
  /// @param value The amount of the underlying asset to permit.
  /// @param deadline The deadline for the permit.
  function permitReserveUnderlying(
    address spoke,
    uint256 reserveId,
    address onBehalfOf,
    uint256 value,
    uint256 deadline,
    uint8 permitV,
    bytes32 permitR,
    bytes32 permitS
  ) external;

  /// @notice Allows contract to renounce its position manager role for the specified user.
  /// @param spoke The address of the registered Spoke.
  /// @param user The address of the user to renounce the position manager role for.
  function renouncePositionManagerRole(address spoke, address user) external;

  /// @notice Registers or deregisters the Spoke.
  /// @param spoke The address of the Spoke.
  /// @param registered `true` to register, `false` to deregister.
  function registerSpoke(address spoke, bool registered) external;

  /// @notice Returns whether the specified Spoke is registered.
  /// @param spoke The address of the Spoke.
  /// @return `true` if the Spoke is registered, `false` otherwise.
  function isSpokeRegistered(address spoke) external view returns (bool);
}

src/spoke/interfaces/ISpoke.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

import {IAccessManaged} from 'src/dependencies/openzeppelin/IAccessManaged.sol';
import {IIntentConsumer} from 'src/interfaces/IIntentConsumer.sol';
import {IMulticall} from 'src/interfaces/IMulticall.sol';
import {IHubBase} from 'src/hub/interfaces/IHubBase.sol';
import {IExtSload} from 'src/interfaces/IExtSload.sol';

type ReserveFlags is uint8;

/// @title ISpoke
/// @author Aave Labs
/// @notice Full interface for Spoke.
interface ISpoke is IAccessManaged, IIntentConsumer, IExtSload, IMulticall {
  /// @notice Intent data to set user position managers with EIP712-typed signature.
  /// @param onBehalfOf The address of the user on whose behalf position manager can act.
  /// @param updates The array of position manager updates.
  /// @param nonce The nonce for the signature.
  /// @param deadline The deadline for the signature.
  struct SetUserPositionManagers {
    address onBehalfOf;
    PositionManagerUpdate[] updates;
    uint256 nonce;
    uint256 deadline;
  }

  /// @notice Sub-Intent data to apply position manager update for user.
  /// @param positionManager The address of the position manager.
  /// @param approve True to approve the position manager, false to revoke approval.
  struct PositionManagerUpdate {
    address positionManager;
    bool approve;
  }

  /// @notice Reserve level data.
  /// @dev underlying The address of the underlying asset.
  /// @dev hub The address of the associated Hub.
  /// @dev assetId The identifier of the asset in the Hub.
  /// @dev decimals The number of decimals of the underlying asset.
  /// @dev collateralRisk The risk associated with a collateral asset, expressed in BPS.
  /// @dev flags The packed boolean flags of the reserve (a wrapped uint8).
  /// @dev dynamicConfigKey The key of the last reserve dynamic config.
  struct Reserve {
    address underlying;
    //
    IHubBase hub;
    uint16 assetId;
    uint8 decimals;
    uint24 collateralRisk;
    ReserveFlags flags;
    uint32 dynamicConfigKey;
  }

  /// @notice Reserve configuration. Subset of the `Reserve` struct.
  /// @dev collateralRisk The risk associated with a collateral asset, expressed in BPS.
  /// @dev paused True if all actions are prevented for the reserve.
  /// @dev frozen True if new activity is prevented for the reserve.
  /// @dev borrowable True if the reserve is borrowable.
  /// @dev receiveSharesEnabled True if the liquidator can receive collateral shares during liquidation.
  struct ReserveConfig {
    uint24 collateralRisk;
    bool paused;
    bool frozen;
    bool borrowable;
    bool receiveSharesEnabled;
  }

  /// @notice Dynamic reserve configuration data.
  /// @dev collateralFactor The proportion of a reserve's value eligible to be used as collateral, expressed in BPS.
  /// @dev maxLiquidationBonus The maximum extra amount of collateral given to the liquidator as bonus, expressed in BPS. 100_00 represents 0.00% bonus.
  /// @dev liquidationFee The protocol fee charged on liquidations, taken from the collateral bonus given to the liquidator, expressed in BPS.
  struct DynamicReserveConfig {
    uint16 collateralFactor;
    uint32 maxLiquidationBonus;
    uint16 liquidationFee;
  }

  /// @notice Liquidation configuration data.
  /// @dev targetHealthFactor The ideal health factor to restore a user position during liquidation, expressed in WAD.
  /// @dev healthFactorForMaxBonus The health factor under which liquidation bonus is maximum, expressed in WAD.
  /// @dev liquidationBonusFactor The value multiplied by `maxLiquidationBonus` to compute the minimum liquidation bonus, expressed in BPS.
  struct LiquidationConfig {
    uint128 targetHealthFactor;
    uint64 healthFactorForMaxBonus;
    uint16 liquidationBonusFactor;
  }

  /// @notice User position data per reserve.
  /// @dev drawnShares The drawn shares of the user position.
  /// @dev premiumShares The premium shares of the user position.
  /// @dev premiumOffsetRay The premium offset of the user position, used to calculate the premium, expressed in asset units and scaled by RAY.
  /// @dev suppliedShares The supplied shares of the user position.
  /// @dev dynamicConfigKey The key of the user position dynamic config.
  struct UserPosition {
    uint120 drawnShares;
    uint120 premiumShares;
    //
    int200 premiumOffsetRay;
    //
    uint120 suppliedShares;
    uint32 dynamicConfigKey;
  }

  /// @notice Position manager configuration data.
  /// @dev approval The mapping of position manager user approvals.
  /// @dev active True if the position manager is active.
  struct PositionManagerConfig {
    mapping(address user => bool) approval;
    bool active;
  }

  /// @notice User position status data.
  /// @dev map The map of bitmap buckets for the position status.
  /// @dev riskPremium The risk premium of the user position, expressed in BPS.
  struct PositionStatus {
    mapping(uint256 bucket => uint256) map;
    uint24 riskPremium;
  }

  /// @notice User account data describing a user position and its health.
  /// @dev riskPremium The risk premium of the user position, expressed in BPS.
  /// @dev avgCollateralFactor The weighted average collateral factor of the user position, expressed in WAD.
  /// @dev healthFactor The health factor of the user position, expressed in WAD. 1e18 represents a health factor of 1.00.
  /// @dev totalCollateralValue The total collateral value of the user position, expressed in units of Value.
  /// @dev totalDebtValueRay The total debt value of the user position, expressed in units of Value and scaled by RAY.
  /// @dev activeCollateralCount The number of active collaterals, which includes reserves with `collateralFactor` > 0, `enabledAsCollateral` and `suppliedAmount` > 0.
  /// @dev borrowCount The number of borrowed reserves of the user position.
  struct UserAccountData {
    uint256 riskPremium;
    uint256 avgCollateralFactor;
    uint256 healthFactor;
    uint256 totalCollateralValue;
    uint256 totalDebtValueRay;
    uint256 activeCollateralCount;
    uint256 borrowCount;
  }

  /// @notice Emitted when the immutable variables of the Spoke are set.
  /// @param oracle The address of the oracle.
  /// @param maxUserReservesLimit The max user reserves limit.
  event SetSpokeImmutables(address indexed oracle, uint16 maxUserReservesLimit);

  /// @notice Emitted when a liquidation config is updated.
  /// @param config The new liquidation config.
  event UpdateLiquidationConfig(LiquidationConfig config);

  /// @notice Emitted when a reserve is added.
  /// @param reserveId The identifier of the reserve.
  /// @param assetId The identifier of the asset.
  /// @param hub The address of the Hub where the asset is listed.
  event AddReserve(uint256 indexed reserveId, uint256 indexed assetId, address indexed hub);

  /// @notice Emitted when a reserve configuration is updated.
  /// @param reserveId The identifier of the reserve.
  /// @param config The reserve configuration.
  event UpdateReserveConfig(uint256 indexed reserveId, ReserveConfig config);

  /// @notice Emitted when the price source of a reserve is updated.
  /// @param reserveId The identifier of the reserve.
  /// @param priceSource The address of the new price source.
  event UpdateReservePriceSource(uint256 indexed reserveId, address indexed priceSource);

  /// @notice Emitted when a dynamic reserve config is added.
  /// @dev The config key is the next available key for the reserve, which is now the latest config
  /// key of the reserve.
  /// @param reserveId The identifier of the reserve.
  /// @param dynamicConfigKey The key of the added dynamic config.
  /// @param config The dynamic reserve config.
  event AddDynamicReserveConfig(
    uint256 indexed reserveId,
    uint32 indexed dynamicConfigKey,
    DynamicReserveConfig config
  );

  /// @notice Emitted when a dynamic reserve config is updated.
  /// @param reserveId The identifier of the reserve.
  /// @param dynamicConfigKey The key of the updated dynamic config.
  /// @param config The dynamic reserve config.
  event UpdateDynamicReserveConfig(
    uint256 indexed reserveId,
    uint32 indexed dynamicConfigKey,
    DynamicReserveConfig config
  );

  /// @notice Emitted on updatePositionManager action.
  /// @param positionManager The address of the position manager.
  /// @param active True if position manager has become active.
  event UpdatePositionManager(address indexed positionManager, bool active);

  /// @notice Emitted on the supply action.
  /// @param reserveId The reserve identifier of the underlying asset.
  /// @param caller The transaction initiator, and supplier of the underlying asset.
  /// @param user The owner of the modified position.
  /// @param suppliedShares The amount of supply shares minted.
  /// @param suppliedAmount The amount of underlying asset supplied.
  event Supply(
    uint256 indexed reserveId,
    address indexed caller,
    address indexed user,
    uint256 suppliedShares,
    uint256 suppliedAmount
  );

  /// @notice Emitted on the withdraw action.
  /// @param reserveId The reserve identifier of the underlying asset.
  /// @param caller The transaction initiator, and recipient of the underlying asset being withdrawn.
  /// @param user The owner of the modified position.
  /// @param withdrawnShares The amount of supply shares burned.
  /// @param withdrawnAmount The amount of underlying asset withdrawn.
  event Withdraw(
    uint256 indexed reserveId,
    address indexed caller,
    address indexed user,
    uint256 withdrawnShares,
    uint256 withdrawnAmount
  );

  /// @notice Emitted on the borrow action.
  /// @param reserveId The reserve identifier of the underlying asset.
  /// @param caller The transaction initiator, and recipient of the underlying asset being borrowed.
  /// @param user The owner of the position on which debt is generated.
  /// @param drawnShares The amount of debt shares minted.
  /// @param drawnAmount The amount of underlying asset borrowed.
  event Borrow(
    uint256 indexed reserveId,
    address indexed caller,
    address indexed user,
    uint256 drawnShares,
    uint256 drawnAmount
  );

  /// @notice Emitted on the repay action.
  /// @param reserveId The reserve identifier of the underlying asset.
  /// @param caller The transaction initiator who is repaying the underlying asset.
  /// @param user The owner of the position whose debt is being repaid.
  /// @param drawnShares The amount of drawn shares burned.
  /// @param totalAmountRepaid The amount of drawn and premium underlying assets repaid.
  /// @param premiumDelta A struct representing the changes to premium debt after repayment.
  event Repay(
    uint256 indexed reserveId,
    address indexed caller,
    address indexed user,
    uint256 drawnShares,
    uint256 totalAmountRepaid,
    IHubBase.PremiumDelta premiumDelta
  );

  /// @dev Emitted when a borrower is liquidated.
  /// @param collateralReserveId The identifier of the reserve used as collateral, to receive as a result of the liquidation.
  /// @param debtReserveId The identifier of the reserve to be repaid with the liquidation.
  /// @param user The address of the borrower getting liquidated.
  /// @param liquidator The address of the liquidator.
  /// @param receiveShares True if the liquidator received collateral in supplied shares rather than underlying assets.
  /// @param debtAmountRestored The amount of debt restored, expressed in asset units.
  /// @param drawnSharesLiquidated The amount of drawn shares liquidated.
  /// @param premiumDelta A struct representing the changes to premium debt after liquidation.
  /// @param collateralAmountRemoved The amount of collateral removed, expressed in asset units.
  /// @param collateralSharesLiquidated The total amount of collateral shares liquidated.
  /// @param collateralSharesToLiquidator The amount of collateral shares that the liquidator received.
  event LiquidationCall(
    uint256 indexed collateralReserveId,
    uint256 indexed debtReserveId,
    address indexed user,
    address liquidator,
    bool receiveShares,
    uint256 debtAmountRestored,
    uint256 drawnSharesLiquidated,
    IHubBase.PremiumDelta premiumDelta,
    uint256 collateralAmountRemoved,
    uint256 collateralSharesLiquidated,
    uint256 collateralSharesToLiquidator
  );

  /// @notice Emitted when a reserve deficit is reported to the Hub.
  /// @param reserveId The identifier of the reserve.
  /// @param user The address of the user.
  /// @param drawnShares The amount of drawn shares reported as deficit.
  /// @param premiumDelta The premium delta data struct reported as deficit.
  event ReportDeficit(
    uint256 indexed reserveId,
    address indexed user,
    uint256 drawnShares,
    IHubBase.PremiumDelta premiumDelta
  );

  /// @notice Emitted on setUsingAsCollateral action.
  /// @param reserveId The reserve identifier of the underlying asset.
  /// @param caller The transaction initiator.
  /// @param user The owner of the position being modified.
  /// @param usingAsCollateral Whether the reserve is enabled or disabled as collateral.
  event SetUsingAsCollateral(
    uint256 indexed reserveId,
    address indexed caller,
    address indexed user,
    bool usingAsCollateral
  );

  /// @notice Emitted on updateUserRiskPremium action.
  /// @param user The owner of the position being modified.
  /// @param riskPremium The new risk premium (BPS) value of user.
  event UpdateUserRiskPremium(address indexed user, uint256 riskPremium);

  /// @notice Emitted when a user's dynamic config is refreshed for all reserves to their latest config key.
  /// @param user The address of the user.
  event RefreshAllUserDynamicConfig(address indexed user);

  /// @notice Emitted when a user's dynamic config is refreshed for a single reserve to its latest config key.
  /// @param user The address of the user.
  /// @param reserveId The identifier of the reserve.
  event RefreshSingleUserDynamicConfig(address indexed user, uint256 reserveId);

  /// @notice Emitted on setUserPositionManager or renouncePositionManagerRole action.
  /// @param user The address of the user on whose behalf position manager can act.
  /// @param positionManager The address of the position manager.
  /// @param approve True if position manager approval was granted, false if it was revoked.
  event SetUserPositionManager(address indexed user, address indexed positionManager, bool approve);

  /// @notice Emitted on refreshPremiumDebt action.
  /// @param reserveId The identifier of the reserve.
  /// @param user The address of the user.
  /// @param premiumDelta The change in premium values.
  event RefreshPremiumDebt(
    uint256 indexed reserveId,
    address indexed user,
    IHubBase.PremiumDelta premiumDelta
  );

  /// @notice Thrown when an asset is not listed on the Hub when adding a reserve.
  error AssetNotListed();

  /// @notice Thrown when adding a new reserve if that reserve already exists for a given Hub/assetId pair.
  error ReserveExists();

  /// @notice Thrown when adding a new reserve if an asset id is invalid.
  error InvalidAssetId();

  /// @notice Thrown when adding a new reserve if the asset decimals are invalid.
  error InvalidAssetDecimals();

  /// @notice Thrown when updating a reserve if it is not listed.
  error ReserveNotListed();

  /// @notice Thrown when a reserve is not borrowable during a `borrow` action.
  error ReserveNotBorrowable();

  /// @notice Thrown when a reserve is paused during an attempted action.
  error ReservePaused();

  /// @notice Thrown when a reserve is frozen.
  /// @dev Can only occur during an attempted `supply`, `borrow`, or `setUsingAsCollateral` action.
  error ReserveFrozen();

  /// @notice Thrown when an action causes a user's health factor to fall below the liquidation threshold.
  error HealthFactorBelowThreshold();

  /// @notice Thrown when reserve is not enabled as collateral during liquidation.
  error ReserveNotEnabledAsCollateral();

  /// @notice Thrown when a specified reserve is not supplied by the user during liquidation.
  error ReserveNotSupplied();

  /// @notice Thrown when a specified reserve is not borrowed by the user during liquidation.
  error ReserveNotBorrowed();

  /// @notice Thrown when an unauthorized caller attempts an action.
  error Unauthorized();

  /// @notice Thrown if a config key is uninitialized when updating a dynamic reserve config.
  error DynamicConfigKeyUninitialized();

  /// @notice Thrown for an invalid zero address.
  error InvalidAddress();

  /// @notice Thrown when the oracle decimals are not 8 in the constructor.
  error InvalidOracleDecimals();

  /// @notice Thrown when the maximum user reserves limit is zero in the constructor.
  error InvalidMaxUserReservesLimit();

  /// @notice Thrown when a collateral risk exceeds the maximum allowed.
  error InvalidCollateralRisk();

  /// @notice Thrown if a liquidation config is invalid when it is updated.
  error InvalidLiquidationConfig();

  /// @notice Thrown when a liquidation fee is invalid.
  error InvalidLiquidationFee();

  /// @notice Thrown when a collateral factor and max liquidation bonus are invalid.
  error InvalidCollateralFactorAndMaxLiquidationBonus();

  /// @notice Thrown when trying to set zero collateralFactor on historic dynamic configuration keys.
  error InvalidCollateralFactor();

  /// @notice Thrown when a self-liquidation is attempted.
  error SelfLiquidation();

  /// @notice Thrown during liquidation when a user's health factor is not below the liquidation threshold.
  error HealthFactorNotBelowThreshold();

  /// @notice Thrown when collateral or debt dust remains after a liquidation, and neither reserve is fully liquidated.
  error MustNotLeaveDust();

  /// @notice Thrown when a debt to cover input is zero.
  error InvalidDebtToCover();

  /// @notice Thrown when the liquidator tries to receive shares for a collateral reserve that is frozen or is not enabled to receive shares.
  error CannotReceiveShares();

  /// @notice Thrown when the maximum number of dynamic config keys is reached.
  error MaximumDynamicConfigKeyReached();

  /// @notice Thrown when user attempts to exceed either the maximum allowed collateral or borrowed reserves.
  error MaximumUserReservesExceeded();

  /// @notice Updates the liquidation config.
  /// @param config The new liquidation config.
  function updateLiquidationConfig(LiquidationConfig calldata config) external;

  /// @notice Adds a new reserve to the Spoke.
  /// @dev Allowed even if the Spoke has not yet been added to the Hub.
  /// @dev Allowed even if the `active` flag is `false`.
  /// @dev Allowed even if the Spoke has been added but the `addCap` is zero.
  /// @param hub The address of the Hub where the asset is listed.
  /// @param assetId The identifier of the asset in the Hub.
  /// @param priceSource The address of the price source for the asset.
  /// @param config The initial reserve configuration.
  /// @param dynamicConfig The initial dynamic reserve configuration.
  /// @return The identifier of the newly added reserve.
  function addReserve(
    address hub,
    uint256 assetId,
    address priceSource,
    ReserveConfig calldata config,
    DynamicReserveConfig calldata dynamicConfig
  ) external returns (uint256);

  /// @notice Updates the reserve config for a given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @param reserveId The identifier of the reserve.
  /// @param params The new reserve config.
  function updateReserveConfig(uint256 reserveId, ReserveConfig calldata params) external;

  /// @notice Updates the price source of a reserve.
  /// @param reserveId The identifier of the reserve.
  /// @param priceSource The address of the price source.
  function updateReservePriceSource(uint256 reserveId, address priceSource) external;

  /// @notice Updates the dynamic reserve config for a given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev Appends dynamic config to the next available key; reverts if `MAX_ALLOWED_DYNAMIC_CONFIG_KEY` is reached.
  /// @param reserveId The identifier of the reserve.
  /// @param dynamicConfig The new dynamic reserve config.
  /// @return dynamicConfigKey The key of the added dynamic config.
  function addDynamicReserveConfig(
    uint256 reserveId,
    DynamicReserveConfig calldata dynamicConfig
  ) external returns (uint32 dynamicConfigKey);

  /// @notice Updates the dynamic reserve config for a given reserve at the specified key.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev Reverts with `DynamicConfigKeyUninitialized` if the config key has not been initialized yet.
  /// @dev Reverts with `InvalidCollateralFactor` if the collateral factor is 0.
  /// @param reserveId The identifier of the reserve.
  /// @param dynamicConfigKey The key of the config to update.
  /// @param dynamicConfig The new dynamic reserve config.
  function updateDynamicReserveConfig(
    uint256 reserveId,
    uint32 dynamicConfigKey,
    DynamicReserveConfig calldata dynamicConfig
  ) external;

  /// @notice Allows an approved caller (admin) to toggle the active status of position manager.
  /// @param positionManager The address of the position manager.
  /// @param active True if positionManager is to be set as active.
  function updatePositionManager(address positionManager, bool active) external;

  /// @notice Supplies an amount of underlying asset of the specified reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev The Spoke pulls the underlying asset from the caller, so prior token approval is required.
  /// @dev Caller must be `onBehalfOf` or an authorized position manager for `onBehalfOf`.
  /// @param reserveId The reserve identifier.
  /// @param amount The amount of asset to supply.
  /// @param onBehalfOf The owner of the position to add supply shares to.
  /// @return The amount of shares supplied.
  /// @return The amount of assets supplied.
  function supply(
    uint256 reserveId,
    uint256 amount,
    address onBehalfOf
  ) external returns (uint256, uint256);

  /// @notice Withdraws a specified amount of underlying asset from the given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev Providing an amount greater than the maximum withdrawable value signals a full withdrawal.
  /// @dev Caller must be `onBehalfOf` or an authorized position manager for `onBehalfOf`.
  /// @dev Caller receives the underlying asset withdrawn.
  /// @param reserveId The identifier of the reserve.
  /// @param amount The amount of asset to withdraw.
  /// @param onBehalfOf The owner of position to remove supply shares from.
  /// @return The amount of shares withdrawn.
  /// @return The amount of assets withdrawn.
  function withdraw(
    uint256 reserveId,
    uint256 amount,
    address onBehalfOf
  ) external returns (uint256, uint256);

  /// @notice Borrows a specified amount of underlying asset from the given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev It reverts if the user would borrow more than the maximum allowed number of borrowed reserves.
  /// @dev Caller must be `onBehalfOf` or an authorized position manager for `onBehalfOf`.
  /// @dev Caller receives the underlying asset borrowed.
  /// @param reserveId The identifier of the reserve.
  /// @param amount The amount of asset to borrow.
  /// @param onBehalfOf The owner of the position against which debt is generated.
  /// @return The amount of shares borrowed.
  /// @return The amount of assets borrowed.
  function borrow(
    uint256 reserveId,
    uint256 amount,
    address onBehalfOf
  ) external returns (uint256, uint256);

  /// @notice Repays a specified amount of underlying asset to a given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev The Spoke pulls the underlying asset from the caller, so prior approval is required.
  /// @dev Caller must be `onBehalfOf` or an authorized position manager for `onBehalfOf`.
  /// @param reserveId The identifier of the reserve.
  /// @param amount The amount of asset to repay.
  /// @param onBehalfOf The owner of the position whose debt is repaid.
  /// @return The amount of shares repaid.
  /// @return The amount of assets repaid.
  function repay(
    uint256 reserveId,
    uint256 amount,
    address onBehalfOf
  ) external returns (uint256, uint256);

  /// @notice Liquidates a user position.
  /// @dev It reverts if the reserves associated with any of the given reserve identifiers are not listed.
  /// @dev The Spoke pulls underlying repaid debt assets from caller (Liquidator), hence it needs prior approval.
  /// @param collateralReserveId The reserveId of the underlying asset used as collateral by the liquidated user.
  /// @param debtReserveId The reserveId of the underlying asset borrowed by the liquidated user, to be repaid by Liquidator.
  /// @param user The address of the user to liquidate.
  /// @param debtToCover The desired amount of debt to cover.
  /// @param receiveShares True to receive collateral in supplied shares, false to receive in underlying assets.
  function liquidationCall(
    uint256 collateralReserveId,
    uint256 debtReserveId,
    address user,
    uint256 debtToCover,
    bool receiveShares
  ) external;

  /// @notice Allows suppliers to enable/disable a specific supplied reserve as collateral.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev It reverts if the user exceeds the maximum allowed collateral reserves when enabling.
  /// @dev Reserves with zero supplied or zero collateral factor count towards the max allowed collateral reserves.
  /// @dev Caller must be `onBehalfOf` or an authorized position manager for `onBehalfOf`.
  /// @param reserveId The reserve identifier of the underlying asset.
  /// @param usingAsCollateral True if the user wants to use the supply as collateral.
  /// @param onBehalfOf The owner of the position being modified.
  function setUsingAsCollateral(
    uint256 reserveId,
    bool usingAsCollateral,
    address onBehalfOf
  ) external;

  /// @notice Allows updating the risk premium on onBehalfOf position.
  /// @dev Caller must be `onBehalfOf`, an authorized position manager for `onBehalfOf`, or admin.
  /// @param onBehalfOf The owner of the position being modified.
  function updateUserRiskPremium(address onBehalfOf) external;

  /// @notice Allows updating the dynamic configuration for all collateral reserves on onBehalfOf position.
  /// @dev Caller must be `onBehalfOf`, an authorized position manager for `onBehalfOf`, or admin.
  /// @param onBehalfOf The owner of the position being modified.
  function updateUserDynamicConfig(address onBehalfOf) external;

  /// @notice Enables a user to grant or revoke approval for a position manager.
  /// @dev Allows approving inactive position managers.
  /// @param positionManager The address of the position manager.
  /// @param approve True to approve the position manager, false to revoke approval.
  function setUserPositionManager(address positionManager, bool approve) external;

  /// @notice Enables a user to grant or revoke approval for an array of position managers using an EIP712-typed intent.
  /// @dev Uses keyed-nonces where for each key's namespace nonce is consumed sequentially.
  /// @dev Allows duplicated updates and the last one is persisted. Allows approving inactive position managers.
  /// @param params The structured setUserPositionManagers parameter.
  /// @param signature The EIP712-compliant signature bytes.
  function setUserPositionManagersWithSig(
    SetUserPositionManagers calldata params,
    bytes calldata signature
  ) external;

  /// @notice Allows position manager (as caller) to renounce their approval given by the user.
  /// @param user The address of the user.
  function renouncePositionManagerRole(address user) external;

  /// @notice Allows consuming a permit signature for the given reserve's underlying asset.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev The Spoke must be configured as the spender.
  /// @param reserveId The identifier of the reserve.
  /// @param onBehalfOf The address of the user on whose behalf the permit is being used.
  /// @param value The amount of the underlying asset to permit.
  /// @param deadline The deadline for the permit.
  /// @param permitV The v parameter of the permit signature.
  /// @param permitR The r parameter of the permit signature.
  /// @param permitS The s parameter of the permit signature.
  function permitReserve(
    uint256 reserveId,
    address onBehalfOf,
    uint256 value,
    uint256 deadline,
    uint8 permitV,
    bytes32 permitR,
    bytes32 permitS
  ) external;

  /// @notice Returns the liquidation config struct.
  function getLiquidationConfig() external view returns (LiquidationConfig memory);

  /// @notice Returns the number of listed reserves on the Spoke.
  /// @dev Count includes reserves that are not currently active.
  function getReserveCount() external view returns (uint256);

  /// @notice Returns the total amount of supplied assets of a given reserve.
  /// @param reserveId The identifier of the reserve.
  /// @return The amount of supplied assets.
  function getReserveSuppliedAssets(uint256 reserveId) external view returns (uint256);

  /// @notice Returns the total amount of supplied shares of a given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @param reserveId The identifier of the reserve.
  /// @return The amount of supplied shares.
  function getReserveSuppliedShares(uint256 reserveId) external view returns (uint256);

  /// @notice Returns the debt of a given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev The total debt of the reserve is the sum of drawn debt and premium debt.
  /// @param reserveId The identifier of the reserve.
  /// @return The amount of drawn debt.
  /// @return The amount of premium debt.
  function getReserveDebt(uint256 reserveId) external view returns (uint256, uint256);

  /// @notice Returns the total debt of a given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev The total debt of the reserve is the sum of drawn debt and premium debt.
  /// @param reserveId The identifier of the reserve.
  /// @return The total debt amount.
  function getReserveTotalDebt(uint256 reserveId) external view returns (uint256);

  /// @notice Returns the reserve identifier for a given asset in a Hub.
  /// @dev It reverts if no reserve is associated with the given asset identifier.
  /// @param hub The address of the Hub.
  /// @param assetId The identifier of the asset on the Hub.
  /// @return The identifier of the reserve.
  function getReserveId(address hub, uint256 assetId) external view returns (uint256);

  /// @notice Returns the reserve struct data in storage.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @param reserveId The identifier of the reserve.
  /// @return The reserve struct.
  function getReserve(uint256 reserveId) external view returns (Reserve memory);

  /// @notice Returns the reserve configuration struct data in storage.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @param reserveId The identifier of the reserve.
  /// @return The reserve configuration struct.
  function getReserveConfig(uint256 reserveId) external view returns (ReserveConfig memory);

  /// @notice Returns the dynamic reserve configuration struct at the specified key.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev Does not revert if `dynamicConfigKey` is unset.
  /// @param reserveId The identifier of the reserve.
  /// @param dynamicConfigKey The key of the dynamic config.
  /// @return The dynamic reserve configuration struct.
  function getDynamicReserveConfig(
    uint256 reserveId,
    uint32 dynamicConfigKey
  ) external view returns (DynamicReserveConfig memory);

  /// @notice Returns two flags indicating whether the reserve is used as collateral and whether it is borrowed by the user.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev Even if enabled as collateral, it will only count towards user position if the collateral factor is greater than 0.
  /// @param reserveId The identifier of the reserve.
  /// @param user The address of the user.
  /// @return True if the reserve is enabled as collateral by the user.
  /// @return True if the reserve is borrowed by the user.
  function getUserReserveStatus(uint256 reserveId, address user) external view returns (bool, bool);

  /// @notice Returns the amount of assets supplied by a specific user for a given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @param reserveId The identifier of the reserve.
  /// @param user The address of the user.
  /// @return The amount of assets supplied by the user.
  function getUserSuppliedAssets(uint256 reserveId, address user) external view returns (uint256);

  /// @notice Returns the amount of shares supplied by a specific user for a given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @param reserveId The identifier of the reserve.
  /// @param user The address of the user.
  /// @return The amount of shares supplied by the user.
  function getUserSuppliedShares(uint256 reserveId, address user) external view returns (uint256);

  /// @notice Returns the debt of a specific user for a given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev The total debt of the user is the sum of drawn debt and premium debt.
  /// @param reserveId The identifier of the reserve.
  /// @param user The address of the user.
  /// @return The amount of drawn debt.
  /// @return The amount of premium debt.
  function getUserDebt(uint256 reserveId, address user) external view returns (uint256, uint256);

  /// @notice Returns the total debt of a specific user for a given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @dev The total debt of the user is the sum of drawn debt and premium debt.
  /// @param reserveId The identifier of the reserve.
  /// @param user The address of the user.
  /// @return The total debt amount.
  function getUserTotalDebt(uint256 reserveId, address user) external view returns (uint256);

  /// @notice Returns the full precision premium debt of a specific user for a given reserve.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @param reserveId The identifier of the reserve.
  /// @param user The address of the user.
  /// @return The amount of premium debt, expressed in asset units and scaled by RAY.
  function getUserPremiumDebtRay(uint256 reserveId, address user) external view returns (uint256);

  /// @notice Returns the user position struct in storage.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @param reserveId The identifier of the reserve.
  /// @param user The address of the user.
  /// @return The user position struct.
  function getUserPosition(
    uint256 reserveId,
    address user
  ) external view returns (UserPosition memory);

  /// @notice Returns the most up-to-date user account data information.
  /// @dev Utilizes user's current dynamic configuration of user position.
  /// @param user The address of the user.
  /// @return The user account data struct.
  function getUserAccountData(address user) external view returns (UserAccountData memory);

  /// @notice Returns the risk premium from the user's last position update.
  /// @param user The address of the user.
  /// @return The risk premium of the user from the last position update, expressed in BPS.
  function getUserLastRiskPremium(address user) external view returns (uint256);

  /// @notice Returns the liquidation bonus for a given health factor, based on the user's current dynamic configuration.
  /// @dev It reverts if the reserve associated with the given reserve identifier is not listed.
  /// @param reserveId The identifier of the reserve.
  /// @param user The address of the user.
  /// @param healthFactor The health factor of the user, expressed in WAD.
  /// @return The liquidation bonus for the user, expressed in BPS.
  function getLiquidationBonus(
    uint256 reserveId,
    address user,
    uint256 healthFactor
  ) external view returns (uint256);

  /// @notice Returns whether positionManager is currently activated by governance.
  /// @param positionManager The address of the position manager.
  /// @return True if positionManager is currently active.
  function isPositionManagerActive(address positionManager) external view returns (bool);

  /// @notice Returns whether positionManager is active and approved by user.
  /// @param user The address of the user.
  /// @param positionManager The address of the position manager.
  /// @return True if positionManager is active and approved by user.
  function isPositionManager(address user, address positionManager) external view returns (bool);

  /// @notice Returns the address of the external `LiquidationLogic` library.
  function getLiquidationLogic() external pure returns (address);

  /// @notice Returns the type hash for the SetUserPositionManagers intent.
  /// @return The bytes-encoded EIP-712 struct hash representing the intent.
  function SET_USER_POSITION_MANAGERS_TYPEHASH() external view returns (bytes32);

  /// @notice Returns the address of the AaveOracle contract.
  function ORACLE() external view returns (address);

  /// @notice Returns the maximum allowed number of collateral and borrow reserves per user (each counted separately).
  function MAX_USER_RESERVES_LIMIT() external view returns (uint16);
}

src/spoke/interfaces/ISpokeConfigurator.sol

// SPDX-License-Identifier: LicenseRef-BUSL
pragma solidity ^0.8.0;

import {ISpoke} from 'src/spoke/interfaces/ISpoke.sol';

/// @title ISpokeConfigurator
/// @author Aave Labs
/// @notice Interface for the SpokeConfigurator.
interface ISpokeConfigurator {
  /// @notice Thrown when an address parameter is the zero address.
  error InvalidAddress();

  /// @notice Updates the price source of a reserve.
  /// @dev The price source must implement IPriceFeed.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param priceSource The new price source.
  function updateReservePriceSource(address spoke, uint256 reserveId, address priceSource) external;

  /// @notice Updates the liquidation target health factor of a spoke.
  /// @param spoke The address of the Spoke.
  /// @param targetHealthFactor The new liquidation target health factor.
  function updateLiquidationTargetHealthFactor(address spoke, uint256 targetHealthFactor) external;

  /// @notice Updates the health factor for max liquidation bonus of a spoke.
  /// @param spoke The address of the Spoke.
  /// @param healthFactorForMaxBonus The new health factor for max liquidation bonus.
  function updateHealthFactorForMaxBonus(address spoke, uint256 healthFactorForMaxBonus) external;

  /// @notice Updates the liquidation bonus factor of a spoke.
  /// @param spoke The address of the Spoke.
  /// @param liquidationBonusFactor The new liquidation bonus factor.
  function updateLiquidationBonusFactor(address spoke, uint256 liquidationBonusFactor) external;

  /// @notice Updates the liquidation config of a spoke.
  /// @param spoke The address of the Spoke.
  /// @param liquidationConfig The new liquidation config.
  function updateLiquidationConfig(
    address spoke,
    ISpoke.LiquidationConfig calldata liquidationConfig
  ) external;

  /// @notice Adds a new reserve to a spoke.
  /// @dev The asset corresponding to the reserve must be already listed on the Hub.
  /// @dev The price source must implement IPriceFeed.
  /// @param spoke The address of the Spoke.
  /// @param hub The address of the Hub where the asset corresponding to the reserve is listed.
  /// @param assetId The identifier of the asset.
  /// @param priceSource The address of the price source.
  /// @param config The configuration of the reserve.
  /// @param dynamicConfig The dynamic configuration of the reserve.
  /// @return reserveId The identifier of the reserve.
  function addReserve(
    address spoke,
    address hub,
    uint256 assetId,
    address priceSource,
    ISpoke.ReserveConfig calldata config,
    ISpoke.DynamicReserveConfig calldata dynamicConfig
  ) external returns (uint256);

  /// @notice Updates the paused flag of a reserve.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param paused The new paused flag.
  function updatePaused(address spoke, uint256 reserveId, bool paused) external;

  /// @notice Updates the frozen flag of a reserve.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param frozen The new frozen flag.
  function updateFrozen(address spoke, uint256 reserveId, bool frozen) external;

  /// @notice Updates the borrowable flag of a reserve.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param borrowable The new borrowable flag.
  function updateBorrowable(address spoke, uint256 reserveId, bool borrowable) external;

  /// @notice Updates whether receiving shares on liquidation is enabled.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param receiveSharesEnabled The new receiveSharesEnabled flag.
  function updateReceiveSharesEnabled(
    address spoke,
    uint256 reserveId,
    bool receiveSharesEnabled
  ) external;

  /// @notice Updates the collateral risk of a reserve.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param collateralRisk The new collateral risk.
  function updateCollateralRisk(address spoke, uint256 reserveId, uint256 collateralRisk) external;

  /// @notice Adds a dynamic config to a reserve, identical to the latest one but with the specified collateral factor.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param collateralFactor The new collateral factor.
  /// @return The dynamicConfigKey of the added dynamic configuration.
  function addCollateralFactor(
    address spoke,
    uint256 reserveId,
    uint16 collateralFactor
  ) external returns (uint32);

  /// @notice Updates an existing collateral factor of a reserve at the specified key.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param dynamicConfigKey The key of the dynamic config to update.
  /// @param collateralFactor The new collateral factor.
  function updateCollateralFactor(
    address spoke,
    uint256 reserveId,
    uint32 dynamicConfigKey,
    uint16 collateralFactor
  ) external;

  /// @notice Adds a dynamic config to a reserve, identical to the latest one but with the specified max liquidation bonus.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param maxLiquidationBonus The new max liquidation bonus.
  /// @return The dynamicConfigKey of the added dynamic configuration.
  function addMaxLiquidationBonus(
    address spoke,
    uint256 reserveId,
    uint256 maxLiquidationBonus
  ) external returns (uint32);

  /// @notice Updates an existing liquidation bonus of a reserve at the specified key.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param dynamicConfigKey The key of the dynamic config to update.
  /// @param maxLiquidationBonus The new liquidation bonus.
  function updateMaxLiquidationBonus(
    address spoke,
    uint256 reserveId,
    uint32 dynamicConfigKey,
    uint256 maxLiquidationBonus
  ) external;

  /// @notice Adds a dynamic config to a reserve, identical to the latest one but with the specified liquidation fee.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param liquidationFee The new liquidation fee.
  /// @return The dynamicConfigKey of the added dynamic configuration.
  function addLiquidationFee(
    address spoke,
    uint256 reserveId,
    uint256 liquidationFee
  ) external returns (uint32);

  /// @notice Updates an existing liquidation fee of a reserve at the specified key.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param dynamicConfigKey The key of the dynamic config to update.
  /// @param liquidationFee The new liquidation fee.
  function updateLiquidationFee(
    address spoke,
    uint256 reserveId,
    uint32 dynamicConfigKey,
    uint256 liquidationFee
  ) external;

  /// @notice Adds a dynamic config to a reserve.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param dynamicConfig The new dynamic config.
  /// @return dynamicConfigKey The key of the added dynamic config.
  function addDynamicReserveConfig(
    address spoke,
    uint256 reserveId,
    ISpoke.DynamicReserveConfig calldata dynamicConfig
  ) external returns (uint32);

  /// @notice Updates the dynamic config of a reserve at the specified key.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  /// @param dynamicConfigKey The key of the dynamic config to update.
  /// @param dynamicConfig The new dynamic config.
  function updateDynamicReserveConfig(
    address spoke,
    uint256 reserveId,
    uint32 dynamicConfigKey,
    ISpoke.DynamicReserveConfig calldata dynamicConfig
  ) external;

  /// @notice Pauses all reserves of a spoke.
  /// @param spoke The address of the Spoke.
  function pauseAllReserves(address spoke) external;

  /// @notice Freezes all reserves of a spoke.
  /// @param spoke The address of the Spoke.
  function freezeAllReserves(address spoke) external;

  /// @notice Pauses a reserve of a spoke.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  function pauseReserve(address spoke, uint256 reserveId) external;

  /// @notice Freezes a reserve of a spoke.
  /// @param spoke The address of the Spoke.
  /// @param reserveId The identifier of the reserve.
  function freezeReserve(address spoke, uint256 reserveId) external;

  /// @notice Updates the active flag of a spoke's position manager.
  /// @param spoke The address of the Spoke.
  /// @param positionManager The address of the position manager.
  /// @param active The new active flag.
  function updatePositionManager(address spoke, address positionManager, bool active) external;
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 44444444,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "erc4626-tests/=lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.