> 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/architecture/contract-architecture/oracle.md).

# Oracle

`PriceOracle` provides on-chain collateral prices for the Vault's mint and redeem operations, normalised to 18-decimal precision.

**Primary source.** Official Chainlink Data Feeds, read via `AggregatorV3Interface.latestRoundData()`.

**Optional cross-check.** A secondary source may be configured per token, drawn from Pyth, RedStone, Chronicle, a Curve EMA, or a Uniswap V3 TWAP. Where a cross-check is configured and the two sources disagree, **the lower price is taken**. This is deliberately conservative: on mint it means the depositor receives no more ELUSD than the weaker price justifies, and it removes the incentive to time a deposit against a single stale feed.

Peg protection (capping and flooring at $1) is applied by the Vault on top of the raw oracle price.

***

## How it works

1. The Vault calls `PriceOracle.getPrice(token)` when a user mints or redeems.
2. `PriceOracle` calls `AggregatorV3Interface.latestRoundData()` on the configured Chainlink feed for that token.
3. The price is validated (must be positive, must not be stale) and normalized from the feed's native decimals (typically 8) to 18 decimals.
4. The normalized price is returned to the Vault, which then applies peg protection before calculating the ELUSD or collateral amount.

***

## Price normalization

Chainlink feeds report prices in 8 decimals. `PriceOracle` converts them to 18 decimals before returning:

```
normalizedPrice = rawPrice × 10^(18 − feedDecimals)
```

All callers receive prices at 18-decimal precision regardless of the underlying feed format.

***

## Staleness protection (heartbeat)

Each token has a configurable **heartbeat**: the maximum acceptable age for a price update in seconds. If the latest Chainlink round is older than the heartbeat the call reverts with `StalePrice`.

* Default heartbeat: **3600 seconds** (1 hour).
* Per-token heartbeats can be set at configuration time; passing `0` uses the default.

**There is no failover that keeps mint and redeem operating.** If the configured feed for a token is stale or unavailable, `getPrice` reverts and minting and redeeming for that token halt until it recovers. The system fails closed rather than transacting on an unreliable price. The optional cross-check exists to make the price more conservative, not to substitute for a failed primary feed.

***

## Peg protection (implemented in Vault)

The oracle returns the raw market price. The Vault adds a second layer of protection specifically for stablecoin collateral:

| Operation  | Rule                   | Effect                                                             |
| ---------- | ---------------------- | ------------------------------------------------------------------ |
| **Mint**   | Price is capped at $1  | Cannot over-mint ELUSD when a stablecoin trades above peg          |
| **Redeem** | Price is floored at $1 | Cannot extract excess collateral when a stablecoin depegs below $1 |

```
// Vault._getStablecoinPriceForMint()
effectivePrice = min(oraclePrice, ONE_DOLLAR)

// Vault._getStablecoinPriceForRedeem()
effectivePrice = max(oraclePrice, ONE_DOLLAR)
```

***

## Oracle flow

```mermaid
graph TD
    Start[Vault requests price] --> CheckType{Oracle configured?}
    CheckType -->|No| FeedNotSet[Revert: FeedNotSet]
    CheckType -->|Yes| Fetch[Call Chainlink latestRoundData]
    Fetch --> CheckStale{Age > heartbeat?}
    CheckStale -->|Yes| StalePrice[Revert: StalePrice]
    CheckStale -->|No| CheckPositive{price > 0?}
    CheckPositive -->|No| InvalidPrice[Revert: InvalidPrice]
    CheckPositive -->|Yes| Normalize[Normalize to 18 decimals]
    Normalize --> ReturnToVault[Return to Vault]
    ReturnToVault --> Op{Operation?}
    Op -->|Mint| Cap[Cap at $1]
    Op -->|Redeem| Floor[Floor at $1]
    Cap --> Calc[Calculate amount]
    Floor --> Calc
```

***

## Mainnet feed configuration

| Token | Chainlink feed                                                                                                          | Heartbeat |
| ----- | ----------------------------------------------------------------------------------------------------------------------- | --------- |
| USDC  | [`0x8fFfFfd4AfB6115b954Bd326cbe7B4BA576818f6`](https://etherscan.io/address/0x8fFfFfd4AfB6115b954Bd326cbe7B4BA576818f6) | 3600 s    |
| USDT  | Configured at deployment                                                                                                | 3600 s    |
| USDe  | Configured at deployment                                                                                                | 3600 s    |

***

## Configuration structure

```solidity
struct ChainlinkConfig {
    AggregatorV3Interface feed;  // Chainlink AggregatorV3 address
    uint256 heartbeat;           // Max acceptable price age (seconds)
    uint8 feedDecimals;          // Decimals of the Chainlink feed (typically 8)
}
```

***

## Admin functions

All admin functions require the `CONTRACT_ADMIN` role via `AccessManagerUpgradeable`.

| Function                                     | Description                                             |
| -------------------------------------------- | ------------------------------------------------------- |
| `configureChainlink(token, feed, heartbeat)` | Add or update a Chainlink feed for a token              |
| `setDefaultHeartbeat(newHeartbeat)`          | Update the fallback heartbeat used when `heartbeat = 0` |
| `deactivateToken(token)`                     | Remove pricing for a token (sets oracle type to `NONE`) |

***

## View functions

| Function               | Returns                         |
| ---------------------- | ------------------------------- |
| `getPrice(token)`      | Current price in 18-decimal USD |
| `getOracleType(token)` | `NONE` or `CHAINLINK`           |
| `decimals()`           | Always `18`                     |

***

## Errors

| Error                            | Cause                                           |
| -------------------------------- | ----------------------------------------------- |
| `FeedNotSet(token)`              | Token has no configured Chainlink feed          |
| `StalePrice(token, age, maxAge)` | Latest round is older than the heartbeat        |
| `InvalidPrice()`                 | Chainlink returned a zero or negative price     |
| `InvalidAddress(addr)`           | Zero address passed to a configuration function |

***

## Emergency response

If a Chainlink feed becomes unavailable or returns anomalous prices:

1. Pause minting and redeeming for the affected token via the Vault (`PAUSE_OPERATOR` role).
2. Monitor the Chainlink feed for recovery.
3. Communicate status to users.
4. If the feed does not recover, reconfigure or deactivate the token via `deactivateToken()`.
