39 min read
Overview
An xStock, a token that tracks the price of one US-listed stock or exchange-traded fund (ETF), trades on Solana around the clock, while the stock behind it trades for six and a half hours on a weekday. The two prices drift apart, and anyone holding or trading the token has the same questions. Is the token cheap or expensive against the stock right now, what would an order of a given size cost, and is new money arriving or leaving? A live dashboard fed by Solana gRPC can answer them. A block explorer can't, because the answers sit across more than 1,500 mints, every decentralized exchange (DEX) that lists them, and a stock price that lives offchain.
This guide walks through a sample app that answers those questions live. It streams every xStocks mint with Solana gRPC, decodes each transaction into a trade, transfer, mint, or redemption, and turns the result into a dashboard of pricing, cost, and flow signals.
Note: This guide is for educational purposes only. Quicknode does not provide financial advice or endorse any trading strategies. Always do your own research before making any investment decisions.
- xStocks are tokenized US stocks and ETFs that trade on Solana at all hours, so each token's price can sit above or below the price of its stock
- Solana gRPC compressed filters let one subscription cover all 1,500+ xStocks mints, where a standard filter accepts 10 to 50 addresses
- The sample app decodes transactions from token balance changes and compares onchain prices with stock prices and live swap quotes
- This guide builds a TypeScript server and React dashboard that show each ticker's gap to its stock, the cost to buy by order size, mint and redeem flows, and upcoming dividends and splits
What You Will Need
This guide assumes familiarity with TypeScript and with how Solana transactions, token accounts, and Token-2022 extensions work. Readers new to Solana gRPC can start with Monitor Solana Programs with Solana gRPC.
The guide also requires:
- Node.js v24+
- pnpm, which installs the versions pinned in the repository's lockfile
- A Quicknode account with a Solana mainnet endpoint that has Solana gRPC enabled. Solana gRPC is included with Scale and Business plans.
- Git and a code editor
- A free Jupiter API key, used for stock prices, swap quotes, and DEX labels
The sample app uses the following dependencies:
| Dependency | Version |
|---|---|
@triton-one/yellowstone-grpc | 10.0.0 |
@solana/kit | 8.6.0 |
@solana-program/token-2022 | 0.20.1 |
bs58 | 6.0.0 |
react | 19.3.1 |
vite | 8.3.8 |
concurrently | 10.0.7 |
tsx | 4.23.15 |
typescript | 5.9.3 |
Use @triton-one/yellowstone-grpc v10 or later. Compressed filters need v5.0.9, and reading version 1 transactions needs v6.0.0. Close to half of xStocks transactions are version 1, and an older client loses their compute and fee settings while decoding without reporting an error.
What Are xStocks?
xStocks are tokens issued by Backed that each track one US-listed stock or ETF. NVDAx tracks Nvidia and SPYx tracks the SPDR S&P 500 ETF. On Solana, every xStock is a Token-2022 mint with the Scaled UI Amount extension, and all of them share one mint authority.
Four properties of these tokens shape the dashboard's design:
One mint authority covers every xStock. The issuer key 7pt9tkctJPK7PPNQJ77GKg8ZffSF6QxoMiCFYHxrtaCj is the mint authority of all of them. A single filter on that key finds the full set, including tickers listed after deployment.
The set is too large for a standard subscription. Standard Solana gRPC filters accept 10 to 50 pubkeys depending on the plan. Tracking over 1,500 mints requires compressed filters, which encode the whole set into a cuckoo filter of about 8 KiB.
Balances rebase. xStocks use the Scaled UI Amount extension. Each mint stores a multiplier, and the share count a holder sees is the raw token amount times that multiplier. Backed raises the multiplier when the underlying stock pays a dividend and changes it sharply for a split. Raw amounts in transaction data do not include the multiplier, so the app applies it to every amount it displays.
The token price floats against the stock. Nothing pins a DEX price to the stock price from one trade to the next. The gap between them is the premium, and it widens most when US markets are closed and the stock price stands still. Minting is what pulls a premium back. When a token trades above its stock, newly minted tokens add supply at the higher price, so the dashboard watches mints and redemptions as closely as trades.
Trading on centralized exchanges that list xStocks happens offchain. Only deposits to and withdrawals from those exchanges reach Solana, and they appear in the dashboard as transfers.
What Does the xStocks Dashboard Show?
The xStocks dashboard is made up of nine panels, each showing one set of live data from the app: alerts, the gap to stock over time, the gap by ticker, where tokens go, volume by ticker, trading pace, the cost to buy by order size, net minting and redemption, and upcoming dividends and splits.
Each panel answers one question a trader, analyst, or holder would ask, and each has a "How this is worked out" note in the app that explains its math. The panels below appear in the order the page shows them.
Alerts

The alerts panel lists tickers that trade unusually low against their own stock price during US market hours. Each row gives the gap, the cost of a $10,000 buy against the stock, how many standard deviations the gap sits below that ticker's usual gap, the best route, and how long the condition has held.
The data behind it: the gap signals from the transaction stream and the Jupiter Price API, checked against a live $10,000 quote from the Jupiter Swap API. A ticker appears only when its gap is two or more standard deviations below normal and at least 0.25% under the stock, the quote still lands below the stock, the stock price is under 30 seconds old, the token traded in the last 5 minutes, and the condition has held for a minute. Flag Tickers Trading Below the Stock builds it.
Gap to Stock over Time

The headline chart plots the four busiest tickers' gap to their stock price, where 0% means the token trades at the same price as the stock. Shaded bands mark US market hours. Markers show tokens minted (▲), tokens redeemed (▼), and dividends or splits (◆), so a reader can watch a gap close after new supply arrives. The chart accepts up to 12 tickers.
The data behind it: the token price is the volume-weighted price of exchange trades from the transaction stream, sampled every 15 seconds. The stock price comes from the Jupiter Price API. A gray dashed line means the stock price is over 5 minutes old. A ticker with no trade in 15 minutes has no gap until it trades again. Sample Gaps Every 15 Seconds builds it.
Gap by Ticker

This table ranks the 10 busiest tickers by gap, widest first, with a band marking 0.5% either side of the stock price. "Is that normal?" says whether today's gap is typical or unusual for that ticker. "Gaps usually close in" gives the typical time from the first new tokens being minted to the gap returning to normal. A short time means arbitrage is working for that ticker. A gap prefixed with ~ is approximate because the stock price is over 30 seconds old, and a grayed gap rests on a stock price over 5 minutes old.
The data behind it: the same 15-second gap samples as the chart. The app compares each gap with the ticker's own gaps since startup and counts two standard deviations or more as unusual. Close times come from mint events in the transaction stream. Compare Each Gap to Normal and Time How Fast Gaps Close build it.
Where Tokens Go

This panel splits all token movement into exchange trades, wallet transfers, lending, pool deposits, and mints or redemptions, with a dollar total for each. Deposits to centralized exchanges such as Kraken and Bybit show up as wallet transfers, because the app has no address labels.
The data behind it: every event the classifier decodes from the transaction stream. Transfers and mints are valued at the stock price. Classify Transactions from Balance Changes builds it.
Volume by Ticker

This bar list ranks tickers by dollar volume of exchange trades. It shows the top 11 and groups the rest as Others. Clicking a bar opens that ticker's page.
The data behind it: trade events from the transaction stream, summed in dollars over the selected time window. Classify Transactions from Balance Changes builds it.
Trading Pace

"Trading pace" compares each ticker's dollar volume in the last 5 minutes with its average 5-minute volume since the app started, and highlights tickers trading at twice that rate or more. "Move since the close" fills in while the US market is closed. It shows how far the token has moved from the last stock price seen during market hours, an early read on onchain sentiment that is not a forecast of the opening price.
The data behind it: trade events from the transaction stream for the pace, and the last in-session stock price from the Jupiter Price API for the move. Measure Trading Pace and Compute the Move Since the Close build it.
Cost to Buy by Order Size

This table shows what a $1,000, $10,000, and $50,000 USDC buy would cost on the five busiest tickers, as a percentage above or below the stock price, along with the best route. Each figure includes both the current gap and the extra cost of the order's size. A negative figure means the token is cheaper than the stock.
The data behind it: quotes from the Jupiter Swap API, refreshed once a minute, compared with the stock price from the Jupiter Price API. When the stock price is over 5 minutes old, the larger sizes are compared with the $1,000 quote instead. With no $1,000 quote either, only the price is shown. Quote the Cost to Buy by Order Size builds it.
Minted and Redeemed

This diverging bar chart shows net dollars minted (right) or redeemed (left) per ticker. Minting is how new money enters an xStock, so a large mint on a ticker trading above its stock often comes before the gap closes. Tickers that net to less than $1 are left out. Moving tokens between blockchains also mints and burns, so not every bar is new demand.
The data behind it: mint and redeem events from the transaction stream, valued at the stock price, with supply confirmed from the account stream. Track Supply from the Account Stream builds it.
Dividends and Splits

This table lists every multiplier change the issuer has scheduled, before it takes effect. Each row gives the type, the change in shares per token, when it applies, and the multiplier before and after. Wallet balances update on their own when the change takes effect, and past changes appear as ◆ on the gap chart.
The data behind it: each mint account stores its current multiplier and, when a change is scheduled, the new value and its start time. The app reads these at startup and then from the account stream, so a change appears as soon as the issuer schedules it. Show Dividends and Splits Before They Happen builds it.
Ticker Pages
Clicking a ticker opens its own page with a price chart against the stock, cost by order size, trading activity, supply over time, its multiplier, and its largest recent trades.
How Does the xStocks Dashboard Work?
The xStocks dashboard is a Node.js server and a React frontend. The server finds every xStocks mint, streams their transactions and account updates over Solana gRPC, decodes each transaction into an event, and polls Jupiter for stock prices and swap quotes. It holds all state in memory and pushes a snapshot to the browser every 2 seconds.
The server does its work in this order:
- Mint registry.
getProgramAccountsfinds every Token-2022 mint whose mint authority is the issuer key. The registry refreshes every 10 minutes. - Initial state.
getMultipleAccountsreads each mint's supply, symbol, multiplier, and any scheduled multiplier change. - Compressed filters. One cuckoo filter built from the mint set goes into two subscriptions.
cuckoo_account_includematches transactions that reference any xStocks mint, andcuckoo_accounts_filtermatches writes to the mint accounts themselves. - Stream loop. Updates wait in a per-slot buffer until that slot's block metadata arrives with the block time.
- Classifier. Each transaction's token balance changes become one event per xStocks mint it moved.
- Price and quote polling. Two timers fetch stock prices and swap quotes from Jupiter.
- Sampler. Every 15 seconds the store records each traded ticker's gap to its stock and updates the signals built on it.
- Browser. The server pushes an aggregated snapshot over Server-Sent Events (SSE) every 2 seconds.
The app has no database and no backfill. Charts start empty and fill while it runs, and every baseline the dashboard compares against is learned after startup.
Set Up the Project
Clone the sample app and install its dependencies:
git clone https://github.com/quiknode-labs/qn-guide-examples.git
cd qn-guide-examples/solana/xstocks-dashboard
pnpm install
Next, get your endpoint details. In the Quicknode dashboard, open your Solana mainnet endpoint and copy the HTTP Provider URL. It has the form https://your-endpoint.solana-mainnet.quiknode.pro/your-token/. Solana gRPC uses the same host on port 443, and the token moves out of the path into its own value.
Create a .env file in the project root:
QN_GRPC_ENDPOINT=https://your-endpoint.solana-mainnet.quiknode.pro:443
QN_GRPC_TOKEN=your-token
QN_RPC_URL=https://your-endpoint.solana-mainnet.quiknode.pro/your-token/
JUP_API_KEY=your-jupiter-api-key
The project layout:
server/
config.ts Environment variables and constants
rpc.ts JSON-RPC helper with retry
registry.ts Mint discovery and mint account parsing
stream.ts Solana gRPC subscription, buffering, reconnect
classify.ts Transaction classifier
venues.ts Program labels for DEXs, routers, and lending
prices.ts Stock price and quote polling
market.ts US market hours
store.ts Rolling in-memory state, signals, and snapshots
index.ts Startup sequence and HTTP server
shared/types.ts Types shared by server and browser
web/ React dashboard
Get a Jupiter API Key
The app calls Jupiter's APIs for three things: the stock price behind each token, swap quotes for the cost panel, and the map of DEX program labels. It sends every request to api.jup.ag with an x-api-key header and polls stock prices every 30 seconds.
To get a key:
- Go to the Jupiter Developer Portal and sign in with Google, GitHub, or an email and password.
- Create a team, or join your organization's existing team.
- Generate an API key in that team and copy it.
The Free plan allows 60 requests a minute across the Price and Swap APIs. Stock prices and quotes together use about 38. Set the key as JUP_API_KEY in .env. The server won't start without it.
The sections below walk through the server in two halves. The first half collects the data: it finds the mints, streams them, and decodes what arrives. The second half turns that data into the signals the dashboard shows. You can run the app first and read along, or skip ahead to Run the Dashboard.
Discover Every xStocks Mint
A Token-2022 mint account starts with its mint authority, stored as a 4-byte option tag followed by the 32-byte key. The authority key therefore sits at byte offset 4, and a memcmp filter at that offset returns every mint the issuer controls. discoverMints in server/registry.ts makes the call:
const accounts = await withRetry("getProgramAccounts", 4, () =>
rpc<{ pubkey: string }[]>("getProgramAccounts", [
TOKEN_2022,
{
commitment: "finalized",
encoding: "base64",
dataSlice: { offset: 0, length: 0 },
filters: [{ memcmp: { offset: 4, bytes: ISSUER } }],
},
]),
);
if (accounts.length > 0) return { addresses: accounts.map((a) => a.pubkey), source: "getProgramAccounts" };
dataSlice with a length of zero tells the node to return addresses only. The next step reads the account data in batches, so the scan response stays small.
A scan of the whole Token-2022 program is a heavy call. The first request against a node that has not cached the result can fail with HTTP 504 and {"code":-32100,"message":"Request timed out after 8000ms"}. Later calls return in a few seconds or less. withRetry makes four attempts with exponential backoff, which is enough in most cases.
If every attempt fails, discoverMints falls back to Backed's public token list at https://api.xstocks.fi/api/v1/token and takes the Solana deployments from it. That list is missing some mints that exist onchain and includes a few older Backed tokens with a different mint authority. The app treats it as a list of candidates, and the next step verifies each one onchain.
Read Supply and Multiplier State
readMintStates fetches the candidate mints 100 at a time with getMultipleAccounts at finalized commitment. It drops any account that is not owned by the Token-2022 program or whose mint authority is not the issuer key, which is what makes the fallback list safe to use. Each remaining account goes through parseMintAccount:
export function parseMintAccount(address: string, data: Uint8Array, previous?: MintState): MintState | null {
try {
const mint = mintDecoder.decode(data);
const extensions = isSome(mint.extensions) ? mint.extensions.value : [];
const scaled = extensions.find((e) => e.__kind === "ScaledUiAmountConfig");
const metadata = extensions.find((e) => e.__kind === "TokenMetadata");
let symbol = previous?.symbol ?? address.slice(0, 6);
let name = previous?.name ?? symbol;
if (metadata) {
symbol = metadata.symbol || symbol;
name = metadata.name || name;
}
return {
address,
symbol,
name,
decimals: mint.decimals,
supplyRaw: mint.supply,
multiplier: scaled?.multiplier ?? 1,
newMultiplier: scaled?.newMultiplier ?? 1,
newMultiplierEffectiveTimestamp: scaled ? Number(scaled.newMultiplierEffectiveTimestamp) : 0,
};
} catch {
return null;
}
}
The Scaled UI config and the token metadata are extensions stored after the base mint data. Their byte offsets differ from mint to mint, so reading them at a fixed position returns garbage for some tickers. getMintDecoder from @solana-program/token-2022 decodes the base mint and walks the extension list, returning each extension tagged with its __kind. The ScaledUiAmountConfig extension carries three fields the app needs. multiplier is the current value, newMultiplier is the next value, and newMultiplierEffectiveTimestamp is the Unix time when the next value takes over.
The same function parses mint account updates from the stream later, so the startup read and the live path share one decoder. The supply recorded here is the baseline for every supply change the dashboard reports, and the scheduled multiplier changes it finds fill the dividends and splits table before the stream has delivered anything.
Subscribe with Compressed Filters
With the mint set in memory, buildRequest in server/stream.ts creates one CompressedAccountFilterSet and attaches it to both subscriptions:
export function buildRequest(mints: Iterable<string>, fromSlot?: number): { request: SubscribeRequest; filter: CompressedAccountFilterSet } {
const addresses = [...mints];
// Leave headroom above the entry count so inserts don't saturate the table.
const filter = new CompressedAccountFilterSet(Math.max(addresses.length * 2, 100));
for (const address of addresses) filter.insert(address);
const request: SubscribeRequest = {
commitment: CommitmentLevel.FINALIZED,
accounts: {},
slots: {},
transactions: {},
transactionsStatus: {},
blocks: {},
// Block metadata carries blockTime, which transaction updates do not.
blocksMeta: { blockTimes: {} },
entry: {},
blockFooter: {},
accountsDataSlice: [],
};
filter.insertIntoSubscribeRequest(request, "xstocksMints");
request.transactions.xstocksTransactions = { ...filter.toTransactionFilter(), vote: false, failed: false };
if (fromSlot) request.fromSlot = String(fromSlot);
return { request, filter };
}
The two filter methods map to the two subscription types:
insertIntoSubscribeRequestadds acuckoo_accounts_filterto the accounts subscription. The server sends an update whenever a tracked mint account is written, which happens on a mint, a burn, or a multiplier change.toTransactionFilterreturns acuckoo_account_includefor the transactions subscription. The server sends any transaction whose account keys include a tracked mint.
The transaction filter matches on the mint because every xStocks transfer the app has observed uses transferChecked, which lists the mint as an account. A plain transfer instruction does not reference the mint and would not match.
The capacity passed to the constructor is twice the entry count, which keeps inserts from failing as the table fills. For about 1,500 mints, each serialized filter is 8 KiB.
connectOnce opens the connection and sends the request:
this.client = new Client(config.grpcEndpoint, config.grpcToken, {
grpcDefaultCompressionAlgorithm: 1, // 0 = gzip, 1 = zstd
grpcMaxDecodingMessageSize: 64 * 1024 * 1024,
} as ConstructorParameters<typeof Client>[2]);
await this.client.connect();
this.connected = true;
const { request } = buildRequest(this.store.mints.keys(), fromSlot);
const stream = await this.client.subscribe(request);
The client sends the token as the x-token header. Turning on compression matters for cost, because Solana gRPC on port 443 meters the compressed size of what it delivers when the client negotiates compression.
When the registry refresh finds a new mint, resubscribe builds a fresh request and writes it to the open stream with stream.write(request). The new filters replace the old ones without a reconnect.
Hold Updates Until Block Time Arrives
Scaled UI conversion and stock pricing both need the time a transaction landed. SubscribeUpdateTransaction carries a slot and no timestamp. Block time arrives separately on the block metadata update for that slot, and at finalized commitment the metadata comes after the slot's transactions.
The blocksMeta entry in the request subscribes to that metadata. handle then sorts each update into a per-slot bucket and flushes the bucket when its block time is known:
private handle(update: SubscribeUpdate) {
const { store } = this;
if (update.transaction?.transaction) {
const info = update.transaction.transaction;
store.status.counters.transactions++;
const keys = allAccountKeys(info);
// Re-check the compressed filter match against the exact mint set.
if (!referencesTrackedMint(info, keys, store.mints)) {
store.status.counters.falsePositives++;
return;
}
// Transactions arrive before their block's metadata. Hold them until blockTime is known.
this.slotBucket(Number(update.transaction.slot)).transactions.push({ info, keys });
} else if (update.account?.account) {
const address = bs58.encode(update.account.account.pubkey);
if (!store.mints.has(address)) {
store.status.counters.falsePositives++;
return;
}
store.status.counters.accountUpdates++;
this.slotBucket(Number(update.account.slot)).accounts.push({
address,
data: update.account.account.data,
writeVersion: BigInt(update.account.account.writeVersion ?? 0),
});
} else if (update.blockMeta) {
const slot = Number(update.blockMeta.slot);
const blockTime = Number(update.blockMeta.blockTime?.timestamp ?? 0) * 1000 || Date.now();
this.lastSlot = Math.max(this.lastSlot, slot);
store.status.slot = this.lastSlot;
store.status.slotTime = blockTime;
// Flush this slot and anything older that never got metadata (skipped slots have none).
for (const [pendingSlot, bucket] of this.pending) {
if (pendingSlot > slot) continue;
this.pending.delete(pendingSlot);
this.flush(pendingSlot, blockTime, bucket);
}
}
}
Re-Check Every Match
A cuckoo filter stores a short fingerprint of each key, so the server forwards some updates for keys that are not in your set. The false positive rate for transactions is about 1%. Mint accounts change rarely, so during a quiet period most of the account updates that reach the client can be false positives. handle discards both kinds before they enter a bucket.
For transactions, the exact check has to cover every account the transaction can touch. Static account keys are only part of that list. Versioned transactions also load accounts from address lookup tables, and those addresses are in the transaction's metadata:
export function allAccountKeys(info: SubscribeUpdateTransactionInfo): string[] {
return [
...(info.transaction?.message?.accountKeys ?? []),
...(info.meta?.loadedWritableAddresses ?? []),
...(info.meta?.loadedReadonlyAddresses ?? []),
].map((key) => bs58.encode(key));
}
export function referencesTrackedMint(info: SubscribeUpdateTransactionInfo, keys: string[], mints: Map<string, MintState>): boolean {
if (keys.some((key) => mints.has(key))) return true;
const balances = [...(info.meta?.preTokenBalances ?? []), ...(info.meta?.postTokenBalances ?? [])];
return balances.some((balance) => mints.has(balance.mint));
}
If you check static keys alone, you will discard real swaps that reach the mint through a lookup table.
Classify Transactions from Balance Changes
Every panel that counts or prices activity starts from the classifier's output. It never parses DEX instruction data. Every program that moves an xStock changes a token balance, and the transaction metadata lists each token account's balance before and after. classifyTransaction in server/classify.ts turns those two lists into a net change per owner and mint:
// Net change per owner and mint. An account missing from one side counts as zero there.
const deltas = new Map<string, Map<string, bigint>>();
const held = new Map<string, bigint>(); // `${owner}|${mint}` -> pre + post, a rough size of the holder
const apply = (balance: (typeof meta.preTokenBalances)[number], sign: bigint) => {
const amount = BigInt(balance.uiTokenAmount?.amount ?? "0");
const perMint = deltas.get(balance.owner) ?? new Map<string, bigint>();
perMint.set(balance.mint, (perMint.get(balance.mint) ?? 0n) + sign * amount);
deltas.set(balance.owner, perMint);
const key = `${balance.owner}|${balance.mint}`;
held.set(key, (held.get(key) ?? 0n) + amount);
};
for (const balance of meta.preTokenBalances) apply(balance, -1n);
for (const balance of meta.postTokenBalances) apply(balance, 1n);
Grouping by owner collapses the intermediate hops of a routed swap. A router's temporary accounts net to zero and drop out, leaving the wallets and pools whose holdings changed.
For each xStocks mint with a non-zero change, the classifier applies these rules in order:
- Mint or redeem. The changes across all owners do not add up to zero, so supply changed. A positive sum is a mint and a negative sum is a redemption.
- Lending deposit or withdrawal. The transaction invokes a lending program (Kamino Lend or Jupiter Lend) and no DEX. The direction comes from whether a signer sent or received the tokens.
- Liquidity add or remove. A DEX program is present, but no owner has an opposite change in another asset. An owner whose USDC or SOL moves the same way as the xStock does not count as paired, even though LP tokens move the other way. A deposit sends both assets and receives LP tokens, and a withdrawal does the reverse. A token minted or burned in the same transaction, such as an LP token or a position NFT, never counts as the other side of a trade, so one-sided deposits are caught too. Wrapped SOL is the exception, because routers wrap and unwrap it within the transaction.
- Transfer. Tokens move between owners and nothing comes back.
- Buy or sell. An owner's xStock change pairs with an opposite change in another asset, and the owner's USDC or SOL does not move the same way as the xStock. The dollar value comes from that owner's USDC, USDT, or SOL leg, and the price is dollars divided by shares.
These five kinds are the five segments of the "Where tokens go" panel. Buys and sells also feed volume, trading pace, and the onchain price behind every gap figure.
A trade whose computed price is more than 50% away from the stock price usually settled against another token on a multi-hop route. The app keeps the trade, values it at the stock price, and leaves it out of the gap calculation.
Identify Traders
In about half of xStocks trades, no transaction signer owns a token account that changed. Routers, bots, and program-owned accounts trade on behalf of wallets, and both the pool and the trader show opposite xStock and USDC changes. The classifier handles this in three steps:
- If a signer took part, the signer is the trader. The owners on the other side go into a
poolOwnersset. - Otherwise, if every paired owner moved the xStock the same way, they are all pools, and the trader is the largest non-pool owner moving it the other way. This covers a swap routed through native SOL, where the trader's payment never shows as a token balance change.
- Otherwise, owners already in
poolOwnersare excluded, and among the owners left, the one holding fewer tokens is the trader, because pools hold inventory and traders usually start or end near zero.
Buy and sell labels on trades that reach the third step are a best guess. The dashboard's volume and price figures do not depend on that label, but the wallet count in the volume summary and the largest trades list on each ticker page do.
Attribute Venues
A single transaction can touch several pools, plus fee programs that forward the same tokens. Crediting the first labeled program in the transaction puts multi-hop volume on the wrong venue.
The classifier walks innerInstructions instead. Each inner instruction has a stackHeight, so the program one level up is its caller. transferCalls records the caller of every transferChecked on the mint, and pickVenue counts only the transfers into or out of the pool-side owners. The caller that moved the most tokens names the venue, which the ticker page shows beside each of its largest trades. Labels come from Jupiter's program map at /swap/v1/program-id-to-label, loaded at startup, with a built-in list in server/venues.ts as a fallback.
Convert Raw Amounts with the Scaled UI Multiplier
The uiTokenAmount.uiAmount field in gRPC transaction metadata equals the raw amount divided by 10^decimals. It does not include the Scaled UI multiplier. For a mint with a multiplier of 1.001701, treating that field as a share count understates every trade by 0.17%, and the error grows with each dividend.
The app converts raw amounts itself with two small functions:
/** The multiplier that applies at `unixSeconds`. */
export function multiplierAt(mint: MintState, unixSeconds: number): number {
const scheduled = mint.newMultiplierEffectiveTimestamp;
return scheduled !== 0 && unixSeconds >= scheduled ? mint.newMultiplier : mint.multiplier;
}
export function rawToShares(mint: MintState, raw: bigint | number, unixSeconds: number): number {
return (Number(raw) / 10 ** mint.decimals) * multiplierAt(mint, unixSeconds);
}
multiplierAt takes the block time of the transaction, which is why the stream loop waits for block metadata. The stream loop stores blockTime in milliseconds, so the classifier converts it with Math.floor(blockTime / 1000) before it calls rawToShares, because newMultiplierEffectiveTimestamp is in Unix seconds. A trade in the slot before a multiplier change and a trade in the slot after it use different values.
The same rule applies to any raw amount from another source. The app multiplies outAmount from a Jupiter quote by the multiplier before computing a price per share. Jupiter's usdPrice is already quoted per scaled share and needs no adjustment.
Show Dividends and Splits Before They Happen
Backed schedules a multiplier change by writing newMultiplier and a future newMultiplierEffectiveTimestamp to the mint. That write arrives on the accounts subscription, and changes scheduled before the app started are in the startup read. The store lists every mint whose effective timestamp is still in the future as an upcoming corporate action, and it labels the action from the ratio between the two values. A ratio above 1.2 or below 0.8 is a split, and anything smaller is a dividend.
The dividends and splits table shows each one with a countdown and the percentage change in shares per token. When the timestamp passes, the store records the action as applied, marks it on the gap chart, and adds a step to the supply chart, since every holder's share count changed without any token moving.
Track Supply from the Account Stream
The mint account is the source of truth for supply. onMintAccount in server/store.ts compares each update's supplyRaw with the previous value and records the change, converted to shares at block time. The ticker page shows that figure next to the net of the mint and redeem events the classifier decoded from transactions. When the two numbers disagree, the classifier has missed a transaction type, which makes the pair a useful check on your own decoder.
The "Minted and redeemed" panel values each ticker's net flow at the stock price and leaves out tickers that net to less than $1. Treat the figure as an upper bound on new demand. Moving tokens between blockchains can also mint and burn on Solana, and the app does not separate those moves from issuance.
Poll Stock Prices from Jupiter
Everything so far came from Solana. Judging whether a token is cheap or expensive needs one offchain number, the price of the stock itself, and this is where the second half of the server begins.
The app reads that price from Jupiter's Price API v3. For an xStocks mint, the response includes a stockData object with the underlying stock's price and the time it was last updated. startPricePolling in server/prices.ts requests up to 50 mints per call, every 30 seconds:
for (let i = 0; i < Math.max(1, wanted.length); i += 49) {
const ids = [WSOL, ...wanted.slice(i, i + 49)];
try {
const prices = await getJson<Record<string, PriceEntry>>(`${PRICE_URL}?ids=${ids.join(",")}`);
if (prices[WSOL]?.usdPrice) store.solPrice = prices[WSOL].usdPrice;
for (const mint of ids) {
const stock = prices[mint]?.stockData;
// Without a readable timestamp the price's age is unknown. Keep the previous one.
const updatedAt = stock ? Date.parse(stock.updatedAt) : NaN;
if (stock?.price && Number.isFinite(updatedAt)) store.refs.set(mint, { price: stock.price, updatedAt });
}
} catch (error) {
failed = error as Error;
}
}
The poll covers up to 138 of the most recently active tickers plus a short seed list, so it does not request prices for hundreds of mints that never appear in the stream. Wrapped SOL rides along in every batch to price trades that settled in SOL. Each batch has its own try, so one failed request leaves the other batches' prices in place. A price without a readable updatedAt is skipped, because the app can't tell how old it is.
stockData refreshes about once a minute, so polling faster would not make the price any fresher. That lag decides how much the dashboard can claim about any gap, and the next section builds it into every figure.
Turn Events into Pricing Signals
With trades and stock prices both in the store, a timer calls store.sample() every 15 seconds. Each pass records one gap sample per traded ticker, and the signals in the "Gap by ticker" and "Trading pace" tables are computed from those samples and from the event list. None of them has history at startup, so each one stays hidden behind a "Still learning" label until it has enough data, and the dashboard says how long is left.
Sample Gaps Every 15 Seconds
The gap is the token's price relative to the stock's:
gap = onchain price / stock price - 1
A single trade is a noisy price. As buys and sells arrive, addEvents adds each one's dollars and shares to two running totals, skipping trades under $5. sample divides the totals to get a volume-weighted price for the interval and then resets them:
const ref = this.refs.get(mint);
const traded = rt.accShares > 0;
const recent = rt.lastPriceT !== null && now - rt.lastPriceT <= ONCHAIN_STALE_MS;
const on = traded ? rt.accUsd / rt.accShares : recent ? rt.lastPrice : null;
rt.accUsd = 0;
rt.accShares = 0;
const stale = !ref || now - ref.updatedAt > REF_STALE_MS;
if (ref && open && !stale) rt.lastSessionRef = ref.price;
rt.samples.push({ t: now, on, ref: ref?.price ?? null, stale });
if (rt.samples.length > MAX_SAMPLES) rt.samples.shift();
A ticker with no trades in the interval carries its last trade price forward for up to 15 minutes (ONCHAIN_STALE_MS). After that, the sample has no onchain price and the ticker shows no gap until it trades again, since an old trade measured against a current stock price would report the stock's move as a gap. Each ticker keeps at most 5,760 samples, which is 24 hours at 15 seconds. The gap chart draws these samples, shades the intervals returned by marketSessions in server/market.ts, and appears once a ticker has two of them.
Mark Gaps That Rest on an Old Stock Price
A stock can move in the minute between two stockData updates. During that minute the dashboard would report the stock's move as a gap in the token. The app handles this with three freshness levels, set in gap in server/store.ts:
- Fresh. The stock price is under 30 seconds old, or the US market is closed and the stock price is not moving.
- Aging. The market is open and the stock price is over 30 seconds old. The dashboard prefixes the gap with
~to mark it approximate. - Stale. The stock price is over 5 minutes old. The dashboard grays the gap out, draws that stretch of the chart as a dashed line, and keeps the sample out of every baseline below.
Without the stale level, a frozen price feed would show up as a steadily growing premium. If you need gaps you can act on within a minute, replace the polled price with a streaming equity feed and keep the rest of the pipeline.
Compare Each Gap to Normal
A 0.4% premium means different things on different tickers. A heavily traded ETF token may never stray that far, while a thinly traded stock token may sit there all day. The "Is that normal?" column answers with a z-score, the number of standard deviations between the current gap and the ticker's own average gap since startup:
const premiums = rt.samples.filter((s) => s.on !== null && s.ref !== null && !s.stale).map((s) => (s.on! / s.ref! - 1) * 100);
let z: number | null = null;
if (premiums.length >= MIN_BASELINE_SAMPLES && premiumPct !== null && !stale) {
const mean = premiums.reduce((a, b) => a + b, 0) / premiums.length;
const sd = Math.sqrt(premiums.reduce((a, b) => a + (b - mean) ** 2, 0) / premiums.length);
z = sd > 1e-9 ? (premiumPct - mean) / sd : 0;
}
MIN_BASELINE_SAMPLES is 20, so a ticker needs 5 minutes of fresh samples before it gets a reading. The frontend turns the number into words in web/src/insights.ts. Under one standard deviation reads "Typical", one to two reads "A little high" or "A little low", and two or more reads "Unusually high" or "Unusually low".
The baseline is whatever the app has seen since it started. A z-score from the first half hour compares the gap with very little, and one computed overnight compares it with overnight gaps only. The table shows the length of the baseline so a reader can weigh the label.
Time How Fast Gaps Close
Minting is the mechanism that pulls a premium down, so the time between a mint and the gap closing shows whether that mechanism is working for a ticker. The store measures it in episodes. An episode opens in addEvents when a mint arrives while the ticker trades at least 0.2% above its stock:
if (event.type === "mint" && rt.episodeStart === null) {
const premium = this.currentPremium(event.mint);
if (premium !== null && premium >= 0.2) rt.episodeStart = event.t;
}
It closes in sample at the first fresh sample with a trade in its interval where the gap is back to 0.05% or less. A stock move alone can't close an episode:
if (rt.episodeStart !== null && traded && on !== null && ref && !stale) {
const premium = (on / ref.price - 1) * 100;
if (premium <= 0.05) {
rt.closeDurations.push((now - rt.episodeStart) / 1000);
if (rt.closeDurations.length > 200) rt.closeDurations.shift();
rt.episodeStart = null;
}
}
The "Gaps usually close in" column shows the median of those durations. Expect it to stay empty for a while. A ticker gets a figure only after it has been minted during a premium and then traded back to its stock price while the app was running. The triangles on the gap chart mark the same mints and redemptions, so you can see a gap narrow after new tokens arrive without waiting for the median.
Measure Trading Pace
Volume by ticker shows what is trading. Trading pace shows what is trading more than it usually does. signal in server/store.ts walks the event list once per ticker, splitting trade dollars into the last 5 minutes and everything earlier:
if (baselineSec >= 30 * 60) {
let recent = 0;
let earlier = 0;
const from = Math.max(this.startedAt, now - DAY_MS);
for (let i = this.events.length - 1; i >= 0; i--) {
const event = this.events[i];
// Events arrive in slot order, not time order, so scan a minute past the cutoff.
if (event.t < from - 60_000) break;
if (event.t < from || event.mint !== mint || !TRADE.has(event.type) || event.usd === null) continue;
if (event.t >= now - 5 * 60_000) recent += event.usd;
else earlier += event.usd;
}
const periods = (now - 5 * 60_000 - from) / (5 * 60_000);
const average = periods > 0 ? earlier / periods : 0;
spike = average > 0 ? recent / average : null;
}
The result is a ratio of the last 5 minutes to an average 5 minutes. The dashboard flags a ratio of two or more as a spike and labels 0.5 or less "Quiet". The app waits 30 minutes before showing it, since a shorter history makes almost any burst look unusual.
Compute the Move Since the Close
When the US market closes, the stock price stops and the token keeps trading. The distance between them is the closest thing onchain data has to an after-hours quote. While the market is open, sample saves each fresh stock price as lastSessionRef. Once it closes, signal measures the token against that saved price:
impliedOpenPct: !this.status.marketOpen && rt.lastPrice !== null && (rt.lastSessionRef ?? ref?.price)
? (rt.lastPrice / (rt.lastSessionRef ?? ref!.price) - 1) * 100
: null,
If the app started after the close, it has no session price of its own and falls back to the current stock price from Jupiter.
The dashboard labels this column "Move since the close" and says it shows onchain sentiment. It is one token's last trade, often in a thin overnight market, and it does not predict where the stock opens.
server/market.ts treats 9:30 to 16:00 New York time on weekdays as the session, minus a list of full-day New York Stock Exchange (NYSE) holidays that runs through 2027. On NYSE's early-close days, such as the day after Thanksgiving, the session ends at 13:00. Extend both lists from NYSE's holiday calendar if you run the app past 2027.
Quote the Cost to Buy by Order Size
The gap describes the last trade. Someone about to buy needs the price of their own trade, which depends on its size and on the liquidity available at that moment. startQuotePolling in server/prices.ts asks Jupiter's Swap API for that price directly. Once a minute, it requests a USDC buy of $1,000, $10,000, and $50,000 for the five busiest tickers of the last hour:
for (const usd of QUOTE_SIZES_USD) {
try {
const quote = await getJson<{ outAmount: string; routePlan: { swapInfo: { label: string } }[] }>(
`${QUOTE_URL}?inputMint=${USDC}&outputMint=${mint}&amount=${usd * 1e6}&slippageBps=50`,
);
// outAmount is raw. Apply the Scaled UI multiplier to get shares.
const shares = (Number(quote.outAmount) / 10 ** state.decimals) * multiplierNow(state);
const price = usd / shares;
// The store measures each size against the stock price when it reads the quote.
sizes.push({ usd, price, impactPct: null, route: [...new Set(quote.routePlan.map((leg) => leg.swapInfo.label))].join(" + ") });
} catch {
// No route at this size. Leave it out.
}
await new Promise((r) => setTimeout(r, 400));
}
outAmount is a raw token amount, so it goes through the multiplier like every other amount in the app. Dividing the dollars spent by the shares received gives the price per share for that order size.
A quote can be a few minutes old by the time it is shown, and the stock may have moved since. So the poller stores only prices, and quoteNow in server/store.ts measures each size against the latest stock price whenever the dashboard or the alert check reads it:
const ref = this.refs.get(mint);
const fresh = ref && now - ref.updatedAt < REF_STALE_MS ? ref.price : null;
const k1 = quote.sizes.find((size) => size.usd === 1_000)?.price ?? null;
const base = fresh ?? k1;
const baseline: SlippageBaseline = fresh !== null ? "stock" : k1 !== null ? "1k" : null;
return { t: quote.t, baseline, sizes: quote.sizes.map((size) => ({ ...size, impactPct: base !== null ? (size.price / base - 1) * 100 : null })) };
Each figure therefore combines the current gap with the extra cost of the order's size. A negative number means the quoted route buys the token for less than the stock. When the stock price is stale, the sizes are compared with the $1,000 quote, which isolates the size effect, and the dashboard labels them "vs $1K". With no $1,000 quote either, the dashboard shows only the quoted price. A size with no route is left blank. quoteNow returns nothing for a quote over 3 minutes old, so a ticker that drops out of the five busiest stops showing its last quote as current.
Flag Tickers Trading Below the Stock
The Alerts panel at the top of the page combines the signals above into one list. evaluateOpportunities in server/store.ts runs on every sample and lists a ticker only when all of these hold:
- The US market is open and the stock price is under 30 seconds old. The stock price updates about once a minute, so it spends part of each minute older than that. Those checks pause and nothing new is judged until a fresher price arrives. The hold timer and any listed ticker carry over only while a $10,000 quote under 3 minutes old still lands below the stock price.
- The token traded in the last 5 minutes.
- The gap is at least two standard deviations below the ticker's average and at least 0.25% below the stock price.
- A $10,000 quote under 3 minutes old still lands below the current stock price. The check compares the quoted price with the latest stock price, because the stock may have moved since the quote was taken.
- The conditions above have held for a full minute.
The quote check matters most. A token can show a discount on its last trade that disappears once a real order moves the pool. Tickers that pass every test except the quote are added to the next quote poll, so the list is not limited to the five busiest.
The panel reports conditions in the data. It lists the discount, the route, and how long the condition has held, and it makes no recommendation.
Push Snapshots to the Browser
The browser never talks to Solana or Jupiter. It opens one SSE connection to /api/events, and the server writes a full snapshot of the dashboard to it every 2 seconds:
const push = () => response.write(`data: ${JSON.stringify(store.snapshot(params))}\n\n`);
push();
const timer = setInterval(push, 2_000);
response.on("close", () => clearInterval(timer));
The connection's query string carries three settings: the time window (15m, 1h, or all), the tickers drawn on the gap chart, and the ticker page being viewed, if any. store.snapshot computes the four headline figures, the per-ticker tables, and the chart series for that window on each push. Changing the window in the UI reopens the connection with new parameters.
Memory stays flat during long runs because every collection is capped. Events are dropped after 24 hours or past 300,000 entries, each ticker keeps 5,760 samples, and the all window means since startup up to 24 hours.
Reconnect and Replay Missed Slots
StreamManager.run wraps the subscription in a loop that reconnects with exponential backoff, from 1 second up to a 30-second cap. A watchdog also destroys the stream if no update arrives for 30 seconds, since a connection can stall without raising an error.
Solana gRPC retains roughly 3,000 recent slots and replays them when a request sets fromSlot. On reconnect, the app asks for the last slot it processed minus 32:
// Replay the slots missed while disconnected when they are still within reach. The current
// slot is unknown until the stream answers, so estimate the outage from wall-clock time.
const missedSlots = (Date.now() - this.lastDataAt) / SLOT_MS + 32;
if (this.lastSlot > 0 && (missedSlots > MAX_REPLAY_SLOTS || this.replayFailures >= MAX_REPLAY_ATTEMPTS)) {
// Too far back to replay. Resume at the tip and keep the gap.
console.warn(`[stream] skipping replay: about ${Math.round(missedSlots)} slots missed, ${this.replayFailures} failed replays`);
this.lastSlot = 0;
}
const fromSlot = this.lastSlot > 0 ? this.lastSlot - 32 : undefined;
replaying = Boolean(fromSlot);
this.connected = false;
await this.connectOnce(fromSlot);
The current slot is unknown until the stream answers, so the app estimates the outage from the time since the last update at 400 ms per slot. Past 2,500 slots, the missed range is likely gone and the app skips the replay. It also gives up after three replays that fail once the connection is open, which is where a rejected fromSlot shows up. A network outage fails earlier, at connect(), and doesn't count against the replay.
The overlap means the server resends some transactions the app already holds. flush keeps a set of the last 200,000 signatures and skips any it has seen, so a replay never double counts volume. Mint account writes replay too. onMintAccount records the slot and write version of the last update it applied and ignores anything older, so a replay can't move supply or the multiplier back. When the app skips a replay, it resumes at the tip, marks the gap on its charts, and flags the volume and net minted figures for that window as partial.
To watch this path, send the server process a SIGUSR2 signal. It drops the connection on purpose:
kill -USR2 $(pgrep -f "server/index.ts")
The client library also ships subscribeWithReconnect(), which handles reconnection for you. The sample app runs its own loop so the dashboard can show the attempt count and the gap.
Run the Dashboard
Start the server and the frontend together:
npm run dev
The API server listens on http://127.0.0.1:8787, and Vite serves the dashboard at http://localhost:5173. Open the Vite URL. A startup screen lists four steps as they finish: finding mints, reading mint state, building filters, and connecting the stream. The server log shows the same sequence:
[server] http://127.0.0.1:8787
[registry] 1560 candidate mints from getProgramAccounts
[registry] 1560 xStocks mints tracked
[prices] Jupiter Price API, polling every 30s
[stream] live
Your mint count will differ as Backed lists new tickers.
Once the stream is live, the panels fill in at different speeds, and an empty panel in the first minutes is expected:
- Right away. The four headline figures, volume by ticker, and "Where tokens go" update as trades arrive. The dividends and splits table is complete from the startup read.
- After about 30 seconds. The gap chart appears once a ticker has two samples, and the first cost quotes arrive.
- After 5 minutes. The "Is that normal?" column replaces "Still learning" with a reading.
- After 30 minutes. Trading pace starts comparing against its average.
- Whenever the market provides it. "Gaps usually close in" needs a mint during a premium, "Move since the close" fills in only while the US market is closed, and Alerts lists tickers only while it is open.
Use the window switch at the top to move between the last 15 minutes, the last hour, and everything since startup. Click any ticker to open its page, where the supply panel shows the account stream's supply change next to the classifier's decoded net.
The counters object in the response reports transactions received, false positives discarded, account updates, and events stored. Comparing falsePositives with transactions shows the filter's false positive rate on live data.
To serve the built frontend from the Node.js server on a single port, run npm run build followed by npm run server, then open http://127.0.0.1:8787.
Next Steps
- Backfill history. The app starts empty, and every baseline starts with it. Load the last day of activity with Quicknode Streams or
getSignaturesForAddressso the charts and the z-scores have data on first load. - Persist events and samples. Write them to a database so a restart keeps its history and the 24-hour cap no longer applies. A longer baseline also lets you compare a gap with the same hour on previous days.
- Use a streaming stock price. A feed that updates every second removes the
~state and makes the gap usable at shorter horizons. - Label addresses. Map known exchange hot wallets and lending vaults to names. That separates exchange deposits from wallet-to-wallet transfers, which look identical onchain.
- Chart liquidation levels. For xStocks posted as collateral on Kamino Lend and Jupiter Lend, read the open positions and show how much collateral gets liquidated at each price.
- Track another token set. Point the registry at a different issuer. The Scaled UI Amount guide covers the extension in more depth if your tokens rebase.
Wrapping Up
You now have a dashboard that says whether an xStock is cheap or expensive against its stock, what an order would cost, and whether tokens are being minted or redeemed, all from one Solana gRPC connection and two polled APIs. The collection half finds the mints from their shared mint authority, streams them through two compressed filters, and decodes transactions from balance changes at the multiplier in effect at block time. The signal half samples each ticker's gap, compares it with that ticker's own history, and marks every figure whose stock price is too old to trust.
The same structure works for any large token set with an offchain reference price. Swap the registry for a different mint authority, program, or wallet list and the price poller for a different feed, and the filters, the stream loop, the classifier, and the sampler carry over.
Resources
- Sample app source code, the full server and dashboard this guide walks through
- Solana gRPC Overview, for endpoints, authentication, and transaction versions
- Compressed Filters, for the cuckoo filter lifecycle and client version floors
- Monitor Solana Programs with Solana gRPC (TypeScript), for a first subscription if Solana gRPC is new to you
- Scaled UI Amount Token Extension, for the multiplier fields the app reads from each mint
- xStocks, the issuer's site and token list
- Jupiter Price API, for the stock prices behind each token
- Jupiter Swap API, for the swap quotes in the cost panel
Frequently Asked Questions
Why does the dashboard use compressed filters instead of a standard Solana gRPC filter?
A standard Solana gRPC filter accepts 10 to 50 pubkeys depending on the plan, and there are over 1,500 xStocks mints. A compressed filter encodes the whole set as a cuckoo filter of about 8 KiB, so one subscription covers every mint. The trade-off is a false positive rate of about 1%, which the app removes by re-checking each update against its exact mint set.
How does the dashboard decide whether an xStock is cheap or expensive?
Every 15 seconds the app takes the volume-weighted price of each ticker's onchain trades and divides it by the stock price from Jupiter's Price API. The result minus one is the gap. It then compares the current gap with that ticker's own gaps since the app started, as a z-score, and labels two standard deviations or more as unusual.
Why is a gap marked with a ~ or grayed out?
The stock price the app uses refreshes about once a minute. While the US market is open, a stock price over 30 seconds old may trail the real stock, so the gap is prefixed with ~ to mark it approximate. A stock price over 5 minutes old is treated as stale. The gap is grayed out and left out of every baseline.
Why are share counts different from the raw token amounts in a transaction?
xStocks use the Token-2022 Scaled UI Amount extension. The share count a holder sees is the raw amount, divided by 10 to the power of the mint's decimals, times a multiplier stored on the mint. The uiTokenAmount field in gRPC transaction metadata does not apply that multiplier, so the app multiplies every raw amount by the multiplier that was in effect at the transaction's block time.
How does the dashboard know about a dividend or split before it happens?
Backed schedules a change by writing newMultiplier and newMultiplierEffectiveTimestamp to the mint account. The app reads those fields for every mint at startup and receives later writes on its accounts subscription. Any mint whose effective timestamp is in the future is shown as an upcoming corporate action, labeled as a split when the multiplier changes by more than 20% and as a dividend otherwise.
