For the complete documentation index, see llms.txt. This page is also available as Markdown.

PythPrices

📄 View Source Code

Overview

PythPrices integrates the Pyth Network oracle for high-frequency, low-latency price feeds. It provides real-time USD pricing with confidence intervals and exponential notation support for maximum precision.

Core Features:

  • Pull-Based Updates: On-demand price updates with fee optimization

  • Confidence Intervals: Price uncertainty metrics for risk assessment

  • Batch Processing: Multi-asset updates in single transaction

  • Exponential Pricing: Handles both positive and negative exponents

The module implements automatic fee calculation for updates, strict validation of price freshness and confidence, efficient caching to minimize update costs, and comprehensive error handling for failed updates.

Architecture & Dependencies

PythPrices is built using a modular architecture with direct Pyth Network integration:

Core Module Dependencies

  • LocalGov: Provides governance functionality with access control

  • Addys: Address resolution for protocol contracts

  • PriceSourceData: Asset registration and pause state management

  • TimeLock: Time-locked changes for feed management

External Integration

  • Pyth Network: Direct integration with Pyth oracle contracts

  • Pull Oracle Model: Off-chain prices brought on-chain as needed

  • Update Fee System: Automatic fee payment for price updates

Module Initialization

Immutable Configuration

Data Structures

PythPrice Struct

Raw price data from Pyth Network:

PythFeedConfig Struct

Configuration for each asset's price feed:

PendingPythFeed Struct

Tracks pending feed changes during timelock:

State Variables

Feed Configuration

  • feedConfig: HashMap[address, PythFeedConfig] - Maps assets to Pyth feed configurations

  • pendingUpdates: HashMap[address, PendingPythFeed] - Pending changes

  • maxConfidenceRatio: uint256 - Maximum allowed confidence ratio (default: percentage of price)

Constants

  • NORMALIZED_DECIMALS: constant(uint256) = 18 - Standard decimals

  • MAX_PRICE_UPDATES: constant(uint256) = 20 - Max batch updates

Inherited State

From modules:

  • Governance state (LocalGov)

  • Pause state and asset registry (PriceSourceData)

  • TimeLock configuration

System Architecture Diagram

Constructor

__init__

Initializes PythPrices with governance settings and Pyth Network address.

Parameters

Name
Type
Description

_ripeHq

address

RipeHq contract for protocol integration

_tempGov

address

Initial temporary governance address

_pythNetwork

address

Pyth Network contract address

_minPriceChangeTimeLock

uint256

Minimum timelock for feed changes

_maxPriceChangeTimeLock

uint256

Maximum timelock for feed changes

Deployment Requirements

  • Pyth Network address must not be empty

  • Contract requires ETH balance for update fees

Example Usage

Core Price Functions

getPrice

Retrieves the current price for an asset from Pyth Network.

Parameters

Name
Type
Description

_asset

address

Asset to get price for

_staleTime

uint256

Maximum age for price data in seconds. The caller is responsible for providing this value. A value of 0 disables the staleness check for this call.

_priceDesk

address

Not used in Pyth implementation

Returns

Type
Description

uint256

Normalized price in 18 decimals (0 if invalid)

Process Flow

  1. Feed Lookup: Gets Pyth feed ID for asset

  2. Price Query: Calls getPriceUnsafe for gas efficiency

  3. Validation: Checks price > 0 and not stale

  4. Exponent Handling: Normalizes to 18 decimals

  5. Confidence Adjustment: Subtracts confidence interval

Example Usage

getPriceAndHasFeed

Returns price and feed existence status.

Returns

Type
Description

uint256

Current price (0 if no feed)

bool

True if feed exists

getLastPriceAndLastUpdate

Returns the last price and last update timestamp for an asset.

Parameters

Name
Type
Description

_asset

address

Asset to get price and timestamp for

Returns

Type
Description

uint256

Last price in 18 decimals (0 if no feed)

uint256

Last update timestamp (0 if no feed)

Notes

  • Does not apply staleness checks

  • Useful for checking when price was last updated

Price Update Functions

updatePythPrice

Brings fresh price data on-chain for configured feeds. Requires ETH payment for Pyth update fee.

Parameters

Name
Type
Description

_payload

Bytes[2048]

Signed price update from Pyth

Returns

Type
Description

bool

True if update successful

Process

  1. Fee Calculation: Gets required fee from Pyth

  2. Balance Check: Ensures contract has ETH

  3. Update Call: Submits payload with fee

  4. Event Emission: Logs update details

Example Usage

updateManyPythPrices

Updates multiple price feeds in a single transaction.

Parameters

Name
Type
Description

_payloads

DynArray[Bytes[2048], MAX_PRICE_UPDATES]

Multiple updates (max 20)

Returns

Type
Description

uint256

Number of successful updates

Stops processing on first failure to save gas.

updatePythPriceNoPay

Updates a price feed without requiring ETH payment (uses contract balance).

Parameters

Name
Type
Description

_payload

Bytes[2048]

Signed price update from Pyth

Returns

Type
Description

bool

True if update successful

Access

Only callable by addresses with lite action permission (via MissionControl)

Notes

  • Uses existing contract ETH balance for fees

  • Useful for automated keepers that don't send ETH with call

Feed Management Functions

addNewPriceFeed

Initiates addition of a new Pyth price feed.

Parameters

Name
Type
Description

_asset

address

Asset to add price feed for

_feedId

bytes32

Pyth Network price feed ID

_staleTime

uint256

Maximum age for price data in seconds (0 uses MissionControl default)

Access

Only callable by governance

Validation

  • Feed must exist in Pyth Network

  • Asset must not already have a feed

  • Feed must return valid price

Events Emitted

  • NewPythFeedPending - Contains feed ID and confirmation block

Example Usage

confirmNewPriceFeed

Confirms a pending feed addition after timelock.

Process Flow

  1. Re-validation: Ensures feed still valid

  2. Timelock Check: Verifies time passed

  3. Configuration Save: Stores feed ID

  4. Asset Registration: Adds to PriceSourceData

Events Emitted

  • NewPythFeedAdded - Confirms feed is active

updatePriceFeed

Updates existing feed to new Pyth feed ID.

Used when Pyth migrates feeds or better feeds become available.

disablePriceFeed

Removes a price feed from the system.

Requires time-locked confirmation like other changes.

ETH Balance Management

recoverEthBalance

Withdraws ETH from contract (for excess update fees).

Parameters

Name
Type
Description

_recipient

address

Address to receive ETH

Access

Only callable by governance

Example Usage

Configuration Functions

setMaxConfidenceRatio

Sets the maximum allowed confidence ratio for price validation.

Parameters

Name
Type
Description

_newRatio

uint256

New max confidence ratio (must be < 100%)

Returns

Type
Description

bool

True if successfully set

Access

Only callable by Switchboard

Events Emitted

  • MaxConfidenceRatioUpdated - New ratio value

Notes

  • Ratio must be less than HUNDRED_PERCENT (100%)

  • Ratio cannot be same as current value

  • Higher ratio = more lenient confidence checks

Price Processing Details

Exponent Handling

Pyth uses flexible decimal representation:

Confidence Adjustment

Conservative pricing approach:

Staleness Check

Uses publish time, not block time:

Validation Functions

isValidNewFeed

Checks if a new feed configuration is valid.

Validation Checks

  1. No Existing Feed: Asset must not have feed

  2. Feed Exists: Must exist in Pyth Network

  3. Valid Price: Must return non-zero price

  4. Asset Valid: Non-empty address

isValidUpdateFeed

Validates feed updates with additional checks:

  • New feed must differ from current

  • Asset must have existing feed

isValidDisablePriceFeed

Ensures:

  • Feed exists

  • Asset is registered in PriceSourceData

Events

Feed Management Events

  • NewPythFeedPending - New feed initiated

  • NewPythFeedAdded - Feed confirmed

  • NewPythFeedCancelled - Addition cancelled

  • PythFeedUpdatePending - Update initiated

  • PythFeedUpdated - Update confirmed

  • PythFeedUpdateCancelled - Update cancelled

  • DisablePythFeedPending - Removal initiated

  • PythFeedDisabled - Feed removed

  • DisablePythFeedCancelled - Removal cancelled

Operational Events

  • PythPriceUpdated - Price update submitted

  • EthRecoveredFromPyth - ETH withdrawn

  • MaxConfidenceRatioUpdated - Max confidence ratio changed

All events include relevant addresses, feed IDs, and action details.

Security Considerations

Access Control

  • Governance Only: All feed management restricted

  • Public Updates: Anyone can update prices (pays fee)

  • Time-locked Changes: Prevents rushed modifications

Price Security

  • Confidence Intervals: Built-in uncertainty handling

  • Staleness Protection: Publish time validation

  • Signature Verification: Handled by Pyth Network

  • Conservative Estimates: Subtracts confidence

Integration Safety

  • Gas Efficiency: Uses getPriceUnsafe for views

  • Fee Management: Automatic fee calculation

  • Balance Checks: Prevents failed updates

  • Batch Limits: Max 20 updates per transaction

Common Integration Patterns

Price Update Automation

Multi-Asset Updates

Feed Migration

Last updated