# Envio docs: HyperIndex on Solana and Fuel > Solana programs (instruction and slot handlers, decoding, config) and Fuel contracts. 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 (this file): 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](https://docs.envio.dev/llms-hypersync-solana-fuel.txt): 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 - Getting Started on Solana - Solana Instruction Handlers - Decoding Instructions - Solana Slot Handlers - Solana Configuration File - EVM vs Solana - Fuel - Indexing Sway Farm on the Fuel Network --- # Indexing on Solana > Index Solana programs with HyperIndex - instruction-level handlers, IDL-aware decoding, CPI/inner-instruction support, account activity, and slot handlers. HyperIndex indexes Solana programs at the **instruction level**. You select the programs and instructions you care about, HyperIndex decodes their arguments and accounts from an IDL (Anchor, Shank or Codama) or a layout you declare, and writes the results to Postgres with an auto-generated GraphQL API. Inner instructions (CPIs), **account balance activity**, transaction metadata and program logs are all available. It is powered by [HyperSync for Solana](https://docs.envio.dev/docs/HyperSync/solana), the same high-performance data engine behind EVM indexing, so historical backfills are fast and you never touch an RPC node for the bulk of indexing. :::info Stable since v3.11 The SVM API - configuration, handlers and payload types - is final and follows semver like the rest of HyperIndex. Building on Solana? [Say hello on Discord](https://discord.gg/envio); we'd love your input on what to prioritize next. ::: ## Two ways to index Solana | Approach | API | Data source | Use it for | | --- | --- | --- | --- | | **Instruction handlers** | [`indexer.onInstruction`](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers) | HyperSync | The main path: decode and index program instructions (swaps, deposits, mints, transfers…), including inner/CPI instructions, with per-account balance activity. | | **Slot handlers** | [`indexer.onSlot`](https://docs.envio.dev/docs/HyperIndex/solana/slot-handlers) | HyperSync for the slots; your own RPC calls through the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api) for anything else | Per-slot orchestration, time-series snapshots, or pulling extra data from RPC on a schedule. | Most indexers use instruction handlers. Slot handlers are for cases where you need to run logic on a slot cadence rather than react to a specific instruction. HyperSync is the only built-in Solana data source: the `rpc` field in `config.yaml` is accepted but unused. For raw, low-level data you can also query [HyperSync for Solana](https://docs.envio.dev/docs/HyperSync/solana) directly. ## Quickstart ```bash pnpx envio init ``` Choose **Svm** at the ecosystem prompt, then pick the **USDC Transfers (SPL Token instructions)** template - a working SPL Token instruction indexer with tests. See [Getting Started](https://docs.envio.dev/docs/HyperIndex/solana/getting-started) for the full walkthrough. The HyperSync endpoint comes from the chain id, so there's nothing to configure beyond picking a `start_slot` - see [choosing a start slot](https://docs.envio.dev/docs/HyperIndex/solana/configuration#choosing-an-endpoint-and-a-start-slot). ## Mental model: coming from EVM? If you've used HyperIndex on EVM, the shift is mostly vocabulary: | EVM | Solana | | --- | --- | | Contract + ABI | Program + IDL | | Event (`onEvent`) | Instruction (`onInstruction`) | | Block (`onBlock`) | Slot (`onSlot`) | | `event.params` | `instruction.args` | [EVM vs Solana](https://docs.envio.dev/docs/HyperIndex/solana/evm-vs-solana) has the full mapping. ## What's supported today - **Instruction indexing** via [`indexer.onInstruction`](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers): match by program + discriminator. - **IDL-aware decoding**: point at an Anchor (legacy or 0.30+), Shank or Codama IDL and every instruction it declares becomes indexable, with its arguments and account names. No IDL? [Declare the layout yourself](https://docs.envio.dev/docs/HyperIndex/solana/decoding#inline-layout-no-idl). - **Inner instructions (CPIs)**: decoded the same way as top-level ones, with a full instruction path so you can reconstruct the call tree. - **Account activity**: pre/post lamport and SPL Token (and Token-2022) balances per account, so you get net value movement without indexing every transfer. See [account activity](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers#account-activity). - **Transaction metadata & logs**: fee payer, fee, compute units, success, the transaction signature, and per-instruction program logs (opt-in via the handler's [`fields`](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers#selecting-fields) option). - **Slot handlers** via [`indexer.onSlot`](https://docs.envio.dev/docs/HyperIndex/solana/slot-handlers) + the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api) for RPC enrichment. - **Local dev + GraphQL + Envio Cloud**: the same workflow and hosting as EVM. ## What is not supported yet These are gaps in the built-in instruction-handler surface, not hard limits: for most of them you can still pull the data yourself by calling out to RPC from a handler with the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api), you just don't get it as a struct field for free. - **Account-change subscriptions.** There is no `onAccount`/program-account handler. `instruction.accounts` gives you the accounts an instruction touched and, with `fields.accountActivity`, their pre/post lamport and token balances for that transaction - but not arbitrary account state. For that, read the account over RPC in a handler with the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api). - **A separate log handler.** Logs are a field on the instruction, not their own handler. - **Dynamic registration.** No Solana equivalent of [dynamic contracts](https://docs.envio.dev/docs/HyperIndex/dynamic-contracts): programs are declared in `config.yaml`, not registered at runtime. - **Wildcard indexing across programs.** A registration always names one program. - **No-code contract import.** Solana has no `contract-import` flow, so you configure programs by hand. (IDLs are wired up in `config.yaml`, not auto-imported.) - **ReScript.** Solana indexers are TypeScript only. Codegen emits no ReScript for `ecosystem: svm`, and if you ask `envio init` for ReScript it prints `Note: SVM templates are only available in TypeScript. Creating a TypeScript project.` and creates a TypeScript project. If the piece you need is on this list, [tell us on Discord](https://discord.gg/envio): there's a good chance we can sequence the work to unblock you, or point you at a [HyperSync-direct](https://docs.envio.dev/docs/HyperSync/solana) path that gets the data today. ## In this section - **[Getting Started](https://docs.envio.dev/docs/HyperIndex/solana/getting-started)**: scaffold and run your first Solana indexer. - **[Instruction Handlers](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers)**: `onInstruction`, the instruction object, account activity, CPIs, testing. - **[Decoding Instructions](https://docs.envio.dev/docs/HyperIndex/solana/decoding)**: IDLs, discriminators, inline layouts, supported types. - **[Slot Handlers](https://docs.envio.dev/docs/HyperIndex/solana/slot-handlers)**: `onSlot` and RPC enrichment. - **[Configuration](https://docs.envio.dev/docs/HyperIndex/solana/configuration)**: the `config.yaml` reference for `ecosystem: svm`. - **[EVM vs Solana](https://docs.envio.dev/docs/HyperIndex/solana/evm-vs-solana)**: every difference in one place. --- # Getting Started on Solana > Scaffold, configure, and run your first Solana indexer with HyperIndex. This guide takes you from nothing to a running Solana indexer with a live GraphQL API. If you've used HyperIndex on EVM the workflow is identical: only the config and handlers differ. ## Prerequisites - [Node.js](https://nodejs.org) 22.15.0 or newer and [pnpm](https://pnpm.io). The commands below use `pnpm`/`pnpx`; npm, Yarn, and Bun work too if you swap the equivalents - [Docker Desktop](https://www.docker.com/products/docker-desktop/) (for the local Postgres + GraphQL stack) - A HyperSync API token: the CLI's login flow sets this up for you, or generate one in the [Envio Cloud portal](https://envio.dev/app/api-tokens). See [API tokens](https://docs.envio.dev/docs/HyperSync/api-tokens). ## 1. Scaffold a project ```bash pnpx envio init ``` Choose **Svm** at the ecosystem prompt, then pick the **USDC Transfers (SPL Token instructions)** template: a working indexer of every USDC transfer through the SPL Token program, with tests. The non-interactive equivalent needs an Envio API token, so create one at [envio.dev/app/api-tokens](https://envio.dev/app/api-tokens) and export it first, or pass `--api-token `. ```bash export ENVIO_API_TOKEN=your_token_here pnpx envio init svm template --template usdc-transfers --name my-indexer -d my-indexer ``` The template scaffolds: ```text my-indexer/ ├── config.yaml # chains + programs/instructions ├── schema.graphql # the entities you index into ├── src/ │ ├── handlers/…ts # your onInstruction / onSlot handlers │ └── indexer.test.ts # tests, with simulated instructions ├── .env # ENVIO_API_TOKEN └── package.json ``` `envio init` also runs codegen, installs dependencies, and initializes git. ## 2. Pick a start slot `start_slot` in `config.yaml` is a **slot number**, not a block number. Three common choices: | `start_slot` | Indexes from | | --- | --- | | `latest` | The head when the indexer is first deployed. Fastest way to see live data. | | A few tens of thousands of slots below the head | A short backfill, good for trying things out. | | The slot your program was deployed at | Its full history. | Check the current head to pick a number: ```bash curl -s https://solana.hypersync.xyz/height # => 450012618 ``` :::note History doesn't reach genesis yet As of September 2026, mainnet goes back to around slot 391,000,000. A `start_slot` before that doesn't error - the indexer starts from the earliest indexed slot instead. See [choosing a start slot](https://docs.envio.dev/docs/HyperIndex/solana/configuration#choosing-an-endpoint-and-a-start-slot). ::: ## 3. Run it ```bash pnpm install # if you didn't let init do it pnpm envio codegen # regenerate types from config.yaml + schema.graphql pnpm envio dev # start Postgres + the indexer + GraphQL (Docker) ``` `envio dev` brings up the local stack and runs the indexer. It doesn't watch files, so restart it after changes. The GraphQL playground (Hasura) is at **http://localhost:8080** (default admin secret `testing`). See [Navigating Hasura](https://docs.envio.dev/docs/HyperIndex/navigating-hasura). To run the pieces separately: ```bash pnpm envio local docker up # start Postgres + Hasura pnpm envio codegen pnpm envio start # run the indexer against the running stack ``` :::tip Re-run codegen after config/schema changes Editing `config.yaml` or `schema.graphql` (including adding a program, instruction, or IDL) requires `pnpm envio codegen` to regenerate the typed `envio` module and the entity types in `.envio/`. ::: ## 4. Add your own program Add an entry to the top-level `programs` list, then write a handler for it: ```yaml title="config.yaml" programs: - name: MyProgram program_id: MyProgram1111111111111111111111111111111111 idl: ./idls/my-program.json ``` With an `idl` (Anchor, Shank or Codama) every instruction it declares is indexable and you select them by name. Without one, declare the `discriminator`, `accounts` and `args` yourself - see [Decoding Instructions](https://docs.envio.dev/docs/HyperIndex/solana/decoding). ```typescript title="src/handlers/MyProgram.ts" import { indexer } from "envio"; indexer.onInstruction( { program: "MyProgram", instruction: "swap", fields: { instruction: ["args", "accounts"], block: ["time"] }, }, async ({ instruction, context }) => { // instruction.args and instruction.accounts are typed after codegen }, ); ``` A registration reads only the fields it lists in `fields`, and can narrow what it indexes with `where` - both are covered in [Instruction Handlers](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers). Re-run `pnpm envio codegen` after editing `config.yaml`. ## Next steps - [Configuration](https://docs.envio.dev/docs/HyperIndex/solana/configuration): every `config.yaml` field for Solana. - [Instruction Handlers](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers): the full instruction object, account activity, CPIs, and testing. - [Decoding Instructions](https://docs.envio.dev/docs/HyperIndex/solana/decoding): IDLs, discriminators, inline layouts, supported types. - [Deploy to Envio Cloud](https://docs.envio.dev/docs/HyperIndex/hosted-service): host your Solana indexer the same way as EVM. - [How to Index and Track Stablecoin Transfers on Solana](https://docs.envio.dev/blog/index-solana-stablecoin-transfers): a tested tutorial that tracks USDC, USDT, PYUSD and USDG across both token programs, including inner transfers. --- # Instruction Handlers > Register and write Solana instruction handlers with indexer.onInstruction - the instruction object, decoded args and accounts, field selection, filters, account activity, CPIs, and testing. On Solana you react to **instructions** instead of EVM events. Register a handler with `indexer.onInstruction`; it fires once for every matched instruction (top-level or inner) of the configured program. ```typescript import { indexer } from "envio"; indexer.onInstruction( { program: "", instruction: "" }, async ({ instruction, context }) => { // your logic here }, ); ``` `program` is the `name` you gave it under the top-level `programs` in `config.yaml`. `instruction` is a name from that program's `instructions` list, or - when the program points at an `idl` - any instruction the IDL declares. :::note Run codegen after config/schema changes The `envio` module exposes a unified `indexer` value plus types derived from your `config.yaml` and `schema.graphql`. Run **`pnpm codegen`** whenever you change either file. After codegen, `program`/`instruction` autocomplete and `instruction.args` / `instruction.accounts` are typed per instruction. ::: ## A complete handler ```typescript import { indexer } from "envio"; /** Only the listed fields are fetched, so keep it to what the handlers read. */ const fields = { instruction: ["accounts", "args", "path"], transaction: ["signature", "transactionIndex"], block: ["time"], } as const; indexer.onInstruction( { program: "SplToken", instruction: "transferChecked", fields }, async ({ instruction, context }) => { context.Transfer.set({ id: `${instruction.block.slot}-${instruction.transaction.transactionIndex}-${instruction.path.join(".")}`, amount: instruction.args.amount, // bigint, decoded from the u64 source: instruction.accounts.source.address, // base58 destination: instruction.accounts.destination.address, signer: instruction.accounts.authority.address, txSignature: instruction.transaction.signature, slot: instruction.block.slot, timestamp: instruction.block.time, }); }, ); ``` An instruction whose data the configured layout rejects is skipped rather than delivered undecoded, so `args` and `accounts` need no null checks. ## Selecting fields A registration carries only the data it asks for. List it in `fields`: ```typescript const fields = { instruction: ["args", "accounts", "path", "isInner", "programId", "data", "accountArguments"], transaction: ["signature", "feePayer", "success", "fee", "computeUnitsConsumed"], accountActivity: ["token.mint", "token.owner", "token.decimals", "lamports.pre", "lamports.post"], block: ["time", "hash", "height", "parentSlot", "parentHash"], log: ["kind", "message"], } as const; ``` | Knob | Adds | | --- | --- | | `instruction` | `args`, `accounts`, `accountArguments`, `programId`, `data`, `path`, `isInner`. | | `transaction` | `transactionIndex`, `signature`, `feePayer`, `success`, `err`, `fee`, `computeUnitsConsumed`, `accountKeys`, `recentBlockhash`, `version`, `allSignatures`. | | `accountActivity` | Per-account balances and token info on `instruction.accounts..activity` and `instruction.transaction.accountActivities`. Field names: `address`, `transactionAccountIndex`, `isSigner`, `isWritable`, `lamports.pre`, `lamports.post`, `token.mint`, `token.owner`, `token.decimals`, `token.preAmount`, `token.postAmount`. See [account activity](#account-activity). | | `block` | `time`, `hash`, `height`, `parentSlot`, `parentHash` on top of the always-present `slot`. | | `log` | `instruction.logs`, the program logs scoped to this instruction. | Reading a field you didn't select is a **compile error** naming the knob to add, not a runtime `undefined`. Write the selection inline in the registration, or declare it `as const` (as above) so its element types still name the fields. `instruction.programName`, `instruction.instructionName`, `instruction.discriminator` and `instruction.block.slot` are always available. To type a helper or a handler declared outside the registration, pass the selection and the config names to the exported types: ```typescript import type { SvmInstruction, SvmOnInstructionHandler } from "envio"; type TransferInstruction = SvmInstruction; const handleTransfer: SvmOnInstructionHandler = async ({ instruction, context }) => { /* ... */ }; ``` :::tip `signature`, not `allSignatures[0]` The identifying transaction id is the scalar `instruction.transaction.signature`. `allSignatures` is the array of every signer's signature and is selected separately - selecting `signature` doesn't give you `allSignatures`. Nearly every handler wants the scalar. ::: ## The instruction object ```typescript type SvmInstruction = { programName: string; // the program name from config instructionName: string; // the instruction name from config or IDL discriminator: string; // the matched hex prefix, e.g. "0x0c" programId: string; // base58 data: Uint8Array; // raw instruction data path: readonly number[]; // CPI path, e.g. [0] or [0, 1] isInner: boolean; // true => inner (CPI) instruction args: { ... }; // decoded Borsh arguments, typed per instruction accounts: { [name]: SvmInstructionAccount }; // named account slots accountArguments: readonly string[]; // every account address, positionally logs: readonly { kind: string; message: string }[]; // kind: "invoke" | "success" | "failed" | "consumed" | "log" | "data" | other transaction: SvmTransaction; block: { slot: number /* + selected block fields */ }; }; ``` - **`args`** is keyed by the argument names from the IDL or the inline `args` layout, typed after codegen. See [supported types](https://docs.envio.dev/docs/HyperIndex/solana/decoding#supported-argument-types). - **`accounts`** is keyed by the slot names you declared. Each entry is `{ address, accountName, instructionAccountIndex, activity }`. - **`accountArguments`** is the positional list of addresses, including slots you never named. - **`path`** locates the instruction in the transaction's call tree - see [inner instructions](#inner-instructions-cpis). ### `instruction.transaction` ```typescript type SvmTransaction = { transactionIndex: number; signature: string; // the transaction id, a scalar feePayer: string; success: boolean; err: string | undefined; fee: bigint; // lamports computeUnitsConsumed: bigint | undefined; accountKeys: readonly string[]; // static keys, then lookup-table writable, then readonly recentBlockhash: string; version: string | undefined; allSignatures: readonly string[]; accountActivities: readonly SvmAccountActivity[]; // with fields.accountActivity }; ``` The object is always there; each field is readable only when the registration selected it, so a missing selection is a compile error on the property rather than a crash on `undefined`. ### Account activity Selecting `fields.accountActivity` attaches per-account, per-transaction activity: pre/post **lamport** balances and pre/post **SPL Token** (and Token-2022) balances. `postAmount − preAmount` is the balance *change*, which is the cleanest way to capture net value flow without indexing every transfer. ```typescript type SvmAccountActivity = { address: string; transactionAccountIndex: number; isSigner: boolean; isWritable: boolean; lamports: { pre: bigint; post: bigint } | undefined; token: | { mint: string; owner: string; // owner after the tx, or before it if the tx closed the account decimals: number; preAmount: bigint | undefined; // absent if the account was created in the tx postAmount: bigint | undefined; // absent if it was closed in the tx } | undefined; }; ``` It arrives in two places: on a named account as `instruction.accounts..activity` (the account's own row, or `undefined` when the transaction reports none for it), and on `instruction.transaction.accountActivities` for every account the transaction touched. ```typescript const fields = { instruction: ["accounts"], transaction: ["signature"], accountActivity: ["token.mint", "token.decimals", "token.preAmount", "token.postAmount"], } as const; indexer.onInstruction( { program: "Jupiter", instruction: "sharedAccountsRoute", fields }, async ({ instruction, context }) => { for (const { address, token } of instruction.transaction.accountActivities) { if (!token) continue; context.TokenDelta.set({ id: `${instruction.transaction.signature}:${address}`, mint: token.mint, decimals: token.decimals, delta: (token.postAmount ?? 0n) - (token.preAmount ?? 0n), // signed }); } }, ); ``` :::tip Amounts are `bigint` Balances are raw base units typed as **`bigint`**, so use `?? 0n` rather than `?? "0"` for the absent case. Both amounts absent means the entry carries no movement at all, which is worth distinguishing from a genuine zero. ::: ## Filtering with `where` `where` narrows a registration server-side, so filtered-out instructions are never fetched or decoded: ```typescript indexer.onInstruction( { program: "SplToken", instruction: "transferChecked", fields, where: { accounts: { mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" }, isInner: false, block: { slot: { _gte: 445_000_000 } }, }, }, handler, ); ``` | Key | Effect | | --- | --- | | `accounts` | Match named account slots against a pubkey or a list of them. Keys within one group are AND-ed; pass an array of groups to OR them. | | `isInner` | `true` matches only inner (CPI) instructions, `false` only top-level ones. Omit it to match both. | | `block.slot._gte` | A per-registration start slot. It overrides the chain's `start_slot` for this handler. Only `_gte` is supported here - use [`indexer.onSlot`](https://docs.envio.dev/docs/HyperIndex/solana/slot-handlers) for `_lte` / `_every`. | Only slots you named in `accounts` are filterable (`_` placeholders and unnamed trailing slots are not), and only the first 10 positions (0-9). Naming a later slot in `where.accounts` throws at registration: `Account "" is at position , and only the first 10 accounts of an instruction can be filtered.` A bad `where` (an unknown key, an empty pubkey list, a value that isn't a base58 pubkey) also throws at registration, with a message that names the program and instruction. ## Inner instructions (CPIs) HyperIndex decodes inner instructions (those invoked by other programs via cross-program invocation) exactly like top-level ones. Two fields let you reconstruct the call tree: - **`isInner`**: `false` for a top-level instruction, `true` for a CPI. - **`path`**: the position in the tree. `[0]` is the first top-level instruction, `[0, 1]` the second inner instruction it invoked, `[0, 1, 2]` one level deeper. ```typescript const path = instruction.path; // e.g. [0, 1] const id = path.join("."); // "0.1" const depth = path.length - 1; // 1 const parent = path.length > 1 ? path.slice(0, -1).join(".") : undefined; ``` A registration matches both inner and outer occurrences by default; narrow it with `where: { isInner: true }` or `false`. :::info EVM difference EVM "internal calls" aren't surfaced as first-class events. On Solana, CPIs are real indexable instructions: a Jupiter route's underlying Raydium/Orca swaps are all visible if you index those programs. ::: ## The context object `context` is the same as in EVM handlers - the per-entity operations (`set`, `get`, `getOrThrow`, `getOrCreate`, `getWhere`, `deleteUnsafe`), `context.log`, `context.effect` for [Effects](https://docs.envio.dev/docs/HyperIndex/effect-api), and `context.isPreload`. See the [Event Handlers context](https://docs.envio.dev/docs/HyperIndex/event-handlers#context-object). Two things carry over from EVM that matter here: - `context.chain` is `{ id, isRealtime }`, and `id` is `7565164` on Solana mainnet. - [Preload optimization](https://docs.envio.dev/docs/HyperIndex/preload-optimization) runs every handler twice, so keep writes idempotent and guard non-idempotent side effects with `if (context.isPreload) return;`. A deterministic Solana entity id combines the slot, the transaction index and the instruction path: ```typescript const id = `${instruction.block.slot}-${instruction.transaction.transactionIndex}-${instruction.path.join(".")}`; ``` ## Testing Solana indexers use the same [test framework](https://docs.envio.dev/docs/HyperIndex/testing) as EVM ones. Two things are SVM-specific: chain overrides are keyed by the numeric chain id (`7565164`), and `simulate` items describe instructions rather than events. ```typescript import { createTestIndexer } from "envio"; const SOLANA = 7565164; const indexer = createTestIndexer(); await indexer.process({ chains: { [SOLANA]: { simulate: [ { program: "SplToken", instruction: "transferChecked", slot: 445_000_000, path: [1, 0], args: { amount: 250_000n, decimals: 6 }, accounts: { source: { address: SOURCE }, mint: { address: USDC }, destination: { address: DESTINATION }, authority: { address: AUTHORITY }, }, block: { time: 1_800_000_000 }, transaction: { signature: SIGNATURE, transactionIndex: 4 }, }, ], }, }, }); ``` A simulated instruction defaults its `data` to the configured discriminator bytes and its `path` to `[0]`, and only runs when its `slot` is inside the configured range. `transaction.accountActivities` entries are joined onto the named accounts at process time, so a handler reading `accounts.destination.activity.token.mint` is testable without a live endpoint. To run against real data, pass a pinned slot window instead and let the indexer fetch it from HyperSync: ```typescript await indexer.process({ chains: { [SOLANA]: { startBlock: 445_000_000, endBlock: 445_000_060 } }, }); ``` That needs `ENVIO_API_TOKEN`. Without one the run fails at once with `An Envio API token is required for using HyperSync as a data-source.` A token the server rejects (HTTP 401) is retried with backoff rather than failing fast, so that run hangs until the test timeout instead of erroring. Since it hits the real endpoint, assert on shape and invariants ("produced rows", "delta equals post minus pre") rather than exact counts. ## Related - [Decoding Instructions](https://docs.envio.dev/docs/HyperIndex/solana/decoding) - what `args` and `accounts` contain. - [Configuration](https://docs.envio.dev/docs/HyperIndex/solana/configuration): programs, instructions, discriminators, account slots. - [Slot Handlers](https://docs.envio.dev/docs/HyperIndex/solana/slot-handlers): the other Solana handler type. - [How to Index and Track Stablecoin Transfers on Solana](https://docs.envio.dev/blog/index-solana-stablecoin-transfers): a tested indexer that uses `where` filters, account activity and inner instructions together. --- # Decoding Instructions > How HyperIndex decodes Solana instructions - IDLs (Anchor, Shank, Codama) for programs that have one, and discriminators, inline layouts and Borsh argument types for programs that don't. Solana instruction data is a packed [Borsh](https://borsh.io/) byte string with no self-describing structure: unlike an EVM log, there's no ABI travelling with it. HyperIndex needs to know which bytes identify an instruction and how to read the rest, and there are two ways to tell it: - **Point at an IDL.** The usual path, and nothing else on this page applies. - **Declare the layout yourself.** For programs with no IDL - most native ones. ## Point at an IDL {#idls} Give the program an IDL JSON file (relative to `config.yaml`). Anchor 0.30+, legacy Anchor, Shank and Codama IDLs all work through the same path: ```yaml programs: - name: Jupiter program_id: JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4 idl: ./idls/jupiter.json ``` That's the whole configuration. Every usable instruction the IDL declares is indexable - names, discriminators, argument layouts, ordered account names (including nested account groups) and the IDL's `types` registry all come from the file - so you select what you index by name in [`onInstruction`](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers) and read `instruction.args` and `instruction.accounts` typed after codegen. Names are used exactly as the IDL spells them, with no case conversion, so check the file before you write a handler (an Anchor 0.30+ IDL is usually snake_case, a legacy one camelCase). Accounts inside a nested group are flattened and prefixed with the group name: `owner` inside the group `depositAccounts` becomes `depositAccountsOwner`. An instruction the IDL declares but HyperIndex can't decode or dispatch (it references an undefined or recursive type, or has exactly the same discriminator bytes as another instruction) is left out of the catalog, and codegen prints the reason: ```text Warning: program '' will not index '' from the IDL: ``` A discriminator that is only a prefix of another one is not a collision. Both instructions stay in the catalog, and a call goes to every selected instruction whose discriminator its data starts with (see [Discriminators](#discriminators)). Add an `instructions` row only to override or extend the catalog: - A row whose `name` the IDL declares **replaces** that instruction, and must spell out both `accounts` and `args`. This is also how you index an instruction codegen left out. - A row with a new name **adds** an instruction the IDL didn't declare. The [argument type table](#supported-argument-types) below describes what the IDL's types become in TypeScript. Everything else on this page is about programs without an IDL. ## Programs without an IDL For a program with no IDL - most native programs - you declare the pieces an IDL would have carried: which bytes select the instruction, what its arguments look like, and what to call its accounts. ### Discriminators {#discriminators} The discriminator is a `0x`-prefixed hex prefix of the instruction data, of any whole number of bytes. Every instruction whose data carries the prefix is dispatched to it. - **Format:** hex only, with the `0x` prefix. Base58 and decimal are not accepted (base58 is only for `program_id`). - **Native / non-Anchor programs:** whatever leading byte(s) the program uses (SPL Token `transfer` is `0x03`; Raydium AMM v4 `swap` is `0x09`). - **Anchor programs:** the 8-byte Anchor sighash, which an `idl` carries for you. - **The whole program:** `"0x"` - the empty prefix, carried by every call. ```yaml instructions: - name: swap discriminator: "0x09" # 1-byte native - name: sharedAccountsRoute discriminator: "0xc1209b3341d69c81" # 8-byte Anchor sighash ``` `instruction.discriminator` in a handler reads back the same string you wrote in `config.yaml`, so a config value and a handler comparison always match. :::note Overlapping prefixes all fire Dispatch is by prefix, not by exclusive match, so an entry whose prefix a call carries always receives it. A program-wide `"0x"` entry fires alongside a keyed one, and two entries may deliberately share a prefix - for example the layouts before and after a program upgrade. Each decodes with its own `args`, and one whose layout rejects the data is skipped for that call. ::: ### Declaring the layout {#inline-layout-no-idl} `args` is the Borsh argument list in order (after the discriminator); `accounts` names the positional account slots. ```yaml programs: - name: Raydium program_id: 675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8 instructions: - name: swap discriminator: "0x09" accounts: # positional: slot 0 is tokenProgram, etc. - tokenProgram - amm - userSourceTokenAccount - userDestTokenAccount args: - { name: amountIn, type: u64 } - { name: minAmountOut, type: u64 } ``` Account slots also accept `?optional` (the key is absent when the call omits the slot or fills it with the program id) and `_` (holds a position without naming it). See [account slots](https://docs.envio.dev/docs/HyperIndex/solana/configuration#account-slots). :::warning Verify positional layouts For native programs the account order is the program's canonical layout, not something HyperIndex can verify. Check it against a real transaction. Accounts beyond your named list still arrive, positionally, in `instruction.accountArguments`. ::: ### `args` is also a filter {#args-is-also-a-filter} Setting `args` attaches a decoder, and a call whose data the layout rejects is **skipped** rather than delivered undecoded. That makes the three states meaningfully different: | `args` | Behavior | | --- | --- | | omitted | No decoder at all. Every matched call is indexed and the payload stays raw, reachable as `instruction.data`. Selecting `"args"` in the handler's `fields.instruction` then throws at registration, since there is nothing to decode. | | `[]` | The instruction takes no arguments, so only calls carrying nothing past the discriminator are indexed. | | a list | Only calls whose data decodes cleanly against the layout are indexed. | The layout rejects data that is too short, has **bytes left over** after the last argument, carries an invalid `bool`, `option` or `enum` tag, holds invalid UTF-8 in a `string`, or decodes to a NaN or infinite float. Bytes left over count, so declare every argument the instruction takes: a layout that stops early skips every call, with no error. An `idl` always declares the layout of the instructions it names, empty included. ## Supported argument types These are the types you can write in `args`, and also what HyperIndex understands from an IDL. The right column is the TypeScript type each value has in `instruction.args` after codegen. | `type` | Type in `instruction.args` | | --- | --- | | `bool` | `boolean` | | `u8` `u16` `u32`, `i8` `i16` `i32`, `f32` `f64` | `number` | | `u64` `u128` `i64` `i128` | `bigint` | | `string` | `string` | | `pubkey` (alias `publicKey`) | `string` (base58) | | `bytes` | `Uint8Array` | | `{ option: }` | the value, or `null` | | `{ vec: }` | `readonly T[]` - but `vec` is a `Uint8Array` | | `{ array: [, ] }` | a readonly N-tuple - but `[u8, N]` is a `Uint8Array` | | `{ struct: [ {name,type}, … ] }` | object | | `{ enum: [ {name, fields?}, … ] }` | a variant name as a string literal, or `{ VariantName: { …fields } }` for a variant with fields (an IDL tuple variant's fields are named `_0`, `_1`, …) | ```yaml args: - { name: amount, type: u64 } # bigint - { name: authority, type: pubkey } # base58 string - { name: maybeOwner, type: { option: pubkey } } # string | null - { name: seedHash, type: { array: [u8, 32] } } # Uint8Array - { name: side, type: { enum: [{ name: Bid }, { name: Ask }] } } # "Bid" | "Ask" ``` Nominal types are declared inline at the field that uses them. There's no way to name one in YAML and refer to it elsewhere - attach an `idl` to the program when its types are shared between instructions. Two things worth knowing about the decoded output: - **Byte arrays are `Uint8Array`.** `bytes`, `vec` and `[u8; N]` all decode to `Uint8Array`, so a 32-byte hash doesn't come back as a base58 string. - **Address lookup tables need no configuration.** ALT-resolved addresses arrive in the instruction's account list and are mapped positionally like any other. ## Related - [Configuration](https://docs.envio.dev/docs/HyperIndex/solana/configuration): where `idl`, `discriminator`, `args` and `accounts` live. - [Instruction Handlers](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers): using `args` and `accounts` in handlers. --- # Slot Handlers > Run logic on every Solana slot or an interval with indexer.onSlot, and enrich it with RPC data via the Effect API. `indexer.onSlot` runs logic on every slot or at an interval, the Solana equivalent of EVM [block handlers](https://docs.envio.dev/docs/HyperIndex/block-handlers). Use it for time-series snapshots, periodic aggregations, or pulling extra data from RPC on a schedule with the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api). For indexing program activity, reach for [instruction handlers](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers) instead. ```typescript import { indexer } from "envio"; indexer.onSlot({ name: "MySlotHandler" }, async ({ slot, context }) => { context.log.info(`Processing slot ${slot}`); }); ``` Slot handlers **self-register**: they need no entry in `config.yaml` beyond the chain itself. With no `where`, the handler runs on every slot. The chain's HyperSync source drives the slots; the `rpc` field in `config.yaml` is unused, so an RPC URL your effects call belongs in your own environment variable. ## Options `indexer.onSlot(options, handler)`: - **`name`** (required): unique name, used for logging, metrics, and progress tracking. - **`where`** (optional): `({ chain }) => false | true | { slot: { _gte?, _lte?, _every? } }`. Evaluated once per chain at registration to decide which chains the handler runs on and over which slot range/interval. It must return a value on every path: an implicit `undefined` is not accepted. ```typescript indexer.onSlot( { name: "SlotSampler", where: ({ chain }) => chain.id === 7565164 ? { slot: { _gte: 385_453_000, // start slot (inclusive) _lte: 385_500_000, // end slot (inclusive) _every: 100, // every 100th slot }, } : false, }, async ({ slot, context }) => { context.SlotPing.set({ id: slot.toString(), slot }); }, ); ``` :::note Differences from EVM `onBlock` - The handler argument is `{ slot: number, context }`: a plain slot number, **not** a `block` object. - The filter key is `slot` (with `_gte` / `_lte` / `_every`), not `block.number`. - There's no `interval` option; express intervals with `_every`. `_every` aligns to `_gte` (or the chain start): it fires when `(slot − _gte) % _every === 0`. ::: ## The handler The handler receives `{ slot, context }`: - **`slot`**: the slot number being processed (a plain `number`). - **`context`**: entity operations (one object per `schema.graphql` entity, with `get` / `getOrThrow` / `getWhere` / `getOrCreate` / `set` / `deleteUnsafe`), plus `context.log`, `context.effect`, `context.chain` (`id` is `7565164` on Solana mainnet), and `context.isPreload`. This is the same context as EVM handlers; see the [Event Handlers context](https://docs.envio.dev/docs/HyperIndex/event-handlers#context-object). ## Enriching with RPC data via Effects A slot number alone is rarely enough, so pair `onSlot` with an [Effect](https://docs.envio.dev/docs/HyperIndex/effect-api) to fetch block/transaction/account data from RPC. Effects are deduplicated and cached, and can be rate-limited so you don't exhaust your RPC provider. `S` (from `envio`) builds the input/output schemas (it's the [Sury](https://github.com/DZakh/sury) library). ```typescript import { indexer, createEffect, S } from "envio"; const blockSchema = S.schema({ blockhash: S.string, blockHeight: S.nullable(S.number), blockTime: S.nullable(S.number), }); const getBlock = createEffect( { name: "getBlock", input: { slot: S.number }, output: S.nullable(blockSchema), rateLimit: { calls: 3, per: "second" }, }, async ({ input }) => { const res = await fetch(process.env.ENVIO_MAINNET_RPC_URL!, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "getBlock", params: [input.slot, { maxSupportedTransactionVersion: 1, transactionDetails: "none" }], }), }); const { result } = await res.json(); return result ?? null; }, ); indexer.onSlot({ name: "BlockTracker" }, async ({ slot, context }) => { const block = await context.effect(getBlock, { slot }); if (!block) { context.log.info(`Slot ${slot} has no block (skipped leader)`); return; // some slots produce no block } context.BlockInfo.set({ id: slot.toString(), hash: block.blockhash, height: block.blockHeight ?? undefined, time: block.blockTime ? new Date(block.blockTime * 1000) : undefined, }); }); ``` :::tip Not every slot has a block On Solana a slot may be skipped (the leader produced no block). Handle the empty result rather than assuming `getBlock` always returns data. ::: ### Preload double-run Like all V3 handlers, slot handlers run twice (a parallel preload pass to warm the cache, then the ordered pass). Effects are cached across both runs, so reads are cheap, but guard non-idempotent side effects with `if (context.isPreload) return;`. See [Preload Optimization](https://docs.envio.dev/docs/HyperIndex/preload-optimization). ## Slot handlers vs instruction handlers Reach for [instruction handlers](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers) to index *what programs did*, and slot handlers to do something *on a cadence*. They compose: an instruction handler records activity, and a slot handler rolls it into periodic snapshots. The [overview](https://docs.envio.dev/docs/HyperIndex/solana#two-ways-to-index-solana) compares the two side by side. For raw, low-level data over large ranges, query [HyperSync for Solana](https://docs.envio.dev/docs/HyperSync/solana) directly. ## Related - [Instruction Handlers](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers): the main Solana handler type. - [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api): external/RPC calls, caching, rate limiting. - [Configuration](https://docs.envio.dev/docs/HyperIndex/solana/configuration): chains, programs, and start slot. --- # Solana Configuration File > The config.yaml reference for Solana (ecosystem svm) indexers - chains, programs, instructions, discriminators, IDLs, and account slots. A Solana indexer is defined by a `config.yaml` with `ecosystem: svm`. It tells HyperIndex which chain to read, which programs and instructions to match, and how to decode them. This page is the field-by-field reference; for the *meaning* of discriminators, IDLs and argument types see [Decoding Instructions](https://docs.envio.dev/docs/HyperIndex/solana/decoding). Add this line at the top of the file for editor autocompletion and validation: ```yaml # yaml-language-server: $schema=./node_modules/envio/svm.schema.json ``` ## A complete example ```yaml title="config.yaml" # yaml-language-server: $schema=./node_modules/envio/svm.schema.json name: my-solana-indexer description: Index Jupiter swaps and SPL Token transfers ecosystem: svm chains: - id: solana start_slot: 437000000 # a SLOT number, not a block number programs: # --- decoded from an IDL --- - name: Jupiter program_id: JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4 idl: ./idls/jupiter.json # every usable instruction of the IDL is indexable # --- decoded from an inline layout (no IDL) --- - name: SplToken program_id: TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA instructions: - name: transfer discriminator: "0x03" accounts: [source, destination, authority] args: - name: amount type: u64 ``` Handlers then select what they index and which fields they read - see [Instruction Handlers](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers). ## Top-level fields | Field | Required | Default | Notes | | --- | --- | --- | --- | | `name` | ✅ | - | Project name. | | `ecosystem` | ✅ | - | Must be `svm`. | | `chains` | ✅ | - | One or more Solana clusters to index (see below). | | `programs` | - | - | Programs to index. Declared **once for the whole project**, not per chain. | | `description` | - | - | Free-text description. | | `schema` | - | `schema.graphql` | Path to your GraphQL schema. | | `handlers` | - | `src/handlers` | Directory that handler files are auto-loaded from. | | `full_batch_size` | - | `5000` | Target number of instructions processed per batch. | | `storage` | - | `postgres: true` | Storage backends (`postgres`, `clickhouse`). | | `disable_default_cross_chain` | - | `false` | Make entities and effect caches [per-chain](https://docs.envio.dev/docs/HyperIndex/multichain-indexing#per-chain-data-mode) instead of shared. | :::note No EVM-style global fields For Solana, several EVM top-level fields don't apply: `contracts`, `rollback_on_reorg`, `save_full_history`, `raw_events`, `field_selection`, `address_format` and `bytes_type`. Reorgs are handled automatically on the HyperSync source (it rolls back on reorg), field selection is per handler (the [`fields` option](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers#selecting-fields)), addresses are base58, and `Bytes` is always a `Uint8Array`. ::: ## `chains` Each entry is one Solana cluster. | Field | Required | Default | Notes | | --- | --- | --- | --- | | `id` | ✅ | - | The cluster: the label `solana` (7565164), `solana-devnet` (7565165), or an explicit number for another cluster. SVM has no native numeric chain id, so Envio assigns the label ids. | | `start_slot` | ✅ | - | The **slot** to start indexing from, or `latest` to start from the current head (see below). | | `end_slot` | - | - | Stop at this slot. Useful for finite backfills. | | `block_lag` | - | - | Stay this many slots behind the head. | | `hypersync_config` | - | the chain id's public endpoint | Block containing `url`. Optional for `solana` and `solana-devnet`; required for any other chain id, which otherwise fails with `Chain has no default HyperSync endpoint`. | | `rpc` | - | - | Accepted but unused: HyperSync is the only Solana data source. | | `skip` | - | `false` | Exclude the chain from indexing and migrations. | ```yaml chains: - id: solana start_slot: 437000000 - id: solana-devnet start_slot: latest ``` A chain entry accepts only the fields above. The EVM names `start_block` and `end_block` have no alias on Solana: config parsing rejects them as unknown fields, so write `start_slot` and `end_slot`. :::tip EVM difference: the id is a label EVM chains use the public numeric chain ID. Solana clusters have no such id, so you write `solana` or `solana-devnet` and HyperIndex maps them to `7565164` / `7565165` - the values you see as `context.chain.id` in handlers and as the key in [test indexer](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers#testing) chain overrides. Before v3.8 the Solana chain id was `0`. ::: ### Starting from the head `start_slot: latest` resolves the current head once, when the indexer is first deployed, and persists the concrete slot. A normal resume (a crash or a process restart) picks up from the stored slot, so downtime is backfilled rather than skipped; `envio dev`/`envio start` with `-r` re-resolves it against the head at that time. ### Choosing an endpoint and a start slot The endpoint follows the chain id, so the only real decision is the start slot: | Chain | Chain id | Endpoint | | --- | --- | --- | | Mainnet | `solana` (7565164) | `https://solana.hypersync.xyz` | | Devnet | `solana-devnet` (7565165) | `https://solana-devnet.hypersync.xyz` | Each endpoint serves history back to its earliest indexed slot, not to genesis - mainnet is around slot **391,000,000** as of September 2026, and we keep extending it backwards. `GET /height` returns the current head. :::warning A `start_slot` before the earliest indexed slot doesn't error The indexer starts from the earliest indexed slot instead, so a backfill can look healthy while silently skipping every slot before that. To test a candidate slot, send a one-slot bounded query and compare `next_slot` to `from_slot`: equal means the slot isn't indexed yet, `from_slot + 1` means served (see the [HyperSync curl examples](https://docs.envio.dev/docs/HyperSync/solana-curl-examples)). Need history further back? [Tell us on Discord](https://discord.gg/envio). ::: ## `programs` Programs are defined once for the whole project; `program_id` says where each one lives on every chain. | Field | Required | Default | Notes | | --- | --- | --- | --- | | `name` | ✅ | - | A unique name you choose. Used in handlers (`onInstruction({ program: "" })`) and in generated types. | | `program_id` | ✅ | - | Base58 program address. A single value is allowed only when the config defines one chain; with several, give a mapping keyed by chain id, naming every one of them and writing `_` for a chain the program isn't deployed on. | | `idl` | - | - | Path to an IDL JSON (Anchor 0.30+, legacy Anchor, Shank or Codama), relative to `config.yaml`. Every usable instruction becomes indexable, and `onInstruction` selects by name. | | `instructions` | - | - | Instructions to index. Required when there's no `idl`; with an `idl`, use it only to override or add instructions (see below). | ```yaml programs: - name: SplToken program_id: solana: TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA solana-devnet: TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA - name: MyProgram program_id: solana: MyPr0gram11111111111111111111111111111111111 solana-devnet: _ # not deployed there ``` ### `instructions` Each entry declares one instruction of the program. | Field | Required | Default | Notes | | --- | --- | --- | --- | | `name` | ✅ | - | The instruction name, unique per program. It's the key in `onInstruction({ instruction: "" })` and in the generated types. | | `discriminator` | ✅ | - | `0x`-prefixed hex prefix of the instruction data to dispatch on, of any whole number of bytes; an 8-byte value is the standard Anchor discriminator. The empty prefix `"0x"` matches every instruction of the program. See [discriminators](https://docs.envio.dev/docs/HyperIndex/solana/decoding#discriminators). | | `accounts` | - | - | Positional account slots, in the order the program expects them. The Nth entry names slot N and surfaces it as `instruction.accounts.`. | | `args` | - | - | Borsh argument layout. Setting it attaches a decoder that also filters - see [`args` is also a filter](https://docs.envio.dev/docs/HyperIndex/solana/decoding#args-is-also-a-filter). | With an `idl`, both `accounts` and `args` are required on a row whose name the IDL declares (that row replaces the IDL's version of it); a row with a new name adds an instruction the IDL didn't declare. ```yaml instructions: - name: transferChecked discriminator: "0x0c" accounts: [source, mint, destination, authority] args: - name: amount type: u64 - name: decimals type: u8 ``` ### Account slots Entries in `accounts` are positional, and three forms are accepted: | Form | Meaning | | --- | --- | | `payer` | A slot the call always carries. Surfaces as `instruction.accounts.payer`. | | `?authority` | An optional slot. The key is absent from `instruction.accounts` when the call omits the slot or fills it with the program id. | | `_` | Holds a position without naming it, so the slots after it keep theirs. Never surfaced, never filterable, and the list may not end with one. | Naming a slot is what makes it filterable from a handler's [`where.accounts`](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers#filtering-with-where); the raw positional addresses are available either way through `instruction.accountArguments`. ## Choosing what to index Solana's highest-frequency programs (SPL Token, System) produce enormous volumes of instructions, and matching them unfiltered can swamp a backfill. Narrow a registration with a [`where`](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers#filtering-with-where) filter on account keys, or read value flow from [account activity](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers#account-activity) on a protocol instruction instead of indexing every `transfer`. ## Related - [Decoding Instructions](https://docs.envio.dev/docs/HyperIndex/solana/decoding): IDLs, discriminators, inline layouts, argument types. - [Instruction Handlers](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers): what arrives in the handler, field selection, and filters. - [Schema file](https://docs.envio.dev/docs/HyperIndex/schema): defining the entities you write to (same as EVM). --- # EVM vs Solana > Every difference between indexing EVM chains and Solana with HyperIndex - concepts, config, handlers, and what isn't supported yet. The HyperIndex workflow is the same on both: define a `config.yaml` and `schema.graphql`, write handlers, run `codegen`, then `dev`/`start`. What changes is the unit of work: EVM indexes **events** emitted by **contracts**, Solana indexes **instructions** executed by **programs**. This page collects every difference in one place. ## Concept mapping | EVM | Solana | | --- | --- | | Smart contract | Program | | ABI | IDL (Anchor, Shank, Codama) or a declared layout | | Event / log | Instruction | | `indexer.onEvent` | `indexer.onInstruction` | | `event.params.` | `instruction.args.` | | Event signature / topic0 | Instruction discriminator | | Indexed event args | Named account slots, filtered with the handler's `where.accounts` | | `indexer.onBlock` | `indexer.onSlot` | | Block number | Slot number | | Address `0x…` (20 bytes, hex) | Pubkey (32 bytes, base58) | | Internal calls (not surfaced) | Inner instructions / CPIs (first-class) | | `bigint` params | `u64`+ args as `bigint`, smaller ints as `number` | ## Config differences | | EVM | Solana | | --- | --- | --- | | `ecosystem` | `evm` (default) | `svm` | | What you list | `contracts` (with `abi_file_path`, `address`, `events`) | top-level `programs` (with `program_id`, optional `idl`, `instructions`) | | Chain identity | `chains[].id` (public chain ID) | `chains[].id` is a cluster label: `solana` (7565164) or `solana-devnet` (7565165) | | Start of indexing | `start_block` (a block number, or `latest`) | `start_slot` (a **slot** number, or `latest`) | | Matching key | event signature (from ABI) | `discriminator` (a hex data prefix of any byte length) | | Decoding source | ABI | an IDL (Anchor, Shank, Codama) or an inline `args` + `accounts` layout | | Field selection | the handler's `fields` option, or `field_selection` in `config.yaml` | the handler's `fields` option only, with the extra `instruction`, `accountActivity` and `log` knobs | | Data source config | HyperSync endpoint inferred from `chains[].id` | inferred from `chains[].id` too; set `hypersync_config.url` to pin a specific one | | Data source | HyperSync or RPC | HyperSync only; `chains[].rpc` is accepted but unused | | Reorg options | `rollback_on_reorg`, `save_full_history` | none: reorg rollback is always on | :::note `chains`, not `networks` Current HyperIndex uses `chains` for both EVM and Solana. (V2 used `networks` for EVM; if you see that in an old guide, it's the same idea.) ::: ## Handler differences **EVM:** ```typescript indexer.onEvent( { contract: "ERC20", event: "Transfer" }, async ({ event, context }) => { const from = event.params.from; // decoded by ABI const amount = event.params.value; // bigint const chainId = event.chainId; const contract = event.srcAddress; // 0x… hex }, ); ``` **Solana:** ```typescript const fields = { instruction: ["args", "accounts", "isInner", "programId"], transaction: ["signature"], } as const; indexer.onInstruction( { program: "Jupiter", instruction: "sharedAccountsRoute", fields }, async ({ instruction, context }) => { const inAmount = instruction.args.inAmount; // bigint, decoded from the u64 const sourceMint = instruction.accounts.sourceMint.address; // base58 const programId = instruction.programId; // base58 const slot = instruction.block.slot; const txSig = instruction.transaction.signature; // needs fields.transaction const isInner = instruction.isInner; // CPI? }, ); ``` Key handler-level differences: - **A failed decode never reaches the handler.** EVM `event.params` is always populated (the ABI is known); on Solana an instruction whose data the configured layout rejects is skipped, so `args` and `accounts` need no null checks. - **Accounts are objects, not strings.** `instruction.accounts.` is `{ address, accountName, instructionAccountIndex, activity }` - read `.address` for the pubkey. - **Addresses are base58.** No `0x` lowercase/checksum concerns; pubkeys are base58 strings. - **Every field is opt-in.** Instruction, transaction, account-activity, block and log fields all come from the registration's [`fields`](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers#selecting-fields); on EVM the event always carries some block context. - **The chain id is a big number.** `context.chain.id === 7565164` on mainnet (`7565165` on devnet). ## CPIs vs internal calls On EVM, a contract calling another contract doesn't emit a separate indexable event for the internal call. On Solana, **cross-program invocations are real instructions**: if you index the inner program, you receive them, with `isInner: true` and a `path` that reconstructs the call tree. This makes Solana's composability directly indexable (e.g. the Raydium/Orca swaps underneath a Jupiter route). See [Inner instructions](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers#inner-instructions-cpis). ## Account activity Solana instructions can carry **pre/post lamport and SPL Token balances** for the accounts a transaction touched (`fields.accountActivity`). This gives you net value movement (the balance *change*) without indexing every transfer instruction; there's no direct EVM equivalent built into the event. The amounts are `bigint` raw base units, and each token entry carries the mint's `decimals`. See [Account activity](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers#account-activity). ## Slots vs blocks - `start_slot` is a **slot**, and history doesn't reach genesis yet - see [choosing a start slot](https://docs.envio.dev/docs/HyperIndex/solana/configuration#choosing-an-endpoint-and-a-start-slot). - Some slots have **no block** (skipped leader). Slot handlers must handle the empty case. - The handler arg for `onSlot` is `{ slot: number }`, not a `block` object. ## Not supported on Solana (yet) Contract import, dynamic registration, wildcard indexing across programs, account-change and log handlers, and ReScript codegen have no Solana equivalent today. The [overview](https://docs.envio.dev/docs/HyperIndex/solana#what-is-not-supported-yet) lists each one and what to reach for instead. What's the same: the [schema file](https://docs.envio.dev/docs/HyperIndex/schema), the entity `context` API, the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api), local Docker dev, the GraphQL/Hasura layer, [preload optimization](https://docs.envio.dev/docs/HyperIndex/preload-optimization), and [Envio Cloud](https://docs.envio.dev/docs/HyperIndex/hosted-service) deployment. ## Related - [Solana Overview](https://docs.envio.dev/docs/HyperIndex/solana) - [Configuration](https://docs.envio.dev/docs/HyperIndex/solana/configuration) - [Instruction Handlers](https://docs.envio.dev/docs/HyperIndex/solana/instruction-handlers) - [Decoding Instructions](https://docs.envio.dev/docs/HyperIndex/solana/decoding) --- # Indexing on Fuel Network > Explore how to index and query real-time and historical data on Fuel Network with HyperIndex. ## Introduction Envio supports the [Fuel Network](https://fuel.network/) on mainnet and testnet. This page shows how to use HyperIndex with Fuel’s architecture and features. Fuel offers several advantages as a modular execution layer including: - Parallel transaction execution - State-minimized design - UTXO-based architecture - Advanced FuelVM capabilities ## HyperIndex for Fuel [HyperIndex](https://docs.envio.dev/docs/HyperIndex/overview.md) enables developers to easily index and query real-time and historical data on Fuel Network with the same powerful features available for EVM chains. ### Getting Started with Fuel Indexing You can start indexing Fuel contracts in two ways: 1. **Quick Start (5-minute tutorial)**: Follow our step-by-step [tutorial](https://docs.envio.dev/docs/HyperIndex/tutorial-indexing-fuel.md) to create your first Fuel indexer quickly. 2. **No-Code Contract Import**: Use our [Contract Import](https://docs.envio.dev/docs/HyperIndex/quickstart.md) tool to automatically generate configuration and schema files for your Fuel contracts. ### Example Fuel Indexers Looking for inspiration? Check out these indexers built by projects in the Fuel ecosystem: | Project | Type | GitHub Repository | | --- | --- | --- | | Spark | Orderbook DEX | [github](https://github.com/compolabs/spark-envio-indexer) | | [Mira](https://mira.ly/) | AMM DEX | [github](https://github.com/mira-amm/mira-indexer) | | [Thunder](https://thundernft.market/) | NFT Marketplace | [github](https://github.com/ThunderFuel/thunder-indexer) | | [Swaylend](https://swaylend.com/) | Lending Protocol | [github](https://github.com/Swaylend/swaylend-monorepo/tree/develop/apps/indexer) | | Greeter | Tutorial | [github](https://github.com/enviodev/fuel-greeter) | :::caution These repositories use older HyperIndex versions Each indexer above pins an `envio` version from v1 or v2, so its handler code uses the pre-v3 API and won't run as-is on current HyperIndex. Use them for schema and config ideas, and this page for the v3 handler API. For a current starting point, run `pnpx envio init fuel template --template greeter`. ::: ### Features Supported on Fuel HyperIndex for Fuel supports all the core features available in the EVM version: - ✅ [No-code Contract Import](https://docs.envio.dev/docs/HyperIndex/quickstart.md) - ✅ [Dynamic Contracts / Factory Tracking](https://docs.envio.dev/docs/HyperIndex/dynamic-contracts.md) - ✅ [Testing Framework](https://docs.envio.dev/docs/HyperIndex/testing) - ✅ [Envio Cloud](https://docs.envio.dev/docs/HyperIndex/hosted-service.md) - ✅ [Wildcard Indexing](https://docs.envio.dev/docs/HyperIndex/wildcard-indexing.md) ## Fuel-Specific Event Types ### Understanding Fuel's Event Model Fuel's event model differs significantly from EVM. Instead of predefined events, Fuel uses a more flexible approach with various receipt types that can be indexed. ### LOG_DATA Receipts (Primary Event Type) The most common event type in Fuel is the `LOG_DATA` receipt, created by the `log` instruction in [Sway](https://docs.fuel.network/docs/sway/) contracts. Unlike Solidity's `emit` which requires predefined event structures, Sway's `log` function allows passing any data, providing greater flexibility. #### Configuration Example: ```yaml ecosystem: fuel chains: - id: 0 # Fuel testnet start_block: 1 contracts: - name: SwayContract abi_file_path: "./abis/SwayContract.json" address: "0x123..." events: - name: NewGreeting logId: "8500535089865083573" ``` The `logId` is a unique identifier for the logged struct, which you can find in your contract's ABI file. `chains[].id` is `0` for Fuel testnet and `9889` for Fuel mainnet. HyperIndex picks the HyperFuel endpoint from the id (`https://fuel-testnet.hypersync.xyz` or `https://fuel.hypersync.xyz`); any other id fails with `Fuel network id is not supported` unless you set `hyperfuel_config.url`. Add `# yaml-language-server: $schema=./node_modules/envio/fuel.schema.json` at the top of `config.yaml` for editor validation. #### Auto-detection of logId: If your event name matches the logged struct name in Sway, you can omit the `logId`: ```yaml events: - name: NewGreeting # Will automatically detect logId if it matches the struct name ``` > **Tip**: Instead of manually configuring events, use the [Contract Import](https://docs.envio.dev/docs/HyperIndex/quickstart.md) tool which automatically detects events and generates the proper configuration. ### Additional Fuel Event Types Fuel allows indexing several additional receipt types not available in EVM: | Event Type | Description | Example Configuration | | --- | --- | --- | | `Mint` | Triggered when a contract mints tokens | `- name: Mint` | | `Burn` | Triggered when a contract burns tokens | `- name: Burn` | | `Transfer` | Combines `TRANSFER` and `TRANSFER_OUT` receipts | `- name: Transfer` | | `Call` | Triggered when a contract calls another contract | `- name: Call` | #### Using Custom Names: You can rename these events while maintaining their type: ```yaml events: - name: MintMyNft # Custom name type: mint # Actual event type ``` `type` accepts `logData`, `mint`, `burn`, `transfer` and `call`. Without it, the type is derived from the event name and falls back to `logData`. > **Note**: All event types can be used with [Wildcard Indexing](https://docs.envio.dev/docs/HyperIndex/wildcard-indexing.md). ### Transfer Event Specifics The `Transfer` event type combines two Fuel receipt types: - `TRANSFER`: Emitted when a contract transfers tokens to another contract - `TRANSFER_OUT`: Emitted when a contract transfers tokens to a wallet > **Important**: Transfers between wallets are not included in the `Transfer` event type. ## Event Object Structure in Handlers When handling Fuel events, the event object structure differs from EVM: ```typescript // Example Fuel event handler import { indexer } from "envio"; indexer.onEvent( { contract: "SwayContract", event: "NewGreeting" }, async ({ event, context }) => { // Access event parameters const message = event.params.message; // Access block information const blockHeight = event.block.height; const blockTime = event.block.time; const blockId = event.block.id; // Access transaction information const txId = event.transaction.id; // Access source contract address const sourceContract = event.srcAddress; // Access log position const logIndex = event.logIndex; // Store data context.Greeting.set({ id: event.transaction.id, message: message, timestamp: blockTime, }); }, ); ``` Compared with EVM: - `event.block` carries `id`, `height` and `time`, and `event.transaction` carries `id`. - Block ranges key on `block.height`, not `block.number`: a handler's `where` takes `{ block: { height: { _gte: 1_000_000 } } }`, and an [`indexer.onBlock`](https://docs.envio.dev/docs/HyperIndex/block-handlers) handler receives `{ block: { height }, context }` and filters with `block.height._gte` / `_lte` / `_every`. ## HyperFuel [HyperFuel](https://docs.envio.dev/docs/HyperSync/hyperfuel) is Envio's low-level data API for the Fuel Network (equivalent to [HyperSync](https://docs.envio.dev/docs/HyperSync/overview) for EVM chains). HyperFuel provides: - High-performance data access - Flexible query capabilities - Multiple data formats (Parquet, Arrow, typed data) - Complete historical data ### Available Clients Access HyperFuel data using any of these clients: - **Rust**: [hyperfuel-client-rust](https://github.com/enviodev/hyperfuel-client-rust) - **Python**: [hyperfuel-client-python](https://github.com/enviodev/hyperfuel-client-python) - **Node.js**: [hyperfuel-client-node](https://github.com/enviodev/hyperfuel-client-node) - **JSON API**: [hyperfuel-json-api](https://github.com/enviodev/hyperfuel-json-api) ### HyperFuel Endpoints - **Mainnet**: https://fuel.hypersync.xyz - **Testnet**: https://fuel-testnet.hypersync.xyz For detailed information, see the [HyperFuel documentation](https://docs.envio.dev/docs/HyperSync/hyperfuel). ## About Fuel Network [Fuel](https://fuel.network/) is an operating system purpose-built for Ethereum rollups with unique architecture focused on: - **P**arallelization: Execute transactions concurrently for higher throughput - **S**tate-minimized execution: Efficient storage and computation model - **I**nteroperability: Seamless integration with other blockchain systems Powered by the FuelVM, Fuel expands Ethereum's capabilities without compromising security or decentralization. ### Resources - [Website](https://fuel.network/) - [Twitter](https://twitter.com/fuel_network) - [Discord](https://discord.com/invite/xfpK4Pe) - [Documentation](https://docs.fuel.network/) ## Need Help? If you encounter any issues with Fuel indexing, please: 1. Check our [Troubleshooting](https://docs.envio.dev/docs/HyperIndex/common-issues.md) guides 2. Join our [Discord](https://discord.gg/envio) for community support 3. Create an issue in our [GitHub repository](https://github.com/enviodev/hyperindex) --- # Indexing Sway Farm on the Fuel Network > Learn how to index Sway Farm on Fuel and track player events with Envio. HyperIndex supports any EVM-compatible blockchain and the [Fuel](https://fuel.network/) Network. Blockchain indexers are vital to the success of any dApp. In this tutorial, we will create an Envio indexer for the Fuel dApp [Sway Farm](https://swayfarm.xyz/) step by step. Sway Farm is a simple farming game and for the sake of a real-world example, let's create the indexer for a leaderboard of all farmers 🧑‍🌾 ![Sway Farm](https://docs.envio.dev/docs-assets/tutorial-indexing-fuel-farm.webp) ## About Fuel [Fuel](https://fuel.network/) is an operating system purpose-built for Ethereum rollups. Fuel's unique architecture allows rollups to solve for PSI (parallelization, state minimized execution, interoperability). Powered by the FuelVM, Fuel aims to expand Ethereum's capability set without compromising security or decentralization. [Website](https://fuel.network/) | [X](https://twitter.com/fuel_network?lang=en) | [Discord](https://discord.com/invite/xfpK4Pe) ## Prerequisites ### Environment tooling - **[Node.js](https://nodejs.org/en/download/current)** _(22.15.0 or newer)_ - **[pnpm](https://pnpm.io/installation)** _(recommended but not required)_ - **[Docker Desktop](https://www.docker.com/products/docker-desktop/)** _(required to run the Envio indexer locally)_ > **Note:** Docker is specifically required to run your blockchain indexer locally. You can skip Docker installation if you plan only to use Envio Cloud. ## Initialize the project Now that you have installed the prerequisite packages let's begin the practical steps of setting up the indexer. Open your terminal in an empty directory and initialize a new indexer by running the command: ```bash pnpx envio init ``` In the following prompt, choose the directory where you want to set up your project. The default is the current directory, but in the tutorial, I'll use the indexer name: ```bash ? Specify a folder name (ENTER to skip): (.) sway-farm-indexer ``` Next, choose the blockchain ecosystem. You can choose between `Evm`, `Svm` and `Fuel`. Handlers are generated in TypeScript by default: ```bash ? Choose blockchain ecosystem Evm Svm > Fuel [↑↓ to move, enter to select, type to filter] ``` In the following prompt, you can choose an initialization option. There's a Greeter template for Fuel, which is an excellent way to learn more about HyperIndex. But since we have an existing contract, the `From ABI File` option is the best way to create an indexer: ```bash ? Choose an initialization option > From ABI File - Use your own ABI file Template: Greeter [↑↓ to move, enter to select, type to filter] ``` > A separate [Tutorial](https://docs.envio.dev/docs/HyperIndex/greeter-tutorial.md) page provides more details about the `Greeter` template. Next it'll ask us for an ABI file. You can find it in the `./out/debug` directory after building your [Sway](https://docs.fuel.network/docs/sway/) contract with `forc build`: ```bash ? What is the path to your json abi file? ./sway-farm/contract/out/debug/contract-abi.json ``` > Don't have the Sway toolchain? Download the ABI used in this tutorial with `curl -o contract-abi.json https://raw.githubusercontent.com/enviodev/sway-farm-indexer/main/abis/swayfarm-abi.json`, then enter `./contract-abi.json` at the prompt. After the ABI file is provided, Envio parses all possible events you can use for indexing. All events start selected. The receipt types `Transfer`, `Mint`, `Burn` and `Call` are also listed, unselected, and the order can differ between runs: ```bash ? Which events would you like to index? > [x] NewPlayer [x] PlantSeed [x] SellItem [x] InvalidError [x] Harvest [x] BuySeeds [x] LevelUp [x] StrLog [↑↓ to move, space to select one, → to all, ← to none, type to filter] ``` Let's select the events we want to index. I opened the code of the [contract file](https://github.com/FuelLabs/sway-farm/blob/47e3ed5a91593ebcf8d2c67ae6fad41d9954c8a8/contract/src/abi_structs.sw#L365-L406) and realized that for a leaderboard we need only events which update player information. Hence, I left only `NewPlayer`, `LevelUp`, and `SellItem` selected in the list. We'd want to index more events in real life, but this is enough for the tutorial. ```bash ? Which events would you like to index? > [x] NewPlayer [ ] PlantSeed [x] SellItem [ ] InvalidError [ ] Harvest [ ] BuySeeds [x] LevelUp [ ] StrLog [↑↓ to move, space to select one, → to all, ← to none, type to filter] ``` > 📖 For the tutorial we only need to index `LOG_DATA` receipts, but you can also index `Mint`, `Burn`, `Transfer` and `Call` receipts. Read more about [Supported Event Types](https://docs.envio.dev/docs/HyperIndex/fuel#additional-fuel-event-types). Just a few simple questions left. Let's call our contract `SwayFarm`: ```bash ? What is the name of this contract? SwayFarm ``` Choose the network the contract is deployed on: ```bash ? Choose network: Mainnet > Testnet [↑↓ to move, enter to select, type to filter] ``` Set an address for the deployed contract: ```bash ? What is the address of the contract? 0xf5b08689ada97df7fd2fbd67bee7dea6d219f117c1dc9345245da16fe4e99111 [Use the proxy address if your abi is a proxy implementation] ``` Finish the initialization process: ```bash ? Would you like to add another contract? > I'm finished Add a new address for same contract on same network Add a new contract (with a different ABI) [Current contract: SwayFarm, on network: Fuel Testnet] ``` Add your Envio API token. Pick **Create a new API token** to open the token page, or **Add an existing API token**, then paste it at the `? Add your API token:` prompt: ```bash ? Add an Envio API token to your .env file? > Create a new API token (Opens https://envio.dev/app/api-tokens) Add an existing API token [↑↓ to move, enter to select, type to filter] ``` If you see the following lines, it means we are already halfway through 🙌 ``` Your indexer is ready! Pick how you'd like to run it: 1. cd sway-farm-indexer && pnpm test # run the tests (recommended for AI) 2. cd sway-farm-indexer && pnpm dev # run locally 3. cd sway-farm-indexer && pnpm start # run in production ``` Let's open the indexer in an IDE and start adjusting it for our farm 🍅 ## Walk through initialized indexer At this point, we should already have a working indexer. You can start it by running `pnpm dev`, which we cover in more detail later in the tutorial. Everything is configured by modifying the 3 files below. Let's walk through each of them. - config.yaml [`Guide`](https://docs.envio.dev/docs/HyperIndex/configuration-file.md) - schema.graphql [`Guide`](https://docs.envio.dev/docs/HyperIndex/schema.md) - src/handlers/SwayFarm.ts [`Guide`](https://docs.envio.dev/docs/HyperIndex/event-handlers.md) ### `config.yaml` The `config.yaml` outlines the specifications for the indexer, including details such as chain and contract specifications and the event information to be used in the indexing process. ```yaml # yaml-language-server: $schema=./node_modules/envio/fuel.schema.json name: sway-farm-indexer disable_default_cross_chain: true ecosystem: fuel chains: - id: 0 start_block: 0 contracts: - name: SwayFarm address: - "0xf5b08689ada97df7fd2fbd67bee7dea6d219f117c1dc9345245da16fe4e99111" abi_file_path: abis/swayfarm-abi.json events: - name: SellItem logId: '11192939610819626128' - name: LevelUp logId: '9956391856148830557' - name: NewPlayer logId: '169340015036328252' ``` The events are listed in the order you selected them. In the tutorial, we don't need to adjust it in any way. But later you can modify the file and add more events for indexing. As a nice to have, you can use a [Sway](https://docs.fuel.network/docs/sway/) struct name without specifying a `logId`, like this: ```yaml - name: SellItem - name: LevelUp - name: NewPlayer ``` ### `schema.graphql` The `schema.graphql` file serves as a representation of your application's data model. It defines entity types that directly correspond to database tables, and the event handlers you create are responsible for creating and updating records within those tables. Additionally, the GraphQL API is automatically generated based on the entity types specified in the `schema.graphql` file, to allow access to the indexed data. > 🧠 A separate [Guide](https://docs.envio.dev/docs/HyperIndex/schema.md) page provides more details about the `schema.graphql` file. For the leaderboard, we need only one entity representing the player. Replace the contents of `schema.graphql` with a single `Player` entity: ```graphql type Player { id: ID! farmingSkill: BigInt! totalValueSold: BigInt! } ``` We will use the user address as an ID. The fields `farmingSkill` and `totalValueSold` are `u64` in Sway, so to safely map them to JavaScript value, we'll use `BigInt`. ### `src/handlers/SwayFarm.ts` The event handlers generated by contract import are quite simple and only add an entity to a DB when a related event is indexed. Here is a simplified version of the generated code for one event: ```typescript /* * Please refer to https://docs.envio.dev for a thorough guide on all Envio indexer features */ import { indexer, type Entity } from "envio"; indexer.onEvent( { contract: "SwayFarm", event: "SellItem" }, async ({ event, context }) => { const entity: Entity<"SwayFarm_SellItem"> = { id: `${event.chainId}_${event.block.height}_${event.logIndex}`, }; context.SwayFarm_SellItem.set(entity); }, ); ``` Let's modify the handlers to update the `Player` entity instead. But before we start, we need to run `pnpm codegen` to generate utility code and types for the `Player` entity we've added. ```bash pnpm codegen ``` It's time for a little bit of coding. Replace the contents of `src/handlers/SwayFarm.ts` with the code below. The indexer is very simple; it requires us only to pass event data to an entity. ```typescript import { indexer } from "envio"; /** Registers a handler that processes NewPlayer event on the SwayFarm contract and stores the players in the DB */ indexer.onEvent( { contract: "SwayFarm", event: "NewPlayer" }, async ({ event, context }) => { // Set the Player entity in the DB with the initial values context.Player.set({ // The address in Sway is a union type of user Address and ContractID. Envio supports most of the Sway types, and the address value was decoded as a discriminated union 100% typesafe id: event.params.address.payload.bits, // Initial values taken from the contract logic farmingSkill: 1n, totalValueSold: 0n, }); }, ); indexer.onEvent( { contract: "SwayFarm", event: "LevelUp" }, async ({ event, context }) => { const playerInfo = event.params.player_info; context.Player.set({ id: event.params.address.payload.bits, farmingSkill: playerInfo.farming_skill, totalValueSold: playerInfo.total_value_sold, }); }, ); indexer.onEvent( { contract: "SwayFarm", event: "SellItem" }, async ({ event, context }) => { const playerInfo = event.params.player_info; context.Player.set({ id: event.params.address.payload.bits, farmingSkill: playerInfo.farming_skill, totalValueSold: playerInfo.total_value_sold, }); }, ); ``` Without overengineering, simply set the player data into the database. What's nice is that whenever your ABI or entities in `schema.graphql` change, Envio regenerates types and shows the compilation error. > 🧠 You can find an earlier version of this indexer on [GitHub](https://github.com/enviodev/sway-farm-indexer). It was built with HyperIndex v2, so its handlers use the older API; the code on this page is the current one. ## Starting the Indexer > 📢 Make sure you have docker open The following commands will start the docker and create databases for indexed data. Make sure to re-run `pnpm dev` if you've made some changes. ```bash pnpm dev ``` Nice, the indexer syncs the historical blocks and then keeps up with new events as they come in. ## View the indexed results Let's check indexed players on the local Hasura server. ```bash open http://localhost:8080 ``` The Hasura admin-secret / password is `testing`, and the tables can be viewed in the data tab or queried from the playground. ```graphql query MyQuery { InactivePlayers: Player_aggregate(where: {totalValueSold: {_eq: "0"}}) { aggregate { count } } ActivePlayers: Player_aggregate(where: {totalValueSold: {_neq: "0"}}) { aggregate { count avg { farmingSkill totalValueSold } } } Player(limit: 5, order_by: {totalValueSold: desc}) { id totalValueSold farmingSkill } } ``` ![GraphiQL example](https://docs.envio.dev/docs-assets/tutorial-indexing-fuel-graphiql.webp) Now, we can easily get the top 5 players, the number of inactive and active players, and the average sold value. What's left is a nice UI for the Sway Farm leaderboard, but that's not the tutorial's topic. > 🧠 A separate [Guide](https://docs.envio.dev/docs/HyperIndex/navigating-hasura.md) page provides more details about navigating Hasura. ## Deploy the indexer to Envio Cloud Once you have verified that the indexer is working for your contracts, then you are ready to deploy the indexer to Envio Cloud. Deploying an indexer to Envio Cloud allows you to extract information via graphQL queries into your front-end or some back-end application. Navigate to the [Envio Cloud](https://envio.dev/app/login) to start deploying your indexer and refer to this [documentation](https://docs.envio.dev/docs/HyperIndex/hosted-service.md) for more information on deploying your indexer. ## What next? Once you have successfully finished the tutorial, you are ready to become a blockchain indexing wizard! Join our [Discord](https://discord.gg/envio) channel to make sure you catch all new releases. ---