/substreams:substreams-devfrom substreams
Assists with cross-cutting Substreams development: manifests, module graphs (map/store/index), protobuf, build/run, and performance. Routes chain-specific work to dedicated skills.
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 cross-cutting Substreams development: manifests, module graphs, protobuf, build/run, and performance. Chain-specific contract/program work lives in dedicated skills.
| User goal | Skill |
|---|---|
| Ethereum / EVM contracts (ABI, logs, eth_call, Uniswap, ERC-20) | substreams-ethereum |
| Solana programs (walk_instructions, SPL, Anchor, Raydium, …) | substreams-solana |
| SQL sink module / Postgres / ClickHouse | substreams-sql |
| Custom app sink (Go/JS/…) | substreams-sink |
| Run sink yourself / host on StreamingFast | substreams-sink-deploy-local / substreams-hosted-sink |
| Porting a subgraph or contract to Substreams | substreams-convert |
| Testing strategy | substreams-testing |
| Manifest, stores, indexes, cloning, graph-out basics | this skill (substreams-dev) |
Project pins substreams 0.7.x or below (prost, not buffa) | substreams-dev-legacy |
Always establish the target chain early. If the user has not said Ethereum vs Solana (or another family), ask before writing code — then follow the chain skill for implementation details.
substreams 0.8.0 replaced prost with buffa as the
protobuf implementation. This is the single most important thing to establish before writing any
code, because the two generate incompatible types and cannot be mixed in one dependency tree.
Check the user's Cargo.toml first. Everything below — codegen, field access, handler
signatures — follows from which row they are on.
substreams | Protobuf | EVM | Solana | SQL sink |
|---|---|---|---|---|
| 0.8.0 + | buffa | substreams-ethereum 0.12+ | substreams-solana 0.16+ | substreams-database-change 5+ |
| 0.7.x and below | prost | substreams-ethereum 0.11 | substreams-solana 0.15 | substreams-database-change 4 |
Never mix rows. A prost-generated substreams-ethereum against substreams 0.8 does not
compile; worse, some mismatches link successfully and pull two substreams copies into the binary.
cargo tree | grep substreams should show exactly one version.
This skill documents the buffa stack. On the prost stack these differ:
| prost (≤ 0.7) | buffa (0.8+) | |
|---|---|---|
| Codegen | substreams protogen wrote a temporary buf.gen.yaml for the prost plugin and deleted it after | a checked-in buf.gen.yaml pins the buffa plugin |
| Generated code | src/pb/, or OUT_DIR for a project that ran prost_build from its own build.rs | checked in under src/pb/, regenerated on demand |
| Singular message field | Option<T>, unwrap to read | MessageField<T>, derefs to a default |
| Enum field | i32, compare with as i32 | EnumValue<E>, compare with the variant |
| Encoding | returns Result | infallible |
| Lazy views | not available | lazy_views=true, &FooLazyView<'_> handlers |
Load substreams-dev-legacy instead. It is this skill frozen at its last pre-buffa revision, so
its codegen, field access and crate versions are correct for 0.7.x. Either help the user upgrade all
four crates together to the top row, or work from that skill — do not hand a 0.7 user buffa idioms,
because MessageField, EnumValue, .as_option() and lazy handlers do not exist there.
Substreams indexes blockchain data through composable Rust modules compiled to WASM, executed in parallel by the engine, with cursor-based reorg handling.
substreams.yaml): modules, networks, dependencieswasm32-unknown-unknownGeneric layout — domain protobufs are generated by buf generate from a buf.gen.yaml and the
result is checked in. EVM additionally uses abi/ + Abigen in a build.rs; Solana does not.
my-substreams/
├── substreams.yaml # Manifest (manual) — must include protobuf: + binaries:
├── README.md # Package docs for substreams.dev registry (manual)
├── Cargo.toml # Rust dependencies (manual)
├── buf.gen.yaml # buffa codegen config (manual)
├── build.rs # EVM only: Abigen for ABI bindings
├── proto/events.proto # Schema definitions (manual)
├── src/
│ ├── lib.rs # Rust module code + mod pb; (manual)
│ └── pb/ # Generated protobuf Rust — checked in, never hand-edited
└── target/ # Build output (gitignored)
Do not hand-write generated proto Rust. Generate it and commit the result:
# 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
lazy_views=true emits the *LazyView types that make lazy handlers possible (see Performance);
unknown_fields=false drops round-trip fidelity WASM modules do not need and keeps decode cheap.
Nothing extra goes in [build-dependencies] for this — buf does the generation, not cargo.
src/pb/mod.rs is generated. The buffa plugin emits one stitcher per proto package
(myproject.v1.mod.rs) but no top-level mod.rs tying them together, so substreams build and
substreams protogen write that file, wiring up every package the descriptor set reaches:
// @generated by substreams
#![allow(clippy::all)]
pub mod myproject {
pub mod v1 {
include!("myproject.v1.mod.rs");
}
}
The first line is an ownership marker. A mod.rs that does not start with it is treated as
someone else's and left untouched, so a project that already hand-writes the file keeps it. Commit
what the CLI writes. Add **/.last_generated_hash to .gitignore; substreams build and
substreams protogen write it themselves, to skip regeneration when nothing changed without going
back to buf, and neither ignores it for you.
substreams protogen # Proto bindings only (fast iteration)
substreams build # Full WASM + spkg
Chain-specific scaffolding (full Solana / EVM Cargo + build.rs + packable manifest): substreams-solana / substreams-ethereum.
substreams build for protobuf codegenrustup target add wasm32-unknown-unknownsubstreams run against hosted endpoints requires auth. Get an API key from The Graph Market.
substreams auth # interactive; exchanges the key and stores the token locally
Alternative: export SUBSTREAMS_API_KEY="…" (or SUBSTREAMS_API_TOKEN="<jwt>" for a bearer token directly).
If you send the user to a browser login, treat it like Portal device login: show the link, end the turn, and wait for the user to confirm — do not background-poll or busy-wait.
This is data-plane auth, not Portal auth.
SUBSTREAMS_API_KEY/SUBSTREAMS_API_TOKENauthenticatesubstreams runagainst the streaming data endpoints. The StreamingFast Portal admin API (billing, usage, hosted deployments) is separate — seethegraph-market-api. A Portal bearer token will not authenticatesubstreams run. Reach for that skill only for plan, quota, usage, or deployment status.
Before writing code, confirm the items below. If any is missing or ambiguous, ask — do not assume silently.
Bad: one message with 6 free-text questions and no options. Good: "Which chain?" → options → answer → next turn "Where should output go?" → options including custom.
| Required input | Why it matters | Example choices (always end with custom) |
|---|---|---|
| Target chain | Routes to substreams-ethereum vs substreams-solana | Ethereum mainnet · Other EVM · Solana mainnet · Other / custom |
| Contract / program ID(s) | EVM address vs Solana program ID | Known protocol names · Other / paste address |
| Data to capture | Events / instructions / state | Protocol presets · Other / describe fields |
| Output / sink destination | See destination list below | Full list · Other / custom |
| Block or slot range | initialBlock and test range | Suggested windows · Head / recent · Other / enter range |
| Thresholds or filters | Min value, mint allowlist, etc. | None · Suggested filter · Other / custom |
| Block sparsity | If the target appears in only some blocks, a block index filter is a near-mandatory cost optimization | Sparse (index filter) · Every block · Other / not sure |
| Choice | What it means | Follow-on skill |
|---|---|---|
substreams run only | Typed protobuf; verify with CLI/GUI first | this skill + chain skill |
| SQL — self-managed | User runs substreams sink postgres/clickhouse into Postgres/ClickHouse | substreams-sql → substreams-sink-deploy-local |
| SQL — StreamingFast hosted | StreamingFast runs the SQL sink (Portal; Postgres or ClickHouse only) | substreams-sql → substreams-hosted-sink |
| The Graph / graph-out | EntityChanges for subgraph consumption | substreams-sink |
| Custom app sink | Go/JS/Python/Rust consumer | substreams-sink |
| Not sure yet | Default to run-only; add a sink later | this skill |
| Other / enter a custom answer | Free-text destination | route from answer |
SQL is two destinations, not one: if the user says only "SQL", ask in a separate turn self-managed vs StreamingFast hosted (plus custom). Hosted still needs a correct SQL module (substreams-sql).
Once the chain is known, load and follow substreams-ethereum or substreams-solana. Keep this skill for module graph design, manifest rules, and performance. Chain and sink skills use the same one-question + choices + custom protocol.
If the prompt is concrete and complete, skip the checklist and build immediately.
Before building from scratch, search the registry — an existing package may already index the data you need. Public, no auth required.
Endpoint: GET https://substreams.dev/v1/registry/packages
| Param | Description |
|---|---|
query | Free-text search over package name/keywords |
network | Filter by network (e.g. mainnet) — see the caveat below |
organization | Filter by organization slug |
user | Filter by publisher user login |
featured | true to restrict to featured packages |
page | 1-based page number (default 1) |
page_size | Results per page (default 24, max 100; pageSize also works) |
curl "https://substreams.dev/v1/registry/packages?query=uniswap&page_size=5"
Response shape — fields are omitted, not empty. This is proto3 JSON: default-valued and absent fields do not appear at all.
{
"packages": [
{
"name": "uniswap_v3",
"slug": "uniswap-v3",
"organization": { "name": "Uniswap", "slug": "uniswap" },
"repository": "https://github.com/...",
"downloads": 7,
"releaseCount": 1,
"latestVersion": "v0.1.0",
"network": "mainnet",
"reference": "[email protected]",
"spkg": "https://spkg.io/v1/packages/uniswap-v3/v0.1.0"
}
],
"hasMore": true
}
Parse defensively — every one of these is real:
hasMore is absent when there are no more pages (not false). Treat missing as "done".{} — not {"packages": []}. Treat missing packages as an empty list.network, organization, and repository are omitted when absent. ethereum-common has no network field.name and slug differ: name may use underscores (uniswap_v3), slug uses hyphens (uniswap-v3). URLs are built from the slug.Do not add
network=mainnetreflexively. It excludes packages that have nonetworkfield — includingethereum-common, the foundational package this skill tells you to import.?query=ethereum-commonreturns it;?query=ethereum-common&network=mainnetreturns{}.
spkg vs reference — pick the right one:
spkg — full package URL (https://spkg.io/v1/packages/<slug>/<version>). Use this for execution and for imports:: substreams run <spkg> <module>, substreams gui <spkg>, substreams info <spkg>, imports: { eth_common: <spkg> }.reference — short <slug>@<version> notation. Prefer spkg for scripted use. CLIs older than 1.20.0 rewrite name@version to https://substreams.dev/v1/packages/<name>/<version>, which returns an HTML 404; CLI ≥ 1.20.0 resolves short names through spkg.io. Working download hosts are spkg.io and api.substreams.dev only. There is no @latest tag — pin the version from latestVersion / spkg.Both are absent when no release version is known.
Rate limits: the API is rate-limited per IP. Over-limit requests return 429 with a Retry-After header — honor it and back off. The full contract is published at GET https://substreams.dev/v1/registry/openapi.yaml (source of truth for fields; it does not document the rate limits).
Migrating an existing project? Load
substreams-convertif porting a subgraph or Solana/EVM contract rather than starting fresh.
substreams init, or write the manifest manually.proto files for your data structuressrc/lib.rssubstreams build → .spkgsubstreams run over a small range (~1000 blocks)README.md for the registry (below)Every published package must ship a README.md — it is the package's front page on substreams.dev, and its presence silences the README (package.doc) not found warning.
Required sections: title (matching package.name), one-line description, Overview (2-3 sentences: what data, what chain, intended use), Modules table (every name: from the manifest, with kind + output type + description — consumers need this to know what to substreams run), Prerequisites, and a Quick Start with a real substreams run command over a real block range (not a placeholder).
Do NOT add "Contributing" or "License" sections — the registry pulls license from the manifest.
substreams registry verify ./substreams.yaml # optional preflight
substreams build
substreams publish ./substreams.yaml --yes # or path to .spkg
| Issue | Action |
|---|---|
version_exists / "Release version already exists" | Bump package.version patch (v0.1.0 → v0.1.1), rebuild, publish |
| Package name collision / ownership | Choose a unique package.name, or publish under a team (--team-slug) |
| After successful publish | Web URL is https://substreams.dev/packages/<name>/<version> |
Hosted SQL sink package source (important): after publish, for StreamingFast hosted Deploy prefer:
https://api.substreams.dev/v1/packages/<package-name>/<version>
Verify the URL returns a binary .spkg (size ≈ local file), not HTML. Prefer this as spkg.url over substreams_dev_id alone — some hosted runners mis-parse substreams-dev://name@version. Full flow: substreams-hosted-sink + thegraph-market-api.
Full details: references/module-types.md.
Map — transforms input to output:
- name: map_events
kind: map
inputs:
- source: sf.ethereum.type.v2.Block
output:
type: proto:my.types.Events
Store — aggregates across blocks:
- name: store_totals
kind: store
updatePolicy: add
valueType: int64
inputs:
- map: map_events
Store inputs use block form, never inline commas.
- store: x, mode: deltasis a YAML parse error — a plain scalar may not contain": ". Write:inputs: - store: store_totals mode: deltas # or: get
Index (kind: blockIndex) — emits per-block Keys so downstream modules can skip blocks. The handler is #[substreams::handlers::map] returning Keys. See "Block & Transaction Filtering" below.
initialBlockmodules:
- name: map_events
kind: map
initialBlock: 18000000 # ✅ start of your test/data range
# NOT: 12369621 # ❌ protocol genesis — forces full backfill on every run
Pin initialBlock to the first block your downstream consumer actually needs. The runtime starts at max(--start-block, initialBlock) and walks forward; stores must catch up from initialBlock on each cold start, so a deep genesis pin turns a 100-block test into a multi-hour backfill.
Whenever a Substreams targets only a subset of blocks — a specific contract, program, event signature, account, or transaction type — add a blockFilter. Be aggressive about this. It is the biggest win available for both your iteration speed and your bill: you are billed for blocks the engine actually processes, so a contract active in 0.5% of blocks costs roughly 0.5% as much, and backfills that would take hours finish in minutes. When the cached index shows a whole segment has no match, the server also skips loading the stores and WASM for that segment.
Default shape: raw Block source + blockFilter on a foundational index module. One module reads the block and extracts everything you need; the foundational index is computed once for the whole chain and is very likely already cached, so setting up the filter costs nothing.
imports:
ethereum_common: [email protected] # see "Import forms" below
modules:
- name: map_trades
kind: map
inputs:
- source: sf.ethereum.type.v2.Block
blockFilter:
module: ethereum_common:index_events
query:
string: evt_addr:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 # or `params: true` + a `params` input
output:
type: proto:my.types.v1.Trades
Foundational index modules: ethereum_common:index_events (evt_addr:, evt_sig:), index_calls (call_to:, call_from:, call_method:), index_events_and_calls; solana_common:program_ids_without_votes (program:), program_ids_and_accounts_without_votes (program:, account:). The blockFilter.module's initialBlock cannot be greater than the filtered module's.
Query (SQE): boolean expression over keys — &&, ||, - (not), ( ) grouping. A bare term must match a key exactly: "evt_addr:0xa && -evt_addr:0xspam".
Critical rules:
blockFilter gets blocks skipped — listing the index as a dependency is not enough.evt_addr: vs address:), and values match by literal equality — use 0x-prefixed lowercase hex (EVM checksum/mixed-case addresses never match).map and store modules take a blockFilter; a blockIndex module cannot.blockFilter is block-level, not record-level. On a kept block your module still sees every event/instruction in it — keep an in-handler check on the raw address / program ID (cheap: compare bytes before decoding) unless you use a filtered_* module.Alternatives, in order of preference:
filtered_* module (ethereum_common:filtered_events, filtered_calls, filtered_transactions; solana_common:transactions_by_programid_without_votes) as a map: input — it applies the blockFilter and returns only matching records. It adds a module (data is copied into your module and written to the cache) and drops the surrounding transaction context, so prefer the raw-Block shape above when you need that context or are optimizing for backfill cost. You must override its default params query, or you silently emit the default's data:
inputs:
- map: ethereum_common:filtered_events
params:
ethereum_common:filtered_events: "evt_addr:0xdac17f958d2ee523a2206206994597c13d831ec7"
blockIndex module — only when no foundational index has the keys you need and several of your modules filter on it. An index runs on every block, so for a single module it costs about as much as checking the condition in the module's own code. Build it from a module you already need rather than decoding the block a second time, prefix your keys (evt_addr:), and do not emit values unique to one block (tx hashes). Handler and manifest: references/block-filtering.md.Import forms. With CLI ≥ 1.20.0 a registry package imports as <package>@<version> (or <org>/<package>@<version>); the version is required and @latest is refused. On older CLIs short names fail with package does not exist on the Substreams registry — use the full URL instead: https://spkg.io/v1/packages/ethereum-common/v0.3.3 (hyphenated slug in the URL, underscored package.name in substreams info).
Full guide (SQE syntax, params vs string, use inheritance, foundational indexes, decision flowchart): references/block-filtering.md.
Full spec: references/manifest-spec.md.
specVersion: v0.1.0
package:
name: my-substreams
version: 1.7.1
url: https://github.com/myorg/my-substreams
description: What this substreams does
protobuf:
files:
- events.proto
importPaths:
- ./proto
binaries:
default:
type: wasm/rust-v1
file: ./target/wasm32-unknown-unknown/release/my_substreams.wasm
network: mainnet # see references/networks.md
versionrequires avprefix. Usev0.1.0, not0.1.0. The error (version "0.1.0" should match Semver) is misleading — both are valid semver, but Substreams mandates thevform. Applies topackage.versiononly.
Always set
url+description, add aREADME.md, and never usepackage.doc. Omitting these produces a wall of non-fatal warnings on every build — confusing, looks broken, isn't.package.docis deprecated; delete it if a scaffold includes it and write aREADME.mdinstead (the packager picks it up automatically). Module-leveldoc:fields are fine.
WASM bindgen shims — some crates (solana_program, alloy, chrono) emit bindgen imports under wasm32-unknown-unknown. To compile:
binaries:
default:
type: wasm/rust-v1+wasm-bindgen-shims
The shims allow compilation but do not implement the underlying functionality — avoid calling those imports at runtime.
Always set crate-type = ["cdylib"], release LTO, and declare buffa / buffa-types alongside substreams.
| Chain | Skill for full Cargo.toml | Core crates |
|---|---|---|
| EVM | substreams-ethereum | substreams = "0.8.0", substreams-ethereum = "0.12.0", hex |
| Solana | substreams-solana | substreams = "0.8.0" + substreams-solana (never mix majors), bs58, sha2 |
| SQL DatabaseChanges | substreams-sql | substreams-database-change = "5.0.0" |
Declare
buffaandbuffa-typesyourself — thesubstreamsre-export does not cover them. Generated protobuf code emits absolute::buffa::paths, which resolve only if your own crate hasbuffaas a direct dependency. A downstream crate that relies onsubstreams::buffaalone fails to compile with unresolved-crate errors insrc/pb.substreams = "0.8.0" buffa = { version = "0.9", default-features = false, features = ["std", "fast-utf8"] } buffa-types = { version = "0.9", default-features = false }
Shared pitfalls:
hex-literal uses a hyphen in Cargo.tomlbuffa-types when generated src/pb references Timestamp / Anysubstreams copies — check cargo tree, realign to a matched pair (substreams-solana). Link / multiply-defined errors are more often two buffa copies or a substreams-database-change mismatched to the substreams major — realign then rm -rf target && substreams buildwasm/rust-v1+wasm-bindgen-shims and/or default-features = false on chrono etc.MessageField)Singular message fields are MessageField<T>, not Option<T>. MessageField derefs for reading, so block.header.timestamp replaces block.header.as_ref().unwrap().timestamp — an unset field reads as the default rather than panicking.
| Want | Use |
|---|---|
| Read a nested field | x.field.inner (deref) |
A genuine Option | .as_option() / .into_option() |
| Presence check | .is_set() / .is_unset() |
| Build one | Inner { … }.into() — not Some(Inner { … }) |
| Clear one | MessageField::none() |
There is no DerefMut. Assigning through a deref is a compile error. Mutate with .get_or_insert_default(), .as_option_mut(), .take(), or .modify(f):
x.header.get_or_insert_default().foo = value; // not: x.header.as_mut().unwrap().foo = value
Migration hazard — deleting an unwrap can silently change behavior. Because
MessageFieldderefs to a default, removing an.unwrap_or(x)wherexis not the zero value compiles cleanly and produces wrong numbers. A tokendecimalsfallback of.unwrap_or(18)dropped during migration makes every amount wrong by 10¹⁸ — no error, no panic, just bad data.Rule: when removing an unwrap, check what the fallback was. Zero value → safe to drop. Anything else → keep it explicitly.
Enums are EnumValue<E>, not bare i32: build with TransactionTraceStatus::Succeeded.into(), compare directly (tx.status == TransactionTraceStatus::Succeeded), and use .to_i32() / .as_known() when you need the raw value or an Option<E>.
#[substreams::handlers::map]
pub fn map_events(/* chain block type */) -> Result<Events, Error> {
// Transform one block → typed proto output
Ok(Events::default())
}
#[substreams::handlers::store]
pub fn store_totals(events: Events, store: StoreAddInt64) {
for item in events.items {
store.add(0, &item.key, item.amount as i64);
}
}
substreams-ethereumwalk_instructions + Anchor/SPL: substreams-solanaset_if_not_exists stores, never a HashMap inside a map handler (RPC budget).Result<T, Error>; never panic in handlerssubstreams::log::info! / log::debug! — there is no warn!)substreams run before deployingDuring a backfill the engine spends time reading blocks, running your WASM, reading/writing cached module output, and building stores. Full guide: references/performance.md. The short version:
blockFilter on a foundational index — by far the biggest cost lever (see above)substreams::skip_empty_output() when a module has nothing to emit for a block (below).initialBlock as late as possible — the first block that can contain data for the module (contract/program deployment). Matters most for stores, which always backfill from their initial block.--production-mode enables parallel execution for large ranges (and is the only mode that uses the module cache)initialBlock. Keep old store hashes with use: — references/updating-packages.mdskip_empty_output()#[substreams::handlers::map]
fn map_trades(block: Block) -> Result<Trades, Error> {
substreams::skip_empty_output();
let trades = extract_trades(&block);
Ok(Trades { trades })
}
A module whose inputs are all skipped does not run for that block (only the clock input is ignored in this check). A protobuf message holding only default values counts as empty. Downstream modules therefore stop running too.
db_out). Base58 is especially slow; hex doubles the data size.int64 / float64 store value types when values fit; bigint / bigdecimal cost more to encode, decode, and add.The chain Block and its transactions are large. Cloning them in a handler is the most common self-inflicted performance problem.
Block — copies every transaction with it.&T and copy only the small owned values (a hash string, an amount) into your proto output.String key reused across an inner loop is fine, and cloning a Copy primitive like block.number is a no-op you need not think about.Chain-specific iteration (EVM transactions() / logs_with_calls(), Solana walk_instructions()) belongs to substreams-ethereum and substreams-solana — follow those skills for the correct loop shape, which also determines which records you see, not just how fast you see them.
A handler that takes a lazy view of the block instead of an owned Block decodes nested and repeated fields only when they are read, which measures 2.9-4.9x faster decode on handlers that touch a small slice of the block.
#[substreams::handlers::map]
fn map_transfers(blk: ð::BlockLazyView<'_>) -> Result<MyOutput, Error> {
// nested fields decode when read
}
Lazy is selected purely by the handler signature — no macro flag, no manifest field. blk: ð::BlockLazyView<'_> is lazy, blk: eth::Block is eager. The #[handlers::map] macro reads the argument type and emits the lazy decode path when it sees a reference, so the only thing you change is the signature. The *LazyView types themselves come from lazy_views=true in buf.gen.yaml.
Validation moves to access time. An owned handler decodes the whole block up front; a lazy one surfaces a decode failure as an Err from the accessor that touched the field. In practice this never fires — the block reaching your module was produced and validated by the Substreams stack itself, so a malformed one means something is broken far upstream of you. Treat the error path as defensive programming rather than a case to design around, and propagate it with ? rather than swallowing it with unwrap_or_default().
Measuring:
substreams runexecutes your WASM server-side, so wall-clock time is dominated by network transfer and endpoint queueing, and a code change alters the module hash (cold cache) while the baseline ran warm. It is not a controlled A/B for handler CPU. To measure handler cost, benchmark at the WASM level — seesubstreams-testing.
references/patterns.md — store aggregation, multi-module composition, parameterized modules, error handling.
substreams-ethereumsubstreams-solanasubstreams-sqlAlso load the
substreams-sinkskill when building agraph_outmodule — it has the full working example.
| You want to write to | Output proto | Package |
|---|---|---|
| The Graph / subgraph | EntityChanges | sf.substreams.sink.entity.v1 |
| Postgres / SQL | DatabaseChanges | sf.substreams.sink.database.v1 |
These are NOT interchangeable. Using DatabaseChanges in a graph_out module (or vice versa) compiles but produces a pipeline that fails or emits garbage.
Do not use the substreams-entity-change crate. It is deprecated and no longer supported by graph-node; on top of that its published versions are built against prost and an older substreams major, so they drag a second substreams copy into a buffa pipeline. Inline the proto instead.
proto/entity.proto (exact package name required):
syntax = "proto3";
package sf.substreams.sink.entity.v1;
option go_package = "github.com/streamingfast/substreams-sink-entity-changes/pb/sf/substreams/sink/entity/v1;pbentity";
message EntityChanges {
repeated EntityChange entity_changes = 5; // NOT 1 — see the warning below
}
message EntityChange {
string entity = 1;
string id = 2;
// Deprecated, this is not used within `graph-node`.
uint64 ordinal = 3;
enum Operation {
OPERATION_UNSPECIFIED = 0;
OPERATION_CREATE = 1;
OPERATION_UPDATE = 2;
OPERATION_DELETE = 3;
OPERATION_FINAL = 4;
}
Operation operation = 4;
repeated Field fields = 5;
}
message Value {
oneof typed {
int32 int32 = 1;
string bigdecimal = 2;
string bigint = 3;
string string = 4;
string bytes = 5;
bool bool = 6;
int64 timestamp = 7;
Array array = 10;
}
}
message Array {
repeated Value value = 1;
}
message Field {
string name = 1;
optional Value new_value = 3;
// Deprecated, this is not used within `graph-node`.
optional Value old_value = 5;
}
Wire compatibility — field numbers are not cosmetic. Copy this proto verbatim from the canonical source. Package name, message names, field numbers, and field types must all match exactly.
The failure mode is silent:
entity_changesis tag 5, not 1. Number it 1 and your module still compiles, still runs, and still emits data — but Graph Node reads tag 5, finds nothing, and ingests zero entities with no error. LikewiseOperationmust use theOPERATION_*names (a bareUNSET/CREATEenum changes the generated Rust variants), andbytesis astringfield, notbytes.
The proven-working variant in examples/T3.2-cross-dex-volume/proto/entity.proto omits the deprecated old_value and unused timestamp — safe, since dropping unused optional fields does not shift the tags that matter.
output:
type: proto:sf.substreams.sink.entity.v1.EntityChanges
use crate::pb::sf::substreams::sink::entity::v1::{EntityChange, EntityChanges, Field};
use crate::pb::sf::substreams::sink::entity::v1::entity_change::Operation;
Requires data-plane auth (substreams auth / SUBSTREAMS_API_TOKEN).
# map_clocks emits sf.substreams.v1.Clock for every block; -s -1 starts at chain head.
# Do NOT combine -s -1 with a relative -t +N (the CLI requires an absolute start for +stop).
# Ctrl-C after the first line, or pipe through head.
substreams run https://spkg.io/v1/packages/common/v0.1.0 map_clocks \
-s -1 --network mainnet -o jsonl
Read the first line for the head clock (number / hash). Default endpoint for a network: substreams tools default-endpoint <network>.
Using firecore: firecore tools firehose-client <network-id-alias-or-host> -o json -- -1
substreams graph to visualize dependenciesinitialBlock: see the initialBlock guidance above — a genesis pin makes local runs impracticalNon-fatal package warnings (package.doc deprecated, README (package.doc) not found, URL (package.url) is not set, Description (package.description) is not set): all four clear with a package: block that sets url + description, a sibling README.md, and no doc: field. Builds still succeed. See "Manifest Reference".
Build fails:
version "x.y.z" should match Semver → add the v prefix to package.versionrustup target add wasm32-unknown-unknownbuf is installed (required for proto generation)protobuf.excludePaths with sf/substreams and google when importing spkgsLinking errors ("symbol multiply defined", "failed to load bitcode") — almost always crate version mismatch:
rm -rf target && substreams buildsubstreams or two buffa copies (cargo tree -d)buffa, a stray prost dragged in by a crate that has not migrated, or substreams-database-change mismatched to the substreams majorsubstreams from a mismatched Solana pair often still links — fix the pins anyway (substreams-solana)Missing method on ABI-generated types ("no method named decode"): add use substreams_ethereum::Event; — the trait carries the method.
spkg import 404s:
https://spkg.io/v1/packages/<slug>/<version> or https://api.substreams.dev/v1/packages/<slug>/<version>. Short name@version rewrites to https://substreams.dev/v1/packages/... and 404s (HTML site, not the package API).substreams-ethereum spkg, NOT sf-ethereum (doesn't exist)latestVersion)ethereum-common), while name may use underscoresEmpty output:
initialBlock is at or before the first relevant blockblockFilter query mismatch — lowercase hex?)substreams-ethereum — EVM contracts · substreams-solana — Solana programsreferences/block-filtering.md (opens in a new tab)references/manifest-spec.md (opens in a new tab)references/module-types.md (opens in a new tab)references/networks.md (opens in a new tab)references/patterns.md (opens in a new tab)references/performance.md (opens in a new tab)references/updating-packages.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
substreams, blockchain-data, protobuf, module-graphs, streamingfast
npx claudepluginhub streamingfast/substreams-skills --plugin substreams-dev12 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-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.