Skip to main content
OracleV3 validates every swap against external price feeds before execution, preventing trades at manipulated or stale prices. The oracle aggregates multiple data sources, maintains time-weighted average prices (TWAP), and automatically halts trading when deviation exceeds configured thresholds.

Price Feed Architecture

The oracle consumes price data from bank-provided feeds through the BankFeedAdapter, which validates cryptographic signatures before accepting updates. Each financial institution operates their own price feed with configurable staleness limits and confidence scores.
// Banks sign price updates off-chain using EIP-712
const priceUpdate = {
    assetId: keccak256(stockISIN),
    price: 15025000000, // $150.25 with 8 decimals
    confidence: 9500,   // 95% confidence
    timestamp: Date.now() / 1000,
    nonce: currentNonce + 1
};

const signature = await bankSigner.signTypedData(
    domain,
    types,
    priceUpdate
);

// Submit to chain
await bankFeedAdapter.updateFeedWithSignature(
    stockISIN,
    priceUpdate.price,
    priceUpdate.confidence,
    priceUpdate.timestamp,
    priceUpdate.nonce,
    signature
);
Primary and backup feeds provide redundancy. If the primary feed fails or becomes stale, the oracle automatically queries backup feeds before rejecting swaps.

Deviation Detection

Before every swap, the oracle compares AMM-calculated prices against feed prices to detect manipulation or unexpected divergence.
Price ComparisonDeviationAction
AMM: 100,Oracle:100, Oracle: 1011%Execute - within threshold
AMM: 100,Oracle:100, Oracle: 1055%Execute - high but acceptable
AMM: 100,Oracle:100, Oracle: 11515%Halt - exceeds max deviation
AMM: $100, Oracle: StaleN/ACached price with higher slippage
Configure maximum deviation per asset based on typical volatility and liquidity. Highly liquid securities may use 2-3% thresholds while illiquid assets require 5-10% tolerance to accommodate wider bid-ask spreads.
The oracle calculates absolute percentage deviation between prices:
function calculateDeviation(
    ammPrice: bigint,
    oraclePrice: bigint
): bigint {
    if (oraclePrice === 0n) return 10000n; // 100%
    
    const difference = ammPrice > oraclePrice
        ? ammPrice - oraclePrice
        : oraclePrice - ammPrice;
    
    // Return basis points (10000 = 100%)
    return (difference * 10000n) / oraclePrice;
}
If deviation exceeds the asset’s maxDeviation setting, the oracle emits a DeviationAlert event and halts pool trading. Administrators must manually resume trading through resumeTrading after investigating the cause.Common deviation triggers include:
  • Flash loan attacks temporarily skewing AMM prices
  • Stale oracle feeds during rapid price movements
  • Low liquidity enabling price manipulation
  • News events causing sudden external market moves
  • Technical issues with feed infrastructure

Time-Weighted Average Pricing (TWAP)

The oracle maintains rolling TWAP windows to smooth short-term price volatility and provide more stable reference prices. Each asset stores 30 price samples at regular intervals, weighted by age.
prices
uint256[]
Array of historical prices sampled at regular intervals
timestamps
uint256[]
Corresponding timestamps for each price sample
currentIndex
uint256
Current position in circular buffer, wraps to 0 after filling
lastUpdate
uint256
Timestamp of most recent TWAP update for staleness detection
Query TWAP prices with customizable windows—shorter windows (5-15 minutes) track recent trends while longer windows (30-60 minutes) smooth volatility.
// GET https://api.trusset.org/v1/trading/oracle/twap

const response = await fetch(
  `https://api.trusset.org/v1/trading/oracle/twap?assetId=${assetId}&window=1800`,
  {
    headers: { 'Authorization': `Bearer ${API_KEY}` }
  }
);

const { price, isStale } = await response.json();
// price: weighted average over last 30 minutes
// isStale: true if no recent updates within window

Market Hours Detection

The oracle recognizes traditional market hours (14:00-21:00 UTC, Monday-Friday) and applies different validation rules during after-hours trading.
Standard validation rules apply—use current oracle prices with configured deviation thresholds. Expect tightest spreads and most accurate pricing during these hours.
Market hour detection uses UTC timezone and doesn’t account for holidays automatically. Administrators can manually adjust trading status during exchange closures or special circumstances.

Feed Configuration

Configure oracle behavior per asset including staleness limits, deviation thresholds, and fallback feeds.
configureAssetWithStock
function
Link asset identifier (ISIN) to stock token address and configure all pricing parameters
setPrimaryFeed
function
Designate primary price feed adapter as main data source
setBackupFeed
function
Configure fallback feed for redundancy when primary feed fails
setMaxStaleness
function
Maximum age in seconds before considering price data stale (typically 300-600s)
setMaxDeviation
function
Maximum acceptable difference between AMM and oracle prices in basis points
All configuration changes route through TimelockController, preventing immediate modifications that could disrupt active trading.

Trading Halts

Automatic trading halts occur when oracle validation fails. Halts prevent execution at incorrect prices but don’t affect existing liquidity positions or pending limit orders.
Automatic Halt Conditions:
  • Deviation exceeds configured threshold
  • Both primary and backup feeds stale
  • Underlying stock delisted or halted
  • Oracle detects potential manipulation
Manual Halt Triggers:
  • Regulatory requirements or court orders
  • Security incidents in token or pool contracts
  • Unusual trading patterns under investigation
  • Coordinated halts matching traditional exchange suspensions
Resolution Process:
  1. Identify and resolve root cause (feed restoration, investigation completion)
  2. Validate prices match expected ranges
  3. Submit resumeTrading transaction through timelock
  4. Monitor first swaps after resumption for anomalies
Trading resumes immediately after resumeTrading execution. All pending transactions can proceed once pool active status restores.

Price Caching

The oracle caches the most recent valid price for each asset, enabling continued operation during temporary feed outages. Cached prices serve as fallback values with increased slippage tolerance.
price
uint256
Most recent validated price from any feed source
timestamp
uint256
When this price was recorded, used for staleness detection
confidence
uint256
Feed confidence score at time of caching (basis points)
lastClose
uint256
Previous market close price, used during after-hours trading
Cached prices expire based on configured staleness limits. After expiration, the oracle rejects swaps until fresh feed data arrives, preventing execution on potentially incorrect historical prices.
Oracle prices use 8 decimal precision (1e8 = $1.00) matching financial data standards. Ensure proper decimal conversion when comparing against token balances or pool calculations which typically use 18 decimals.