# Envio docs: HyperSync for Solana and Fuel > Solana HyperSync (query schema, client, curl examples) and HyperFuel, HyperSync for the Fuel network. Generated at build time from the pages of https://docs.envio.dev. Each page below is the full markdown of one docs page, after a `` line. Append `.md` to that URL to fetch the page on its own. The index of every page is https://docs.envio.dev/llms.txt. Context files, one per product area: - [llms-hyperindex.txt](https://docs.envio.dev/llms-hyperindex.txt): HyperIndex core, about 47k tokens. Build, run and test an indexer: getting started, config.yaml, schema, handlers, CLI, testing, troubleshooting. - [llms-hyperindex-advanced.txt](https://docs.envio.dev/llms-hyperindex-advanced.txt): HyperIndex advanced features, about 32k tokens. Factories, the Effect API, wildcard indexing, preload, contract state, IPFS, HyperSync and RPC sources, reorgs, WebSockets. - [llms-hyperindex-reference.txt](https://docs.envio.dev/llms-hyperindex-reference.txt): HyperIndex performance and reference, about 27k tokens. Config schema reference, observability, performance tuning, benchmarks, supported chains and licensing. - [llms-hyperindex-examples.txt](https://docs.envio.dev/llms-hyperindex-examples.txt): HyperIndex examples and tutorials, about 16k tokens. Example indexers (Uniswap v4, Sablier, Velodrome and Aerodrome) and EVM tutorials. - [llms-hyperindex-migration.txt](https://docs.envio.dev/llms-hyperindex-migration.txt): HyperIndex migration guides, about 14k tokens. Upgrade a V2 indexer to V3, or migrate from The Graph, Ponder or Alchemy, by hand or with AI. - [llms-hyperindex-solana-fuel.txt](https://docs.envio.dev/llms-hyperindex-solana-fuel.txt): HyperIndex on Solana and Fuel, about 21k tokens. Solana programs (instruction and slot handlers, decoding, config) and Fuel contracts. - [llms-envio-cloud.txt](https://docs.envio.dev/llms-envio-cloud.txt): Envio Cloud, about 24k tokens. Deploy, monitor and manage hosted indexers: features, CLI, billing, organisations, self-hosting. - [llms-hypersync.txt](https://docs.envio.dev/llms-hypersync.txt): HyperSync core, about 36k tokens. EVM data: quickstart, API tokens, clients, query reference, curl, stream tuning, supported networks, tutorials. - llms-hypersync-solana-fuel.txt (this file): HyperSync for Solana and Fuel, about 15k tokens. Solana HyperSync (query schema, client, curl examples) and HyperFuel, HyperSync for the Fuel network. - [llms-hyperrpc.txt](https://docs.envio.dev/llms-hyperrpc.txt): HyperRPC, about 6k tokens. Read-only JSON-RPC endpoint powered by HyperSync: supported methods, usage and supported networks. Pages in this file: - Solana HyperSync - Solana Query & Response - Solana HyperSync Client - Solana curl Examples - HyperFuel - HyperFuel Query --- # Solana HyperSync > HyperSync for Solana - ultra-fast queries over Solana slots, transactions, instruction calls, logs, and account activity. Solana HyperSync is a query API over Solana history. One endpoint, **`https://solana.hypersync.xyz`**, serves slots, transactions, instruction calls, logs, account activity (SOL + SPL token) and rewards - filtered server-side and returned as columns you choose, in JSON or Apache Arrow. Query it with the [Solana client](https://docs.envio.dev/docs/HyperSync/solana-client.md) or any HTTP client. ## First query: everything an address touched Filters run server-side, so what costs an RPC node a `getSignaturesForAddress` call plus one `getTransaction` per signature is **one request** here, returning only the columns you ask for: ```bash export TOKEN="your-api-token" # see https://envio.dev/app/api-tokens HEAD=$(curl -sS https://solana.hypersync.xyz/height) curl -sS "https://solana.hypersync.xyz/query" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "from_slot": '$((HEAD - 10000))', "to_slot": '$HEAD', "field_selection": { "account_activity": ["slot", "transaction_id", "account", "pre_balance", "post_balance", "mint", "pre_token_balance", "post_token_balance"] }, "account_activity": [ { "account": ["MfDuWeqSHEqTFVYZ7LoexgAK9dxk7cy4DFJWjWMGVWa"] }, { "owner": ["MfDuWeqSHEqTFVYZ7LoexgAK9dxk7cy4DFJWjWMGVWa"] } ] }' ``` Each row is one account's before/after balance in one transaction, and `transaction_id` is the Solana signature. SOL and SPL token movements share the `account_activity` table; the two selections are OR-ed because `account` is the wallet on a SOL row but the token account on a token row, so `owner` catches the token side. `next_slot` tells you where to resume. **Swap the filter, keep the shape.** The same request filters on a program and discriminator (`instruction_calls`), a fee payer or signature (`transactions`), a log kind (`logs`), or a mint or owner (`account_activity`) - AND-ed within one selection object, OR-ed across several. **[See every available filter →](https://docs.envio.dev/docs/HyperSync/solana-query.md#filters)**, grab a ready-made query from [curl Examples](https://docs.envio.dev/docs/HyperSync/solana-curl-examples.md), or build one by clicking in the [Query Builder](https://builder.hypersync.xyz/#solana). :::info How far back history goes History starts at the earliest slot we have indexed rather than at genesis - mainnet is around slot **391,000,000** as of September 2026 - and we keep extending it backwards as we backfill deeper. A range that straddles that slot is served from it onward; one entirely below it comes back empty rather than erroring, with `next_slot` not advancing. Need history further back? [Tell us on Discord](https://discord.gg/envio). ::: **You'll need an API token.** Every endpoint requires a Bearer token except `GET /height` and `GET /height/sse`. Generate one at [https://envio.dev/app/api-tokens](https://envio.dev/app/api-tokens) - see [API tokens](https://docs.envio.dev/docs/HyperSync/api-tokens) for details. **Slots vs blocks:** some slots have no block (skipped leader, etc.), so a query over `[from_slot, to_slot)` can return fewer block rows than the slot span implies. ## Differences vs EVM HyperSync | Concept | EVM | Solana | | --- | --- | --- | | Unit of progress | `block` | `slot` | | Range bounds | `from_block` / `to_block` | `from_slot` / `to_slot` | | Primary filter | `logs`, `transactions`, `traces` | `instruction_calls`, `transactions`, `logs`, `account_activity` | | Match key | event topic + address | program ID + discriminator + account positions | | Logs | Contract events (topics + structured data) | Program output lines (free-form strings; filter by emitter `program_id` and parsed `kind`) | | Pagination | `next_block` | `next_slot` | ## Endpoints | Path | Description | | --- | --- | | `POST /query` | JSON query, JSON response. | | `POST /query/arrow` | Same query; response is Apache Arrow IPC (smaller and faster to decode than JSON). | | `GET /height` | Current synced slot. | | `GET /height/sse` | Server-sent events stream of the head slot (see [curl Examples](https://docs.envio.dev/docs/HyperSync/solana-curl-examples.md#head-slot-sse)). | | `GET /health` | Health check. | | `POST /`, `POST /rpc` | Solana JSON-RPC-compatible facade for tooling that already speaks JSON-RPC. Method coverage is partial, so prefer `POST /query` for indexing. | ## What's coming next - **Deeper history.** The earliest indexed slot keeps moving earlier; backfill depth is prioritized by demand. - **Decoded, higher-level data** on top of the raw tables: IDL-aware decoding and shortcuts for common programs. Until then, the Rust client can [decode instructions](https://docs.envio.dev/docs/HyperSync/solana-client.md#decoding-instructions) from an Anchor IDL on your side. - **Wider JSON-RPC coverage** on the compatibility facade (`POST /` / `POST /rpc`), for tooling that already speaks JSON-RPC. - **More clients.** Today there's the [Rust client](https://docs.envio.dev/docs/HyperSync/solana-client.md); Node bindings are next, Python after that. Want one of these sooner, or hit a missing field or a filter you wish existed? Tell us on [Discord](https://discord.gg/envio) or file it on [GitHub](https://github.com/enviodev/hypersync-client-solana/issues). Share a sample transaction signature or program ID and we'll map it to a concrete query path - the roadmap here is driven by the use cases people bring us. --- # Query & Response > Solana HyperSync query schema, filters, field selection, pagination, and reorg handling. A query selects a slot range, optional filters on instruction calls / transactions / logs / account activity, and the columns you want. The server returns matched rows plus a `next_slot` cursor. Some slots have no block, so `blocks` can be sparse across the requested range. ## Query shape ```json { "from_slot": 391800000, "to_slot": 391800100, "include_all_blocks": false, "instruction_calls": [ ... ], "transactions": [ ... ], "logs": [ ... ], "account_activity": [ ... ], "field_selection": { ... } } ``` - `from_slot` is **inclusive**, `to_slot` is **exclusive**. Omit `to_slot` to run toward the current head. - Within one selection object, all set fields are **AND**-ed. Multiple objects within one array are **OR**-ed. Different arrays are **AND**-ed against each other (see the warning below). - With filters, you get blocks only for slots where something matched. Set `include_all_blocks: true`, or use no filters, to get every block in the range. See [All-blocks mode](#all-blocks-mode). :::warning A second selection array narrows the result, it does not widen it Selections in **different** arrays are intersected. Adding a `transactions` filter next to an `instruction_calls` filter returns only the instructions whose transaction also matches; a selection that matches nothing zeroes **every** table in the response, with no error or warning. Measured on slot 437500000: | Query | Instruction rows | | --- | --- | | `instruction_calls: [{executing_account: [Tokenkeg...], d1: ["03"]}]` alone | 44 | | `transactions: [{fee_payer: [P]}]` alone, where P paid for one of those transactions | 16 | | both together | **2** | | the instruction filter plus `transactions: [{fee_payer: ["1111...1111"]}]` (matches nothing) | **0** | **For a union, send separate queries and merge.** This is about which rows match; whether a matched row's *related* rows come back is decided by `field_selection` (see [Join behavior](#join-behavior)). ::: :::caution Unknown top-level keys are rejected The top-level query object and `field_selection` are strict: an unrecognized key (a removed table such as `balances` / `token_balances`, the removed `include_account_activity` flag, or a misspelled `max_num_*`) fails the whole query rather than silently widening it. Keys **inside** a selection object are still ignored if unknown. To request every activity row in a range, use an empty selection: `"account_activity": [{}]`. A rejected query, like any malformed value (a bad base58 pubkey, an unknown log `kind`), comes back as HTTP 422 with a plain-text body naming the offending key, for example ``Failed to deserialize the JSON body into the target type: balances: unknown field `balances`, expected one of ...``. ::: Several keys were renamed; legacy names are still accepted on input, but responses use the new names. See [Renamed fields and compatibility](#renamed-fields-and-compatibility). ## Filters ### InstructionSelection Selects **instruction calls** (a single program invocation, including inner CPIs). Array key: `instruction_calls` (legacy: `instructions`). | Field | Description | | --- | --- | | `executing_account` | Match the invoked program (base58 pubkeys). Legacy: `program_id`. | | `d1` / `d2` / `d4` / `d8` | First _N_ bytes of instruction data as hex; `0x` prefix optional (`"0x03"` and `"03"` are equivalent). | | `a0` - `a9` | Account pubkey at that **index in the instruction's account metas** (`a0` = first). Which index is "the mint", "the pool", etc. is defined by the program's IDL, not by Solana globally. | | `is_inner` | `true` = inner only, `false` = outer only, omitted = both. | | `tx_success` | `true` = instructions of successful transactions only, `false` = failed only, omitted = both. Legacy: `is_committed`. | `tx_success` is the success of the **parent transaction**, applied to every instruction call of that transaction (Solana metadata only records instructions that actually ran). Set `"tx_success": true` to drop failed transactions server-side. `"tx_success": false` can legitimately match nothing: servers running the failed-transaction trim keep no instruction rows for failed transactions; the transactions themselves are still served (with `err` and `fee`) via the `transactions` table's `success` filter. ### TransactionSelection | Field | Description | | --- | --- | | `fee_payer` | Match fee payer pubkey. | | `transaction_id` | Match by `signatures[0]` (base58), the canonical Solana transaction signature. | | `transaction_index` | Match by `transaction_index`. See [`transaction_index` semantics](#transaction_index-semantics). | | `success` | `true` = succeeded only, `false` = failed only, omitted = both. | ### LogSelection | Field | Description | | --- | --- | | `program_id` | Match log emitter program. | | `kind` | Parsed log line category (below). | | `kind` | Typical meaning | | --- | --- | | `invoke` | `Program invoke ` | | `success` | `Program success` | | `failed` | `Program failed: ...` | | `consumed` | `Program consumed of compute units` | | `log` | `Program log: ...` | | `data` | `Program data: ` | | `other` | Anything else (full text still in `message`) | An unknown `kind` in a filter is an error; on the response side an unrecognized value decodes as `other`. Not every range carries the `invoke` / `success` / `failed` / `consumed` lines: SQD-ingested and default RPC-ingested ranges only carry `log` / `data` / `other`, so do not assume every invocation has an `invoke` row. ### AccountActivitySelection Selects rows of the unified [`account_activity`](#the-account_activity-table) table (native SOL and SPL token movements). An empty selection `{}` matches every activity row in range. | Field | Description | | --- | --- | | `kind` | `"native"` (the rows the old `balances` table held), `"token"` (the old `token_balances` rows), or omitted for both. | | `account` | Match by account address: the token account on a **token** row, the wallet on a **native** row. | | `transaction_id` | Match by the transaction's base58 `signatures[0]`. | | `mint` | Match by mint. Only token rows carry a mint, so this restricts to token activity. | | `owner` | Match by owner (wallet). The stored column is split into `pre_owner` / `post_owner`; this filter matches **either** side, so an in-transaction `SetAuthority(AccountOwner)` change still matches. | | `program_id` | Match by token program id (SPL Token vs Token-2022), pre or post. | | `is_signer` / `is_writable` / `is_fee_payer` / `from_lookup_table` | Header-derived position flags. A null flag matches neither `true` nor `false`. | Because `account` means different things on the two sides, "everything for wallet W" is **two** selections: `[{ "account": ["W"] }, { "owner": ["W"] }]`. ## Field selection `field_selection` chooses columns per table, and also decides which related tables come back: - For a table you **filter** on (a non-empty selection array such as `instruction_calls`), an omitted or empty field list returns **all** its columns. - A table you **don't** filter on comes back only when you list at least one of its fields. The one exception is blocks in [all-blocks mode](#all-blocks-mode). ```json { "field_selection": { "block": ["slot", "blockhash", "block_time"], "instruction_call": ["slot", "executing_account", "data", "d8"], "transaction": ["slot", "fee_payer", "success"] } } ``` ### Available fields (by table) | Table | Fields | | --- | --- | | `block` | `slot`, `blockhash`, `parent_slot`, `parent_blockhash`, `block_time`, `block_height` | | `transaction` | `slot`, `transaction_index`, `transaction_id`, `signatures`, `fee_payer`, `success`, `err`, `fee`, `compute_units_consumed`, `account_keys`, `recent_blockhash`, `version`, `loaded_addresses_writable`, `loaded_addresses_readonly`, `has_dropped_log_messages` | | `instruction_call` | `slot`, `transaction_index`, `instruction_address`, `executing_account`, `executing_account_index`, `account_arguments`, `account_index_arguments`, `data`, `d1`, `d2`, `d4`, `d8`, `a0`-`a9`, `is_inner`, `tx_success`, `error`, `compute_units_consumed` | | `log` | `slot`, `transaction_index`, `instruction_address`, `program_id`, `kind`, `message` | | `account_activity` | `slot`, `transaction_index`, `transaction_id`, `account_index`, `account`, `pre_balance`, `post_balance`, `is_signer`, `is_writable`, `is_fee_payer`, `from_lookup_table`, `mint`, `pre_owner`, `post_owner`, `token_decimals`, `pre_token_balance`, `post_token_balance`, `pre_program_id`, `post_program_id`, `token_state` | | `reward` | `slot`, `pubkey`, `lamports`, `post_balance`, `reward_type`, `commission` | Field notes: - **`tx_success`** (instruction call): see [InstructionSelection](#instructionselection). Legacy column name: `is_committed`. - **`instruction_address`** (instruction call, log): where the instruction sits in the transaction: `[2]` = third top-level instruction; `[2, 0]` = first inner instruction inside it. - **`data` / `d1`-`d8`** (instruction call): hex-encoded instruction bytes, without a `0x` prefix in responses even if your filter used one. - **`executing_account_index` / `account_index_arguments`** (instruction call): positions of the executing account and account arguments in the transaction's resolved key list (`account_keys` ++ ALT writable ++ ALT readonly). Null when the source could not resolve positions. - **`error` / `compute_units_consumed`** (instruction call): per-invocation failure reason (e.g. `"custom program error: 0x1"`) and compute units. SQD serves both directly; RPC and Firehose ranges derive them from the `Program failed` / `consumed` log lines, so both are null where the source did not record them. - **`has_dropped_log_messages`** (transaction): `true` when the validator truncated this transaction's logs, so its `logs` rows are incomplete. Null means the source could not say. - **`transaction_id`** (transaction) and **`token_state`** (account activity) are computed at serving time but selected like any other field. `token_state` is `not_a_token`, `opened` (token account created in this transaction), `closed`, or `persisted`; select it instead of inferring "is this a token row" from null `mint`. ### Value types in responses - **Every response field is optional.** A missing value means "not selected, or the source could not supply it", never zero or false. - **Addresses, hashes and signatures are base58 strings**, parsed strictly (32 bytes for a pubkey/blockhash, 64 for a signature). A malformed value in a filter is an error, not a filter that silently matches nothing. - **Token balances are strings.** `pre_token_balance` / `post_token_balance` are raw base units (scale by `token_decimals`) as decimal strings, so JavaScript consumers don't lose precision above 2^53. Raw SPL amounts are `u64` on-chain in both SPL Token and Token-2022. Lamport fields (`pre_balance` / `post_balance`, `fee`) stay numeric. ### `transaction_index` semantics `transaction_index` is a dense `0..n` rank over the **stored, non-vote** transactions of a slot, in block order. It is **not** the transaction's original position in the block: vote transactions are excluded at ingest, and every source is renumbered onto the same key. `(slot, transaction_index)` is the join key tying `instruction_calls`, `logs`, and `account_activity` rows to their transaction; do not compare it against an index from an RPC `getBlock` response. ### The account_activity table `account_activity` replaces the old `balance` and `token_balance` tables. Each row is one account's activity in one transaction: - **Native side** (`pre_balance`, `post_balance`, lamports): populated when the account's SOL balance changed, null otherwise. - **Token side** (`mint`, `pre_owner`, `post_owner`, `token_decimals`, `pre_token_balance`, `post_token_balance`, `pre_program_id`, `post_program_id`): populated when the account appears in the transaction's token-balance metadata, null otherwise. A row commonly carries both sides, since a token account also holds lamports; the two are independent axes (for wrapped SOL, lamports equal the token amount plus the rent-exempt reserve). A null `pre_owner` means the token account was opened in this transaction, a null `post_owner` that it was closed (same convention for `pre_program_id` / `post_program_id`). `account_index` is the account's position in the transaction's resolved key list; the flags (`is_signer`, `is_writable`, `is_fee_payer`, `from_lookup_table`) come from the message header and are null where a source could not supply them. ## Join behavior The server joins related rows based on which tables you include in `field_selection`. `transactions`, `instruction_calls`, `logs` and `account_activity` share the key `(slot, transaction_index)`; `blocks` and `rewards` join on `slot`. - A transaction **qualifies** when it matches every table you filter on. - Each filtered table returns its matched rows of qualifying transactions. - Each table you select in `field_selection` but don't filter returns **all** its rows for qualifying transactions. Filter on `instruction_calls` and select `transaction` fields, and you get the parent transaction of each matched instruction; filter on `transactions` and select `instruction_call` fields, and you get every instruction, outer and inner, of each matched transaction. - `blocks` and `rewards` come back for the slots of qualifying transactions when you select their fields. There is one join mode and no `join_mode` parameter. Tell us on [Discord](https://discord.gg/envio) or [GitHub](https://github.com/enviodev/hypersync-client-solana/issues) if you need a different shape. ### All-blocks mode With `include_all_blocks: true`, or with no filters at all, you get every block in the range, including slots where nothing matched. Blocks come back even if you select no `block` fields, and then with all their columns, so list the fields you need. Rewards and account activity are not added automatically. Select their fields and they come back for the whole range, not only for matching transactions. If you also filter on `account_activity`, you get only the matching rows, as usual. Whole-range rewards and activity are large, so keep the range small. ## Limits (optional) Approximate server-side caps on rows returned per table: `max_num_blocks`, `max_num_transactions`, `max_num_instructions` (this key keeps the legacy noun; `max_num_instruction_calls` is rejected), `max_num_logs`, `max_num_account_activity`. When you set none, the server applies its own default caps, which are usually fine. Caps cut a response at a whole-slot boundary, so a single slot larger than the cap still comes back in full. ## Response Top-level keys: `next_slot`, `total_execution_time_ms`, optional `rollback_guard`, and one key per table when present: `blocks`, `transactions`, `instruction_calls`, `logs`, `account_activity`, `rewards`. :::caution Each table is an array of row **batches**, not a flat array of rows `instruction_calls` is `[[row, row, ...], ...]`, the same framing EVM HyperSync uses for `data`. A single response is usually one batch, so `table[0]` looks like it works until it hands you a batch instead of a row. Flatten first: in `jq`, `[.instruction_calls[][]]`, and the row count is `[.instruction_calls[][]] | length`. Batches carry no meaning of their own (they do not correspond to blocks or transactions). ::: ```json { "next_slot": 391800050, "total_execution_time_ms": 12, "rollback_guard": null, "blocks": [[{ "slot": 391800000, "blockhash": "8dK...", "block_time": 1731000123 }]], "instruction_calls": [[{ "slot": 391800000, "executing_account": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "account_arguments": ["7xK...", "9mY...", "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"], "data": "33e685a4017f83ad2e0f27c68d080000c61cf79a00000000", "tx_success": true }]], "transactions": [] } ``` Instruction `data` is the raw instruction bytes as hex; for filtering, use the discriminator fields (`d1` / `d2` / `d4` / `d8`). On failure, `transaction.err` is the chain's error structure as a JSON-encoded **string** (e.g. `"{\"InstructionError\":[2,{\"Custom\":2}]}"`), so parse it before inspecting it. ### Pagination Use the response's `next_slot` as the next request's `from_slot`. - **Bounded scan** (`to_slot` set): repeat while `next_slot < to_slot`. - **To head** (no `to_slot`): repeat while `next_slot` strictly increases. If it doesn't, you've caught up to the head or hit a limit; back off. The server may stop before `to_slot` on a row cap, a time budget or a size budget. Each response still covers `[from_slot, next_slot)` completely for every table and holds nothing at or past `next_slot`, so paging this way never skips or repeats a row. ### Reorg detection (`rollback_guard`) `rollback_guard` describes the **server's current in-memory head window**, not the slots in the response: `slot_number` / `blockhash` are the last slot in the window and its hash, `first_slot_number` / `first_previous_blockhash` the first slot in the window and its parent hash. It is present on most responses, including ones far behind head, and `null` when the server has no complete window to describe. The shape mirrors the EVM `RollbackGuard` with Solana naming. ```json { "slot_number": 391800099, "timestamp": 1731000000, "blockhash": "8dK...", "first_slot_number": 391800000, "first_previous_blockhash": "3nF..." } ``` Use it to detect a shallow reorg before committing near-head data: if you have already ingested `first_slot_number - 1` or `slot_number`, compare the blockhashes you stored for them against `first_previous_blockhash` / `blockhash`. A mismatch means what you ingested is no longer on the server's head fork; re-sync from a finalized slot or the newest slot whose hash still agrees. The window moves between calls, so do not compare one page's guard against the next page's, and never treat slot numbers alone as stable identifiers near head; reconcile with `blockhash` / `parent_blockhash`. ## Renamed fields and compatibility Legacy names are still accepted on input, but responses use the new names. | Location | Legacy name | Current name | | --- | --- | --- | | Top-level query | `instructions` | `instruction_calls` | | `InstructionSelection` | `program_id` | `executing_account` | | `InstructionSelection` | `is_committed` | `tx_success` | | `field_selection` | `instruction` | `instruction_call` | | `instruction_call` field | `program_id` | `executing_account` | | `instruction_call` field | `accounts` | `account_arguments` | | `instruction_call` field | `is_committed` | `tx_success` | **Removed, not renamed** (each is a loud error because the envelope rejects unknown keys): - The `balance` / `token_balance` field-selection tables and the top-level `balances` / `token_balances` selections: use `account_activity`. - The top-level `include_account_activity` flag: use `"account_activity": [{}]`. - The `account_activity.owner` **column**, split into `pre_owner` / `post_owner`. The `owner` **filter** is unchanged and matches either side. ## Authentication Every endpoint requires a **Bearer token** except `GET /height` and `GET /height/sse`. See [API tokens](https://docs.envio.dev/docs/HyperSync/api-tokens) for how to generate one. --- # Solana Client > The Solana HyperSync client - install, query, stream, decode Arrow, and handle rate limits. `hypersync-client-solana` is the Rust client for [Solana HyperSync](https://docs.envio.dev/docs/HyperSync/solana.md). It speaks the Arrow endpoint (`POST /query/arrow`), retries transient failures, waits out rate limits, and paginates a slot range across many concurrent requests for you. - [Crates.io](https://crates.io/crates/hypersync-client-solana) - [API docs](https://docs.rs/hypersync-client-solana) - [GitHub](https://github.com/enviodev/hypersync-client-solana) ## Install ```toml [dependencies] hypersync-client-solana = "0.2" hypersync-solana-net-types = "0.2" # SolanaQuery and the selection types tokio = { version = "1", features = ["full"] } anyhow = "1" ``` The query types live in the separate `hypersync-solana-net-types` crate: the client doesn't re-export them, so add both. ## Quick start ```rust use std::sync::Arc; use hypersync_client_solana::{config::ClientConfig, Client}; use hypersync_solana_net_types::query::SolanaQuery; #[tokio::main] async fn main() -> anyhow::Result<()> { let client = Arc::new(Client::new(ClientConfig { url: "https://solana.hypersync.xyz".into(), bearer_token: std::env::var("HYPERSYNC_BEARER_TOKEN").ok(), ..Default::default() })?); let height = client.get_height().await?; let query = SolanaQuery { from_slot: height.saturating_sub(100), to_slot: Some(height), include_all_blocks: true, ..Default::default() }; let resp = client.get(&query).await?; println!("{} blocks, next_slot {}", resp.blocks.len(), resp.next_slot); Ok(()) } ``` `ClientConfig` fields: `url`, `bearer_token`, `http_req_timeout` (30s), `max_num_retries` (12), `retry_base_ms` (500), `retry_ceiling_ms` (5000), and `proactive_rate_limit_sleep` (`true`). See [API tokens](https://docs.envio.dev/docs/HyperSync/api-tokens) for the bearer token. ## Typed rows or Arrow Every method comes in two flavors: typed structs, or the raw Arrow record batches the server sent. | What you want | Single query | Whole slot range | | --- | --- | --- | | Typed structs | `get` | `collect` | | Arrow record batches | `get_arrow` | `collect_arrow` | The typed structs live in `hypersync_client_solana::simple_types`: `Block`, `Transaction`, `InstructionCall`, `Log`, `AccountActivity`, `Reward`, bundled into a `SolanaResponse` with one `Vec` per table. Arrow responses instead carry `data.tables`, a map keyed by table name (`blocks`, `transactions`, `instruction_calls`, `logs`, `account_activity`, `rewards`). Use Arrow when feeding a columnar pipeline (Polars, DataFusion, Parquet); use typed structs for ordinary application code. :::note Every field is `Option` `field_selection` can project any column away, so a `None` means exactly "not selected, or the source could not supply it" - never zero or false. Addresses, hashes, and signatures are the base58 newtypes `Address`, `Hash`, and `Signature`, which parse strictly and reject a malformed value loudly rather than matching nothing. `InstructionCall::stack_height()` is a convenience view over `instruction_address` (its length, matching Solana's native stack height). ::: ## Streaming a range `collect` and `collect_arrow` fan a slot range out across concurrent requests and merge the results; `stream_arrow` gives you the same engine but yields each response as it arrives, in slot order, through an mpsc receiver. ```rust use hypersync_client_solana::config::StreamConfig; let resp = client .collect(query, StreamConfig::default()) .await?; ``` `StreamConfig` for the Solana client: | Option | Default | What it does | | --- | --- | --- | | `concurrency` | `10` | Requests in flight. The main throughput knob, and the lever for making fewer requests per unit time. | | `batch_size` | `1_000` | Slots per chunk before any response size has been measured. | | `min_batch_size` | `100` | Lower clamp on the adaptive chunk size. | | `max_batch_size` | `200_000` | Upper clamp on the adaptive chunk size. | | `response_bytes_ceiling` | `500_000` | Responses above this shrink the next chunk. | | `response_bytes_floor` | `250_000` | Responses below this grow the next chunk. | These are Solana-specific names: the EVM client's `StreamConfig` targets a single `response_bytes_target` instead of a floor/ceiling pair, so the [tuning guide](https://docs.envio.dev/docs/HyperSync/stream-config-tuning) transfers as advice but not field for field. ## Pagination and reorgs A single `get` covers as much of the range as the server's budget allows, so use the response's `next_slot` as the next request's `from_slot`. `collect` and `stream_arrow` do this for you. Responses can carry a `rollback_guard` describing the server's in-memory head window, so you can detect a shallow reorg before committing near-head data. It is absent when the server has no complete window to describe, and on a paginated `collect` it is the guard of the last page that carried one. See [Reorg detection](https://docs.envio.dev/docs/HyperSync/solana-query.md#reorg-detection-rollback_guard) for the algorithm. ## Rate limits The client waits out rate limits and retries, so a stream slows down rather than failing. To read the quota yourself, the Solana client exposes the same surface as the EVM client: `get_with_rate_limit` / `get_arrow_with_rate_limit`, `rate_limit_info()`, `wait_for_rate_limit()`, and the `proactive_rate_limit_sleep` config field. See [Inspecting rate limits from your code](https://docs.envio.dev/docs/HyperSync/stream-config-tuning#inspecting-rate-limits-from-your-code) for the fields, the header mapping, and the one behavioral difference from the EVM client (the Solana `*_with_rate_limit` methods retry a 429; the EVM ones do not). ## Decoding instructions The server returns raw instruction `data`. The `decode` module turns a typed `InstructionCall` into named accounts and arguments, using a schema built from an Anchor IDL (0.30+ or legacy) or a bundled one (`decode::metaplex_token_metadata()` for Metaplex Token Metadata): ```rust use hypersync_client_solana::decode::{decode_instruction, schema_from_anchor_idl_json}; use hypersync_solana_net_types::field_selection::{InstructionField, SolanaFieldSelection}; use hypersync_solana_net_types::query::{InstructionSelection, SolanaQuery}; let schema = schema_from_anchor_idl_json(&std::fs::read_to_string("whirlpool.json")?)?; // The Whirlpool program's calls, with the two columns decoding reads. let query = SolanaQuery { from_slot: height.saturating_sub(100), to_slot: Some(height), instruction_calls: vec![InstructionSelection { executing_account: vec!["whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc".parse()?], ..Default::default() }], field_selection: SolanaFieldSelection { instruction_call: vec![InstructionField::Data, InstructionField::AccountArguments], ..Default::default() }, ..Default::default() }; let resp = client.get(&query).await?; for ix in &resp.instruction_calls { if let Ok(decoded) = decode_instruction(&schema, ix) { println!("{} {} {:?}", decoded.name, decoded.args, decoded.named_accounts); } } ``` `decoded.args` is a `serde_json::Value`: 64- and 128-bit integers are decimal strings, a `pubkey` or `[u8; 32]` is base58, and `bytes` is `0x`-prefixed hex. Accounts past the named list land in `decoded.extra_accounts`. If you list `instruction_call` fields, include `data` and `account_arguments`, as above, so there is something to decode. ## Node bindings The repository also contains napi-rs Node bindings (`node/`), exposing `SolanaClient` with `getHeight()`, `query()`, `getWithRateLimit()`, `rateLimitInfo()`, and `waitForRateLimit()`. They are **not published to npm yet**, so build them from source ([repo](https://github.com/enviodev/hypersync-client-solana)); the streaming methods are Rust only for now. If you use them: - The query object is camelCase (`fromSlot`, `instructionCalls`, `executingAccount`, `fieldSelection`), but `fieldSelection` **values** are the snake_case column names from [Available fields](https://docs.envio.dev/docs/HyperSync/solana-query.md#available-fields-by-table), for example `{ instructionCall: ["executing_account", "tx_success"] }`. - `response.tables` is keyed by table name, so instruction rows are under `instruction_calls`. - `includeAccountActivity` is deprecated; setting it to `true` throws with guidance. Use `accountActivity: [{}]`. ## Upgrading to 0.2.0 `0.2.0` locked the query API. The renames are breaking on the **response** side; the request side still accepts legacy names as aliases. Full mapping (including `is_committed` to `tx_success` and the `account_activity.owner` split into `pre_owner` / `post_owner`): [Renamed fields and compatibility](https://docs.envio.dev/docs/HyperSync/solana-query.md#renamed-fields-and-compatibility). --- # Solana curl Examples > Copy-paste curl examples for the Solana HyperSync API against real protocols. Copy-paste examples against **`https://solana.hypersync.xyz`**. You'll need an API token: generate one at [https://envio.dev/app/api-tokens](https://envio.dev/app/api-tokens) (see [API tokens](https://docs.envio.dev/docs/HyperSync/api-tokens)) and pass it via `Authorization: Bearer `; `GET /height` and `/height/sse` work without one. curl is great for testing; for production, prefer the [Solana client](https://docs.envio.dev/docs/HyperSync/solana-client.md), which uses Arrow and handles pagination, retries, and rate limits for you. ```bash export URL=https://solana.hypersync.xyz export TOKEN="your-api-token" # Every example runs over a short range just below the head HEAD=$(curl -sS "$URL/height") FROM=$((HEAD - 2000)) TO=$((HEAD - 1900)) # JSON POST helper (adds auth + content-type) curl_query() { curl -sS "$URL/query" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "$1" } ``` The examples splice `$FROM` / `$TO` into single-quoted JSON with `'$FROM'`; a range below the earliest indexed slot returns empty tables with `next_slot` not advancing. Discriminator filters accept hex with or without a `0x` prefix. Every response table is an array of row **batches**, so the `jq` below flattens with `[.table[][]]` before indexing or counting (see [Response](https://docs.envio.dev/docs/HyperSync/solana-query.md#response)). Prefer clicking over typing? The **[HyperSync Query Builder](https://builder.hypersync.xyz/#solana)** builds and runs these same queries visually - several of the patterns below have a one-click **Quick start** template (linked inline); paste in your own token before executing. ## Quick checks ```bash curl -sS "$URL/height" curl -sS -H "Authorization: Bearer $TOKEN" "$URL/health" ``` ### Head slot (SSE) ```bash curl -sSN -H "Accept: text/event-stream" "$URL/height/sse" ``` ## Orca Whirlpool (`swap` discriminator) 8-byte Anchor discriminator. Example response shape (truncated): ```bash curl_query '{ "from_slot": '$FROM', "to_slot": '$TO', "field_selection": { "instruction_call": ["slot", "transaction_index", "executing_account", "account_arguments", "data", "d8"], "transaction": ["slot", "signatures", "fee_payer", "success", "fee"] }, "instruction_calls": [{ "executing_account": ["whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"], "d8": ["0xf8c69e91e17587c8"] }] }' | jq '{next_slot, sample_instruction: [.instruction_calls[][]][0], sample_tx: [.transactions[][]][0]}' ``` **Try it:** [Query Builder](https://builder.hypersync.xyz/#solana) → Quick start → **Whirlpool Swaps (d8 Anchor)**. ## SPL Token `Transfer` (`d1`) 1-byte discriminator: `0x03` = `Transfer` (hex with or without `0x`). Token movements come from the unified `account_activity` table (`pre_token_balance` / `post_token_balance` are raw base-unit decimal **strings**). ```bash curl_query '{ "from_slot": '$FROM', "to_slot": '$TO', "field_selection": { "instruction_call": ["slot", "executing_account", "account_arguments", "data", "d1"], "account_activity": ["slot", "transaction_index", "account", "mint", "pre_owner", "post_owner", "token_state", "pre_token_balance", "post_token_balance"] }, "instruction_calls": [{ "executing_account": ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"], "d1": ["0x03"] }] }' ``` **Try it:** [Query Builder](https://builder.hypersync.xyz/#solana) → Quick start → **SPL Token Transfers (d1)**. ## Wallet activity (native SOL + tokens) `account` is the wallet on a native row and the token account on a token row, and fields within one selection are AND-ed, so "everything for wallet W" is **two** selections. ```bash curl_query '{ "from_slot": '$FROM', "to_slot": '$TO', "field_selection": { "account_activity": ["slot", "transaction_id", "account", "pre_balance", "post_balance", "mint", "pre_owner", "post_owner", "token_state", "pre_token_balance", "post_token_balance"] }, "account_activity": [ { "account": ["MfDuWeqSHEqTFVYZ7LoexgAK9dxk7cy4DFJWjWMGVWa"] }, { "owner": ["MfDuWeqSHEqTFVYZ7LoexgAK9dxk7cy4DFJWjWMGVWa"] } ] }' ``` **Try it:** [Query Builder](https://builder.hypersync.xyz/#solana) → Quick start → **Wallet Activity (account OR owner)**. To pull **every** activity row in a range (the replacement for the removed `include_account_activity` flag), use one empty selection: ```bash curl_query '{ "from_slot": '$FROM', "to_slot": '$TO', "field_selection": { "account_activity": ["slot", "account", "pre_balance", "post_balance"] }, "account_activity": [{}] }' ``` **Try it:** [Query Builder](https://builder.hypersync.xyz/#solana) → Quick start → **All Account Activity**. ## Successful transactions only `tx_success` filters instruction calls by the success of their parent transaction, server-side. ```bash curl_query '{ "from_slot": '$FROM', "to_slot": '$TO', "field_selection": { "instruction_call": ["slot", "executing_account", "d8", "tx_success", "error", "compute_units_consumed"] }, "instruction_calls": [{ "executing_account": ["whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"], "tx_success": true }] }' ``` ## Jupiter **or** Orca (program-only OR) Each object in `instruction_calls` is OR-ed; this is the "match by program only" pattern (no discriminator). ```bash curl_query '{ "from_slot": '$FROM', "to_slot": '$TO', "field_selection": { "instruction_call": ["slot", "executing_account", "data", "d8"] }, "instruction_calls": [ { "executing_account": ["JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4"] }, { "executing_account": ["whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"] } ] }' ``` **Try it:** [Query Builder](https://builder.hypersync.xyz/#solana) → Quick start → **Jupiter OR Orca (multi-filter OR)**. ## Transactions by fee payer ```bash curl_query '{ "from_slot": '$FROM', "to_slot": '$TO', "field_selection": { "transaction": ["slot", "signatures", "fee_payer", "success", "fee", "compute_units_consumed"], "instruction_call": ["slot", "executing_account", "data", "account_arguments"] }, "transactions": [{ "fee_payer": ["MfDuWeqSHEqTFVYZ7LoexgAK9dxk7cy4DFJWjWMGVWa"] }] }' ``` **Try it:** [Query Builder](https://builder.hypersync.xyz/#solana) → Quick start → **Txns by Fee Payer**. ## Pump.fun bonding-curve trades (account index) `a2` matches the **third account** in the instruction's account metas (`a0` = first). For Pump.fun's buy/sell instructions the mint is account index 2 per that program's IDL, not a Solana-wide rule. ```bash curl_query '{ "from_slot": '$FROM', "to_slot": '$TO', "field_selection": { "instruction_call": ["slot", "executing_account", "account_arguments", "data", "d8", "a2"], "transaction": ["slot", "fee_payer", "success"] }, "instruction_calls": [{ "executing_account": ["6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"] }] }' ``` ## Raydium AMM logs ```bash curl_query '{ "from_slot": '$FROM', "to_slot": '$TO', "field_selection": { "log": ["slot", "program_id", "kind", "message"], "transaction": ["slot", "fee_payer", "success"] }, "logs": [{ "program_id": ["675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"] }] }' ``` ## Paginating a bounded scan Use the same termination rule as [Query & Response](https://docs.envio.dev/docs/HyperSync/solana-query.md#pagination): stop when `next_slot >= to_slot`, or when `next_slot` does not advance (stuck at head). ```bash SLOT=$FROM while [ "$SLOT" -lt "$TO" ]; do RESP=$(curl_query "{ \"from_slot\": $SLOT, \"to_slot\": $TO, \"field_selection\": { \"instruction_call\": [\"slot\", \"executing_account\", \"d8\"] }, \"instruction_calls\": [{ \"executing_account\": [\"whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc\"] }] }") echo "$RESP" | jq '([.instruction_calls[][]] | length), .next_slot' NEXT=$(echo "$RESP" | jq -r .next_slot) if [ "$NEXT" -ge "$TO" ] || [ "$NEXT" -le "$SLOT" ]; then break fi SLOT=$NEXT done ``` --- # HyperFuel > HyperFuel gives you a high performance way to query and sync Fuel network data using HyperSync. Access real-time and historical data with flexible queries across contracts, events and state. [HyperSync](https://docs.envio.dev/docs/HyperSync/overview) is a high-performance data node and accelerated data query layer that powers Envio’s Indexing framework, [HyperIndex](https://docs.envio.dev/docs/HyperIndex/overview), for up to 2000x faster data retrieval than standard RPC methods. HyperFuel is HyperSync adapted for the [Fuel Network](https://fuel.network/) and is exposed as a low-level API for developers and data analysts to create flexible, high-speed queries for all fuel data. Users can interact with the HyperFuel in Rust, Python, NodeJS clients, or directly via the JSON API to extract data into parquet files, arrow format, or as typed data. Client examples are listed further below. Using HyperFuel, application developers can easily sync and search large datasets in a few minutes. HyperFuel is an ideal solution for indexers, block explorers, data analysts, bridges, and other applications or use cases focused on performance. You can integrate with HyperFuel using any of our clients: | Client | Install | Repository | | --- | --- | --- | | Rust | `cargo add hyperfuel-client` | https://github.com/enviodev/hyperfuel-client-rust | | Python | `pip install hyperfuel` | https://github.com/enviodev/hyperfuel-client-python | | Node.js | `npm install @envio-dev/hyperfuel-client` | https://github.com/enviodev/hyperfuel-client-node | | JSON API | any HTTP client | https://github.com/enviodev/hyperfuel-json-api | :::info HyperFuel supports Fuel mainnet and testnet:
Mainnet: https://fuel.hypersync.xyz
Testnet: https://fuel-testnet.hypersync.xyz ::: :::note HyperFuel requires an API token. Generate one from the [Envio Dashboard](https://envio.dev/app/api-tokens) and pass it to the client when you initialize it: `api_token` in Rust, `bearer_token` in Python, `bearerToken` in Node.js, or an `Authorization: Bearer ` header on the JSON API. The examples below read it from the `ENVIO_API_TOKEN` environment variable. The Rust client refuses to start without one (`api_token is required`). See [API Tokens](https://docs.envio.dev/docs/HyperSync/api-tokens) for more details. ::: ## Example usage Below is an example of a Hyperfuel query in each of our clients searching the first 1,300,000 blocks for all `input` objects of a specific `asset-id`. This example returns 10,543 inputs in around 100ms - not including latency. ## Rust ([repo](https://github.com/enviodev/hyperfuel-client-rust/tree/main/examples)) ```toml [dependencies] hyperfuel-client = "4" tokio = { version = "1", features = ["full"] } serde_json = "1" url = "2" ``` ```rust use hyperfuel_client::{net_types::Query, Client, ClientConfig}; use url::Url; #[tokio::main] async fn main() { let client_config = ClientConfig { url: Some(Url::parse("https://fuel-testnet.hypersync.xyz").unwrap()), api_token: std::env::var("ENVIO_API_TOKEN") .expect("ENVIO_API_TOKEN env var is required, get a token from https://envio.dev/app/api-tokens"), ..Default::default() }; let client = Client::new(client_config).unwrap(); // Construct query in json. Can also construct it as a typed struct (see predicate-root example) let query: Query = serde_json::from_value(serde_json::json!({ // start query from block 0 "from_block": 0, // if to_block is not set, query runs to the end of the chain "to_block": 1300000, // load inputs that have `asset_id` = 0x2a0d0ed9d2217ec7f32dcd9a1902ce2a66d68437aeff84e3a3cc8bebee0d2eea "inputs": [ { "asset_id": ["0x2a0d0ed9d2217ec7f32dcd9a1902ce2a66d68437aeff84e3a3cc8bebee0d2eea"] } ], // fields we want returned from loaded inputs "field_selection": { "input": [ "tx_id", "block_height", "input_type", "utxo_id", "owner", "amount", "asset_id" ] } })) .unwrap(); let res = client.get(&query).await.unwrap(); println!("inputs: {:?}", res.data.inputs); } ``` ## Python ([repo](https://github.com/enviodev/hyperfuel-client-python/blob/main/examples/asset-id.py)) ```python import os import hyperfuel from hyperfuel import InputField import asyncio async def main(): client = hyperfuel.HyperfuelClient( url="https://fuel-testnet.hypersync.xyz", bearer_token=os.environ["ENVIO_API_TOKEN"], ) query = hyperfuel.Query( # start query from block 0 from_block=0, # if to_block is not set, query runs to the end of the chain to_block = 1300000, # load inputs that have `asset_id` = 0x2a0d0ed9d2217ec7f32dcd9a1902ce2a66d68437aeff84e3a3cc8bebee0d2eea inputs=[ hyperfuel.InputSelection( asset_id=["0x2a0d0ed9d2217ec7f32dcd9a1902ce2a66d68437aeff84e3a3cc8bebee0d2eea"] ) ], # what data we want returned from the inputs we loaded field_selection=hyperfuel.FieldSelection( input=[ InputField.TX_ID, InputField.BLOCK_HEIGHT, InputField.INPUT_TYPE, InputField.UTXO_ID, InputField.OWNER, InputField.AMOUNT, InputField.ASSET_ID, ] ) ) res = await client.get_selected_data(query) print("inputs: " + str(res.data.inputs)) asyncio.run(main()) ``` ## Node Js ([repo](https://github.com/enviodev/hyperfuel-client-node/tree/main/examples/asset-id)) ```ts import { HyperfuelClient, Query } from "@envio-dev/hyperfuel-client"; async function main() { const client = HyperfuelClient.new({ url: "https://fuel-testnet.hypersync.xyz", bearerToken: process.env.ENVIO_API_TOKEN, }); const query: Query = { // start query from block 0 fromBlock: 0, // if to_block is not set, query runs to the end of the chain toBlock: 1300000, // load inputs that have `asset_id` = 0x2a0d0ed9d2217ec7f32dcd9a1902ce2a66d68437aeff84e3a3cc8bebee0d2eea inputs: [ { assetId: [ "0x2a0d0ed9d2217ec7f32dcd9a1902ce2a66d68437aeff84e3a3cc8bebee0d2eea", ], }, ], // fields we want returned from loaded inputs fieldSelection: { input: [ "tx_id", "block_height", "input_type", "utxo_id", "owner", "amount", "asset_id", ], }, }; const res = await client.getSelectedData(query); console.log(`inputs: ${JSON.stringify(res.data.inputs)}`); } main(); ``` ## Json Api ([repo](https://github.com/enviodev/hyperfuel-json-api/tree/main/asset-id-query-example)) ```bash curl --request POST \ --url https://fuel-testnet.hypersync.xyz/query \ --header "Authorization: Bearer $ENVIO_API_TOKEN" \ --header 'Content-Type: application/json' \ --data '{ "from_block": 0, "to_block": 1300000, "inputs": [ { "asset_id": ["0x2a0d0ed9d2217ec7f32dcd9a1902ce2a66d68437aeff84e3a3cc8bebee0d2eea"] } ], "field_selection": { "input": [ "tx_id", "block_height", "input_type", "utxo_id", "owner", "amount", "asset_id" ] } }' ``` --- # Query Structure > Explore all fields and parameters for HyperFuel queries. This section is dedicated to giving an exhaustive list of all the fields and query parameters of a HyperFuel query. HyperFuel is extremely powerful but learning how to craft queries can take some practice. It is recommended to look at the examples and reference this page. HyperFuel query structure is the same across clients. ## Top-level query structure Illustrated as json ```json { // The block to start the query from "from_block": Number, // The block to end the query at. If not specified, the query will go until the // end of data. Exclusive, the returned range will be [from_block..to_block). // // The query will return before it reaches this target block if it hits the time limit // configured on the server. The user should continue their query by putting the // next_block field in the response into from_block field of their next query. This implements // pagination. "to_block": Number, // Optional, defaults to latest block // List of receipt selections, the query will return receipts that match any of these selections. // All selections have an OR relationship with each other. "receipts": [{ReceiptSelection}], // Optional // List of input selections, the query will return inputs that match any of these selections. // All selections have an OR relationship with each other. "inputs": [{InputSelection}], // Optional // List of output selections, the query will return outputs that match any of these selections. // All selections have an OR relationship with each other. "outputs": [{OutputSelection}], // Optional // Whether to include all blocks regardless of whether they match a receipt, input, or output selection. Normally // The server will return only the blocks that are related to the receipts, inputs, or outputs in the response. But if this // is set to true, the server will return data for all blocks in the requested range [from_block, to_block). "include_all_blocks": bool, // Optional, defaults to false // The user selects which fields they want returned. Requesting fewer fields will improve // query execution time and reduce the payload size so the user should always use a minimal number of fields. "field_selection": {FieldSelection}, // Maximum number of blocks that should be returned, the server might return more blocks than this number but //It won't overshoot by too much. "max_num_blocks": Number, // Optional, defaults to no maximum // The same soft caps for the other tables. "max_num_transactions": Number, // Optional "max_num_receipts": Number, // Optional "max_num_inputs": Number, // Optional "max_num_outputs": Number, // Optional // Which related rows come back with the matched receipts, inputs and outputs: // "Default" - the matched rows, their transactions and their blocks // "JoinAll" - the above, plus every receipt, input and output of those transactions // "JoinNothing" - the matched rows only "join_mode": String, // Optional, defaults to "Default" } ``` The top-level object and every selection object are strict: an unknown key fails the query with HTTP 400 and a message such as ``invalid JSON: unknown field `bogus`, expected one of `from_block`, `to_block`, ...``. The response is a JSON object with `data` (an array of batches, each holding `blocks`, `transactions`, `receipts`, `inputs` and `outputs` arrays for the tables that matched), `next_block` (use it as the next query's `from_block`), `archive_height` (the server's current height) and `total_execution_time`. ## ReceiptSelection The query takes an array of ReceiptSelection objects and returns receipts that match any of the selections. All fields are optional. Below is an exhaustive list of all fields in a ReceiptSelection JSON object. Reference the [Fuel docs on receipts](https://docs.fuel.network/docs/specs/abi/receipts/#receipts) for field explanations. ```json { // address that emitted the receipt "root_contract_id": [String], // The recipient contract ID "to": [String], // The recipient address "to_address": [String], // The asset id of the coins transferred. "asset_id": [String], // the type of receipt // 0 = Call // 1 = Return, // 2 = ReturnData, // 3 = Panic, // 4 = Revert, // 5 = Log, // 6 = LogData, // 7 = Transfer, // 8 = TransferOut, // 9 = ScriptResult, // 10 = MessageOut, // 11 = Mint, // 12 = Burn, "receipt_type": [Number], // The address of the message sender. "sender": [String], // The address of the message recipient. "recipient": [String], // The contract id of the current context is in an internal context. null otherwise "contract_id": [String], // receipt register values. "ra": [Number], "rb": [Number], "rc": [Number], "rd": [Number], // the status of the transaction that the receipt originated from // 1 = Success // 3 = Failure "tx_status": [Number], // the type of the transaction that the receipt originated from // 0 = script // 1 = create // 2 = mint // 3 = upgrade // 4 = upload "tx_type": [Number] } ``` ## InputSelection The query takes an array of InputSelection objects and returns inputs that match any of the selections. All fields are optional. Below is an exhaustive list of all fields in an InputSelection JSON object. Reference the [Fuel docs on inputs](https://docs.fuel.network/docs/specs/tx-format/input/#input) for field explanations. ```json { // The owning address or predicate root. "owner": [String], // The asset ID of the coins. "asset_id": [String], // The input contract. "contract": [String], // The sender address of the message. "sender": [String], // The recipient address of the message. "recipient": [String], // The type of input // 0 = InputCoin, // 1 = InputContract, // 2 = InputMessage, "input_type": [Number], // the status of the transaction that the input originated from // 1 = Success // 3 = Failure "tx_status": [Number], // the type of the transaction that the input originated from // 0 = script // 1 = create // 2 = mint // 3 = upgrade // 4 = upload "tx_type": [Number] } ``` ## OutputSelection The query takes an array of OutputSelection objects and returns outputs that match any of the selections. All fields are optional. Below is an exhaustive list of all fields in an OutputSelection JSON object. Reference the [Fuel docs on outputs](https://docs.fuel.network/docs/specs/tx-format/output/#output) for field explanations. ```json { // The address the coins were sent to. "to": [String], // The asset id for the coins sent. "asset_id": [String], // The contract that was created. "contract": [String], // the type of output // 0 = CoinOutput, // 1 = ContractOutput, // 2 = ChangeOutput, // 3 = VariableOutput, // 4 = ContractCreated, "output_type": [Number], // the status of the transaction that the input originated from // 1 = Success // 3 = Failure "tx_status": [Number], // the type of the transaction that the input originated from // 0 = script // 1 = create // 2 = mint // 3 = upgrade // 4 = upload "tx_type": [Number] } ``` ## FieldSelection The query takes a FieldSelection JSON object where the user specifies what they want returned from data matched by their `ReceiptSelection`, `OutputSelection`, and `InputSelection`. There is no `BlockSelection` or `TransactionSelection` because the query returns all blocks and transactions that include the data you specified in your `ReceiptSelection`, `OutputSelection`, or `InputSelection`. For best performance, select a minimal amount of fields. *Important note:* all fields draw inspiration from Fuel's [graphql schema](https://docs.fuel.network/docs/graphql/reference/). Mainly Blocks, Transactions, Receipts, Inputs, and Outputs. Enums of each type (ex: Receipt has 12 different types, two of which are Log and LogData, Input has 3: InputCoin, InputContract, InputMessage, and Output has 5: CoinOutput, ContractOutput, ChangeOutput, VariableOutput, ContractCreated) are flattened into the parent type. This is why multiple fields on any returned Receipt, Input, or Output might be null; it's not a field on all possible enums of that type, so null is inserted. All fields are optional. Below is an exhaustive list of all fields in a FieldSelection JSON object. ```json { "block": [ "id", "da_height", "consensus_parameters_version", "state_transition_bytecode_version", "transactions_count", "message_receipt_count", "transactions_root", "message_outbox_root", "event_inbox_root", "height", "prev_root", "time", "application_hash" ], "transaction": [ "block_height", "id", "input_asset_ids", "input_contracts", "input_contract_utxo_id", "input_contract_balance_root", "input_contract_state_root", "input_contract_tx_pointer_tx_index", "input_contract", "policies_tip", "policies_witness_limit", "policies_maturity", "policies_max_fee", "script_gas_limit", "maturity", "mint_amount", "mint_asset_id", "mint_gas_price", "tx_pointer_block_height", "tx_pointer_tx_index", "tx_type", "output_contract_input_index", "output_contract_balance_root", "output_contract_state_root", "witnesses", "receipts_root", "status", "time", "reason", "script", "script_data", "bytecode_witness_index", "bytecode_root", "subsection_index", "subsections_number", "proof_set", "consensus_parameters_upgrade_purpose_witness_index", "consensus_parameters_upgrade_purpose_checksum", "state_transition_upgrade_purpose_root", "salt" ], "receipt": [ "receipt_index", "root_contract_id", "tx_id", "tx_status", "tx_type", "block_height", "pc", "is", "to", "to_address", "amount", "asset_id", "gas", "param1", "param2", "val", "ptr", "digest", "reason", "ra", "rb", "rc", "rd", "len", "receipt_type", "result", "gas_used", "data", "sender", "recipient", "nonce", "contract_id", "sub_id" ], "input": [ "tx_id", "tx_status", "tx_type", "block_height", "input_type", "utxo_id", "owner", "amount", "asset_id", "tx_pointer_block_height", "tx_pointer_tx_index", "witness_index", "predicate_gas_used", "predicate", "predicate_data", "balance_root", "state_root", "contract", "sender", "recipient", "nonce", "data" ], "output": [ "tx_id", "tx_status", "tx_type", "block_height", "output_type", "to", "amount", "asset_id", "input_index", "balance_root", "state_root", "contract" ] } ``` ---