/substreams:substreams-solanafrom substreams
Develop Substreams for Solana programs with CPI-safe instruction walking, program/account filters, and typed protobuf decoding for Anchor, SPL Token, and custom programs like Raydium or Pump.fun.
Ships in substreams. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Expert assistant for Solana program Substreams: instruction walking, decoding, and filters.
Cross-cutting manifests, stores, and performance live in substreams-dev. SQL module → substreams-sql. Self-managed sink ops → substreams-sink-deploy-local. StreamingFast-hosted SQL sink → substreams-hosted-sink.
Solana is not EVM. Do not use ABI/logs/topics patterns here. Decoding model = instructions + accounts + discriminators.
Always decode instruction data into typed fields. Emitting only presence/program filters, raw bytes, hex, base58/base64 blobs, or a JSON string of the payload is invalid for protocol Substreams in this skill.
Each selected instruction gets its own dedicated protobuf message with fields that match that instruction’s args + named accounts.
| Required | Forbidden |
|---|---|
e.g. message Swap { … }, message Deposit { … } — one type per distinct layout | One generic Event / Instruction with optional fields for every ix |
| Distinct message per instruction the user asked for (different args/accounts) | Shared bag: string instruction_name + map / sparse optional args |
Module output may wrap them: repeated Swap swaps and repeated Deposit deposits, or oneof of those messages | Single table of mixed rows with unused columns for other ixs |
| Parse args after the discriminator into named typed values | Leave data as bytes / hex / base64 |
Map account metas to named fields (pool, user, mint, …) | Dump the whole instruction as JSON |
instruction_data_json, raw_data, args_json, serde_json::to_string |
Same layout, multiple discriminators: when two instructions share args + account layout (e.g. Raydium CLMM swap / swap_v2 in T5.3), one message type is fine — match either disc, decode the same fields. Split only when layouts or account maps diverge.
Why: sinks, SQL (schema.table per message), and consumers need stable per-instruction schemas — not opaque blobs or a one-size-fits-all row.
What “structured + one message per instruction” means in practice:
// ✅ One message type per instruction
message Swap {
uint64 slot = 1;
string signature = 2;
string pool = 3;
string amount = 4;
bool is_base_input = 5;
string payer = 6;
}
message Deposit {
uint64 slot = 1;
string signature = 2;
string user_wallet = 3;
string sol_amount = 4;
}
// Output wrapper may hold several lists (or a oneof of Swap | Deposit)
message Events {
repeated Swap swaps = 1;
repeated Deposit deposits = 2;
}
// ❌ One mega-message for all instructions — forbidden
message GenericIx {
string instruction = 1; // "swap" | "deposit" | …
string pool = 2; // only set for swap
string sol_amount = 3; // only set for deposit
bytes raw_data = 4;
}
// ❌ Opaque / JSON — forbidden
message BadSwap {
bytes instruction_data = 1;
string instruction_json = 2;
}
// ✅ Decode into typed locals, then into the proto object
let amount = u64::from_le_bytes(data[8..16].try_into().unwrap());
let is_base_input = data[40] != 0;
let pool = accounts[2].to_string();
out.push(Swap {
slot,
signature: sig.clone(),
pool,
amount: amount.to_string(),
is_base_input,
payer: accounts[0].to_string(),
});
// ❌ Never
// out.push(Event { data_json: serde_json::to_string(&data).unwrap(), .. });
// out.push(Event { raw_data: data.to_vec(), .. });
Scope of the rule:
IDL note: the Anchor IDL file may be JSON on disk — that is only the source of layouts. Runtime output is still typed protobuf objects, never “IDL JSON dump” of instruction data.
Do not write Rust, protos, or manifests until the user has answered (or already stated) the items below.
Same protocol as substreams-dev (and all Substreams skills):
Walk this list top to bottom, one question per turn:
| Order | Question focus | Example choices (always end with custom) |
|---|---|---|
| 1 | Network | Solana mainnet · Solana devnet · Other / custom |
| 2 | Program ID(s) | Known protocols from common-programs · Other / paste program ID |
| 3 | Instruction(s) | Named ix presets for that program · All instructions · Other / list discriminators or names |
| 4 | Account address(es) to track | None (program-wide) · Common mint/pool · Other / paste account(s) |
| 5 | Fields / output shape | Suggested field set · Minimal (slot, sig, key accounts) · Other / describe fields |
| 6 | Output / sink destination | Full list below · Other / custom |
| 7 | Slot range | Suggested window · Recent head · Other / enter slots |
“All instructions” + SQL/ClickHouse: one protobuf message and typically one table per instruction (e.g. 30+ tables for Raydium CLMM). Prefer a ladder for first hosted deploy: high-value ixs (e.g. swap / swap_v2) → liquidity → full surface. If the user insists on all:
index, keys, …) per substreams-sql.substreams run window before hosted Deploy (substreams-hosted-sink).Ask only when destination is unknown. Offer all of these; last = custom:
| Choice | Follow-on |
|---|---|
substreams run only | Verify with CLI/GUI first |
| SQL — self-managed | substreams-sql → substreams-sink-deploy-local |
| SQL — StreamingFast hosted sink | substreams-sql → substreams-hosted-sink |
| The Graph / graph-out | substreams-sink (EntityChanges) |
| Custom app sink | substreams-sink |
| Not sure yet | Start with run-only |
| Other / enter a custom answer | Free-text |
If the user says only “SQL”, ask self-managed vs hosted in a separate turn (plus custom). Hosted still needs a correct SQL module first.
If the user names a protocol without a program ID, propose the mainnet ID from references/common-programs.md as a choice, then still confirm instructions in a later turn.
One turn when ambiguous. Prefer the highest-quality source available.
| Choice | When to use | How you decode |
|---|---|---|
| Anchor IDL (JSON) | User has IDL / anchor build / published IDL | Disc + args + accounts from IDL; optional sol-anchor-beta |
| Program Rust source | No IDL; Anchor source available | sha256("global:<name>") + layout from source |
| Manual / known layout | SPL Token or documented non-Anchor | Known discriminators + fixed LE fields |
| Other / enter a custom answer | User describes another source | Follow their layout; still structured decode |
Decision rules:
Deep dive: references/instruction-parsing.md.
From program ID(s) + account address(es):
source: sf.solana.type.v1.Block as the input and add blockFilter: { module: solana_common:program_ids_without_votes, query: { params: true } } with a - params: string input (program:<base58>; program_ids_and_accounts_without_votes adds account:). The index is computed once for the whole chain and is likely already cached. Read the Block directly: StreamingFast's Solana endpoints no longer serve vote transactions, so blocks_without_votes only adds a module to your pipeline. See substreams-dev → references/block-filtering.md.blockFilter is block-level, so still if ix.program_id() != PROGRAM { continue; } before decoding instruction data, plus optional account membership checks.transactions_by_programid_without_votes — alternative that hands you only transactions touching the program (substreams init → sol-transactions, solana-common); extra module, so prefer (1) unless you want the pre-filtered maps. Override its default params. Still implement domain decoding in your map.Keep the module count small (one extraction map reading the block) and call substreams::skip_empty_output() when a block yields nothing. Keep data as bytes — base58-encode only in the last module (db_out); base58 is slow.
Details: references/loops-and-filters.md.
Prefer the current pair (new projects). Do not mix majors across the table.
| Pair | When |
|---|---|
substreams = "0.8.0" + substreams-solana = "0.16.0" | Default — buffa-generated protobuf types |
substreams = "0.7" + substreams-solana = "0.15" | Existing packages still on prost |
substreams = "0.6" + substreams-solana = "0.14" | Legacy packages / examples that still pin 0.14.x |
[dependencies]
substreams = "0.8.0"
substreams-solana = "0.16.0"
bs58 = "0.4"
buffa = { version = "0.9", default-features = false, features = ["std", "fast-utf8"] }
buffa-types = { version = "0.9", default-features = false }
sha2 = "0.10" # Anchor discriminators when computing at runtime; prefer const bytes in hot paths
[lib]
crate-type = ["cdylib"]
[profile.release]
lto = true
opt-level = "s"
strip = "debuginfo"
Keep the pair matched. substreams-solana declares the substreams version it was built against (0.16.0 → substreams ^0.8.0; 0.15 → ^0.7; 0.14.3 → ^0.6). Pin the row above rather than mixing majors. The 0.16 line generates buffa types; the 0.15 and 0.14 lines generate prost types, and the two do not interoperate.
Mix-major scenarios (do not treat as “always link-error”):
| What you mixed | What actually happens |
|---|---|
substreams 0.6 + substreams-solana 0.15, or 0.7 + 0.14 | Cargo still builds — it silently pulls two substreams copies into the tree. A green build is not proof the pins are right; cargo tree | grep substreams should show one version. |
A buffa row (0.8.0 + 0.16.0) mixed with a prost row, or substreams-database-change 4 on a substreams 0.6 tree | Often real link / type failures — clean with rm -rf target && substreams build after realigning. |
Versioned transactions (v0 / v1). Blocks tag each transaction with version / versioned; v1 transactions also carry transaction_config (compute-unit limit, heap size, loaded-accounts data size limit) on sf.solana.type.v1.Message. Existing packages keep working unchanged. To read these fields use substreams-solana ≥ 0.15.1 (0.16.0 on the buffa row), or refresh vendored sf.solana.type.v1 protos and re-run substreams protogen.
Re-check crates.io/crates/substreams-solana before assuming these pins forever.
No abi/ or substreams-ethereum-abigen for Solana projects.
Your output protos are generated by buf from a checked-in buf.gen.yaml, the same as every other
chain. Solana packages do not need a build.rs.
# buf.gen.yaml
version: v1
plugins:
- plugin: buf.build/anthropics/buffa:v0.9.2
out: src/pb
opt:
- lazy_views=true
- unknown_fields=false
- idiomatic_field_names=true
substreams build generates src/pb/ as part of the build, so that is the command to reach for;
substreams protogen does the codegen step alone when you only want the bindings refreshed. Commit
what it writes, src/pb/mod.rs included (see substreams-dev for the module tree):
// src/lib.rs
mod pb;
use pb::mypackage::v1::{MyEvent, MyEvents};
specVersion: v0.1.0
package:
name: my_solana_substreams
version: 1.7.1
url: https://github.com/myorg/my-solana-substreams
description: What this Solana substreams indexes
# do not add package.doc — write README.md beside the manifest instead
network: solana
protobuf: # REQUIRED — pack fails without these sections
files:
- mypackage/v1/events.proto
importPaths:
- ./proto
binaries: # REQUIRED — pack fails without these sections
default:
type: wasm/rust-v1
# filename = Cargo.toml [package] name with hyphens → underscores
file: ./target/wasm32-unknown-unknown/release/my_solana_substreams.wasm
modules:
- name: map_my_module
kind: map
initialBlock: 320000000 # pin to test/data range — not genesis
inputs:
- source: sf.solana.type.v1.Block
output:
type: proto:mypackage.v1.MyEvents
protobuf: and binaries: are not optional — every working Solana example in this repo carries both; a manifest without them does not pack. Manifest field rationale (version prefix, url/description, no package.doc): substreams-dev.
sf.solana.type.v1.Block is a well-known source — no imports: entry is needed for the block type.
Illustrative skeleton (types MyEvent / MyEvents stand in for your generated protos). Push typed messages after decode — not comments alone.
use substreams::errors::Error;
use substreams_solana::b58;
use substreams_solana::pb::sf::solana::r#type::v1::Block;
// mod pb { … include!(…) } // see build.rs section above
// use pb::mypackage::v1::{MyEvent, MyEvents};
const PROGRAM: [u8; 32] = b58!("YourProgramIdBase58........");
const SWAP_DISC: [u8; 8] = [/* from IDL or sha256("global:swap")[0..8] */];
#[substreams::handlers::map]
fn map_events(block: Block) -> Result<MyEvents, Error> {
let slot = block.slot;
let mut items: Vec<MyEvent> = Vec::new();
// Successful transactions only
for trx in block.transactions() {
let sig = trx.id(); // base58 signature
// Top-level AND inner (CPI) instructions — REQUIRED for DEX/protocol work
for ix in trx.walk_instructions() {
if ix.program_id() != PROGRAM {
continue;
}
let data = ix.data();
let accounts = ix.accounts(); // Vec<Address>, Display = base58
if data.len() < 16 || data[..8] != SWAP_DISC {
continue;
}
// Decode args + named accounts into a structured proto (Hard rule)
let amount = u64::from_le_bytes(data[8..16].try_into().unwrap());
// accounts[N] from IDL / Accounts struct — do not invent indexes
items.push(MyEvent {
slot,
signature: sig.clone(),
amount: amount.to_string(),
// pool: accounts[N].to_string(),
});
let _ = accounts;
}
}
Ok(MyEvents { items })
}
| Rule | Why |
|---|---|
Always prefer trx.walk_instructions() | Yields top-level and inner CPI instructions. Aggregator-routed DEX activity is almost always inner. |
Never use only message.instructions | Top-level only. T5.3 Raydium CLMM eval: ~10% of swaps found vs 100% with walk_instructions. |
block.transactions() = successful only | Failed txs skipped. Good for protocol events. |
| Need failed txs / full counts? | Iterate &block.transactions and check meta.err (stats pattern). |
| Filter program ID first | Cheapest reject before parsing data. |
| Do not invent account indexes | Take from IDL account metas or #[derive(Accounts)] field order (0-based). |
| Structured decode + one message per ix | See Hard rule — typed fields, no raw/JSON mega-messages. |
Full patterns (failed txs, account filters, index modules): references/loops-and-filters.md.
Matching a discriminator is only step 1. You must continue and decode the payload into a structured output object (see Hard rule).
// Prefer compile-time constants (from IDL or precomputed sha256)
const SWAP_DISC: [u8; 8] = [/* from IDL or sha256("global:swap")[0..8] */];
if data.len() < 8 || data[..8] != SWAP_DISC {
continue;
}
// payload starts at data[8..] — little-endian Anchor layout
// Decode each arg into typed locals, then fill a proto message — do not emit JSON of data[8..]
let amount = u64::from_le_bytes(data[8..16].try_into().unwrap());
// ...
Runtime helper (startup/tests only; prefer consts in maps):
use sha2::{Digest, Sha256};
fn anchor_discriminator(name: &str) -> [u8; 8] {
let hash = Sha256::digest(format!("global:{name}").as_bytes());
hash[..8].try_into().unwrap()
}
Same instruction layout family for classic SPL Token and Token-2022. Discriminators and account indexes match for Transfer / TransferChecked; filter by program ID so you do not mix the two:
| Program | Mainnet ID |
|---|---|
| SPL Token | TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA |
| Token-2022 | TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb |
3 = Transfer — accounts [source, dest, authority, …]; no mint → cannot filter by mint reliably.12 = TransferChecked — accounts [source, mint, dest, authority, …]; use this when filtering a mint (e.g. USDC).See references/common-programs.md.
const TRACKED_MINT: [u8; 32] = b58!("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
const TRACKED_POOL: [u8; 32] = b58!("YourPoolAddressBase58...........");
let accounts = ix.accounts();
// Example: TransferChecked mint at index 1 (from layout, not guessed)
if accounts.len() < 2 || accounts[1] != TRACKED_MINT {
continue;
}
// Or: any involvement of a tracked pubkey
let touches = accounts.iter().any(|a| *a == TRACKED_POOL);
if !touches {
continue;
}
When the user gives account addresses in pre-flight, wire them as b58! constants (or params) and filter before emitting.
| Goal | Approach |
|---|---|
| Full block, custom decode | Hand-written map on sf.solana.type.v1.Block (examples T5.x / T6.2) |
| Anchor + IDL | substreams init → sol-anchor-beta, point at IDL JSON |
| Tx filter by program/account | substreams init → sol-transactions (solana-common) |
| Simple program presence | substreams init → sol-hello-world |
After generators, still enforce pre-flight instruction list and account filters for production modules.
build.rs + mod pb include; manifest has protobuf: + binaries:; matched crate pair; network: solana, input sf.solana.type.v1.Block.block.transactions() + walk_instructions() + program ID filter.initialBlock + short substreams run -s <slot> -t +100 -o jsonl.substreams-sql before first deploy.Examples T5.x / T6.2 pin the default buffa pair (substreams 0.8.0 + substreams-solana 0.16.0), the same row new projects should use.
| Example | Pattern |
|---|---|
| T5.1 sol-block-stats | All txs including failed (&block.transactions) |
| T5.2 sol-usdc-transfers | SPL TransferChecked + mint filter |
| T5.3 sol-raydium-swaps | Anchor discs + walk_instructions |
| T5.4 sol-pumpfun-launches | Anchor create + string args + account indexes |
| T6.2 sol-marinade-no-idl | Discriminator + layout from Rust source only |
| Symptom | Fix |
|---|---|
| Far fewer events than expected | You used top-level message.instructions — switch to walk_instructions() |
| Empty output | Wrong program ID, wrong disc, initialBlock past data, or filtering failed txs incorrectly |
| Mint filter never matches | Using SPL Transfer (3) instead of TransferChecked (12); or wrong program (Token vs Token-2022) |
Two substreams versions in cargo tree | Mixed majors (0.6+0.15 / 0.7+0.14). It still builds — realign to a matched pair anyway |
type Address<'_> cannot be dereferenced | ix.accounts() yields owned Address; drop the * (if a == MINT). Only .iter() gives you &Address |
| Wrong account field | Re-check IDL account order or Accounts struct — do not guess indexes |
| Pack / build fails missing protos or wasm | Add protobuf: + binaries: to the manifest, then re-run substreams build |
| Output is hex/base64/JSON of ix data | Decode into typed proto fields — see Hard rule |
| Only discriminator / program filter, no args | Incomplete — parse payload + named accounts for every emitted instruction |
One Event for swap + deposit + create | Split into one message type per instruction |
ClickHouse SYNTAX_ERROR on index / keys | Rename columns in proto (config_index, account_keys) — substreams-sql |
substreams-dev · SQL module: substreams-sql · Hosted sink: substreams-hosted-sink · Self-managed sink: substreams-sink-deploy-local · Testing: substreams-testingWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
12 skills in this plugin
/substreams-bitcoinExpert knowledge for developing Bitcoin Substreams. Use when working with Bitcoin blockchain data, UTXO model, transaction parsing, address extraction, or Esplora API compatibility./substreams-convertExpert knowledge for converting existing blockchain indexing projects into Substreams. Use when migrating a subgraph (The Graph) or a Solana program/contract into a Substreams module pipeline./substreams-devCross-cutting Substreams development — manifests, module graphs (map/store/index), protobuf, performance, debugging. For Ethereum/EVM contract decoding use substreams-ethereum; for Solana programs use substreams-solana; for SQL sinks use substreams-sql./substreams-dev-legacySubstreams development on the pre-buffa stack — substreams 0.7.x and below, where protobuf is prost. Use when the project pins substreams <= 0.7, substreams-ethereum <= 0.11, substreams-solana <= 0.15, or substreams-database-change <= 4, or when Cargo.toml declares prost / prost-build. On substreams 0.8+ use substreams-dev instead; the two stacks generate incompatible types./substreams-ethereumDevelop Substreams for Ethereum and EVM contracts — ABI codegen (Abigen/build.rs), event decoding via match_and_decode, raw topic0 decoding without an ABI, eth_call / RpcBatch, and token-metadata stores. Always decode log data into typed structured protobuf objects (never raw bytes or JSON); one protobuf message type per event. Use when building EVM Substreams, decoding contract events, ERC-20/721/1155, Uniswap/DEX pools, or when the user mentions an Ethereum contract address, ABI, topic0, Solidity, or an EVM chain (Polygon, Arbitrum, Base, BSC, Optimism).
/substreams-hosted-sinkUse when the user wants StreamingFast to host and run a Substreams sink — deploy a .spkg to managed infrastructure (PostgreSQL or ClickHouse only) via the Portal API HostedService. HARD RULE: before any first-time hosted Deploy (or any "ready to deploy?" prompt), stop and offer a substreams run output-quality check as its own turn. For that check, give the user a ready-to-paste substreams run command only (stdout/jsonl) — never substreams sink postgres / any sink binary, never a local ClickHouse/Postgres sync. Building the module is not enough. SF hosts only the sink runner; the user supplies the database. Self-managed sinks: substreams-sink-deploy-local; modules: substreams-sql / substreams-dev.
npx claudepluginhub streamingfast/substreams-skills --plugin substreams-dev