Verified contractPartialBUSL-1.1
PlasmaVault
Address0x0eda7e3d48e5c91c82e33c499711d9e4d3e960be
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,336,747
- Creation transaction
- 0x1e18d88566…fcb4cd97a5
- Libraries
- lib/ipor-fusion/contracts/vaults/PlasmaVault.sol:PlasmaVaultMarketsLib0x3c41…97a3da
66 files
The source code is large: one file is shown at a time. Choose a file in the list.
- lib/ipor-fusion/contracts/vaults/PlasmaVault.solmain69.54 KB
- lib/ipor-fusion/contracts/fuses/IFuseCommon.sol277 B
- lib/ipor-fusion/contracts/handlers/pre_hooks/IPreHook.sol1.13 KB
- lib/ipor-fusion/contracts/handlers/pre_hooks/PreHooksHandler.sol1.91 KB
- lib/ipor-fusion/contracts/handlers/pre_hooks/PreHooksLib.sol7.69 KB
- lib/ipor-fusion/contracts/interfaces/IIporFusionAccessManager.sol6.89 KB
- lib/ipor-fusion/contracts/interfaces/IPlasmaVault.sol3.03 KB
- lib/ipor-fusion/contracts/interfaces/IPlasmaVaultBase.sol3.01 KB
- lib/ipor-fusion/contracts/interfaces/IPlasmaVaultGovernance.sol13.65 KB
- lib/ipor-fusion/contracts/interfaces/IRewardsClaimManager.sol7.18 KB
- lib/ipor-fusion/contracts/libraries/AssetDistributionProtectionLib.sol10.07 KB
- lib/ipor-fusion/contracts/libraries/CallbackHandlerLib.sol7.48 KB
- lib/ipor-fusion/contracts/libraries/FuseStorageLib.sol17.81 KB
- lib/ipor-fusion/contracts/libraries/FusesLib.sol25.37 KB
- lib/ipor-fusion/contracts/libraries/PlasmaVaultConfigLib.sol17.15 KB
- lib/ipor-fusion/contracts/libraries/PlasmaVaultLib.sol42.72 KB
- lib/ipor-fusion/contracts/libraries/PlasmaVaultStorageLib.sol53.04 KB
- lib/ipor-fusion/contracts/libraries/Roles.sol6.45 KB
- lib/ipor-fusion/contracts/libraries/errors/Errors.sol730 B
- lib/ipor-fusion/contracts/libraries/math/IporMath.sol5.12 KB
- lib/ipor-fusion/contracts/managers/access/AccessManagedUpgradeable.sol6.97 KB
- lib/ipor-fusion/contracts/managers/access/IporFusionAccessManager.sol23.22 KB
- lib/ipor-fusion/contracts/managers/access/IporFusionAccessManagerInitializationLib.sol3.49 KB
- lib/ipor-fusion/contracts/managers/access/IporFusionAccessManagersStorageLib.sol9.19 KB
- lib/ipor-fusion/contracts/managers/access/RedemptionDelayLib.sol10.1 KB
- lib/ipor-fusion/contracts/managers/access/RoleExecutionTimelockLib.sol2.22 KB
- lib/ipor-fusion/contracts/managers/context/ContextClient.sol3.69 KB
- lib/ipor-fusion/contracts/managers/context/ContextClientStorageLib.sol4.78 KB
- lib/ipor-fusion/contracts/managers/context/IContextClient.sol2.6 KB
- lib/ipor-fusion/contracts/managers/fee/FeeAccount.sol1.95 KB
- lib/ipor-fusion/contracts/managers/fee/FeeManager.sol40.02 KB
- lib/ipor-fusion/contracts/managers/fee/FeeManagerFactory.sol3.73 KB
- lib/ipor-fusion/contracts/managers/fee/FeeManagerStorageLib.sol15.71 KB
- lib/ipor-fusion/contracts/managers/withdraw/WithdrawManager.sol17.17 KB
- lib/ipor-fusion/contracts/managers/withdraw/WithdrawManagerStorageLib.sol12.63 KB
- lib/ipor-fusion/contracts/price_oracle/IPriceOracleMiddleware.sol2.28 KB
- lib/ipor-fusion/contracts/universal_reader/UniversalReader.sol3.32 KB
- lib/ipor-fusion/contracts/vaults/PlasmaVaultGovernance.sol76.83 KB
- lib/ipor-fusion/contracts/vaults/lib/PlasmaVaultFeesLib.sol6.28 KB
- lib/ipor-fusion/contracts/vaults/lib/PlasmaVaultMarketsLib.sol10.79 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol8.91 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol12.47 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol13.75 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.19 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol4.36 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/access/manager/AccessManager.sol29.36 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/access/manager/AuthorityUtils.sol1.23 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/access/manager/IAccessManaged.sol1.11 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/access/manager/IAccessManager.sol16.09 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/access/manager/IAuthority.sol482 B
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/interfaces/IERC4626.sol12.18 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/interfaces/draft-IERC6093.sol6.53 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol11.14 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol12.41 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol995 B
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/utils/Address.sol6.26 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/utils/Context.sol963 B
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/utils/Multicall.sol1.7 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/utils/math/Math.sol15.12 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/utils/math/SafeCast.sol34.69 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/utils/structs/EnumerableSet.sol12.97 KB
- lib/ipor-fusion/node_modules/@openzeppelin/contracts/utils/types/Time.sol5.1 KB
lib/ipor-fusion/contracts/vaults/PlasmaVault.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IAccessManager} from "@openzeppelin/contracts/access/manager/IAccessManager.sol";
import {AuthorityUtils} from "@openzeppelin/contracts/access/manager/AuthorityUtils.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {ERC4626Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {Errors} from "../libraries/errors/Errors.sol";
import {IporMath} from "../libraries/math/IporMath.sol";
import {IPlasmaVault, FuseAction} from "../interfaces/IPlasmaVault.sol";
import {IFuseCommon} from "../fuses/IFuseCommon.sol";
import {IPlasmaVaultBase} from "../interfaces/IPlasmaVaultBase.sol";
import {IPriceOracleMiddleware} from "../price_oracle/IPriceOracleMiddleware.sol";
import {IRewardsClaimManager} from "../interfaces/IRewardsClaimManager.sol";
import {AccessManagedUpgradeable} from "../managers/access/AccessManagedUpgradeable.sol";
import {PlasmaVaultStorageLib} from "../libraries/PlasmaVaultStorageLib.sol";
import {IporFusionAccessManager} from "../managers/access/IporFusionAccessManager.sol";
import {AssetDistributionProtectionLib, DataToCheck} from "../libraries/AssetDistributionProtectionLib.sol";
import {CallbackHandlerLib} from "../libraries/CallbackHandlerLib.sol";
import {FusesLib} from "../libraries/FusesLib.sol";
import {PlasmaVaultLib} from "../libraries/PlasmaVaultLib.sol";
import {FeeManagerData, FeeManagerFactory, FeeConfig} from "../managers/fee/FeeManagerFactory.sol";
import {FeeManagerInitData} from "../managers/fee/FeeManager.sol";
import {WithdrawManager} from "../managers/withdraw/WithdrawManager.sol";
import {UniversalReader} from "../universal_reader/UniversalReader.sol";
import {ContextClientStorageLib} from "../managers/context/ContextClientStorageLib.sol";
import {PreHooksHandler} from "../handlers/pre_hooks/PreHooksHandler.sol";
import {PlasmaVaultFeesLib} from "./lib/PlasmaVaultFeesLib.sol";
import {PlasmaVaultMarketsLib} from "./lib/PlasmaVaultMarketsLib.sol";
import {RecipientFee} from "../managers/fee/FeeManager.sol";
/// @title PlasmaVault Initialization Data Structure
/// @notice Configuration data structure used during Plasma Vault deployment and initialization
/// @dev Encapsulates all required parameters for vault setup and protocol integration
///
/// Core Configuration:
/// - Asset details (name, symbol, underlying token)
/// - Protocol integrations (fuses, markets, substrates)
/// - Fee structure and management
/// - Access control and security settings
/// - Supply cap and withdrawal parameters
///
/// Integration Components:
/// - Price Oracle: Asset valuation and share price calculation
/// - Market Substrates: Protocol-specific market identifiers
/// - Balance Fuses: Market-specific balance tracking
/// - Fee Configuration: Performance and management fee setup
///
/// Security Features:
/// - Access Manager: Permission and role management
/// - Total Supply Cap: Vault size control
/// - Withdraw Manager: Withdrawal control and validation
/// - Base Contract: Common functionality and security
///
/// Validation Requirements:
/// - Non-zero addresses for critical components
/// - Valid fee configurations within limits
/// - Properly formatted market configs
/// - Compatible protocol integrations
struct PlasmaVaultInitData {
/// @notice Name of the vault's share token
/// @dev Used in ERC20 token initialization
string assetName;
/// @notice Symbol of the vault's share token
/// @dev Used in ERC20 token initialization
string assetSymbol;
/// @notice Address of the token that the vault accepts for deposits
/// @dev Must be a valid ERC20 token contract
address underlyingToken;
/// @notice Address of the price oracle middleware for asset valuation
/// @dev Must support USD as quote currency
address priceOracleMiddleware;
/// @notice Fee configuration for performance and management fees
/// @dev Includes fee rates and recipient addresses
FeeConfig feeConfig;
/// @notice Address of the access control manager contract
/// @dev Manages roles and permissions for vault operations
address accessManager;
/// @notice Address of the base contract providing common functionality
/// @dev Implements core vault logic through delegatecall
address plasmaVaultBase;
/// @notice Address of the withdraw manager contract
/// @dev Controls withdrawal permissions and limits, zero address disables managed withdrawals
address withdrawManager;
/// @notice Address of the votes plugin contract (PlasmaVaultVotesPlugin)
/// @dev Implements optional ERC20Votes functionality through delegatecall, zero address disables voting
address plasmaVaultVotesPlugin;
}
/// @title Market Balance Fuse Configuration
/// @notice Configuration structure linking markets with their balance tracking contracts
/// @dev Maps protocol-specific markets to their corresponding balance fuse implementations
///
/// Balance Fuse System:
/// - Tracks protocol-specific positions and balances
/// - Provides standardized balance reporting interface
/// - Supports market-specific balance calculations
/// - Enables protocol integration monitoring
///
/// Market Integration:
/// - Market ID 0: Special case for protocol-independent fuses
/// - Non-zero Market IDs: Protocol-specific market tracking
/// - Single balance fuse per market
/// - Critical for asset distribution protection
///
/// Use Cases:
/// - Protocol position tracking
/// - Market balance monitoring
/// - Asset distribution validation
/// - Protocol integration management
///
/// Security Considerations:
/// - Validates market existence
/// - Ensures fuse compatibility
/// - Prevents duplicate assignments
/// - Critical for balance integrity
struct MarketBalanceFuseConfig {
/// @notice Identifier of the market this fuse tracks
/// @dev Market ID 0 indicates protocol-independent functionality (e.g., flashloan fuse)
uint256 marketId;
/// @notice Address of the balance tracking contract
/// @dev Must implement protocol-specific balance calculation logic
address fuse;
}
/// @title Market Substrates Configuration
/// @notice Configuration structure defining protocol-specific identifiers for market integration
/// @dev Maps markets to their underlying components and protocol-specific identifiers
///
/// Substrate System:
/// - Defines market components and identifiers
/// - Supports multi-protocol integration
/// - Enables complex market structures
/// - Facilitates balance tracking
///
/// Substrate Types:
/// - Protocol tokens and assets
/// - LP positions and pool identifiers
/// - Market-specific parameters
/// - Protocol vault identifiers
/// - Custom protocol identifiers
///
/// Integration Context:
/// - Used by balance fuses for position tracking
/// - Supports protocol-specific calculations
/// - Enables market validation
/// - Critical for protocol interactions
///
/// Security Considerations:
/// - Validates substrate format
/// - Ensures protocol compatibility
/// - Prevents invalid configurations
/// - Maintains market integrity
struct MarketSubstratesConfig {
/// @notice Unique identifier for the market in the vault system
/// @dev Used to link market operations and balance tracking
uint256 marketId;
/// @notice Array of protocol-specific identifiers for this market
/// @dev Can include:
/// - Asset addresses (as bytes32)
/// - Pool/vault identifiers
/// - Protocol-specific parameters
/// - Market configuration data
bytes32[] substrates;
}
/// @title Plasma Vault - ERC4626 Compliant DeFi Integration Hub
/// @notice Advanced vault system enabling protocol integrations and asset management through fuse system
/// @dev Implements ERC4626 standard with enhanced security and multi-protocol support
///
/// Core Features:
/// - ERC4626 tokenized vault standard compliance
/// - Multi-protocol integration via fuse system
/// - Advanced access control and permissions
/// - Performance and management fee system
/// - Market-specific balance tracking
/// - Protected asset distribution
///
/// Operational Components:
/// - Fuse System: Protocol-specific integration contracts
/// - Balance Tracking: Market-specific position monitoring
/// - Fee Management: Performance and time-based fees
/// - Access Control: Role-based operation permissions
/// - Withdrawal Control: Managed withdrawal process
///
/// Security Features:
/// - Reentrancy protection
/// - Role-based access control
/// - Asset distribution limits
/// - Market balance validation
/// - Withdrawal restrictions
///
/// Integration Architecture:
/// - Delegatecall to base contract for core logic
/// - Fuse contracts for protocol interactions
/// - Price oracle for asset valuation
/// - Balance fuses for position tracking
/// - Callback system for complex operations
///
contract PlasmaVault is
ERC20Upgradeable,
ERC4626Upgradeable,
ReentrancyGuardUpgradeable,
AccessManagedUpgradeable,
UniversalReader,
IPlasmaVault,
PreHooksHandler
{
using Address for address;
using Math for uint256;
using SafeERC20 for IERC20;
/// @notice ISO-4217 currency code for USD represented as address
/// @dev 0x348 (840 in decimal) is the ISO-4217 numeric code for USD
address private constant USD = address(0x0000000000000000000000000000000000000348);
/// @dev Additional offset to withdraw from markets in case of rounding issues
uint256 private constant WITHDRAW_FROM_MARKETS_OFFSET = 10;
/// @dev 10 attempts to withdraw from markets in case of rounding issues
uint256 private constant REDEEM_ATTEMPTS = 10;
uint256 public constant DEFAULT_SLIPPAGE_IN_PERCENTAGE = 2;
error NoSharesToRedeem();
error NoSharesToMint();
error NoAssetsToWithdraw();
error NoSharesToWithdraw();
error NoAssetsToDeposit();
error NoSharesToDeposit();
error UnsupportedFuse();
error UnsupportedMethod();
error WithdrawManagerInvalidSharesToRelease(uint256 sharesToRelease);
error PermitFailed();
error WithdrawManagerNotSet();
error VotesPluginNotEnabled();
event ManagementFeeRealized(uint256 unrealizedFeeInUnderlying, uint256 unrealizedFeeInShares);
event DepositFeeRealized(address recipient, uint256 feeShares);
event ExecuteFinished(address executor, uint256 callsCount, uint256[] marketIds);
/// @notice Fallback function handling delegatecall execution and callbacks
/// @dev Routes execution between callback handling and base contract delegation
///
/// Execution Paths:
/// 1. During Fuse Action Execution:
/// - Handles callbacks from protocol interactions
/// - Validates callback context
/// - Processes protocol-specific responses
///
/// 2. Normal Operation:
/// - Delegates calls to PlasmaVaultBase (which also routes the Votes selectors to the votes plugin)
/// - Maintains vault functionality
/// - Preserves upgrade safety
///
/// Security Considerations:
/// - Validates execution context
/// - Prevents unauthorized callbacks
/// - Maintains delegatecall security
/// - Protects against reentrancy
///
/// @param calldata_ Raw calldata for function execution
/// @return bytes Empty if callback, delegated result otherwise
// solhint-disable-next-line no-unused-vars
fallback(bytes calldata calldata_) external returns (bytes memory) {
if (PlasmaVaultLib.isExecutionStarted()) {
/// @dev Handle callback can be done only during the execution of the FuseActions by Alpha
CallbackHandlerLib.handleCallback();
return "";
}
/// @dev Votes selectors are routed to the votes plugin by the PlasmaVaultBase fallback (code size)
return PLASMA_VAULT_BASE().functionDelegateCall(msg.data);
}
/// @notice The plasma vault base contract address
/// @dev Retrieved from storage library
function PLASMA_VAULT_BASE() public view returns (address) {
return PlasmaVaultStorageLib.getPlasmaVaultBase();
}
/// @notice The plasma vault votes plugin contract address (PlasmaVaultVotesPlugin)
/// @dev Retrieved from storage library. This contract provides optional ERC20Votes functionality.
/// @return The address of the votes plugin contract, or address(0) if voting is not enabled
function PLASMA_VAULT_VOTES_PLUGIN() public view returns (address) {
return PlasmaVaultStorageLib.getPlasmaVaultVotesPlugin();
}
/// @custom:oz-upgrades-unsafe-allow constructor
/// @notice Locks the implementation: only clones (FusionFactory → PlasmaVaultFactory.clone) can be initialized (IL-8979).
constructor() {
_disableInitializers();
}
/// @notice Initializes the PlasmaVault with initialization data (for cloning)
/// @param initData_ Initialization parameters encapsulated in PlasmaVaultInitData struct
/// @dev This method is called after cloning to initialize the contract
function proxyInitialize(PlasmaVaultInitData memory initData_) external initializer {
_initializeVault(initData_);
}
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
/// @notice Executes a sequence of protocol interactions through fuse contracts
/// @dev Processes multiple fuse actions while maintaining vault security and balance tracking
///
/// Execution Flow:
/// 1. Pre-execution
/// - Records initial total assets
/// - Marks execution start
/// - Validates fuse support
///
/// 2. Action Processing
/// - Executes each fuse action sequentially
/// - Tracks affected markets
/// - Handles protocol interactions
/// - Processes callbacks if needed
///
/// 3. Post-execution
/// - Updates market balances
/// - Calculates and applies performance fees
/// - Marks execution end
/// - Validates final state
///
/// Security Features:
/// - Reentrancy protection
/// - Role-based access control
/// - Fuse validation
/// - Market balance verification
/// - Asset distribution protection
///
/// Market Tracking:
/// - Maintains unique market list
/// - Updates balances atomically
/// - Validates market limits
/// - Ensures balance consistency
///
/// @param calls_ Array of FuseAction structs defining protocol interactions
/// @custom:security Non-reentrant and role-restricted
/// @custom:access Restricted to ALPHA_ROLE (managed by ATOMIST_ROLE)
function execute(FuseAction[] calldata calls_) external override nonReentrant restricted {
uint256 callsCount = calls_.length;
uint256[] memory markets = new uint256[](callsCount);
uint256 marketIndex;
uint256 fuseMarketId;
uint256 totalAssetsBefore = _getNetTotalAssets();
PlasmaVaultLib.executeStarted();
for (uint256 i; i < callsCount; ++i) {
if (!FusesLib.isFuseSupported(calls_[i].fuse)) {
revert UnsupportedFuse();
}
fuseMarketId = IFuseCommon(calls_[i].fuse).MARKET_ID();
if (_checkIfExistsMarket(markets, fuseMarketId) == false) {
markets[marketIndex] = fuseMarketId;
marketIndex++;
}
calls_[i].fuse.functionDelegateCall(calls_[i].data);
}
PlasmaVaultLib.executeFinished();
_updateMarketsBalances(markets);
_addPerformanceFee(totalAssetsBefore);
emit ExecuteFinished(_msgSender(), callsCount, markets);
}
/// @notice Updates balances for specified markets and calculates performance fees
/// @dev Refreshes market balances and applies performance fee calculations
///
/// Update Flow:
/// 1. Balance Calculation
/// - Retrieves current total assets
/// - Updates specified market balances
/// - Calculates performance metrics
///
/// 2. Fee Processing
/// - Calculates performance fee
/// - Updates fee data
/// - Applies fee adjustments
///
/// Security Features:
/// - Market validation
/// - Balance verification
/// - Fee calculation safety
/// - Access control via UPDATE_MARKETS_BALANCES_ROLE
///
/// @param marketIds_ Array of market IDs to update
/// @return uint256 Updated total assets after balance refresh
/// @custom:access Restricted to UPDATE_MARKETS_BALANCES_ROLE (Roles.UPDATE_MARKETS_BALANCES_ROLE = 1000)
function updateMarketsBalances(uint256[] calldata marketIds_) external restricted returns (uint256) {
if (marketIds_.length == 0) {
return totalAssets();
}
uint256 totalAssetsBefore = _getNetTotalAssets();
_updateMarketsBalances(marketIds_);
_addPerformanceFee(totalAssetsBefore);
return totalAssets();
}
/// @notice Returns the number of decimals used by the vault shares
/// @dev Overrides both ERC20 and ERC4626 decimals functions to ensure consistency
///
/// Decimal Handling:
/// - Returns same decimals as underlying asset
/// - Maintains ERC20/ERC4626 compatibility
/// - Critical for share price calculations
/// - Used in conversion operations
///
/// Integration Context:
/// - Share/asset conversion
/// - Price calculations
/// - Balance representation
/// - Protocol interactions
///
/// @return uint8 Number of decimals used for share token
/// @custom:access Public view function, no role restrictions
function decimals() public view virtual override(ERC20Upgradeable, ERC4626Upgradeable) returns (uint8) {
return super.decimals();
}
/// @notice Transfers vault shares between addresses
/// @dev Overrides ERC20 transfer with additional access control
///
/// Transfer Mechanics:
/// - Validates transfer permissions
/// - Updates share balances
/// - Maintains voting power
/// - Enforces access control
///
/// Security Features:
/// - Role-based access control
/// - Balance validation
/// - State consistency checks
/// - Voting power updates
///
/// Integration Context:
/// - Share transferability
/// - Secondary market support
/// - Governance participation
/// - Protocol interactions
///
/// @param to_ Recipient address for the transfer
/// @param value_ Amount of shares to transfer
/// @return bool Success of the transfer operation
/// @custom:access Initially restricted, can be set to PUBLIC_ROLE via enableTransferShares
function transfer(
address to_,
uint256 value_
) public virtual override(IERC20, ERC20Upgradeable) restricted returns (bool) {
return super.transfer(to_, value_);
}
/// @notice Transfers vault shares from one address to another with allowance
/// @dev Overrides ERC20 transferFrom with additional access control
///
/// Transfer Mechanics:
/// - Validates transfer permissions
/// - Checks and updates allowances
/// - Updates share balances
/// - Maintains voting power
///
/// Security Features:
/// - Role-based access control
/// - Allowance validation
/// - Balance verification
/// - State consistency checks
///
/// Integration Context:
/// - Delegated transfers
/// - Protocol integrations
/// - Secondary market support
/// - Governance participation
///
/// @param from_ Address to transfer shares from
/// @param to_ Address to transfer shares to
/// @param value_ Amount of shares to transfer
/// @return bool Success of the transfer operation
/// @custom:access Initially restricted, can be set to PUBLIC_ROLE via enableTransferShares
function transferFrom(
address from_,
address to_,
uint256 value_
) public virtual override(IERC20, ERC20Upgradeable) restricted returns (bool) {
return super.transferFrom(from_, to_, value_);
}
/// @notice Deposits underlying assets into the vault
/// @dev Handles deposit validation, share minting, and fee realization
///
/// Deposit Flow:
/// 1. Pre-deposit Checks
/// - Validates deposit amount
/// - Verifies receiver address
/// - Checks deposit permissions
/// - Validates supply cap
///
/// 2. Fee Processing
/// - Realizes pending management fees
/// - Updates fee accounting
/// - Adjusts share calculations
///
/// 3. Asset Transfer
/// - Transfers assets to vault
/// - Calculates share amount
/// - Mints vault shares
/// - Updates balances
///
/// Security Features:
/// - Non-zero amount validation
/// - Address validation
/// - Reentrancy protection
/// - Access control checks
///
/// @param assets_ Amount of underlying assets to deposit
/// @param receiver_ Address to receive the minted shares
/// @return uint256 Amount of shares minted
/// @custom:security Non-reentrant and role-restricted
/// @custom:access Initially restricted to WHITELIST_ROLE, can be set to PUBLIC_ROLE via convertToPublicVault
function deposit(uint256 assets_, address receiver_) public override nonReentrant restricted returns (uint256) {
return _deposit(assets_, receiver_);
}
/// @notice Deposits assets into vault using ERC20 permit for gasless approvals
/// @dev Combines permit signature verification with deposit operation
///
/// Operation Flow:
/// 1. Permit Processing
/// - Verifies permit signature
/// - Updates token allowance
/// - Validates permit parameters
///
/// 2. Deposit Execution
/// - Processes asset transfer
/// - Calculates share amount
/// - Mints vault shares
/// - Updates balances
///
/// Security Features:
/// - Signature validation
/// - Deadline enforcement
/// - Reentrancy protection
/// - Access control checks
///
/// Integration Context:
/// - Gasless deposits
/// - Meta-transaction support
/// - ERC20 permit compatibility
/// - Vault share minting
///
/// @param assets_ Amount of assets to deposit
/// @param receiver_ Address to receive the minted shares
/// @param deadline_ Timestamp until which the signature is valid
/// @param v_ Recovery byte of the signature
/// @param r_ First 32 bytes of the signature
/// @param s_ Second 32 bytes of the signature
/// @return uint256 Amount of shares minted
/// @custom:security Non-reentrant and role-restricted
/// @custom:access Initially restricted to WHITELIST_ROLE, can be set to PUBLIC_ROLE via convertToPublicVault
function depositWithPermit(
uint256 assets_,
address receiver_,
uint256 deadline_,
uint8 v_,
bytes32 r_,
bytes32 s_
) external override nonReentrant restricted returns (uint256) {
try IERC20Permit(asset()).permit(_msgSender(), address(this), assets_, deadline_, v_, r_, s_) {
/// @dev Permit successful, proceed with deposit
} catch {
/// @dev Check if we already have sufficient allowance
if (IERC20(asset()).allowance(_msgSender(), address(this)) < assets_) {
revert PermitFailed();
}
}
return _deposit(assets_, receiver_);
}
/// @notice Mints vault shares by depositing underlying assets
/// @dev Handles share minting with management fee realization
///
/// Minting Flow:
/// 1. Pre-mint Validation
/// - Validates share amount
/// - Checks receiver address
/// - Verifies permissions
///
/// 2. Fee Processing
/// - Realizes pending management fees
/// - Updates fee accounting
/// - Adjusts share calculations
///
/// 3. Share Minting
/// - Calculates asset amount
/// - Transfers assets
/// - Mints shares
/// - Updates balances
///
/// Security Features:
/// - Non-zero amount validation
/// - Address validation
/// - Reentrancy protection
/// - Access control checks
///
/// @dev The deposit fee is a share of the gross shares, the same base as deposit: the receiver gets
/// `shares_`, the fee shares minted to the fee recipient are `shares_ * fee / (1 - fee)` rounded up,
/// so the assets paid equal what a deposit that yields `shares_` costs (IL-8743)
/// @param shares_ Number of vault shares to mint (net of the deposit fee)
/// @param receiver_ Address to receive the minted shares
/// @return depositAssets Amount of assets deposited
/// @custom:security Non-reentrant and role-restricted
/// @custom:access Initially restricted to WHITELIST_ROLE, can be set to PUBLIC_ROLE via convertToPublicVault
function mint(
uint256 shares_,
address receiver_
) public override nonReentrant restricted returns (uint256 depositAssets) {
if (shares_ == 0) {
revert NoSharesToMint();
}
if (receiver_ == address(0)) {
revert Errors.WrongAddress();
}
_realizeManagementFee();
(address feeRecipient, uint256 feeShares) = PlasmaVaultFeesLib.calculateMintDepositFee(shares_);
depositAssets = super.mint(shares_, receiver_);
if (feeShares > 0) {
super._mint(feeRecipient, feeShares);
emit DepositFeeRealized(feeRecipient, feeShares);
}
}
/// @notice Withdraws underlying assets from the vault
/// @dev Handles asset withdrawal with fee realization and market rebalancing
///
/// Withdrawal Flow:
/// 1. Pre-withdrawal
/// - Validates withdrawal amount
/// - Checks addresses
/// - Realizes management fees
/// - Records initial assets
///
/// 2. Market Operations
/// - Withdraws assets from markets
/// - Handles rounding with offset
/// - Updates market balances
/// - Processes performance fees
///
/// 3. Asset Transfer
/// - Burns vault shares
/// - Transfers assets
/// - Updates balances
/// - Validates final state
///
/// Security Features:
/// - Withdrawal limit validation
/// - Reentrancy protection
/// - Access control checks
/// - Balance verification
/// - Market safety checks
///
/// @dev The withdraw fee is a share of the gross shares burned, the same base as redeem: the shares burned
/// equal what a redeem that pays `assets_` burns (gross = net / (1 - fee), rounded up) (IL-8751)
/// @param assets_ Amount of underlying assets to withdraw
/// @param receiver_ Address to receive the withdrawn assets
/// @param owner_ Owner of the vault shares
/// @return withdrawnShares uint256 Amount of shares burned
/// @custom:security Non-reentrant and role-restricted
/// @custom:access PUBLIC_ROLE with WithdrawManager restrictions if enabled
function withdraw(
uint256 assets_,
address receiver_,
address owner_
) public override nonReentrant restricted returns (uint256 withdrawnShares) {
if (assets_ == 0) {
revert NoAssetsToWithdraw();
}
if (receiver_ == address(0) || owner_ == address(0)) {
revert Errors.WrongAddress();
}
/// @dev first realize management fee, then other actions
_realizeManagementFee();
uint256 totalAssetsBefore = _getNetTotalAssets();
address withdrawManager = PlasmaVaultStorageLib.getWithdrawManager().manager;
uint256 sharesToRelease = WithdrawManager(withdrawManager).getSharesToRelease();
uint256 withdrawFee = WithdrawManager(withdrawManager).getWithdrawFee();
uint256 assetsToWithdrawFromMarkets;
if (sharesToRelease > 0) {
/// @dev When shares are in withdrawal request, we need to withdraw more assets to cover the shares and use offset
/// @dev Offset of 0.01% (10001/10000) is added to account for potential rounding errors and price fluctuations during withdrawal
/// @dev WITHDRAW_FROM_MARKETS_OFFSET is kept so a dust release does not strip the buffer for assets_ (IL-8357)
/// @dev The WithdrawManager check needs the released shares plus the GROSS shares (fee included)
/// unallocated, so the pull is sized on the gross amount, as redeem does (IL-8751)
/// @dev WITHDRAW_FROM_MARKETS_OFFSET is grossed up together with assets_: PlasmaVault grosses up the ceil-rounded
/// shares before canWithdrawFromUnallocated (the WithdrawManager only compares), so their rounding
/// error grows by 1 / (1 - fee) and the buffer must grow with it (IL-8357, IL-8838)
assetsToWithdrawFromMarkets =
(
withdrawFee < 1e18
? PlasmaVaultFeesLib.grossUpForWithdrawFee(assets_ + WITHDRAW_FROM_MARKETS_OFFSET, withdrawFee)
: assets_ + WITHDRAW_FROM_MARKETS_OFFSET
) + (convertToAssets(sharesToRelease) * 10001) / 10000;
} else {
assetsToWithdrawFromMarkets = assets_ + WITHDRAW_FROM_MARKETS_OFFSET;
}
_withdrawFromMarkets(assetsToWithdrawFromMarkets, IERC20(asset()).balanceOf(address(this)));
_addPerformanceFee(totalAssetsBefore);
uint256 maxAssets = maxWithdraw(owner_);
if (assets_ > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner_, assets_, maxAssets);
}
uint256 sharesForAssets = super.previewWithdraw(assets_);
if (sharesForAssets == 0) {
revert NoSharesToWithdraw();
}
// The withdraw fee is a share of the gross shares, as in redeem: gross = net / (1 - fee) (IL-8751)
uint256 feeSharesToBurn = WithdrawManager(withdrawManager).canWithdrawFromUnallocated(
PlasmaVaultFeesLib.grossUpForWithdrawFee(sharesForAssets, withdrawFee)
);
withdrawnShares = sharesForAssets + feeSharesToBurn;
super._withdraw(_msgSender(), receiver_, owner_, assets_, sharesForAssets);
if (feeSharesToBurn > 0) {
if (_msgSender() != owner_) {
_spendAllowance(owner_, _msgSender(), feeSharesToBurn);
}
_burn(owner_, feeSharesToBurn);
}
}
function previewDeposit(uint256 assets_) public view override returns (uint256) {
uint256 shares = super.previewDeposit(assets_);
(, uint256 feeShares) = PlasmaVaultFeesLib.prepareForRealizeDepositFee(shares);
return feeShares > 0 ? shares - feeShares : shares;
}
/// @dev The deposit fee is a share of the gross shares, as in deposit: the caller pays for
/// shares_ / (1 - fee) shares and receives shares_ (IL-8743)
function previewMint(uint256 shares_) public view override returns (uint256) {
(, uint256 feeShares) = PlasmaVaultFeesLib.calculateMintDepositFee(shares_);
return super.previewMint(shares_ + feeShares);
}
/// @dev Priced after the pending management fee realization that redeem performs first (IL-8343)
/// @dev Prices the pending management fee only. redeem can also crystallize a pending performance fee
/// (rate above the high-water mark) and refresh stale market balances before it pays, so this can
/// overestimate the assets paid by the caller's share of that fee and of the refresh delta (IL-8489)
function previewRedeem(uint256 shares_) public view override returns (uint256) {
address withdrawManager = PlasmaVaultStorageLib.getWithdrawManager().manager;
if (withdrawManager != address(0)) {
uint256 withdrawFee = WithdrawManager(withdrawManager).getWithdrawFee();
if (withdrawFee > 0) {
shares_ = Math.mulDiv(shares_, 1e18 - withdrawFee, 1e18);
}
}
return _convertToAssetsWithSupply(shares_, _totalSupplyAfterManagementFee(), Math.Rounding.Floor);
}
/// @dev Priced after the pending management fee realization that withdraw performs first (IL-8343)
/// @dev The withdraw fee is a share of the gross shares (as in redeem): returns net / (1 - fee) rounded up,
/// type(uint256).max when the fee is 100% (nothing can be withdrawn) (IL-8751)
/// @dev Prices the pending management fee only. withdraw can also crystallize a pending performance fee
/// (rate above the high-water mark) and refresh stale market balances before it prices the burn, so
/// this can underestimate the shares burned by the caller's share of that fee and of the refresh delta (IL-8489)
function previewWithdraw(uint256 assets_) public view override returns (uint256) {
address withdrawManager = PlasmaVaultStorageLib.getWithdrawManager().manager;
uint256 shares = _convertToSharesWithSupply(assets_, _totalSupplyAfterManagementFee(), Math.Rounding.Ceil);
if (withdrawManager != address(0)) {
// Gross shares that leave `shares` after the fee: gross = shares / (1 - withdrawFee), rounded up.
// A 100% fee leaves nothing to withdraw: type(uint256).max (IL-8751)
return PlasmaVaultFeesLib.grossUpForWithdrawFee(shares, WithdrawManager(withdrawManager).getWithdrawFee());
}
return shares;
}
/// @notice Redeems vault shares for underlying assets
/// @dev Handles share redemption with fee realization and iterative withdrawal
///
/// Redemption Flow:
/// 1. Pre-redemption
/// - Validates share amount
/// - Checks addresses
/// - Realizes management fees
/// - Records initial state
///
/// 2. Asset Withdrawal
/// - Calculates asset amount
/// - Attempts market withdrawals
/// - Handles slippage protection
/// - Retries if needed (up to REDEEM_ATTEMPTS)
///
/// 3. Fee Processing
/// - Calculates performance metrics
/// - Applies performance fees
/// - Updates fee accounting
/// - Finalizes redemption
///
/// Security Features:
/// - Multiple withdrawal attempts
/// - Slippage protection
/// - Reentrancy guard
/// - Balance verification
/// - Access control checks
///
/// @param shares_ Amount of vault shares to redeem
/// @param receiver_ Address to receive the underlying assets
/// @param owner_ Owner of the vault shares
/// @return withdrawnAssets uint256 Amount of underlying assets withdrawn
/// @custom:security Non-reentrant and role-restricted
/// @custom:access PUBLIC_ROLE with WithdrawManager restrictions if enabled
function redeem(
uint256 shares_,
address receiver_,
address owner_
) public override nonReentrant restricted returns (uint256 withdrawnAssets) {
uint256 maxShares = maxRedeem(owner_);
if (shares_ > maxShares) {
revert ERC4626ExceededMaxRedeem(owner_, shares_, maxShares);
}
withdrawnAssets = _redeem(shares_, receiver_, owner_, true);
}
/// @notice Redeems shares from a previously submitted withdrawal request
/// @dev Processes redemption of shares that were part of an approved withdrawal request
///
/// Redemption Flow:
/// 1. Request Validation
/// - Verifies request exists via WithdrawManager
/// - Checks withdrawal window timing
/// - Validates share amount availability
/// - Confirms release funds timestamp
///
/// 2. Share Processing
/// - Executes share redemption
/// - Handles asset transfer
/// - Updates request state
/// - No fee application (unlike standard redeem)
///
/// Security Features:
/// - Request-based access control
/// - Withdrawal window enforcement
/// - Share amount validation
/// - State consistency checks
/// - Atomic execution
/// - Reentrancy protection: shares the ReentrancyGuard flag with deposit/mint/withdraw/redeem/execute,
/// so an instant withdrawal fuse that yields control to an external protocol during the market unwind
/// cannot re-enter the vault while totalAssets() is transiently inflated
///
/// Integration Points:
/// - WithdrawManager for request validation
/// - ERC4626 share redemption
/// - Asset transfer system
/// - Balance tracking
///
/// Important Notes:
/// - Different from standard redeem
/// - No withdrawal fee applied
/// - Requires prior request
/// - Time-window restricted
/// - Request-bound redemption
///
/// @param shares_ Amount of shares to redeem from the request
/// @param receiver_ Address to receive the underlying assets
/// @param owner_ Owner of the shares being redeemed
/// @return uint256 Amount of underlying assets transferred to receiver
/// @custom:access Restricted to accounts with valid withdrawal requests
function redeemFromRequest(
uint256 shares_,
address receiver_,
address owner_
) external override nonReentrant restricted returns (uint256) {
bool canWithdraw = WithdrawManager(PlasmaVaultStorageLib.getWithdrawManager().manager).canWithdrawFromRequest(
owner_,
shares_
);
if (!canWithdraw) {
revert WithdrawManagerInvalidSharesToRelease(shares_);
}
uint256 maxShares = maxRedeem(owner_);
if (shares_ > maxShares) {
revert ERC4626ExceededMaxRedeem(owner_, shares_, maxShares);
}
return _redeem(shares_, receiver_, owner_, false);
}
/// @notice Calculates maximum deposit amount allowed for an address
/// @dev Overrides ERC4626 maxDeposit considering total supply cap
///
/// Calculation Flow:
/// 1. Supply Validation
/// - Retrieves total supply cap
/// - Gets current total supply plus the pending management fee shares
/// - Checks available capacity
///
/// 2. Conversion Logic
/// - Calculates remaining space
/// - Converts to asset amount
/// - Handles edge cases
///
/// Constraints:
/// - Returns 0 if cap is reached
/// - Respects supply cap limits
/// - Considers share/asset ratio
/// - Maintains vault integrity
///
/// @dev Priced after the pending management fee realization that deposit performs before it checks this
/// limit: the fee shares it mints bypass the cap, so they are counted in the supply here (IL-8490)
/// @return uint256 Maximum amount of assets that can be deposited
/// @custom:access Public view function, no role restrictions
function maxDeposit(address) public view virtual override returns (uint256) {
uint256 totalSupplyCap = PlasmaVaultLib.getTotalSupplyCap();
uint256 supply = _totalSupplyAfterManagementFee();
if (supply >= totalSupplyCap) {
return 0;
}
uint256 exchangeRate = _convertToAssetsWithSupply(10 ** uint256(decimals()), supply, Math.Rounding.Floor);
(, uint256 feeShares) = PlasmaVaultFeesLib.prepareForRealizeDepositFee(totalSupplyCap - supply);
uint256 sharesToMint = totalSupplyCap - supply - feeShares;
if (type(uint256).max / exchangeRate < sharesToMint) {
return type(uint256).max;
}
return _convertToAssetsWithSupply(sharesToMint, supply, Math.Rounding.Floor);
}
/// @notice Calculates maximum number of shares that can be minted
/// @dev Overrides ERC4626 maxMint considering total supply cap
///
/// Calculation Flow:
/// 1. Supply Validation
/// - Retrieves total supply cap
/// - Gets current total supply plus the pending management fee shares
/// - Validates remaining capacity
///
/// 2. Share Calculation
/// - Computes available share space
/// - Handles cap constraints
/// - Returns maximum mintable shares
///
/// Constraints:
/// - Returns 0 if cap is reached
/// - Respects total supply limit
/// - Direct share calculation
/// - No asset conversion needed
///
/// @dev Priced after the pending management fee realization that mint performs before it checks this
/// limit: the fee shares it mints bypass the cap, so they are counted in the supply here (IL-8490)
/// @dev Returns the net shares whose gross (net plus the deposit fee, a share of the gross) fits into
/// the remaining cap, so mint(maxMint) does not exceed the cap (IL-8743)
/// @return uint256 Maximum number of shares that can be minted
/// @custom:access Public view function, no role restrictions
function maxMint(address) public view virtual override returns (uint256) {
uint256 totalSupplyCap = PlasmaVaultLib.getTotalSupplyCap();
uint256 supply = _totalSupplyAfterManagementFee();
if (supply >= totalSupplyCap) {
return 0;
}
/// @dev net shares whose gross (net plus the fee minted on top) still fits into the remaining cap (IL-8743)
return PlasmaVaultFeesLib.netSharesForRoom(totalSupplyCap - supply);
}
/// @notice Calculates maximum withdrawal amount considering withdrawal fees
/// @dev Overrides ERC4626 maxWithdraw to account for withdrawal fee deduction
/// @dev Priced after the pending management fee realization that withdraw performs before it checks
/// this limit, so withdraw(maxWithdraw(owner)) does not revert on the management fee shares it mints (IL-8319)
/// @dev Not a hard guarantee: withdraw also crystallizes a pending performance fee (rate above the high-water
/// mark, e.g. after vesting rewards, a donation or a withdraw fee burn) and refreshes stale market
/// balances before it checks this limit, neither of which is simulated here. The in-call limit can then
/// be lower by the owner's share of that fee, and withdraw(maxWithdraw(owner)) reverts with
/// ERC4626ExceededMaxWithdraw. To exit a whole position, use redeem(balanceOf(owner)) (IL-8489)
/// @dev The withdraw fee is a share of the gross shares (as in redeem and previewRedeem): the owner's
/// balance is worth balance * (1 - fee) net shares; 0 when the fee is 100% (IL-8751)
/// @param owner_ The address to calculate max withdrawal for
/// @return uint256 Maximum amount of assets that can be withdrawn
function maxWithdraw(address owner_) public view override returns (uint256) {
address withdrawManager = PlasmaVaultStorageLib.getWithdrawManager().manager;
uint256 ownerShares = balanceOf(owner_);
if (withdrawManager != address(0)) {
uint256 withdrawFee = WithdrawManager(withdrawManager).getWithdrawFee();
if (withdrawFee > 0) {
// The fee is a share of the gross shares (as in redeem): net = gross * (1 - feeRate) (IL-8751)
ownerShares = Math.mulDiv(ownerShares, 1e18 - withdrawFee, 1e18, Math.Rounding.Floor);
}
}
return _convertToAssetsWithSupply(ownerShares, _totalSupplyAfterManagementFee(), Math.Rounding.Floor);
}
/// @notice Claims rewards from integrated protocols through fuse contracts
/// @dev Executes reward claiming operations via delegatecall to fuses
///
/// Claiming Flow:
/// 1. Pre-claim Validation
/// - Validates fuse actions
/// - Checks permissions
/// - Prepares claim context
///
/// 2. Reward Processing
/// - Executes claim operations
/// - Handles protocol interactions
/// - Processes reward tokens
/// - Updates reward balances
///
/// Security Features:
/// - Reentrancy protection
/// - Role-based access
/// - Delegatecall safety
/// - Protocol validation
///
/// @param calls_ Array of FuseAction structs defining reward claim operations
/// @custom:security Non-reentrant and role-restricted
/// @custom:access Restricted to TECH_REWARDS_CLAIM_MANAGER_ROLE (managed by TECH_REWARDS_CLAIM_MANAGER_ROLE)
function claimRewards(FuseAction[] calldata calls_) external override nonReentrant restricted {
uint256 callsCount = calls_.length;
for (uint256 i; i < callsCount; ++i) {
calls_[i].fuse.functionDelegateCall(calls_[i].data);
}
}
/// @notice Returns the total assets in the vault
/// @dev ERC4626 compliant - returns gross total assets inclusive of all fees
///
/// Calculation Flow:
/// 1. Gross Assets
/// - Retrieves vault balance
/// - Adds market positions
/// - Includes pending operations
///
/// ERC4626 Compliance:
/// - Returns gross assets as per ERC4626 spec requirement that totalAssets
/// "MUST be inclusive of any fees that are charged against assets in the Vault"
/// - For net assets after fee deduction, use _getNetTotalAssets() internally
///
/// Important Notes:
/// - Excludes runtime accrued market interest
/// - Excludes runtime accrued performance fees
/// - Does NOT deduct unrealized management fees (ERC4626 compliant)
///
/// @return uint256 Gross total assets in underlying token decimals
/// @custom:access Public view function, no role restrictions
function totalAssets() public view virtual override returns (uint256) {
return _getGrossTotalAssets();
}
/// @notice Returns net total assets after unrealized management fee deduction
/// @dev Used internally for calculations that require fee-adjusted asset values
///
/// Calculation Flow:
/// 1. Gets gross total assets
/// 2. Calculates unrealized management fees
/// 3. Subtracts fees from gross total
/// 4. Returns 0 if fees exceed assets
///
/// Use Cases:
/// - Performance fee calculations (comparing before/after values)
/// - Internal accounting where fee impact matters
///
/// @return uint256 Net total assets in underlying token decimals
function _getNetTotalAssets() internal view returns (uint256) {
uint256 grossTotalAssets = _getGrossTotalAssets();
uint256 unrealizedManagementFee = PlasmaVaultFeesLib.getUnrealizedManagementFee(grossTotalAssets);
if (unrealizedManagementFee >= grossTotalAssets) {
return 0;
} else {
return grossTotalAssets - unrealizedManagementFee;
}
}
/// @notice Returns the total assets in the vault for a specific market
/// @dev Provides market-specific asset tracking without considering fees
///
/// Balance Tracking:
/// 1. Market Assets
/// - Protocol-specific positions
/// - Deposited collateral
/// - Earned yields
/// - Pending operations
///
/// Integration Context:
/// - Used by balance fuses
/// - Market limit validation
/// - Asset distribution checks
/// - Withdrawal calculations
///
/// Important Notes:
/// - Raw balance without fees
/// - Updated by balance fuses
/// - Market-specific tracking
/// - Critical for distribution
///
/// @param marketId_ Identifier of the market to query
/// @return uint256 Total assets in the market in underlying token decimals
/// @custom:access Public view function, no role restrictions
function totalAssetsInMarket(uint256 marketId_) public view virtual returns (uint256) {
return PlasmaVaultLib.getTotalAssetsInMarket(marketId_);
}
/// @notice Returns the current unrealized management fee
/// @dev Calculates accrued management fees since last fee realization
///
/// Calculation Flow:
/// 1. Fee Computation
/// - Gets gross total assets
/// - Retrieves fee configuration
/// - Calculates time-based accrual
/// - Applies fee percentage
///
/// Fee Components:
/// - Time elapsed since last update
/// - Current total assets
/// - Management fee rate
/// - Fee recipient settings
///
/// Important Notes:
/// - Pro-rata time calculation
/// - Based on current assets
/// - Unrealized until claimed
/// - Affects total assets
///
/// @return uint256 Unrealized management fee in underlying token decimals
/// @custom:access Public view function, no role restrictions
function getUnrealizedManagementFee() public view returns (uint256) {
return PlasmaVaultFeesLib.getUnrealizedManagementFee(_getGrossTotalAssets());
}
/// @notice Reserved function for PlasmaVaultBase delegatecall operations
/// @dev Prevents direct calls to updateInternal, only accessible via delegatecall
///
/// Security Features:
/// - Blocks direct execution
/// - Preserves upgrade safety
/// - Maintains access control
/// - Protects vault integrity
///
/// Error Handling:
/// - Reverts with UnsupportedMethod
/// - Prevents unauthorized updates
/// - Guards against direct calls
/// - Maintains security model
///
/// @custom:access Internal function, reverts on direct calls
function updateInternal(address, address, uint256) public {
revert UnsupportedMethod();
}
/// @notice Internal execution function for delegated protocol interactions
/// @dev Handles fuse actions without performance fee calculations
///
/// Execution Flow:
/// 1. Caller Validation
/// - Verifies self-call only
/// - Prevents external access
/// - Maintains security model
///
/// 2. Action Processing
/// - Validates fuse support
/// - Tracks affected markets
/// - Executes protocol actions
/// - Updates market balances
///
/// Security Features:
/// - Self-call restriction
/// - Fuse validation
/// - Market tracking
/// - Balance updates
///
/// @param calls_ Array of FuseAction structs defining protocol interactions
/// @custom:access Internal function, self-call only
function executeInternal(FuseAction[] calldata calls_) external {
if (address(this) != msg.sender) {
revert Errors.WrongCaller(msg.sender);
}
uint256 callsCount = calls_.length;
uint256[] memory markets = new uint256[](callsCount);
uint256 marketIndex;
uint256 fuseMarketId;
for (uint256 i; i < callsCount; ++i) {
if (!FusesLib.isFuseSupported(calls_[i].fuse)) {
revert UnsupportedFuse();
}
fuseMarketId = IFuseCommon(calls_[i].fuse).MARKET_ID();
if (_checkIfExistsMarket(markets, fuseMarketId) == false) {
markets[marketIndex] = fuseMarketId;
marketIndex++;
}
calls_[i].fuse.functionDelegateCall(calls_[i].data);
}
_updateMarketsBalances(markets);
}
function _redeem(
uint256 shares_,
address receiver_,
address owner_,
bool withFee_
) internal returns (uint256 withdrawnAssets) {
if (shares_ == 0) {
revert NoSharesToRedeem();
}
if (receiver_ == address(0) || owner_ == address(0)) {
revert Errors.WrongAddress();
}
/// @dev first realize management fee, then other actions
_realizeManagementFee();
uint256 totalAssetsBefore = _getNetTotalAssets();
address withdrawManager = PlasmaVaultStorageLib.getWithdrawManager().manager;
{
uint256 assetsToRelease = convertToAssets(WithdrawManager(withdrawManager).getSharesToRelease());
for (uint256 i; i < REDEEM_ATTEMPTS; ++i) {
_withdrawFromMarkets(
_includeSlippage(convertToAssets(shares_)) + assetsToRelease,
IERC20(asset()).balanceOf(address(this))
);
}
}
_addPerformanceFee(totalAssetsBefore);
address caller = _msgSender();
if (!withFee_) {
withdrawnAssets = convertToAssets(shares_);
_withdraw(caller, receiver_, owner_, withdrawnAssets, shares_);
} else {
uint256 feeSharesToBurn = WithdrawManager(withdrawManager).canWithdrawFromUnallocated(shares_);
withdrawnAssets = convertToAssets(shares_ - feeSharesToBurn);
if (caller != owner_) {
_spendAllowance(owner_, caller, shares_);
}
_burn(owner_, shares_);
SafeERC20.safeTransfer(IERC20(asset()), receiver_, withdrawnAssets);
emit Withdraw(caller, receiver_, owner_, withdrawnAssets, shares_);
}
}
/// @notice The share scale multiplier for ERC4626 operations
/// @dev Retrieved from storage library
function _SHARE_SCALE_MULTIPLIER() internal view returns (uint256) {
return PlasmaVaultStorageLib.getShareScaleMultiplier();
}
/// @notice Private method containing the common initialization logic
/// @param initData_ Initialization parameters encapsulated in PlasmaVaultInitData struct
/// @dev Common initialization logic of `proxyInitialize`
function _initializeVault(PlasmaVaultInitData memory initData_) private {
super.__ERC20_init(initData_.assetName, initData_.assetSymbol);
super.__ERC4626_init(IERC20(initData_.underlyingToken));
PlasmaVaultStorageLib.setShareScaleMultiplier(10 ** _decimalsOffset());
PlasmaVaultStorageLib.setPlasmaVaultBase(initData_.plasmaVaultBase);
if (initData_.plasmaVaultVotesPlugin != address(0)) {
PlasmaVaultStorageLib.setPlasmaVaultVotesPlugin(initData_.plasmaVaultVotesPlugin);
}
initData_.plasmaVaultBase.functionDelegateCall(
abi.encodeWithSelector(
IPlasmaVaultBase.init.selector,
initData_.assetName,
initData_.accessManager,
type(uint256).max /// @dev default total supply cap is max uint256
)
);
IPriceOracleMiddleware priceOracleMiddleware = IPriceOracleMiddleware(initData_.priceOracleMiddleware);
if (priceOracleMiddleware.QUOTE_CURRENCY() != USD) {
revert Errors.UnsupportedQuoteCurrencyFromOracle();
}
PlasmaVaultLib.setPriceOracleMiddleware(initData_.priceOracleMiddleware);
FeeManagerData memory feeManagerData = FeeManagerFactory(initData_.feeConfig.feeFactory).deployFeeManager(
FeeManagerInitData({
initialAuthority: initData_.accessManager,
plasmaVault: address(this),
iporDaoManagementFee: initData_.feeConfig.iporDaoManagementFee,
iporDaoPerformanceFee: initData_.feeConfig.iporDaoPerformanceFee,
iporDaoFeeRecipientAddress: initData_.feeConfig.iporDaoFeeRecipientAddress,
recipientManagementFees: new RecipientFee[](0),
recipientPerformanceFees: new RecipientFee[](0)
})
);
PlasmaVaultLib.configurePerformanceFee(feeManagerData.performanceFeeAccount, feeManagerData.performanceFee);
PlasmaVaultLib.configureManagementFee(feeManagerData.managementFeeAccount, feeManagerData.managementFee);
PlasmaVaultLib.updateManagementFeeData();
if (initData_.withdrawManager == address(0)) {
revert WithdrawManagerNotSet();
}
PlasmaVaultLib.updateWithdrawManager(initData_.withdrawManager);
}
function _deposit(uint256 assets_, address receiver_) internal returns (uint256) {
if (assets_ == 0) {
revert NoAssetsToDeposit();
}
if (receiver_ == address(0)) {
revert Errors.WrongAddress();
}
_realizeManagementFee();
uint256 sharesGross = super.convertToShares(assets_);
uint256 shares = super.deposit(assets_, receiver_);
if (shares == 0) {
revert NoSharesToDeposit();
}
address withdrawManager = PlasmaVaultStorageLib.getWithdrawManager().manager;
if (withdrawManager != address(0) && sharesGross > shares) {
super._mint(withdrawManager, sharesGross - shares);
}
return shares;
}
function _addPerformanceFee(uint256 totalAssetsBefore_) internal {
uint256 totalAssetsAfter = _getNetTotalAssets();
if (totalAssetsAfter < totalAssetsBefore_) {
return;
}
uint256 actualExchangeRate = convertToAssets(10 ** uint256(decimals()));
/// @dev FeeManager stores the high-water mark as uint128; above that bound skip the performance fee
/// instead of reverting, otherwise a donation into a dust-supply vault would block withdraw/redeem/execute
if (actualExchangeRate > type(uint128).max) {
return;
}
(address recipient, uint256 feeShares) = PlasmaVaultFeesLib.prepareForAddPerformanceFee(
totalSupply(),
decimals(),
_decimalsOffset(),
actualExchangeRate
);
if (recipient == address(0) || feeShares == 0) {
return;
}
/// @dev total supply cap validation is disabled for fee minting
PlasmaVaultLib.setTotalSupplyCapValidation(1);
_mint(recipient, feeShares);
/// @dev total supply cap validation is enabled when fee minting is finished
PlasmaVaultLib.setTotalSupplyCapValidation(0);
}
/// @notice Realizes management fees by minting shares to fee recipient
/// @dev The fee clock advances on every realization. A fee that rounds to zero shares is kept
/// in the pending management fee and minted later, so small/frequent operations cannot
/// suppress it (IL-6959), while a stale clock can never price a dormant period on assets
/// deposited later (IL-8318). With no assets or no shares there is nobody to charge,
/// so the accrual is dropped.
function _realizeManagementFee() internal {
uint256 grossTotalAssets = _getGrossTotalAssets();
/// @dev Empty vault (or dust without shareholders): drop the accrual and restart the clock
if (grossTotalAssets == 0 || totalSupply() == 0) {
PlasmaVaultStorageLib.setPendingManagementFee(0);
PlasmaVaultLib.updateManagementFeeData();
return;
}
(address recipient, uint256 unrealizedFeeInUnderlying) = PlasmaVaultFeesLib.prepareForRealizeManagementFee(
grossTotalAssets
);
uint256 unrealizedFeeInShares = convertToShares(unrealizedFeeInUnderlying);
PlasmaVaultLib.updateManagementFeeData();
if (recipient == address(0) || unrealizedFeeInShares == 0) {
/// @dev Keep the fee that rounded to zero shares for a later realization
PlasmaVaultStorageLib.setPendingManagementFee(unrealizedFeeInUnderlying);
return;
}
PlasmaVaultStorageLib.setPendingManagementFee(0);
/// @dev minting is an act of management fee realization
/// @dev total supply cap validation is disabled for fee minting
PlasmaVaultLib.setTotalSupplyCapValidation(1);
_mint(recipient, unrealizedFeeInShares);
/// @dev total supply cap validation is enabled when fee minting is finished
PlasmaVaultLib.setTotalSupplyCapValidation(0);
emit ManagementFeeRealized(unrealizedFeeInUnderlying, unrealizedFeeInShares);
}
function _includeSlippage(uint256 value_) internal pure returns (uint256) {
/// @dev increase value by DEFAULT_SLIPPAGE_IN_PERCENTAGE to cover potential slippage
return value_ + IporMath.division(value_ * DEFAULT_SLIPPAGE_IN_PERCENTAGE, 100);
}
/// @notice Withdraw assets from the markets
/// @param assets_ Amount of assets to withdraw
/// @param vaultCurrentBalanceUnderlying_ Current balance of the vault in underlying token
function _withdrawFromMarkets(uint256 assets_, uint256 vaultCurrentBalanceUnderlying_) internal {
if (assets_ == 0) {
return;
}
if (assets_ >= vaultCurrentBalanceUnderlying_) {
uint256[] memory markets = PlasmaVaultMarketsLib.withdrawFromMarkets(
asset(),
assets_,
vaultCurrentBalanceUnderlying_
);
_updateMarketsBalances(markets);
}
}
/// @notice Update balances in the vault for markets touched by the fuses during the execution of all FuseActions
/// @param markets_ Array of market ids touched by the fuses in the FuseActions
function _updateMarketsBalances(uint256[] memory markets_) internal {
DataToCheck memory dataToCheck = PlasmaVaultMarketsLib.updateMarketsBalances(
markets_,
asset(),
decimals(),
_decimalsOffset()
);
dataToCheck.totalBalanceInVault = _getGrossTotalAssets();
AssetDistributionProtectionLib.checkLimits(dataToCheck);
}
function _checkIfExistsMarket(uint256[] memory markets_, uint256 marketId_) internal pure returns (bool exists) {
for (uint256 i; i < markets_.length; ++i) {
if (markets_[i] == 0) {
break;
}
if (markets_[i] == marketId_) {
exists = true;
break;
}
}
}
function _getGrossTotalAssets() internal view returns (uint256) {
address rewardsClaimManagerAddress = PlasmaVaultLib.getRewardsClaimManagerAddress();
if (rewardsClaimManagerAddress != address(0)) {
return
IERC20(asset()).balanceOf(address(this)) +
PlasmaVaultLib.getTotalAssetsInAllMarkets() +
IRewardsClaimManager(rewardsClaimManagerAddress).balanceOf();
}
return IERC20(asset()).balanceOf(address(this)) + PlasmaVaultLib.getTotalAssetsInAllMarkets();
}
/**
* @dev Reverts if the caller is not allowed to call the function identified by a selector. Panics if the calldata
* is less than 4 bytes long.
*/
function _checkCanCall(address caller_, bytes calldata data_) internal virtual override {
/// @dev The vault's own external self-calls (e.g. UpdateBalancesPreHook -> updateMarketsBalances) are
/// authorized against the vault, not against a ContextManager context sender.
if (msg.sender == address(this)) {
caller_ = msg.sender;
}
bytes4 sig = bytes4(data_[0:4]);
bool immediate;
uint32 delay;
if (this.transferFrom.selector == sig) {
(address tranferFromAddress, , ) = abi.decode(_msgData()[4:], (address, address, uint256));
/// @dev check if the owner of shares has access to transfer
IporFusionAccessManager(authority()).canCallAndUpdate(tranferFromAddress, address(this), sig);
/// @dev check if the caller has access to transferFrom method
(immediate, delay) = IporFusionAccessManager(authority()).canCallAndUpdate(caller_, address(this), sig);
} else if (this.deposit.selector == sig || this.mint.selector == sig) {
(, address receiver) = abi.decode(_msgData()[4:], (uint256, address));
/// @dev check if the receiver of shares has access to deposit or mint and setup delay
IporFusionAccessManager(authority()).canCallAndUpdate(receiver, address(this), sig);
/// @dev check if the caller has access to deposit or mint and setup delay
(immediate, delay) = AuthorityUtils.canCallWithDelay(authority(), caller_, address(this), sig);
} else if (this.depositWithPermit.selector == sig) {
(, address receiver, , , , ) = abi.decode(
_msgData()[4:],
(uint256, address, uint256, uint8, bytes32, bytes32)
);
/// @dev check if the receiver of shares has access to depositWithPermit and setup delay
IporFusionAccessManager(authority()).canCallAndUpdate(receiver, address(this), sig);
/// @dev check if the caller has access to depositWithPermit and setup delay
(immediate, delay) = AuthorityUtils.canCallWithDelay(authority(), caller_, address(this), sig);
} else if (this.redeem.selector == sig || this.withdraw.selector == sig) {
(, , address owner) = abi.decode(_msgData()[4:], (uint256, address, address));
/// @dev check if the owner of shares has access to redeem or withdraw and setup delay
IporFusionAccessManager(authority()).canCallAndUpdate(owner, address(this), sig);
(immediate, delay) = IporFusionAccessManager(authority()).canCallAndUpdate(caller_, address(this), sig);
} else if (this.transfer.selector == sig) {
(immediate, delay) = IporFusionAccessManager(authority()).canCallAndUpdate(caller_, address(this), sig);
} else {
(immediate, delay) = AuthorityUtils.canCallWithDelay(authority(), caller_, address(this), sig);
}
if (!immediate) {
if (delay > 0) {
AccessManagedStorage storage $ = _getAccessManagedStorage();
$._consumingSchedule = true;
IAccessManager(authority()).consumeScheduledOp(caller_, data_);
$._consumingSchedule = false;
} else {
revert AccessManagedUnauthorized(caller_);
}
}
_runPreHook(sig);
}
function _msgSender() internal view override returns (address) {
return ContextClientStorageLib.getSenderFromContext();
}
function _update(address from_, address to_, uint256 value_) internal virtual override {
PLASMA_VAULT_BASE().functionDelegateCall(
abi.encodeWithSelector(IPlasmaVaultBase.updateInternal.selector, from_, to_, value_)
);
}
function _decimalsOffset() internal view virtual override returns (uint8) {
return PlasmaVaultLib.DECIMALS_OFFSET;
}
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual override returns (uint256) {
return _convertToSharesWithSupply(assets, totalSupply(), rounding);
}
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual override returns (uint256) {
return _convertToAssetsWithSupply(shares, totalSupply(), rounding);
}
function _convertToSharesWithSupply(
uint256 assets_,
uint256 supply_,
Math.Rounding rounding_
) private view returns (uint256) {
return
supply_ == 0
? assets_ * _SHARE_SCALE_MULTIPLIER()
: assets_.mulDiv(supply_ + _SHARE_SCALE_MULTIPLIER(), totalAssets() + 1, rounding_);
}
function _convertToAssetsWithSupply(
uint256 shares_,
uint256 supply_,
Math.Rounding rounding_
) private view returns (uint256) {
return
supply_ == 0
? shares_.mulDiv(1, _SHARE_SCALE_MULTIPLIER(), rounding_)
: shares_.mulDiv(totalAssets() + 1, supply_ + _SHARE_SCALE_MULTIPLIER(), rounding_);
}
/// @notice Total supply after minting the management fee shares that `_realizeManagementFee` would mint now
/// @dev Mirrors `_realizeManagementFee` exactly (same guards, same Floor rounding on the pre-mint supply), so
/// once withdraw/redeem have realized the fee this returns `totalSupply()` and their in-call checks are
/// unchanged. Used by the max/preview views that withdraw/redeem price after realization (IL-8319, IL-8343).
function _totalSupplyAfterManagementFee() private view returns (uint256 supply) {
supply = totalSupply();
uint256 grossTotalAssets = _getGrossTotalAssets();
if (grossTotalAssets == 0 || supply == 0) {
return supply;
}
(address recipient, uint256 unrealizedFeeInUnderlying) = PlasmaVaultFeesLib.prepareForRealizeManagementFee(
grossTotalAssets
);
if (recipient != address(0)) {
supply += _convertToShares(unrealizedFeeInUnderlying, Math.Rounding.Floor);
}
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"lib/ipor-fusion/contracts/vaults/PlasmaVault.sol": {
"PlasmaVaultMarketsLib": "0x3c419c8df73f674c61c49bda4463dcc35297a3da"
}
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/=lib/ipor-fusion/node_modules/@openzeppelin/",
"@chainlink/=lib/ipor-fusion/node_modules/@chainlink/",
"@uniswap/v4-core/=lib/ipor-fusion/node_modules/@uniswap/v4-core/",
"eth-gas-reporter/=node_modules/eth-gas-reporter/",
"ds-test/=lib/forge-std/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"@ipor-protocol-deploy/=contracts/",
"@ipor-fusion/=lib/ipor-fusion/",
"@ipor-protocol/=lib/ipor-protocol/",
"scripts/=scripts/",
"@eth-optimism/=lib/ipor-fusion/node_modules/@eth-optimism/",
"@ethereum-vault-connector/=lib/ipor-fusion/node_modules/ethereum-vault-connector/",
"@layerzerolabs/lz-evm-messagelib-v2/contracts/=lib/ipor-fusion/contracts/vendor/layerzero/messagelib/contracts/",
"@layerzerolabs/lz-evm-oapp-v2/contracts/=lib/ipor-fusion/contracts/vendor/layerzero/oapp/contracts/",
"@layerzerolabs/lz-evm-protocol-v2/contracts/=lib/ipor-fusion/contracts/vendor/layerzero/protocol/contracts/",
"@morpho-org/=lib/ipor-fusion/node_modules/@morpho-org/",
"@pendle/=lib/ipor-fusion/node_modules/@pendle/",
"@prb/test/=lib/ipor-fusion/lib/foundry-random/lib/prb-test/src/",
"@scroll-tech/=lib/ipor-fusion/node_modules/@scroll-tech/",
"@stargatefinance/stg-evm-v2/=lib/ipor-fusion/contracts/vendor/stargate/",
"@uniswap/v3-core/=lib/ipor-fusion/node_modules/@uniswap/v3-core/",
"CramBit/=lib/ipor-fusion/lib/foundry-random/lib/CramBit/",
"abdk-libraries-solidity/=node_modules/abdk-libraries-solidity/",
"base64-sol/=lib/ipor-fusion/node_modules/base64-sol/",
"crambit/=lib/ipor-fusion/lib/foundry-random/lib/CramBit/src/",
"erc4626-tests/=lib/ipor-fusion/node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"ethereum-vault-connector/=lib/ipor-fusion/node_modules/ethereum-vault-connector/",
"foundry-random/=lib/ipor-fusion/lib/foundry-random/src/",
"hardhat-deploy/=node_modules/hardhat-deploy/",
"hardhat/=node_modules/hardhat/",
"ipor-fusion/=lib/ipor-fusion/contracts/",
"openzeppelin-contracts/=lib/ipor-fusion/node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/",
"openzeppelin/=lib/ipor-fusion/node_modules/ethereum-vault-connector/lib/openzeppelin-contracts/contracts/",
"prb-test/=lib/ipor-fusion/lib/foundry-random/lib/prb-test/src/",
"solady/=lib/ipor-fusion/contracts/vendor/solady/src/",
"solidity-bytes-utils/=lib/ipor-fusion/contracts/vendor/solidity-bytes-utils/",
"solmate/=lib/ipor-fusion/node_modules/@uniswap/v4-core/lib/solmate/",
"src/=lib/ipor-fusion/lib/foundry-random/src/",
"test/=lib/ipor-fusion/test/fuses/hypercore/simulation/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.