The foundational components and design principles that enable Pyth Network to deliver high-fidelity, low-latency financial data on-chain.
Pyth Network Price Feeds Architecture
Core Architectural Concepts
Publisher-Collector Model
First-party data is supplied directly by over 90 major exchanges, market makers, and trading firms. These publishers sign price data with their private keys, providing cryptographic proof of origin and timestamp. This model eliminates the need for third-party aggregators, ensuring data integrity and reducing latency from the original source to the blockchain.
Pull-Based Oracle Design
On-demand price updates are fetched by applications only when needed, contrasting with continuous push models. This design minimizes on-chain gas costs and data storage. A smart contract requests the latest price, triggering an update from Pyth's off-chain aggregator. This is critical for cost-efficient DeFi protocols that don't require millisecond-level updates.
Wormhole Cross-Chain Messaging
Price attestations are broadcast as signed messages via the Wormhole protocol. This allows a single price update published on one chain (like Solana) to be securely relayed to over 30 supported blockchain ecosystems. It creates a canonical source of truth, ensuring price consistency and reducing publisher operational overhead across fragmented networks.
Confidence Interval & Status
Each price feed includes a confidence interval representing the statistical spread of publisher submissions, quantifying uncertainty. It also carries a status (e.g., TRADING, HALTED) indicating market conditions. Smart contracts can programmatically check this status and confidence to pause operations during volatile or unreliable data periods, enhancing protocol safety.
On-Chain Aggregation
Median price calculation occurs on-chain from the submitted publisher data, making the aggregation process transparent and verifiable. The protocol discards outliers and computes a robust median, resistant to manipulation from a minority of faulty publishers. This final aggregated price and confidence are then stored in the Pyth price feed account for consumer access.
Price Feed Accounts
On-chain data structures store the current price, confidence, publish timestamp, and exponent for each symbol (e.g., BTC/USD). These accounts are updated by permissioned programs upon valid pull requests. Developers interact with these accounts via client libraries, which handle the low-level logic of parsing the account data and verifying the Wormhole attestations.
Data Flow: From Source to On-Chain
Process overview of how price data is sourced, aggregated, and published to blockchains.
Primary Data Sourcing
First-party data providers submit price data directly to Pyth.
Detailed Instructions
First-party data providers, such as major exchanges and market makers, operate Pythnet publisher clients. These clients collect proprietary price data for specific assets (e.g., BTC/USD, ETH/USD) from their internal order books and trading systems. The data includes a price, confidence interval, and timestamp. Providers sign this data with their private key to prove authenticity before submission. The publisher client then sends the signed price update to the Pythnet application chain, which is a Solana-based blockchain optimized for high-frequency data aggregation.
- Sub-step 1: Configure the publisher client with the correct RPC endpoint for Pythnet.
- Sub-step 2: The client's logic determines the median price and a confidence band (e.g., ±$5) from its internal data.
- Sub-step 3: The client creates and cryptographically signs a message containing the price, confidence, publish time, and a sequence number.
rust// Example of a price attestation structure in Rust pub struct PriceAttestation { pub product_id: Pubkey, pub price: i64, pub conf: u64, pub expo: i32, pub ema_price: i64, pub ema_conf: u64, pub status: PriceStatus, pub num_publishers: u32, pub max_num_publishers: u32, pub timestamp: i64, }
Tip: The confidence interval is crucial for downstream consumers to assess the reliability of the price feed in volatile conditions.
On-Chain Aggregation on Pythnet
Multiple publisher submissions are aggregated into a single authoritative price.
Detailed Instructions
On Pythnet, a smart contract called the price feed program receives submissions from all authorized publishers for a given product. The program performs a robust aggregation algorithm to derive a single consensus price and confidence value. This algorithm is designed to be resistant to outliers and manipulation. It typically involves discarding the top and bottom quartiles of submissions and calculating a weighted median of the remaining values. The resulting aggregated price is stored in an on-chain price account alongside metadata like the number of publishers and the last update time.
- Sub-step 1: The price feed program validates the signature and authority of each incoming publisher submission.
- Sub-step 2: It filters out stale submissions (e.g., older than a few seconds) and checks the price status is "Trading".
- Sub-step 3: The aggregation logic computes the final price, confidence, and an exponential moving average (EMA).
rust// Pseudocode for the core aggregation logic let mut valid_prices: Vec<i64> = submissions.iter().filter(|s| is_valid(s)).map(|s| s.price).collect(); valid_prices.sort(); let mid = valid_prices.len() / 2; let aggregate_price = if valid_prices.len() % 2 == 0 { (valid_prices[mid - 1] + valid_prices[mid]) / 2 } else { valid_prices[mid] };
Tip: The EMA values provide a smoothed price point that is less susceptible to short-term spikes, useful for derivative protocols.
Wormhole Message Passing
The aggregated price is bridged from Pythnet to other blockchains.
Detailed Instructions
The aggregated price data on Pythnet must be made available on other supported chains like Ethereum, Avalanche, or Solana mainnet. This is achieved via the Wormhole generic messaging protocol. A special program on Pythnet, the Pyth Wormhole Contract, observes updates to the price feed accounts. When a new aggregate is posted, this contract packages the price data into a standardized Verified Action Approval (VAA) message. The VAA includes the price, confidence, timestamp, and a Merkle proof of the Pythnet state, all signed by the Wormhole network's guardian set. This signed VAA is emitted as a wormhole message.
- Sub-step 1: The Pyth Wormhole Contract on Pythnet is triggered by a price account update.
- Sub-step 2: It constructs a VAA payload containing the essential price feed data and the Pythnet state root.
- Sub-step 3: The payload is submitted to the core Wormhole bridge contract on Pythnet, which produces the signed VAA.
Tip: The VAA is the canonical, verifiable proof that can be relayed to any Wormhole-connected blockchain. Relayers watch for these messages to forward them.
On-Demand Pull by Target Chain Contracts
Applications on other chains retrieve and verify the price data.
Detailed Instructions
Final delivery uses a pull-based model. A smart contract on a consumer chain (e.g., an Ethereum DApp) does not automatically receive prices. Instead, it must call an on-chain Pyth contract (like PythOracle on Ethereum) to update and retrieve the latest price. This contract stores the signed VAAs relayed from Pythnet. The consumer contract calls an updatePriceFeeds function, providing the VAA as a byte array. The Pyth contract verifies the VAA's Wormhole guardian signatures and the Merkle proof against a known Pythnet state root. If valid, it parses and stores the new price in its local storage.
- Sub-step 1: An off-chain relayer or keeper fetches the signed VAA from the Wormhole network.
- Sub-step 2: A user or keeper transaction calls
updatePriceFeeds(bytes[] memory updateData)on the target chain's Pyth contract. - Sub-step 3: The contract performs signature verification and proof validation, then updates its internal price feed state.
solidity// Example call to update a price feed on Ethereum // updateData is the relayed VAA bytes IPyth pyth = IPyth(0x4305FB66699C3B2702D4d05CF36551390A4c69C6); bytes[] memory updateData = new bytes[](1); updateData[0] = fetchedVaaBytes; // Update the price, paying the required fee uint updateFee = pyth.getUpdateFee(updateData); pyth.updatePriceFeeds{value: updateFee}(updateData); // Now read the latest price PythStructs.Price memory price = pyth.getPrice(priceFeedId);
Tip: The pull model shifts gas costs to the end-user, making the system more efficient for protocols that don't need tick-by-tick updates.
Integration Patterns for Developers
Using the Pyth Price Service
Pythnet publishes price updates to a permissionless on-chain program, the Pyth Price Feed. The most straightforward integration involves reading these stored price updates directly from the program's account data. This pattern is ideal for smart contracts that need to execute logic based on the latest verified price, such as triggering liquidations in a lending protocol or settling a perpetual futures contract.
Key Points
- Low Latency: Contracts read the latest price posted by Pyth's oracle network with minimal delay.
- Data Verification: Each price update includes a confidence interval and a status (e.g., TRADING), allowing contracts to assess data quality.
- Permissionless Access: Any on-chain program can read the price feed data without requiring an API key or whitelist.
- Solana & EVM Support: This pattern is native on Solana and available on EVM chains via the Pyth EVM SDK, which provides a contract interface to the Wormhole-based cross-chain attestations.
Example
A Solana lending protocol like Solend would read the SOL/USD price feed to check a user's collateralization ratio. The contract calls the Pyth program to get the latest price and confidence, then uses the price value to determine if a position is undercollateralized and eligible for liquidation.
Feed Types and Data Characteristics
Comparison of Pyth Network's primary feed categories and their operational parameters.
| Characteristic | Price Feed | EMA Price Feed | Total Return Feed |
|---|---|---|---|
Update Frequency | ~400ms (Solana mainnet) | ~400ms (Solana mainnet) | Daily |
Data Point | Spot Price | Exponentially Weighted Moving Average | Price + Accrued Yield |
Primary Use Case | Real-time trading, liquidation | Oracle inputs for lending/derivatives | Index and structured products |
Publisher Count (Typical) | 30-50 per asset | 30-50 per asset | 5-15 per asset |
Confidence Interval | Yes, ~0.1% of price | Derived from underlying price | No |
Data Structure | Price, confidence, publish time | EMA price, EMA confidence | Net asset value, timestamp |
Example Asset | SOL/USD | ETH/USD EMA | stETH Total Return |
Security and Decentralization Model
Pyth Network's architecture is secured by a multi-layered model combining on-chain programs, a decentralized network of data providers, and economic incentives to ensure data integrity and liveness.
Permissionless Data Provision
Decentralized data sourcing allows any qualified entity to become a publisher. This includes exchanges, market makers, and trading firms. They contribute proprietary price data directly on-chain, creating a diverse and robust dataset. This prevents reliance on a single source and enhances censorship resistance for the feed.
On-Chain Aggregation
The Pythnet Appchain is a dedicated Solana-based blockchain where publisher data is aggregated. It uses a consensus mechanism to combine individual submissions into a single authoritative price and confidence interval. This process occurs off the target chain, reducing gas costs while maintaining cryptographic security guarantees for the final output.
Wormhole Cross-Chain Messaging
Secure data attestation is achieved via the Wormhole protocol. The aggregated price data on Pythnet is attested by its validators, creating a Verifiable Random Function (VRF) signed message. This message is relayed trust-minimally to over 30 supported blockchains. This design ensures the same high-quality data is available across ecosystems without re-aggregation.
Publisher Staking and Slashing
Economic security is enforced through a staking mechanism. Data providers stake PYTH tokens as a bond. Their submissions are continuously evaluated for accuracy and liveness. Provably malicious behavior, such as reporting stale or manipulative data, can result in slashing of their stake. This aligns publisher incentives with network honesty.
First-Party Oracle Design
Data provenance is core to the model. Price data originates directly from first-party sources—the trading venues and market makers themselves—rather than being scraped from public APIs. This provides access to higher-fidelity, low-latency data that reflects genuine trading activity and liquidity, which is critical for DeFi protocols.
Governance and Upgrades
Decentralized protocol control is managed by the PYTH token holders through on-chain governance. This community can vote on critical parameters, such as staking rewards, slashing conditions, and integrations. This ensures the network evolves in a transparent and decentralized manner, reducing central points of failure in its operational management.
Developer Workflow: Integrating a Price Feed
Process overview for fetching and using Pyth price data on-chain.
Select and Identify the Price Feed
Choose the correct price feed ID for your target asset and network.
Detailed Instructions
First, identify the price feed ID for the asset you need (e.g., BTC/USD, ETH/USD). This unique identifier is specific to each blockchain network. For Solana mainnet, the BTC/USD price feed ID is 0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43. On EVM chains like Ethereum or Arbitrum, find the corresponding proxy contract address from the Pyth documentation. You must verify the feed is active and provides the required price confidence interval and exponent for your application. Use the Pyth Network's price service API or published data sources to confirm availability.
- Sub-step 1: Visit the official Pyth documentation or data portal.
- Sub-step 2: Locate the price feed list for your target chain (e.g., Solana, Avalanche).
- Sub-step 3: Copy the exact price feed ID or contract address for integration.
Tip: Always reference the canonical Pyth sources to avoid using deprecated or incorrect feed identifiers.
Fetch the Price Data On-Chain
Interact with the Pyth contract or program to retrieve the latest price update.
Detailed Instructions
On EVM chains, you will call the getPrice or getPriceUnsafe function on the Pyth price feed proxy contract. This returns a PythStructs.Price struct containing the price, conf (confidence interval), expo (exponent), and publishTime. On Solana, you must deserialize the price account data using the pyth_sdk_solana crate or similar client library. The critical step is parsing the raw integer values using the exponent to derive the human-readable price. For example, a price of 42150000000 with an exponent of -8 represents $421.50.
- Sub-step 1: Instantiate a contract instance using the price feed's address and ABI.
- Sub-step 2: Call the
getPrice()function, which may require the price feed ID as a bytes32 parameter. - Sub-step 3: Extract the
price,conf, andexpovalues from the returned struct.
solidity// Example for EVM PythStructs.Price memory priceData = pyth.getPrice(priceFeedId); int64 scaledPrice = priceData.price; int32 exponent = priceData.expo;
Tip: Use
getPriceUnsafefor gas savings if you have an external freshness check, otherwise usegetPricewhich includes staleness verification.
Parse and Normalize the Price
Convert the on-chain integer representation into a usable decimal value.
Detailed Instructions
The raw price and confidence values are integers scaled by 10^expo. You must apply this scaling in your smart contract logic to avoid precision errors. Calculate the normalized price as price * (10 ** exponent). For negative exponents, this effectively divides the price. Always handle the confidence interval appropriately; some applications may reject updates if the confidence is too wide relative to the price, indicating low liquidity. Implement a check like require(priceData.conf * 1e4 < priceData.price, "Low precision"); to ensure data quality.
- Sub-step 1: Calculate the human-readable price:
normalizedPrice = scaledPrice * 10^(expo). - Sub-step 2: Similarly, calculate the normalized confidence:
normalizedConf = conf * 10^(expo). - Sub-step 3: Implement logic to validate the price is not stale by checking the
publishTimeagainst a threshold (e.g., last 5 minutes).
solidity// Normalization example int256 normalizedPrice = int256(scaledPrice) * (10 ** uint256(int256(exponent) + 18)); // Adjusting for typical 18-decimal precision
Tip: Consider storing prices as fixed-point numbers (e.g., with 18 decimals) to maintain consistency with other token math in your protocol.
Integrate Price into Application Logic
Use the normalized price to power your protocol's functions.
Detailed Instructions
With a validated and normalized price, integrate it into your core application logic, such as calculating collateral ratios, triggering liquidations, or settling derivatives. Design your contracts to handle price discontinuities—large jumps between updates—gracefully. Implement circuit breakers or time-weighted average price (TWAP) mechanisms if your application requires smoother price inputs. For DeFi lending, compare the fetched asset price against a loan's collateral value. For a perpetual futures contract, use the price to calculate funding rates and PnL.
- Sub-step 1: Define the business logic function that consumes the price (e.g.,
calculateHealthFactor). - Sub-step 2: Pass the normalized price and confidence values as parameters.
- Sub-step 3: Include failure modes: revert if price is stale, confidence is too high, or the price is non-positive.
solidityfunction isPositionLiquidatable(address user, bytes32 priceFeedId) public view returns (bool) { PythStructs.Price memory priceData = pyth.getPrice(priceFeedId); require(priceData.price > 0, "Invalid price"); // ... application-specific logic using priceData.price ... }
Tip: For high-value transactions, consider consuming multiple price feeds (e.g., from different providers) and using a medianizer for enhanced security.
Test and Deploy with Price Updates
Validate integration using testnet feeds and plan for live data updates.
Detailed Instructions
Thoroughly test your integration using Pyth's testnet or devnet price feeds, which publish mock data. Simulate various market conditions, including price volatility and oracle downtime. Use frameworks like Foundry or Hardhat to write tests that mock the Pyth contract responses. Ensure your contract correctly pays the required update fee if you are using the Pyth pull oracle model on EVM chains, where you must pay to request a price update. For mainnet deployment, establish a reliable method to trigger price updates—either via your own keeper, a decentralized network like Gelato, or by relying on other protocol users to pay the update fee.
- Sub-step 1: Write unit tests that interact with the official Pyth testnet contract addresses.
- Sub-step 2: Test edge cases: zero confidence, stale prices, and extreme price movements.
- Sub-step 3: Calculate and budget for the gas cost of fetching and updating prices on mainnet.
Tip: Monitor the Pyth status page and subscribe to alerts for any network upgrades or feed discontinuations that may affect your integration.
Frequently Asked Questions
Technical Resources and References
Ready to Start Building?
Let's bring your Web3 vision to life.
From concept to deployment, ChainScore helps you architect, build, and scale secure blockchain solutions.