Pyth price feeds
Suggest an editA Solana program cannot fetch a price. Someone has to bring it on chain, and the program has to decide how much to believe it. On Solana there is one more question, because the account that holds the price is also passed in by the caller: is this the feed I meant to read?
A price is a claim made by someone else
Every validator has to execute a transaction and arrive at the same result, so a program cannot make an HTTP request or read anything outside the chain. A lending protocol still needs to know what its collateral is worth in dollars. The only way that number gets on chain is that someone outside sends a transaction that writes it into an account. That someone is an oracle.
Reading an oracle is an ordinary account read. The design question is who you trust to do the writing. If the writer publishes a fake price, your program cannot tell. If the writer goes offline, your program reads an old value. Production oracle systems exist to reduce how much you have to trust any single party.
Why one source is not enough
The simplest oracle is one operator who queries one data source and writes the result on chain. Three failure modes break it:
- The source is wrong. Even reputable exchanges have brief glitches. An API returns the price of a different asset for a few seconds, or volume thins out and the last trade is far from fair value. An oracle that pulls from one place inherits every glitch from that place.
- The operator is malicious. A single party that can push any number on chain has an incentive to do so when the payoff is large enough.
- The operator goes offline. The oracle stops updating and your program keeps operating on an increasingly stale price. By the time anyone notices, positions that should have been liquidated have moved against the protocol.
How Pyth produces a price
In Pyth the data sources themselves are the publishers. Jane Street, Wintermute, Binance, OKX, Cboe Global Markets, and dozens of others run publisher software that posts their own internal prices directly to Pyth, so there are no third-party nodes scraping a public API.
The aggregation happens on Pythnet, a Solana-fork appchain dedicated to oracle data. Each publisher writes its price observation as a transaction on Pythnet. Pythnet validators aggregate the observations into a single price plus a confidence interval, after deduplication, outlier rejection, and confidence-weighted averaging across many publishers. Without Pythnet every publisher would have to write its own price to Solana mainnet and pay fees for it, and the aggregation would run on chain at a large compute cost.
Who brings the price to Solana: from push to pull
The obvious design is for the oracle to write every new price into an account on Solana, and for programs to read that account. This is the push model, and Pyth used to work this way. It has two costs. The oracle pays for a transaction on every update of every feed, whether or not anyone reads that price. And a program reads whatever was written last, so the price is only as fresh as the last update that landed.
Today Pyth works in the pull model, where the user who needs the price brings it. The client downloads the latest signed price update from Pyth's off-chain service, Hermes, and puts it in the same transaction as the action that needs it. The transaction first posts the update to an account, where Pyth's program verifies the signatures, and then your instruction reads it. The price is seconds old at the moment it is used, and nobody pays for updates that nobody reads. In exchange, the user pays for the update, and the client has to fetch it before it can build the transaction. Solana PRO covers this move as an example of role inversion.
So the price your program reads can sit in two kinds of accounts. A price update account is temporary: anyone can create one for a transaction and close it afterwards. A price feed account has a fixed address and holds a sequence of prices for one feed that only moves forward in time; the Pyth Data Association keeps a set of commonly used feeds updated this way and pays for those updates, as in the push model. Both look the same to your program, and in both cases the caller chooses which account to pass.
Three checks before you use the price
Is this the feed I meant? On Ethereum the contract itself holds the address of the price feed, fixed at deployment. On Solana the caller passes the account. Typing it as Account<'info, PriceUpdateV2> proves that the account is owned by Pyth's program, and so that Pyth's program accepted the price it holds, for some feed at some point in time. The program also accepts updates with only part of the signatures checked and records the verification level in the account, and get_price_no_older_than refuses an update that is not fully verified. Neither the owner nor the verification level says which feed, and a caller could pass a real, verified update for a different asset. The feed id has to come from your program, as a constant or a field in your own config account, and the read has to fail if the update is for another feed.
Is it recent enough? A verified update does not expire, and the caller chooses which one to pass, so without an age check the caller can pass an old price that suits them. A price feed account can also fall behind, because Solana congestion can delay updates and publishers can lag during market stress. Nothing forces a minimum update frequency on readers, so your program is responsible for checking the age of the price. get_price_no_older_than accepts the price only if its publish_time is within the window you pass. A window of 60 seconds is appropriate for most active DeFi use cases on Solana. Setting it tighter, say 10 seconds, gives you fresher data at the cost of more false rejections during brief network delays. Setting it looser, say 300 seconds, lets your protocol act on data that may no longer reflect reality. A liquidation engine needs a tight window, while a program that settles once a day can accept far older data.
Do the publishers agree? Pyth reports a price and a confidence interval in the same units. A value of price = 350000000000, conf = 10000000 with exponent -8 means that ETH/USD is about 3500.00, give or take 0.10. The interval reflects how much publishers disagree. In a calm market they converge on nearly the same price and the interval is tight. During a flash crash, an exchange outage, or a lagging publisher, they diverge and the interval widens. A program can refuse to act when the interval is wider than a threshold. The threshold depends on the application: a lending protocol with conservative liquidation parameters might require confidence within 0.5%, and a perpetual exchange willing to take a wider price band might accept 2%. A program that skips this check treats every price as equally reliable.
The price itself is an integer with an exponent, and the real value is price * 10^exponent. Check that it is positive before you cast it to an unsigned type: for a USD-quoted asset it should never be zero or negative, and a misconfigured feed is cheaper to reject here than everywhere downstream.
In code
The handler below reads BTC/USD and does all three checks. get_price_no_older_than fails if the update is older than 60 seconds, belongs to a different feed, or is not fully verified, and the last require! rejects a confidence interval wider than 1% of the price.
use pyth_solana_receiver_sdk::price_update::{get_feed_id_from_hex, PriceUpdateV2};
const BTC_USD_FEED_ID: &str =
"0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43";
#[derive(Accounts)]
pub struct ReadPrice<'info> {
pub price_update: Account<'info, PriceUpdateV2>,
}
pub fn read_price(ctx: Context<ReadPrice>) -> Result<()> {
let feed_id = get_feed_id_from_hex(BTC_USD_FEED_ID)?;
let current = ctx
.accounts
.price_update
.get_price_no_older_than(&Clock::get()?, 60, &feed_id)?;
require!(current.price > 0, OracleError::NegativePrice);
let price = current.price as u64;
require!(
current.conf.checked_mul(100).ok_or(OracleError::Overflow)? <= price,
OracleError::ConfidenceTooWide
);
Ok(())
}What to decide for every price you read
For each price your program uses, answer three questions before writing the handler. Where does the feed id come from, and can the caller influence it? How old can the price be before the action it triggers becomes unsafe? How wide can the confidence interval be? Then decide what the program does when a check fails, because refusing to act is also an outcome the protocol has to be designed for. Solana PRO's fail-fast lesson shows how Drift and Kamino set different thresholds for different actions.