> For the complete documentation index, see [llms.txt](https://docs.elara.fi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.elara.fi/protocol-reference/reference/api-reference/vault/contract.vault.md).

# Vault

[Git Source](https://github.com/TrueFi-Protocol/elara-contracts-v2/blob/9301de6eec32ceafb4021f4e7da883b507799ebc/contracts/vault/Vault.sol)

**Inherits:** [ElaraBase](https://github.com/TrueFi-Protocol/elara-contracts-v2/blob/docs/latest/contracts/base/ElaraBase.sol/abstract.ElaraBase.md), IVault

**Title:** Vault Contract

Multi-stablecoin vault for minting and redeeming elUSD

Invariants:

* Only authorized accounts can update configuration parameters
* All mint and redeem operations require KYC approval for both sender and receiver
* Stablecoin configurations are validated before transactions
* Vault maintains reserves in the treasury for redemptions
* Oracle prices must be valid and not stale when oracle pricing is enabled
* Treasury wealth maintains peg with elUSD supply: elUSD is transferred to vault on redemption and only burned when collateral leaves treasury, ensuring 1:1 backing State machine:
* Vault operates in either paused or unpaused state via {PausableUpgradeable}
* Stablecoins can be individually enabled/disabled for minting and redeeming
* Redemption can be instant (when liquidity is sufficient) or asynchronous (when liquidity is low) Access model:
* Configuration updates are restricted to authorized accounts via {AccessManagedUpgradeable}
* Functionality pause/unpause controlled by authorized accounts
* Stablecoin configuration managed by {ITokenRegistry} contract
* KYC validation performed via {IKYCRegistry} contract Upgradeability:
* Uses {ElaraBase} for UUPS upgradeability pattern
* Initializer must be called exactly once; preserve storage layout for upgrade safety
* Storage gap array prevents layout collisions in future upgrades Cross-contract dependencies:
* {IElUSD} for minting and burning elUSD tokens
* {IKYCRegistry} for validating KYC requirements
* {ITokenRegistry} for retrieving stablecoin configurations
* {PriceOracle} for fetching collateral token prices (optional) External call considerations:
* All external token transfers use {SafeERC20} for safe handling of non-standard ERC20s (reverts on failure, handles non-boolean returns) - Oracle price fetching with automatic peg protection for all stablecoins

**Note:** security-contact: <security@elara.finance>

## State Variables

### elUSD

Reference to the elUSD token contract

* Immutable after initialization; used for minting and burning elUSD tokens during vault operations
* Update via [initialize](https://github.com/TrueFi-Protocol/elara-contracts-v2/blob/docs/latest/contracts/vault/Vault.sol/contract.Vault.md#initialize) during deployment setup
* Security: Critical dependency for all vault operations

```solidity
IElUSD private elUSD
```

### treasuryAdapter

Reference to the TreasuryAdapter contract for treasury operations

* Coordinates treasury operations without holding funds
* Treasury address is managed by TreasuryAdapter
* Set at initialization; immutable after initialization
* Security: Critical for coordinating redemption operations

```solidity
ITreasuryAdapter private treasuryAdapter
```

### feeReceiver

Address receiving collected fees from mint and redeem operations

* Collects fees in collateral tokens from all vault transactions
* Set at initialization
* Security: Critical for fee collection; immutable after initialization

```solidity
address private feeReceiver
```

### oracle

Reference to the price oracle contract for token pricing

* Required oracle-based pricing mechanism for collateral tokens
* Provides dynamic pricing for mint and redeem operations
* Set during initialization and immutable thereafter
* Security: Critical dependency for accurate pricing

```solidity
IPriceOracle private oracle
```

### kycRegistry

Reference to the KYC registry contract for checking user approvals

* Validates KYC approval for all participants in mint and redeem operations
* Required for both sender and receiver addresses in transactions
* Returns true/false for KYC status via {IKYCRegistry-isKycApproved}
* Security: Critical for compliance; blocks unauthorized transactions

```solidity
IKYCRegistry private kycRegistry
```

### tokenRegistry

Reference to the token registry contract for supported stablecoin configurations

* Manages per-stablecoin configurations including fees, enabled operations, and decimal precision
* Validates stablecoin support status via {ITokenRegistry-getTokenConfig}
* Retrieves stablecoin-specific parameters for mint and redeem calculations
* Security: Critical for stablecoin validation; prevents operations with unsupported stablecoins

```solidity
ITokenRegistry private tokenRegistry
```

### stakingContract

Reference to the staking contract for yield distribution

* Address of the ElUSDStake contract that receives yield
* Set at initialization; immutable after initialization
* Security: Critical for yield distribution operations

```solidity
address private stakingContract
```

### redemptionIdCounter

Monotonic counter for redemption operations

Incremented after each redemption initiation; starts at 0

```solidity
uint256 private redemptionIdCounter
```

### queuedRedemptions

Mapping of redemption IDs to queued redemptions

Only queued redemptions are persisted; entry is deleted after settlement

```solidity
mapping(uint256 => Redemption) public queuedRedemptions
```

### elUSDDecimals

Cached ElUSD token decimals value

* Set during initialization by reading from ElUSD token contract
* Used for decimal conversions in mint and redeem calculations
* Immutable after initialization

```solidity
uint8 private elUSDDecimals
```

### oracleDecimals

Cached oracle decimals value

* Set during initialization by reading from oracle contract
* Used to ensure price calculations use correct decimal precision
* Should always be 18 for standard oracle implementation
* Immutable after initialization

```solidity
uint8 private oracleDecimals
```

### \_\_gap

Storage gap for future upgrades (EIP-1967)

```solidity
uint256[50] private __gap
```

## Functions

### initialize

Initializes shared dependencies and registries for the vault

Sets up all required external contract references for vault operations Security:

* Only callable during initialization via {initializer} modifier
* Sets up the base contract via {ElaraBase-\_\_ElaraBase\_init}
* Access control is managed by the {AccessManager} contract
* Stores references to external contracts for vault operations
* Critical for establishing vault dependencies; must be called exactly once per proxy
* TreasuryAdapter can be zero during initialization and set later via [setTreasuryAdapter](https://github.com/TrueFi-Protocol/elara-contracts-v2/blob/docs/latest/contracts/vault/Vault.sol/contract.Vault.md#settreasuryadapter)

```solidity
function initialize(
    address _accessManager,
    address _elUSD,
    address _treasuryAdapter,
    address _feeReceiver,
    address _kycRegistry,
    address _tokenRegistry,
    address _oracle,
    address _stakingContract
)
    external
    initializer;
```

**Parameters**

| Name               | Type      | Description                                            |
| ------------------ | --------- | ------------------------------------------------------ |
| `_accessManager`   | `address` | Address of the AccessManager contract                  |
| `_elUSD`           | `address` | Address of the elUSD token contract                    |
| `_treasuryAdapter` | `address` | Address of the TreasuryAdapter contract (can be zero)  |
| `_feeReceiver`     | `address` | Address receiving collected fees                       |
| `_kycRegistry`     | `address` | Address of the KYC registry contract                   |
| `_tokenRegistry`   | `address` | Address of the token registry contract                 |
| `_oracle`          | `address` | Address of the price oracle contract                   |
| `_stakingContract` | `address` | Address of the staking contract for yield distribution |

### mint

Implementation: Transfers full stablecoin amount from minter to vault first, then distributes fee to feeReceiver and principal to depositWallet. Mints ElUSD to receiver. Validates KYC for sender and receiver. Transfer flow: minter → vault (full amount), vault → feeReceiver (fee), vault → depositWallet (principal), then mints ElUSD. Emits {Minted} event.

```solidity
function mint(
    address token,
    address recipient,
    uint256 tokenAmount
)
    external
    override(IVault)
    whenNotPaused
    nonReentrant;
```

### redeem

Implementation: Transfers ElUSD to vault to maintain 1:1 peg with treasury wealth. Checks liquidity via TreasuryAdapter. If sufficient: burns ElUSD, pulls total collateral from withdrawWallet into vault, then distributes to recipient and feeReceiver. If insufficient: queues redemption for later settlement. Transfer flow (instant): withdrawWallet → vault (total), vault → recipient (principal), vault → feeReceiver (fee). Always emits {RedeemQueued}, additionally emits {RedeemSettled} for instant redemptions.

```solidity
function redeem(
    address token,
    uint256 elUSDAmount,
    address recipient
)
    public
    override(IVault)
    whenNotPaused
    nonReentrant
    returns (uint256 redemptionId);
```

### settleRedemption

Implementation: Validates redemption exists and liquidity is available. Burns ElUSD from vault balance, pulls total collateral from withdrawWallet into vault, then distributes to recipient and feeReceiver. Transfer flow: withdrawWallet → vault (total), vault → recipient (principal), vault → feeReceiver (fee). Emits {RedeemSettled}.

```solidity
function settleRedemption(uint256 redemptionId) external override(IVault) restricted whenNotPaused nonReentrant;
```

### redeem

Convenience overload: redeems elUSD for collateral (token, recipient, amount parameter order).

Delegates to {Vault-redeem(address,uint256,address)}. Same security and peg guarantees apply.

```solidity
function redeem(address token, address recipient, uint256 elUSDAmount) external whenNotPaused;
```

**Parameters**

| Name          | Type      | Description                                     |
| ------------- | --------- | ----------------------------------------------- |
| `token`       | `address` | Address of the collateral stablecoin to receive |
| `recipient`   | `address` | Recipient of the collateral tokens              |
| `elUSDAmount` | `uint256` | Amount of elUSD to redeem (18 decimals)         |

### mintYieldToStaking

Security:

* Only callable by TreasuryAdapter contract
* Mints fresh elUSD without collateral backing (intentional for yield distribution)
* Notifies staking contract via {IElUSDStake-receiveYield}
* Share price increase in staking contract happens automatically due to increased elUSD balance

```solidity
function mintYieldToStaking(uint256 amount) external override(IVault) nonReentrant;
```

### setTreasuryAdapter

Sets the treasury adapter address

Security:

* Uses {restricted} modifier to allow only authorized callers (admin role)
* Can be called after initialization to resolve circular dependency with TreasuryAdapter
* Emits [TreasuryAdapterUpdated](https://github.com/TrueFi-Protocol/elara-contracts-v2/blob/docs/latest/contracts/vault/Vault.sol/contract.Vault.md#treasuryadapterupdated) event

```solidity
function setTreasuryAdapter(address _treasuryAdapter) external restricted;
```

**Parameters**

| Name               | Type      | Description                  |
| ------------------ | --------- | ---------------------------- |
| `_treasuryAdapter` | `address` | New treasury adapter address |

### previewMint

Implementation: Retrieves token config from TokenRegistry, calculates mint fee, applies oracle price via \_calculateOracleMintAmount. Returns net collateral amount, fee amount, and resulting ElUSD amount. Reverts for unsupported tokens.

```solidity
function previewMint(
    address token,
    uint256 tokenAmount
)
    public
    view
    override
    returns (uint256 netAmount, uint256 fee, uint256 elUSDAmount);
```

### previewRedeem

Implementation: Retrieves token config from TokenRegistry, calculates redeem fee in ElUSD, applies oracle price via \_calculateOracleRedeemAmount. Checks treasury liquidity to determine if queuing is needed. Returns token amount, fee, and queue status.

```solidity
function previewRedeem(
    address token,
    uint256 elUSDAmount
)
    public
    view
    override
    returns (uint256 tokenAmount, uint256 fee, bool willBeQueued);
```

### \_calculateOracleMintAmount

Calculates the amount of elUSD to mint based on oracle pricing

Precision-critical calculation with decimal conversion **Price Decimal Conversions:**

* Oracle prices are in decimals specified by oracle.decimals()
* Example: $1.00 = 1\_000\_000\_000\_000\_000\_000 (1e18) for 18 decimal oracle **Token Decimal Handling:**
* USDC/USDT: 6 decimals - 1 USDC = 1\_000\_000 units
* USDe: 18 decimals - 1 USDe = 1\_000\_000\_000\_000\_000\_000 units
* elUSD: Output in elUSD decimals (cached at initialization) **Calculation Flow:**

1. Convert netAmount to elUSD decimals using \_toElUSD helper
2. Apply price by multiplying and dividing by oracle decimal scale
3. Result is in elUSD's decimal precision **Example with USDC at $1.01:**

* Input: 1000 USDC = 1\_000\_000\_000 units (6 decimals)
* Step 1: \_toElUSD converts to 1\_000\_000\_000\_000\_000\_000\_000 (18 decimals)
* Price: $1.01 = 1\_010\_000\_000\_000\_000\_000 (18 decimals)
* Step 2: (1e21 \* 1.01e18) / 1e18 = 1\_010\_000\_000\_000\_000\_000\_000 units = 1010 elUSD **Precision Loss Considerations:**
* Maximum precision preserved by converting to elUSD decimals first
* Dust amounts below 1 unit in token decimals will round to 0
* For USDC (6 decimals): Minimum mintable is 0.000001 USDC (1 unit)

```solidity
function _calculateOracleMintAmount(
    uint256 netAmount,
    uint8 tokenDecimals,
    uint256 price
)
    private
    view
    returns (uint256 elUSDAmount);
```

**Parameters**

| Name            | Type      | Description                                                          |
| --------------- | --------- | -------------------------------------------------------------------- |
| `netAmount`     | `uint256` | Net amount of collateral tokens after fee deduction (token decimals) |
| `tokenDecimals` | `uint8`   | Decimal precision of the collateral stablecoin (typically 6 or 18)   |
| `price`         | `uint256` | Oracle price of the collateral token (in oracle decimals)            |

**Returns**

| Name          | Type      | Description                                              |
| ------------- | --------- | -------------------------------------------------------- |
| `elUSDAmount` | `uint256` | Amount of elUSD that would be minted (in elUSD decimals) |

### \_calculateOracleRedeemAmount

Calculates the amount of collateral tokens to receive based on oracle pricing

Precision-critical calculation converting elUSD to collateral tokens **Inverse Operation of Minting:**

* This reverses the mint calculation to determine collateral output
* Converts elUSD decimal amount to variable-decimal collateral tokens **Calculation Flow:**

1. Remove price effect by scaling elUSD amount and dividing by price
2. Convert from elUSD decimals to token decimals using \_fromElUSD helper **Step-by-Step Breakdown:**
3. elUSDAmount (in elUSD decimals) represents USD value
4. Multiply by oracle decimal scale and divide by price to get token value in elUSD decimals
5. Convert from elUSD decimals to token decimals **Example - Redeeming 1000 elUSD for USDC at $0.99:**

* Input: 1000 elUSD = 1\_000\_000\_000\_000\_000\_000\_000 units (18 decimals)
* Price: $0.99 = 990\_000\_000\_000\_000\_000 (18 decimals)
* Step 1: (1e21 \* 1e18) / 0.99e18 = 1\_010\_101\_010\_101\_010\_101\_010 (18 decimals)
* Step 2: \_fromElUSD converts to 1\_010\_101\_010 units = 1010.101010 USDC (6 decimals) **Precision Considerations:**
* Division happens before decimal conversion to preserve precision
* Very small elUSD amounts may round to 0 tokens
* Price impacts: Lower price = more tokens received
* Minimum redeemable depends on token decimals and price **Edge Cases:**
* Zero price would cause division by zero (prevented by oracle validation)
* Overflow risk minimal due to realistic value ranges
* Underflow possible for dust amounts (< 1 wei equivalent)

```solidity
function _calculateOracleRedeemAmount(
    uint256 elUSDAmountAfterFee,
    uint8 tokenDecimals,
    uint256 price
)
    private
    view
    returns (uint256 tokenAmount);
```

**Parameters**

| Name                  | Type      | Description                                                        |
| --------------------- | --------- | ------------------------------------------------------------------ |
| `elUSDAmountAfterFee` | `uint256` | Amount of elUSD after fee deduction (in elUSD decimals)            |
| `tokenDecimals`       | `uint8`   | Decimal precision of the collateral stablecoin (typically 6 or 18) |
| `price`               | `uint256` | Oracle price of the collateral token (in oracle decimals)          |

**Returns**

| Name          | Type      | Description                                                              |
| ------------- | --------- | ------------------------------------------------------------------------ |
| `tokenAmount` | `uint256` | Amount of collateral tokens that would be received (in token's decimals) |

### \_validateMintOrRedeem

Validates token and KYC requirements for mint or redeem operations

Mechanics:

* Retrieves token configuration from {ITokenRegistry-getTokenConfig}
* Checks if token exists and is supported via {ITokenRegistry-TokenNotSupported}
* Validates mint or redeem is enabled for the token based on txType
* Checks KYC requirements for both sender and receiver
* Ensures transaction amount is above minimum threshold Security:
* Critical validation function for all mint and redeem operations
* Prevents transactions with unsupported tokens
* Enforces mint/redeem enabled status per token
* Validates KYC approval for both parties

```solidity
function _validateMintOrRedeem(
    address token,
    address sender,
    address recipient,
    uint256 amount,
    TxType txType
)
    private
    view;
```

**Parameters**

| Name        | Type      | Description                                                                             |
| ----------- | --------- | --------------------------------------------------------------------------------------- |
| `token`     | `address` | Address of the collateral stablecoin being validated                                    |
| `sender`    | `address` | Address of the sender initiating the transaction                                        |
| `recipient` | `address` | Address of the recipient of the transaction                                             |
| `amount`    | `uint256` | Transaction amount being validated (token decimals for mint, elUSD decimals for redeem) |
| `txType`    | `TxType`  | Type of transaction (MINT or REDEEM) to validate against                                |

### \_getStablecoinPriceForMint

Retrieves the stablecoin price for minting operations

Mechanics:

* Fetches price from oracle via {PriceOracle-getPrice}
* Caps price at $1 if above peg to protect protocol Security:
* Protects protocol from minting too much ElUSD when stablecoins trade above peg
* Critical for pricing all mint operations

```solidity
function _getStablecoinPriceForMint(address token) private view returns (uint256 price);
```

**Parameters**

| Name    | Type      | Description                                |
| ------- | --------- | ------------------------------------------ |
| `token` | `address` | Address of the stablecoin to get price for |

**Returns**

| Name    | Type      | Description                                    |
| ------- | --------- | ---------------------------------------------- |
| `price` | `uint256` | Stablecoin price for minting (oracle decimals) |

### \_getStablecoinPriceForRedeem

Retrieves the stablecoin price for redemption operations

Mechanics:

* Fetches price from oracle via {PriceOracle-getPrice}
* Floors price at $1 if below peg to protect protocol Security:
* Protects protocol from redeeming too much collateral when stablecoins depeg below $1
* Critical for pricing all redeem operations

```solidity
function _getStablecoinPriceForRedeem(address token) private view returns (uint256 price);
```

**Parameters**

| Name    | Type      | Description                                |
| ------- | --------- | ------------------------------------------ |
| `token` | `address` | Address of the stablecoin to get price for |

**Returns**

| Name    | Type      | Description                                      |
| ------- | --------- | ------------------------------------------------ |
| `price` | `uint256` | Stablecoin price for redeeming (oracle decimals) |

### \_convertDecimals

Converts an amount from one decimal precision to another

Mechanics:

* If fromDecimals equals toDecimals, returns the amount unchanged
* If fromDecimals is less than toDecimals, multiplies amount by 10^(toDecimals - fromDecimals)
* If fromDecimals is greater than toDecimals, divides amount by 10^(fromDecimals - toDecimals)
* Uses pure math operations with no state changes

```solidity
function _convertDecimals(uint256 amount, uint8 fromDecimals, uint8 toDecimals) private pure returns (uint256);
```

**Parameters**

| Name           | Type      | Description                                   |
| -------------- | --------- | --------------------------------------------- |
| `amount`       | `uint256` | Amount to convert (in fromDecimals precision) |
| `fromDecimals` | `uint8`   | Current decimal precision of the amount       |
| `toDecimals`   | `uint8`   | Target decimal precision to convert to        |

**Returns**

| Name     | Type      | Description                              |
| -------- | --------- | ---------------------------------------- |
| `<none>` | `uint256` | Converted amount in toDecimals precision |

### \_toElUSD

Converts an amount to elUSD decimal precision

Mechanics:

* Converts amount from fromDecimals precision to elUSD decimal precision
* Uses cached elUSDDecimals value set during initialization

```solidity
function _toElUSD(uint256 amount, uint8 fromDecimals) private view returns (uint256);
```

**Parameters**

| Name           | Type      | Description                                   |
| -------------- | --------- | --------------------------------------------- |
| `amount`       | `uint256` | Amount to convert (in fromDecimals precision) |
| `fromDecimals` | `uint8`   | Current decimal precision of the amount       |

**Returns**

| Name     | Type      | Description                                 |
| -------- | --------- | ------------------------------------------- |
| `<none>` | `uint256` | Amount converted to elUSD decimal precision |

### \_fromElUSD

Converts an elUSD amount to a specified decimal precision

Mechanics:

* Converts amount from elUSD decimal precision to toDecimals precision
* Uses cached elUSDDecimals value set during initialization

```solidity
function _fromElUSD(uint256 amount, uint8 toDecimals) private view returns (uint256);
```

**Parameters**

| Name         | Type      | Description                            |
| ------------ | --------- | -------------------------------------- |
| `amount`     | `uint256` | Amount in elUSD decimal precision      |
| `toDecimals` | `uint8`   | Target decimal precision to convert to |

**Returns**

| Name     | Type      | Description                              |
| -------- | --------- | ---------------------------------------- |
| `<none>` | `uint256` | Amount converted to toDecimals precision |

### \_calculateFee

Calculates fee amount based on basis points

Mechanics:

* Calculates fee as (amount \* basisPoints) / 10,000
* 10,000 represents 100% (basis points divisor)
* Uses pure math operations with no state changes

```solidity
function _calculateFee(uint256 amount, uint256 basisPoints) private pure returns (uint256);
```

**Parameters**

| Name          | Type      | Description                         |
| ------------- | --------- | ----------------------------------- |
| `amount`      | `uint256` | Base amount to calculate fee from   |
| `basisPoints` | `uint256` | Fee rate in basis points (0-10,000) |

**Returns**

| Name     | Type      | Description                                                      |
| -------- | --------- | ---------------------------------------------------------------- |
| `<none>` | `uint256` | Fee amount calculated from the base amount and basis points rate |

## Events

### VaultInitialized

Emitted when the contract is initialized

```solidity
event VaultInitialized(
    address accessManager,
    address elUSD,
    address treasuryAdapter,
    address feeReceiver,
    address kycRegistry,
    address tokenRegistry,
    address oracle,
    address stakingContract
);
```

**Parameters**

| Name              | Type      | Description                     |
| ----------------- | --------- | ------------------------------- |
| `accessManager`   | `address` | Address of the access manager   |
| `elUSD`           | `address` | Address of the ElUSD token      |
| `treasuryAdapter` | `address` | Address of the treasury adapter |
| `feeReceiver`     | `address` | Address of the fee receiver     |
| `kycRegistry`     | `address` | Address of the KYC registry     |
| `tokenRegistry`   | `address` | Address of the token registry   |
| `oracle`          | `address` | Address of the oracle           |
| `stakingContract` | `address` | Address of the staking contract |

### TreasuryAdapterUpdated

Emitted when the treasury adapter address is updated

```solidity
event TreasuryAdapterUpdated(address indexed oldTreasuryAdapter, address indexed newTreasuryAdapter);
```

**Parameters**

| Name                 | Type      | Description                       |
| -------------------- | --------- | --------------------------------- |
| `oldTreasuryAdapter` | `address` | Previous treasury adapter address |
| `newTreasuryAdapter` | `address` | New treasury adapter address      |

## Structs

### Redemption

Persisted data for a queued redemption

Written at initiation when not immediately settled; deleted upon settlement

```solidity
struct Redemption {
    /// @dev Address that initiated the redemption
    address redeemer;
    /// @dev Collateral token to be returned on settlement
    address token;
    /// @dev Amount of elUSD locked in the vault (18 decimals)
    uint256 elUSDAmount;
    /// @dev Amount of collateral to send to recipient on settlement (token decimals)
    uint256 tokenAmount;
    /// @dev Fee amount to send to feeReceiver on settlement (token decimals)
    uint256 fee;
    /// @dev Address to receive the collateral tokens on settlement
    address recipient;
}
```

## Enums

### TxType

Transaction type enumeration for fee calculations

Used to differentiate between mint and redeem operations for fee computation

```solidity
enum TxType {
    MINT,
    REDEEM
}
```
