PythPrices
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 configurationspendingUpdates: HashMap[address, PendingPythFeed]- Pending changesmaxConfidenceRatio: uint256- Maximum allowed confidence ratio (default: percentage of price)
Constants
NORMALIZED_DECIMALS: constant(uint256) = 18- Standard decimalsMAX_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
_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
_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
uint256
Normalized price in 18 decimals (0 if invalid)
Process Flow
Feed Lookup: Gets Pyth feed ID for asset
Price Query: Calls getPriceUnsafe for gas efficiency
Validation: Checks price > 0 and not stale
Exponent Handling: Normalizes to 18 decimals
Confidence Adjustment: Subtracts confidence interval
Example Usage
getPriceAndHasFeed
Returns price and feed existence status.
Returns
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
_asset
address
Asset to get price and timestamp for
Returns
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
_payload
Bytes[2048]
Signed price update from Pyth
Returns
bool
True if update successful
Process
Fee Calculation: Gets required fee from Pyth
Balance Check: Ensures contract has ETH
Update Call: Submits payload with fee
Event Emission: Logs update details
Example Usage
updateManyPythPrices
Updates multiple price feeds in a single transaction.
Parameters
_payloads
DynArray[Bytes[2048], MAX_PRICE_UPDATES]
Multiple updates (max 20)
Returns
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
_payload
Bytes[2048]
Signed price update from Pyth
Returns
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
_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
Re-validation: Ensures feed still valid
Timelock Check: Verifies time passed
Configuration Save: Stores feed ID
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
_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
_newRatio
uint256
New max confidence ratio (must be < 100%)
Returns
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
No Existing Feed: Asset must not have feed
Feed Exists: Must exist in Pyth Network
Valid Price: Must return non-zero price
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 initiatedNewPythFeedAdded- Feed confirmedNewPythFeedCancelled- Addition cancelledPythFeedUpdatePending- Update initiatedPythFeedUpdated- Update confirmedPythFeedUpdateCancelled- Update cancelledDisablePythFeedPending- Removal initiatedPythFeedDisabled- Feed removedDisablePythFeedCancelled- Removal cancelled
Operational Events
PythPriceUpdated- Price update submittedEthRecoveredFromPyth- ETH withdrawnMaxConfidenceRatioUpdated- 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