Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions OracleAggregatorArchitecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# OracleAggregator

## Requirements

- The lending protocol (ALP / FCM) depends on a single trusted oracle interface that returns either a valid price or nil if the price should not be trusted.
- The lending protocol does not contain any logic for validating prices and simply consumes the output of the trusted oracle.
- The oracle aggregator combines multiple price sources such as on-chain DEX prices and off-chain price feeds.
- A price is considered usable only if the sources are reasonably aligned within a configurable tolerance and recent price changes are not anomalous.
- If sources diverge beyond tolerance or show suspicious short-term volatility, the aggregator returns nil and the protocol skips actions like liquidation or rebalancing.
- Governance is responsible for configuring which sources are used and what tolerances apply, not the lending protocol itself.
- This separation is intentional so the lending protocol remains reusable and does not encode assumptions about specific oracle implementations.

---
# Design draft: The following sections outline ideas that are still being designed.

## Aggregate price

To avoid the complexity of calculating a median, we instead use a trimmed mean: removing the maximum and minimum values to protect against "oracle jitter."

## Oracle spread

A **Pessimistic Relative Spread** calculation is used. This measures the distance between the most extreme values in the oracles ($Price_{max}$ and $Price_{min}$) relative to the lowest value.

$$
\text{Spread} = \frac{Price_{max} - Price_{min}}{Price_{min}}
$$

A price set is considered **Coherent** only if the calculated spread is within the configured tolerance ($\tau$):

$$
\text{isCoherent} =
\begin{cases}
\text{true} & \text{if } \left( \frac{Price_{max} - Price_{min}}{Price_{min}} \right) \le \tau \\
\text{false} & \text{otherwise}
\end{cases}
$$
## Short-term volatility

The oracle maintains a ring buffer of the last `n` aggregated prices with timestamps,
respecting `minTimeDelta` and `maxTimeDelta`.
Prices are collected on calls to `price()`.
If multiple updates occur within the same `minTimeDelta`, only the most recent price is retained.

The pessimistic relative price move is:

$$
\text{Move} = \frac{Price_{max} - Price_{min}}{Price_{min}}
$$

The price history is considered **Stable** only if the move is below the configured
maximum allowed move.

$$
\text{isStable} =
\begin{cases}
\text{true} & \text{if } \text{Move} \le \text{maxMove} \\
\text{false} & \text{otherwise}
\end{cases}
$$
131 changes: 131 additions & 0 deletions cadence/contracts/FlowOracleAggregatorV1.cdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import "FlowToken"
import "DeFiActions"

access(all) contract FlowOracleAggregatorV1 {

access(all) entitlement Governance

access(all) struct PriceOracleAggregator: DeFiActions.PriceOracle {
access(contract) var uniqueID: DeFiActions.UniqueIdentifier?
access(self) let unit: Type
access(all) let oracles: [{DeFiActions.PriceOracle}]

access(all) var maxSpread: UFix64

init(uniqueID: DeFiActions.UniqueIdentifier?, unitOfAccount: Type, maxSpread: UFix64) {
self.uniqueID = uniqueID
self.unit = unitOfAccount
self.oracles = []
self.maxSpread = maxSpread
}

access(all) view fun unitOfAccount(): Type {
return self.unit
}

access(all) view fun id(): UInt64? {
return self.uniqueID?.id
}

access(all) fun price(ofToken: Type): UFix64? {
let prices = self.getPrices()
if prices.length == 0 {
return nil
}
let minAndMaxPrices = self.getMinAndMaxPrices(prices: prices)
if !self.isWithinSpreadTolerance(minPrice: minAndMaxPrices.minPrice, maxPrice: minAndMaxPrices.maxPrice) {
return nil
}
return self.trimmedMeanPrice(prices: prices, minPrice: minAndMaxPrices.minPrice, maxPrice: minAndMaxPrices.maxPrice)
}

access(all) fun getID(): DeFiActions.UniqueIdentifier? {
return self.uniqueID
}

access(contract) fun setID(_ id: DeFiActions.UniqueIdentifier?) {
self.uniqueID = id
}

access(all) fun getComponentInfo(): DeFiActions.ComponentInfo {
return DeFiActions.ComponentInfo(
type: self.getType(),
id: self.id(),
innerComponents: []
)
}

access(contract) view fun copyID(): DeFiActions.UniqueIdentifier? {
return self.uniqueID
}

access(Governance) fun setMaxSpread(_ maxSpread: UFix64) {
self.maxSpread = maxSpread
}

access(self) fun getMaxSpread(): UFix64 {
return self.maxSpread
}

access(self) fun getPrices(): [UFix64] {
let prices: [UFix64] = []
for oracle in self.oracles {
let price = oracle.price(ofToken: self.unit)
prices.append(price!)
}
return prices
}

access(self) fun getMinAndMaxPrices(prices: [UFix64]): MinAndMaxPrices {
var minPrice = UFix64.max
var maxPrice = UFix64.min
for price in prices {
if price < minPrice {
minPrice = price
}
if price > maxPrice {
maxPrice = price
}
}
return MinAndMaxPrices(minPrice: minPrice, maxPrice: maxPrice)
}

access(self) view fun trimmedMeanPrice(prices: [UFix64], minPrice: UFix64, maxPrice: UFix64): UFix64? {
switch prices.length {
case 0:
return nil
case 1:
return prices[0]
case 2:
return (prices[0] + prices[1]) / 2.0
}
var sum = 0.0
for price in prices {
if price != minPrice && price != maxPrice {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If prices is [3,3,3,3,3], all same values, we would trim too many values.

sum = sum + price
}
}
sum = sum - (minPrice + maxPrice)
return sum / UFix64(prices.length - 2)
}

access(self) view fun isWithinSpreadTolerance(minPrice: UFix64, maxPrice: UFix64): Bool {
let spread = (maxPrice - minPrice) / minPrice
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what if minPrice is 0?

return spread <= self.maxSpread
}
}

access(all) fun createPriceOracleAggregator(uniqueID: DeFiActions.UniqueIdentifier?, unitOfAccount: Type, maxSpread: UFix64): PriceOracleAggregator {
return PriceOracleAggregator(uniqueID: uniqueID, unitOfAccount: unitOfAccount, maxSpread: maxSpread)
}

access(all) struct MinAndMaxPrices {
access(all) let minPrice: UFix64
access(all) let maxPrice: UFix64

init(minPrice: UFix64, maxPrice: UFix64) {
self.minPrice = minPrice
self.maxPrice = maxPrice
}
}
}
42 changes: 42 additions & 0 deletions cadence/tests/oracle_aggregator_test.cdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import Test
import BlockchainHelpers

import "FlowOracleAggregatorV1"
import "DeFiActions"
import "FlowToken"
import "test_helpers.cdc"

access(all) var snapshot: UInt64 = 0

access(all) fun setup() {
deployContracts()
var err = Test.deployContract(
name: "FlowOracleAggregatorV1",
path: "../contracts/FlowOracleAggregatorV1.cdc",
arguments: []
)
Test.expect(err, Test.beNil())

snapshot = getCurrentBlockHeight()
Test.commitBlock()
}

access(all) fun beforeEach() {
Test.reset(to: snapshot)
}

access(all) fun test_create_aggregator() {
let aggregator = FlowOracleAggregatorV1.createPriceOracleAggregator(
uniqueID: DeFiActions.createUniqueIdentifier(),
unitOfAccount: Type<@FlowToken.Vault>(),
maxSpread: 0.05
)
}

access(all) fun test_create_aggregator() {
let aggregator = FlowOracleAggregatorV1.createPriceOracleAggregator(
uniqueID: DeFiActions.createUniqueIdentifier(),
unitOfAccount: Type<@FlowToken.Vault>(),
maxSpread: 0.05
)
}
6 changes: 6 additions & 0 deletions flow.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@
"testing": "0000000000000007"
}
},
"FlowOracleAggregatorV1": {
"source": "./cadence/contracts/FlowOracleAggregatorV1.cdc",
"aliases": {
"testing": "0000000000000007"
}
},
"MockDexSwapper": {
"source": "./cadence/contracts/mocks/MockDexSwapper.cdc",
"aliases": {
Expand Down