# Envio docs: HyperIndex advanced features > Factories, the Effect API, wildcard indexing, preload, contract state, IPFS, HyperSync and RPC sources, reorgs, WebSockets. 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 (this file): 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](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: - Loading Dynamic Contracts / Factories - Effect API - Wildcard Indexing & Topic Filtering - Preload Optimization - Migrate HyperIndex V2 loaders to V3 handlers - Accessing Contract State in Event Handlers - Using IPFS with Envio Indexers - HyperSync as Data Source - RPC as Data Source - Chain Reorganization Support - Generated Indexing Files - Terminology & Key Concepts - Subscribe to HyperIndex GraphQL over WebSockets - Query Conversion Guide - Envio docs MCP server for AI coding assistants --- # Loading Dynamic Contracts / Factories > Learn how to track and index dynamically created contracts from factory contracts. ## Introduction Many blockchain systems use factory patterns where new contracts are created dynamically. Common examples include: - DEXes like Uniswap where each trading pair creates a new contract - NFT platforms that deploy new collection contracts - Lending protocols that create new markets as isolated contracts When indexing these systems, you need a way to discover and track these dynamically created contracts. Envio provides powerful tools to handle this use case. ### Contract Registration Handler Instead of a template based approach, we've introduced a `contractRegister` handler that can be added to any event. This allows you to easily: - Register contracts from any event handler. - Use conditions and any logic you want to register contracts. - Have nested factories which are registered by other factories. ```typescript import { indexer } from "envio"; indexer.contractRegister( { contract: "", event: "" }, async ({ event, context }) => { context.chain..add(); }, ); ``` The `contractRegister` context is smaller than a handler's. It has only: - `context.chain.id` - the chain the event came from - `context.chain..add(address)` - registers an address for a contract named in `config.yaml`. The address is validated and converted to your `address_format`. - `context.log` - the logger There are no entity operations or `context.effect` here, and accessing anything else throws. To store data from the same event, register a separate `indexer.onEvent` handler for it. Like `indexer.onEvent`, call `indexer.contractRegister` at the top level of a handler file, with an `async` function. ## Example: NFT Factory Pattern Let's look at a complete example using an NFT factory pattern. ### Scenario - `NftFactory` contract creates new `SimpleNft` contracts - We want to index events from all NFTs created by this factory - Each time a new NFT is created, the factory emits a `SimpleNftCreated` event ### 1. Configure Your Contracts in config.yaml ```yaml name: nftindexer description: NFT Factory chains: - id: 1337 start_block: 0 contracts: - name: NftFactory abi_file_path: abis/NftFactory.json address: "0x4675a6B115329294e0518A2B7cC12B70987895C4" # Factory address is known events: - event: SimpleNftCreated (string name, string symbol, uint256 maxSupply, address contractAddress) - name: SimpleNft abi_file_path: abis/SimpleNft.json # No address field - we'll discover these addresses from events events: - event: Transfer (address from, address to, uint256 tokenId) ``` Note that: - The `NftFactory` contract has a known address specified in the config - The `SimpleNft` contract has no address, as we'll register instances dynamically ### 2. Create the Contract Registration Handler In your `src/handlers/.ts` file: ```typescript import { indexer } from "envio"; // Register SimpleNft contracts whenever they're created by the factory indexer.contractRegister( { contract: "NftFactory", event: "SimpleNftCreated" }, async ({ event, context }) => { // Register the new NFT contract using its address from the event context.chain.SimpleNft.add(event.params.contractAddress); context.log.info( `Registered new SimpleNft at ${event.params.contractAddress}` ); }, ); // Handle Transfer events from all SimpleNft contracts indexer.onEvent( { contract: "SimpleNft", event: "Transfer" }, async ({ event, context }) => { // Your event handling logic here context.log.info( `NFT Transfer at ${event.srcAddress} - Token ID: ${event.params.tokenId}` ); // Example: Store transfer information in the database // ... }, ); ``` ## Async Contract Register A `contractRegister` handler can `await` before it registers. This is a unique feature of Envio that allows you to perform an external call to determine the address of the contract to register. Call `add` before the handler's promise resolves; calling it afterwards throws. ```typescript import { indexer } from "envio"; indexer.contractRegister( { contract: "NftFactory", event: "SimpleNftCreated" }, async ({ event, context }) => { const version = await getContractVersion(event.params.contractAddress); if (version === "v2") { context.chain.SimpleNftV2.add(event.params.contractAddress); } else { context.chain.SimpleNft.add(event.params.contractAddress); } }, ); ``` ## Coming from TheGraph? If you're migrating from a subgraph that uses **data source templates** (`DataSource.create()`), the equivalent in Envio is the `contractRegister` handler. | TheGraph | Envio (HyperIndex) | | --- | --- | | Define a template in `subgraph.yaml` | Define the contract in `config.yaml` without an `address` | | Call `MyTemplate.create(address)` in a mapping | Call `context.chain.MyContract.add(address)` in a `contractRegister` handler | | Templates are triggered from other mappings | `contractRegister` runs before the event handler, on any event | The key difference is that Envio's `contractRegister` is more flexible - you can add conditional logic, perform async calls, and register contracts from any event, not just from a dedicated factory mapping. For a step-by-step migration guide, see [Migrating from a Subgraph](https://docs.envio.dev/docs/HyperIndex/migration-guide). ## When to Use Dynamic Contract Registration Use dynamic contract registration when: - Your system includes factory contracts that deploy new contracts over time - You want to index events from all instances of a particular contract type - The addresses of these contracts aren't known at the time you create your indexer ## Important Notes - **Block Coverage**: When a dynamic contract is registered, Envio will index all events from that contract in the same block where it was created, even if those events happened in transactions before the registration event. This is particularly useful for contracts that emit events during their construction. - **Triggering Event**: Any event can trigger a registration - it doesn't have to be the one that created the contract. You might register a token when you see it added to a registry, or when it's first used, rather than at deployment. ## Scaling to Very Large Factories There is no practical ceiling on how many addresses a factory can register. Before v3.5, HyperIndex started to struggle at around 8 million addresses. That limit is gone - indexers with billions of registered addresses are supported. You don't need to configure anything for this. Once a contract accumulates enough addresses, HyperIndex automatically changes how it filters events for that contract: instead of asking the data source for a specific address list, it fetches events more broadly and filters them locally. The switch is per contract, so one large factory doesn't affect how your other contracts are indexed. The trade-off is that a very large factory fetches more data than its handlers ultimately use, since the filtering happens after the fetch rather than before it. That's what keeps indexing fast at this scale. To see how many addresses a chain has registered, watch `envio_indexing_addresses` on the [metrics endpoint](https://docs.envio.dev/docs/HyperIndex/observability#available-metrics). ## Debugging Tips - Use logging in your `contractRegister` function to confirm contracts are being registered. - If you're not seeing events from your dynamic contracts, verify they're being properly registered in database. For more information on writing event handlers, see the [Event Handlers Guide](https://docs.envio.dev/docs/HyperIndex/event-handlers.md). For an end-to-end example on a live chain, [indexing every tokenized asset on Robinhood Chain](https://docs.envio.dev/blog/index-robinhood-chain-data) uses `contractRegister` to discover every stock token contract from a single factory event, with the full config, schema and handler. --- # Effect API > Learn how to use the Effect API for external calls in handlers. The Effect API provides a powerful and convenient way to perform external calls from your handlers. It's especially effective when used with [Preload Optimization](https://docs.envio.dev/docs/HyperIndex/preload-optimization): - **Automatic batching**: Calls of the same kind are automatically batched together - **Intelligent memoization**: Calls are memoized, so you don't need to worry about the handler function being called multiple times - **Deduplication**: Calls with the same arguments are deduplicated to prevent overfetching - **Persistence**: Built-in support for result persistence for indexer reruns (opt-in via `cache: true`) - **Future enhancements**: We're working on automatic retry logic and enhanced caching workflows πŸ—οΈ To use the Effect API, you first need to define an effect using `createEffect` function from the `envio` package: ```typescript import { createEffect, S } from "envio"; export const getMetadata = createEffect( { name: "getMetadata", input: S.string, output: { description: S.string, value: S.bigint, }, rateLimit: { calls: 5, per: "second", }, cache: true, }, async ({ input, context }) => { const response = await fetch(`https://api.example.com/metadata/${input}`); const data = await response.json(); context.log.info(`Fetched metadata for ${input}`); return { description: data.description, value: data.value, }; } ); ``` The first argument is an options object that describes the effect: - `name` (required) - the name of the effect used for debugging and logging. It also names the cache table and cache file, so it may contain only letters, numbers, `_`, `-` and `.`, and can't start with a dot. Any other name throws `Invalid effect name ""` when the effect is created. - `input` (required) - the input type of the effect - `output` (required) - the output type of the effect - `rateLimit` (required) - the maximum calls allowed per timeframe, or `false` to disable - `cache` (optional, default `false`) - save effect results in the database to prevent duplicate calls - `crossChain` (optional) - whether the cache and rate limit are shared across all chains (default: `true`, or `false` when the indexer sets `disable_default_cross_chain`). See [Per-Chain Effects](#per-chain-effects) The second argument is an `async` function that receives `{ input, context }` and returns the output. Its `context` has: - `context.log` - the same logger as in handlers - `context.effect` - calls another effect - `context.cache` - set it to `false` to skip caching this call's result - `context.chain.id` - the calling chain, on `crossChain: false` effects only If the function throws, the `context.effect` call in your handler rejects with that error. There is no automatic retry, so catch errors you can recover from inside the effect. > **Note:** For type definitions, you should use `S` from the `envio` package, which uses [Sury](https://github.com/DZakh/sury) library under the hood. `input` and `output` take a schema, or a plain object or tuple of schemas, which is the same as wrapping it in `S.schema(...)`. `S` exposes `string`, `number`, `int32`, `boolean`, `bigint`, `bigDecimal`, `address`, `jsonString`, `unknown`, `never`, `schema`, `object`, `array`, `tuple`, `record`, `union`, `optional`, `nullable`, `merge`, `shape`, `transform`, `refine`, `parseOrThrow` and `assertOrThrow`. Use `S.Infer` to get a schema's TypeScript type. `S.address` is typed as `Address` but only checks that the value is a string. An effect that needs no input takes `input: undefined` and is called with `context.effect(myEffect, undefined)`. After defining an effect, you can use `context.effect` to call it from your handler or another effect. The `context.effect` function accepts an effect as the first argument and the effect's input as the second argument: ```typescript import { indexer } from "envio"; indexer.onEvent( { contract: "ERC20", event: "Transfer" }, async ({ event, context }) => { const metadata = await context.effect(getMetadata, event.params.from); // Process the event with the metadata }, ); ``` ### Reading On-Chain State (eth_call) The Effect API is how you perform `eth_call`-style reads from your handlers - for example, reading a token balance, fetching a contract's name, or querying any view function at a specific block. ### Viem Transport Batching You can use `viem` or any other blockchain client inside your effect functions. When doing so, it's highly recommended to enable the `batch` option to group all effect calls into fewer RPC requests: ```typescript // Create a public client to interact with the blockchain const client = createPublicClient({ chain: mainnet, // Enable batching to group calls into fewer RPC requests transport: http(rpcUrl, { batch: true }), }); // Get the contract instance for your contract const lbtcContract = getContract({ abi: erc20Abi, address: "0x8236a87084f8B84306f72007F36F2618A5634494", client: client, }); // Effect to get the balance of a specific address at a specific block export const getBalance = createEffect( { name: "getBalance", input: { address: S.string, blockNumber: S.optional(S.bigint), }, output: S.bigint, rateLimit: { calls: 5, per: "second", }, cache: true, }, async ({ input, context }) => { try { // If blockNumber is provided, use it to get balance at that specific block const options = input.blockNumber ? { blockNumber: input.blockNumber } : undefined; const balance = await lbtcContract.read.balanceOf( [input.address as `0x${string}`], options ); return balance; } catch (error) { context.log.error(`Error getting balance for ${input.address}: ${error}`); // Return 0 on error to prevent processing failures return BigInt(0); } } ); ``` ### Persistence By default, effect results are not persisted in the database. This means if the effect with the same input is called again, the function will be executed the second time. To persist effect results, you can set the `cache` option to `true` when creating the effect. This will save the effect results in the database and reuse them in future indexer runs. You can also override caching for a specific call by setting `context.cache = false`, which prevents storing results for that execution, especially useful when handling failed responses. Example setting cache to false with context.cache: ```typescript export const getBalance = createEffect( { // effect options output: S.optional(S.bigint), // the output must allow the fallback value cache: true, }, async ({ input, context }) => { try { // your effect logic } catch (_) { // Don't cache failed response context.cache = false; return undefined; } } ); ``` Every effect cache creates a table in the database: `envio_effect_` for a cross-chain effect, and `envio__effect_` per chain for a `crossChain: false` effect. You can see it and query in Hasura console with admin secret. A cached result is checked against the effect's current `output` schema when it's loaded. If you change the schema and an old result no longer matches it, that entry is ignored and the effect runs again for that input. The `envio_effect_cache_invalidations` metric counts these. Also, use our [Development Console](https://envio.dev/console) to track the cache size and see number of calls which didn't hit the cache. ### Reuse Effect Cache on Indexer Reruns To prevent invalid data we don't keep the effect cache on indexer reruns. But you can explicitly configure cache, which should be preloaded when the indexer is rerun. Open [Development Console](https://envio.dev/console) of the running indexer which accumulated the cache. You'll be able to see the `Sync Cache` button right at the `Effects` section. Clicking the button will load the cache from the indexer database to the `.envio/cache` directory in your indexer project. When the indexer is rerun by using `envio dev` or `envio start -r` call, the initial cache will be loaded from the `.envio/cache` directory and used for the indexer run. Each cache is a TSV file: `.envio/cache/.tsv` for a cross-chain effect and `.envio/cache//.tsv` for a per-chain one. > **Note:** This doesn't support rollbacks on reorgs. The support for reorgs will be added in the future. ### Cache on Envio Cloud Envio Cloud provides built-in cache management for Effect API results, allowing you to save and restore caches directly from the dashboard without committing files to your repository. **Key Features:** - **Save Cache**: Capture effect data from any deployment with one click via Quick Actions - **Cache Settings**: Manage caches in Settings > Cache - enable/disable caching and select which cache to use - **Automatic Restore**: New deployments automatically preload effect data from your selected cache This eliminates the need to commit `.envio/cache` to your repository and removes file size limitations. For detailed instructions, see the [Effect API Cache documentation](https://docs.envio.dev/docs/HyperIndex/hosted-service-features#effect-api-cache). ### Rate Limit The `rateLimit` option controls how frequently an effect can run within a given timeframe. You can set it to `false` to disable rate limiting or define a custom limit such as calls per second, minute, or a duration in milliseconds. ```typescript // Effect to get the balance of a specific address at a specific block export const getBalance = createEffect( { name: "getBalance", input: { address: S.string, blockNumber: S.optional(S.bigint), }, output: S.bigint, // rateLimit: false, // you can set rateLimit to false if needed rateLimit: { calls: 5, per: "second", // also supports "minute" or a duration in milliseconds }, cache: true, }, async ({ input, context }) => { // your effect logic } ); ``` Watch the following video to learn more about createEffect and other updates introduced in [v2.32.0](https://github.com/enviodev/hyperindex/releases/tag/v2.32.0). [Video: Envio v2.32.0](https://www.youtube.com/watch?v=yvUVzV1ifig) ### Per-Chain Effects By default an effect is **cross-chain**: one cache and one rate-limit budget are shared by every chain. That's correct when the input fully identifies the result - an IPFS hash means the same thing whichever chain asked for it. It's wrong when the same input means different things per chain. A token address on Ethereum and the same address on Base are different contracts, so a shared cache would serve one chain's result to the other. Since v3.3, set `crossChain: false` to scope an effect to the chain that called it: (With [`disable_default_cross_chain: true`](https://docs.envio.dev/docs/HyperIndex/multichain-indexing#per-chain-data-mode) the default flips: an effect that doesn't state `crossChain` gets one cache per chain, and `crossChain: true` opts it back into a shared one.) ```typescript import { createEffect, S } from "envio"; export const getTokenName = createEffect( { name: "getTokenName", input: S.string, output: S.string, // Each chain gets its own 5 calls/second budget rateLimit: { calls: 5, per: "second", }, cache: true, crossChain: false, }, async ({ input, context }) => { // context.chain is only available on `crossChain: false` effects const client = clientsByChainId[context.chain.id]; return await client.readContract({ address: input, abi: erc20Abi, functionName: "name", }); }, ); ``` Setting `crossChain: false` changes three things: - **Cache** - entries are keyed per chain, so two chains calling with the same input each get their own result. - **Rate limit** - each chain gets its own budget rather than competing for a shared one. An effect limited to 5 calls/second across 3 chains now allows 15 calls/second in total. - **`context.chain`** - the handler gains `context.chain.id`, the chain the effect was called on. Accessing `context.chain` on a cross-chain effect throws. A per-chain effect always runs for the chain of the handler that started the call, even when one effect calls another. A cross-chain effect has no chain, so it can't call a per-chain effect; that throws `The cross-chain effect "" cannot call the chain-scoped effect ""`. :::warning `crossChain` is part of the effect's cache identity. Changing it on an effect with `cache: true` invalidates the existing cached results, and they will be refetched on the next run. ::: ### Sending Notifications (Webhooks) You can use the Effect API to send push notifications or webhook calls when specific events occur. This is useful for alerting systems, Discord/Slack bots, or triggering downstream workflows. ```typescript import { createEffect, S } from "envio"; export const sendWebhook = createEffect( { name: "sendWebhook", input: { event: S.string, data: S.string, }, output: S.boolean, rateLimit: { calls: 10, per: "second", }, // Don't cache webhook calls - we want them to fire every time cache: false, }, async ({ input, context }) => { try { await fetch("https://your-webhook-url.com/notify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ event: input.event, data: input.data }), }); return true; } catch (error) { context.log.error(`Webhook failed: ${error}`); return false; } } ); ``` Then call it from your handler: ```typescript import { indexer } from "envio"; indexer.onEvent( { contract: "MyContract", event: "LargeTransfer" }, async ({ event, context }) => { await context.effect(sendWebhook, { event: "large_transfer", data: JSON.stringify({ from: event.params.from, to: event.params.to, amount: event.params.value.toString(), }), }); }, ); ``` :::warning Webhook effects will fire on every indexer re-run unless you set `cache: true`. If you cache them, the webhook will only fire once per unique input. Consider which behavior is appropriate for your use case. ::: ### Migrate from Experimental If you're migrating from `experimental_createEffect` to `createEffect`, remove the `experimental_` prefix and add the `rateLimit` option, which is now required. In `experimental_createEffect`, the `rateLimit` option was optional and defaulted to `false`. ```diff typescript - export const getBalance = experimental_createEffect( + export const getBalance = createEffect( { name: "getBalance", input: { address: S.string, blockNumber: S.optional(S.bigint), }, output: S.bigint, + rateLimit: { + calls: 5, + per: "second", + }, cache: true, }, async ({ input, context }) => { // your effect logic } ); ``` --- # Wildcard Indexing & Topic Filtering > Learn how to index events using wildcard indexing feature and topic based filtering. Wildcard indexing is a feature that allows you to index all events matching a specified event signature without requiring the contract address from which the event was emitted. This is useful in cases such as indexing contracts deployed through factories, where the factory contract does not emit any events upon contract creation. It also enables indexing events from all contracts implementing a standard (e.g. all ERC20 transfers). :::note Wildcard Indexing is supported on [HyperSync](https://docs.envio.dev/docs/HyperIndex/hypersync), [HyperFuel](https://docs.envio.dev/docs/HyperIndex/fuel), and [RPC](https://docs.envio.dev/docs/HyperIndex/rpc-sync) data sources. Since v3.3, an RPC-backed indexer can register **multiple** wildcard events - earlier versions allowed only one. ::: ## Index all ERC20 transfers As an example, let's say we want to index all ERC20 `Transfer` events. Start with a [`config.yaml`](https://docs.envio.dev/docs/HyperIndex/configuration-file) file: ```yaml name: transfer-indexer chains: - id: 1 start_block: 0 contracts: - name: ERC20 events: - event: Transfer(address indexed from, address indexed to, uint256 value) ``` Let's also define some entities in [`schema.graphql`](https://docs.envio.dev/docs/HyperIndex/schema) file, so our handlers can store the processed data: ```graphql type Transfer { id: ID! from: String! to: String! } ``` And the last bit is to register an event handler in the `src/handlers`. Note how we pass the `wildcard: true` option to enable wildcard indexing: ```typescript import { indexer } from "envio"; indexer.onEvent( { contract: "ERC20", event: "Transfer", wildcard: true }, async ({ event, context }) => { context.Transfer.set({ id: `${event.chainId}_${event.block.number}_${event.logIndex}`, from: event.params.from, to: event.params.to, }); }, ); ``` After running your indexer with `pnpm dev` you will have all ERC20 `Transfer` events indexed, regardless of the contract address from which the event was emitted. ## Topic Filtering Indexing all ERC20 `Transfer` events can be noisy. Use Topic Filtering to keep only the events you need. When registering an event handler or a contract registration handler, provide the `where` option (formerly `eventFilters` in V2). Filter by each `indexed` event parameter by returning `{ params: [...] }`. `where` takes either a filter object or a callback that returns one. The indexer calls the callback once per chain when the handler is registered, not once per event. A filter has two optional keys: - `params` - one object of indexed-parameter values (all must match), or an array of such objects (any may match). Only `indexed` parameters can be used; any other name throws `Invalid where configuration. The event doesn't have an indexed parameter "" and can't use it for filtering`. - `block.number._gte` - the first block this registration processes, overriding the contract's `start_block`. Only `_gte` is supported. On Fuel the key is `block.height`. A callback can also return `false` to skip the chain, or `true` to keep every event on it. Let's say you only want to index `Mint` events where the `from` address is equal to `ZERO_ADDRESS`: ```typescript import { indexer } from "envio"; const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"; indexer.onEvent( { contract: "ERC20", event: "Transfer", wildcard: true, where: () => ({ params: [{ from: ZERO_ADDRESS }] }), }, async ({ event, context }) => { //... your handler logic }, ); ``` To start one registration later than the rest of its contract, add `block` next to `params`: ```typescript where: { params: { from: ZERO_ADDRESS }, block: { number: { _gte: 18_000_000 } } }, ``` ## Multiple Filters If you want to index both `Mint` and `Burn` events you can provide multiple filters as an array, and an event is indexed if it matches any one of them. Within a single filter, all parameters must match. Also, every parameter can accept an array to filter by multiple possible values. We'll use it to filter by a group of whitelisted addresses in the example below: ```typescript import { indexer } from "envio"; const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"; const WHITELISTED_ADDRESSES = [ "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "0x70997970C51812dc3A010C7d01b50e0d17dc79C8", "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC", ]; indexer.onEvent( { contract: "ERC20", event: "Transfer", wildcard: true, where: () => ({ params: [ { from: ZERO_ADDRESS, to: WHITELISTED_ADDRESSES }, { from: WHITELISTED_ADDRESSES, to: ZERO_ADDRESS }, ], }), }, async ({ event, context }) => { //... your handler logic }, ); ``` :::note On [RPC data sources](https://docs.envio.dev/docs/HyperIndex/rpc-sync), passing an array requires v3.3 or later. HyperSync supports it on all V3 versions. ::: ## Different Filters per Chain For [Multichain Indexers](https://docs.envio.dev/docs/HyperIndex/multichain-indexing) the `where` callback receives `{ chain }` and you can read `chain.id` to filter by different values per chain: ```typescript import { indexer } from "envio"; const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"; const WHITELISTED_ADDRESSES = { 1: ["0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"], 137: [ "0x70997970C51812dc3A010C7d01b50e0d17dc79C8", "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC", ], }; indexer.onEvent( { contract: "ERC20", event: "Transfer", wildcard: true, where: ({ chain }) => ({ params: [ { from: ZERO_ADDRESS, to: WHITELISTED_ADDRESSES[chain.id] }, { from: WHITELISTED_ADDRESSES[chain.id], to: ZERO_ADDRESS }, ], }), }, async ({ event, context }) => { //... your handler logic }, ); ``` ## Index all ERC20 transfers to your Contract Besides `chain.id` you can also read the contract's configured (and dynamically registered) addresses from `chain..addresses`. For example, if you have a `Safe` contract, you can index all ERC20 transfers sent specifically to/from your `Safe` contracts. The `where` callback can read `chain.Safe.addresses`, so we need to define the `Transfer` event on the `Safe` contract: ```yaml name: locker chains: - id: 1 start_block: 0 contracts: - name: Safe events: - event: Transfer(address indexed from, address indexed to, uint256 value) address: - "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" - "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" - "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC" ``` ```typescript import { indexer } from "envio"; indexer.onEvent( { contract: "Safe", event: "Transfer", wildcard: true, where: ({ chain }) => ({ params: [ { from: chain.Safe.addresses }, { to: chain.Safe.addresses }, ], }), }, async ({ event, context }) => {}, ); ``` This example is not much different from using a `WHITELISTED_ADDRESSES` constant, but this becomes much more powerful when the `Safe` contract addresses are [registered dynamically](https://docs.envio.dev/docs/HyperIndex/dynamic-contracts) by a factory contract: ```yaml name: locker chains: - id: 1 start_block: 0 contracts: - name: SafeRegistry events: - event: NewSafe(address safe) address: - "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" - name: Safe events: - event: Transfer(address indexed from, address indexed to, uint256 value) ``` ```typescript import { indexer } from "envio"; indexer.contractRegister( { contract: "SafeRegistry", event: "NewSafe" }, async ({ event, context }) => { context.chain.Safe.add(event.params.safe); }, ); indexer.onEvent( { contract: "Safe", event: "Transfer", wildcard: true, where: ({ chain }) => ({ params: [ { from: chain.Safe.addresses }, { to: chain.Safe.addresses }, ], }), }, async ({ event, context }) => {}, ); ``` ### Assert ERC20 Transfers in Handler After you got all ERC20 Transfers relevant to your contracts, you can additionally filter them in the handler. For example, to get only `USDC` transfers: ```typescript import { indexer } from "envio"; const USDC_ADDRESS = { 84532: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", 11155111: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238", }; indexer.onEvent( { contract: "Safe", event: "Transfer", wildcard: true, where: ({ chain }) => ({ params: [ { from: chain.Safe.addresses }, { to: chain.Safe.addresses }, ], }), }, async ({ event, context }) => { // Filter and store only the USDC transfers that involve a Safe address if (event.srcAddress === USDC_ADDRESS[event.chainId]) { context.Transfer.set({ id: `${event.chainId}_${event.block.number}_${event.logIndex}`, from: event.params.from, to: event.params.to, }); } }, ); ``` ## Contract Register Example The same `where` option can be applied to `indexer.contractRegister`. Here is an example where we only register Uniswap pools that contain DAI token: ```typescript import { indexer } from "envio"; const DAI_ADDRESS = "0x6B175474E89094C44Da98b954EedeAC495271d0F"; indexer.contractRegister( { contract: "UniV3Factory", event: "PoolCreated", where: () => ({ params: [{ token0: DAI_ADDRESS }, { token1: DAI_ADDRESS }], }), }, async ({ event, context }) => { const poolAddress = event.params.pool; context.chain.UniV3Pool.add(poolAddress); }, ); ``` :::note Wildcard registrations are matched by event signature. If the same signature is declared on more than one contract in your `config.yaml`, set `wildcard: true` on just one of them. ::: For an end-to-end example on a live chain, [How to Build a HyperEVM Indexer on Hyperliquid](https://docs.envio.dev/blog/index-hyperevm-data) uses a wildcard `Transfer` handler with a `where` filter on `to` to keep only transfers into Hyperliquid's system addresses, with the full config, schema and handler. --- # Preload Optimization > Learn how preload optimization improves event handlers with batched reads and parallel external calls. > **Important!** Preload optimization makes your handlers run **twice**. In HyperIndex V3, preload optimization is **always on** - there is no flag to enable or disable it. This optimization enables HyperIndex to efficiently preload entities used by handlers through batched database queries, while ensuring events are processed synchronously in their original order. When combined with the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api) for external calls, this feature delivers performance improvements of multiple orders of magnitude compared to other indexing solutions. [Video](https://www.youtube.com/watch?v=QqbH78CEid8) ## Configure Nothing to configure. Previously, V2 required the `preload_handlers: true` flag in [`config.yaml`](https://docs.envio.dev/docs/HyperIndex/configuration-file). In V3 the flag has been removed and the optimization is always active. If your project still has `preload_handlers:` in `config.yaml`, delete it - V3 will reject the field. ## Why Preload? To ensure reliable data, HyperIndex guarantees that all events will be processed in the same order as they occurred on-chain. This guarantee is crucial as it allows you to build indexers that depend on the sequential order of events. However, this leads to a challenge: Handlers must run one at a time, sequentially for each event. Any asynchronous operations will block the entire process. To solve this, we introduced Preload Optimization. It combines in-memory storage, batching, deduplication, and the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api) to parallelize asynchronous operations across batches of events. ## How It Works? With Preload Optimization handlers run twice per event: 1. **First Run (Preload Phase)**: All event handlers run concurrently for the whole batch of events. During the phase all DB write operations are skipped and only DB read operations and external calls are performed. 2. **Second Run (Processing Phase)**: Each event handler runs sequentially in the on-chain order. During the phase it'll get the data from the in-memory store, reflecting changes made by previously processed events. This double execution pattern ensures that entities created by earlier events in the batch are available to later events. ### The Database I/O Problem Consider this common pattern of getting entities in event handlers: ```typescript import { indexer } from "envio"; indexer.onEvent( { contract: "ERC20", event: "Transfer" }, async ({ event, context }) => { const sender = await context.Account.get(event.params.from); const receiver = await context.Account.get(event.params.to); // Process the transfer... }, ); ``` **Without Preload Optimization:** If you're processing 5,000 transfer events, each with unique `from` and `to` addresses, this results in **10,000 total database roundtrips**-one for each sender and receiver lookup (2 per event Γ— 5,000 events). This creates a significant bottleneck that slows down your entire indexing process. **With Preload Optimization:** During the Preload Phase, all 5,000 events are processed in parallel. HyperIndex batches database reads that occur simultaneously into single database queries - one query for sender lookups and one for receiver lookups. The loaded accounts are cached in memory. After the Preload Phase completes, the second processing phase begins. This phase runs handlers sequentially in on-chain order, but instead of making database calls, it retrieves the data from the in-memory cache. For our example of 5,000 transfer events, this optimization reduces database roundtrips from 10,000 calls to just 2! #### Optimizing for Concurrency You can further optimize performance by requesting multiple entities concurrently: ```typescript import { indexer } from "envio"; indexer.onEvent( { contract: "ERC20", event: "Transfer" }, async ({ event, context }) => { // Request sender and receiver concurrently for maximum efficiency const [sender, receiver] = await Promise.all([ context.Account.get(event.params.from), context.Account.get(event.params.to), ]); // Process the transfer... }, ); ``` This approach can reduce the database roundtrips to just 1 for the entire batch of events! ### The External Calls Problem Let's say you want to populate your indexer with offchain data: ```typescript import { indexer } from "envio"; indexer.onEvent( { contract: "ERC20", event: "Transfer" }, async ({ event, context }) => { // Without Preload: Blocking external calls const metadata = await fetch( `https://api.example.com/metadata/${event.params.from}` ); // Process the transfer... }, ); ``` **Without Preload Optimization:** If you're processing 5,000 transfer events, each with an external call, this results in **5,000 sequential external calls**-each waiting for the previous one to complete. This can turn a fast indexing process into a slow, sequential crawl. **With Preload Optimization:** Since handlers run **twice** for each event, making direct external calls can be problematic. The [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api) provides a solution. During the Preload Phase, it batches all external calls and runs them in parallel. Then during the Processing Phase, it runs the handlers sequentially, retrieving the already requested data from the in-memory store. ```typescript import { S, createEffect, indexer } from "envio"; const fetchMetadata = createEffect( { name: "fetchMetadata", input: { from: S.string, }, output: { decimals: S.number, symbol: S.string, }, rateLimit: { calls: 5, per: "second", }, }, async ({ input }) => { const response = await fetch( `https://api.example.com/metadata/${input.from}` ); const data = await response.json(); return { decimals: data.decimals, symbol: data.symbol }; } ); indexer.onEvent( { contract: "ERC20", event: "Transfer" }, async ({ event, context }) => { // With Preload: Performs the call in parallel const metadata = await context.effect(fetchMetadata, { from: event.params.from, }); // Process the transfer... }, ); ``` Assuming an average call takes 200ms, this optimization reduces the total processing time for 5,000 events from ~16 minutes to ~200 milliseconds - making it 5,000 times faster! Learn more about the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api) in our dedicated guide. ### Preload Phase Behavior The Preload Phase is a special phase that runs before the actual event processing. It's designed to preload data that will be used during event processing. Key characteristics of the Preload Phase: - It runs in parallel for all events in the batch - Exceptions won't crash the indexer but will silently abort the Preload Phase for that specific event - All storage updates are ignored - All `context.log` calls are ignored During the second run (Processing Phase), all operations become fully enabled: - Exceptions will crash the indexer if not handled - Entity setting operations will persist to the database - Logging will output to the console This two-phase design allows the Preload Phase to optimistically attempt loading data that may not exist yet, while ensuring data consistency during the Processing Phase when all operations are executed normally. ## Double-Run Footgun As mentioned above, the Preload Phase gives a lot of benefits for the event processing, but also it means that you must be aware of its double-run nature: - Never call `fetch` or other external calls directly in the handler. - Use the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api) instead. - Or use `context.isPreload` to guarantee that the code will run once. Due to the optimistic nature of the Preload Phase, the Effect API may occasionally execute with stale data, leading to redundant external calls. If you need to ensure that external calls are made with the most up-to-date data, you can use the `context.isPreload` check to restrict execution to only the processing phase. > Note: This will disable the Preload Optimization for the external calls. ```typescript import { indexer } from "envio"; indexer.onEvent( { contract: "ERC20", event: "Transfer" }, async ({ event, context }) => { const sender = await context.Account.getOrThrow(event.params.from); if (context.isPreload) { return; } const metadata = await fetch( `https://api.example.com/metadata/${sender.metadataId}` ); }, ); ``` ## Best Practices - Use `Promise.all` to load multiple entities concurrently for better performance - Place database reads and external calls at the beginning of your handler to maximize the benefits of Preload Optimization - Consider using `context.isPreload` to exit early from the Preload Phase after loading required data ## Migrating from Loaders The Preload Optimization for handlers was born from a concept we had before called [Loaders](https://docs.envio.dev/docs/HyperIndex/loaders). The `handlerWithLoader` API has been removed in V3 - move the loader code into the handler and rely on the always-on Preload Phase. ```typescript // V2 β€” removed in V3 ERC20.Transfer.handlerWithLoader({ loader: async ({ event, context }) => { // Load sender and receiver accounts efficiently const sender = await context.Account.get(event.params.from); const receiver = await context.Account.get(event.params.to); // Return the loaded data to the handler return { sender, receiver, }; }, handler: async ({ event, context, loaderReturn }) => { const { sender, receiver } = loaderReturn; // Process the transfer with the pre-loaded data // No database lookups needed here! }, }); // V3 import { indexer } from "envio"; indexer.onEvent( { contract: "ERC20", event: "Transfer" }, async ({ event, context }) => { // Load sender and receiver accounts efficiently const sender = await context.Account.get(event.params.from); const receiver = await context.Account.get(event.params.to); // To imitate the behavior of the loader, // we can use `context.isPreload` to make next code run only once. // Note: This is not required, but might be useful for CPU-intensive operations. if (context.isPreload) { return; } // Process the transfer with the pre-loaded data }, ); ``` --- # Loaders Optimization (Removed in V3) > Historical reference for the HyperIndex V2 loaders API, removed in V3, showing how to move loader code inline into a handler that now preloads automatically. :::warning The `handlerWithLoader` API and the `loaders` flag in `config.yaml` were removed in HyperIndex V3. [Preload Optimization](https://docs.envio.dev/docs/HyperIndex/preload-optimization) is now always on - there is no flag to enable or disable it. This page is kept for historical context and to help V2 projects migrate. ::: ## What Were Loaders? Loaders were a feature in early V2 versions of HyperIndex that significantly improved database access performance for event handlers. They worked by implementing the [Preload Optimization](https://docs.envio.dev/docs/HyperIndex/preload-optimization) - loading required data upfront before processing events. The preloaded data would then be available to event handlers through a `loaderReturn` object, eliminating the need for individual database queries during event processing. In V2, handlers with loaders didn't have a Preload Phase and always ran once. In V3, every handler runs through the Preload Phase automatically, so the dedicated `handlerWithLoader` API and the `loaders:` config flag have both been removed. The V2 shape looked like this (no longer accepted in V3): ```typescript // V2 only β€” removed in V3 ContractName.EventName.handlerWithLoader({ // The loader function runs before event processing starts loader: async ({ event, context }) => { // Load all required data from the database // Return the data needed for event processing return {}; // This will be available in the handler as loaderReturn }, // The handler function processes each event with pre-loaded data handler: async ({ event, context, loaderReturn }) => { // Process the event using the data returned by the loader }, }); ``` ## How It Works in V3 In V3 the optimization is built in. See [Preload Optimization - How It Works?](https://docs.envio.dev/docs/HyperIndex/preload-optimization#how-it-works) for the full mechanics. The two-phase execution is identical to what loaders provided, just without a separate API. For example, this is how a V2 loader is rewritten as a regular V3 handler - the only thing that changed is that the loader code now lives inline at the top of the handler: ```typescript // V2 β€” removed ERC20.Transfer.handlerWithLoader({ loader: async ({ event, context }) => { // Load sender and receiver accounts efficiently const sender = await context.Account.get(event.params.from); const receiver = await context.Account.get(event.params.to); // Return the loaded data to the handler return { sender, receiver, }; }, handler: async ({ event, context, loaderReturn }) => { const { sender, receiver } = loaderReturn; // Process the transfer with the pre-loaded data // No database lookups needed here! }, }); // V3 β€” Preload Optimization is always on import { indexer } from "envio"; indexer.onEvent( { contract: "ERC20", event: "Transfer" }, async ({ event, context }) => { // Load sender and receiver accounts efficiently const sender = await context.Account.get(event.params.from); const receiver = await context.Account.get(event.params.to); // To imitate the behavior of the loader, // we can use `context.isPreload` to make next code run only once. // Note: This is not required, but might be useful for CPU-intensive operations. if (context.isPreload) { return; } // Process the transfer with the pre-loaded data }, ); ``` If your project still has `loaders: true` or `preload_handlers: true` in `config.yaml`, remove both fields - V3 will reject them. --- # Accessing Contract State in Event Handlers > Learn how to efficiently fetch and store token contract data from events using RPC, multicall, and caching. > **Example Repository:** The complete code for this guide can be found [here](https://github.com/enviodev/rpc-token-data-example) ## Introduction This guide demonstrates how to access on-chain contract state from your event handlers. You'll learn how to: 1. Make RPC calls to external contracts within your event handlers 2. Batch multiple calls using multicall for efficiency 3. Learn about [Preload Optimisation](https://docs.envio.dev/docs/HyperIndex/preload-optimization) and how it makes your indexer thousands of times faster 4. Use [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api) with built-in caching and Viem transport level batching 5. Handle common edge cases that arise when accessing token contract data ## The Challenge: Token Data from Pool Creation Events ### Scenario We want to track token information (name, symbol, decimals) for every token involved in a [Uniswap V3 pool creation event](https://docs.uniswap.org/contracts/v3/reference/core/interfaces/IUniswapV3Factory#poolcreated). ### Problem The Uniswap V3 factory `PoolCreated` event only provides token addresses, not their metadata: ```yaml PoolCreated(address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool) ``` To get the token name, symbol, and decimals, we need to: 1. Extract the token addresses from the event 2. Make RPC calls to each token's contract 3. Store this data alongside our pool information ## Prerequisites This guide assumes: - Basic familiarity with Envio indexing - Understanding of the [viem library](https://viem.sh/) for making contract calls - Access to an Ethereum RPC endpoint ([dRPC](https://drpc.org/) recommended) For a gentle introduction to viem with a similar example, check out this [medium article](https://medium.com/@0xape/typescript-and-viem-quickstart-for-blockchain-scripting-3f1846970b6f). ## Implementation Steps ### Step 1: Setup the Indexer Configuration First, create a new indexer: ```bash pnpx envio init ``` When prompted, enter the Ethereum mainnet Uniswap V3 Factory address: `0x1F98431c8aD98523631AE4a59f267346ea31F984` Then modify your configuration to focus only on the PoolCreated event: ```yaml # config.yaml name: uniswap-v3-factory-token-indexer chains: - id: 1 start_block: 0 contracts: - name: UniswapV3Factory address: - "0x1F98431c8aD98523631AE4a59f267346ea31F984" events: - event: PoolCreated(address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool) ``` ### Step 2: Define the Schema Create a schema that captures both pool and token information: ```graphql # schema.graphql type Token { id: ID! # token address name: String! symbol: String! decimals: Int! } type Pool { id: ID! # unique identifier token0: Token! token1: Token! fee: BigInt! tickSpacing: BigInt! pool: String! # pool address } ``` ### Step 3: Implement the Event Handler The event handler needs to: 1. Create a Pool entity from the event data 2. Make RPC calls to fetch token information for both token0 and token1 3. Create Token entities with the retrieved data **Important!** Preload optimization makes your handlers run **twice**. So instead of direct RPC calls, we're doing it through `context.effect` - the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api). Learn how Preload Optimization works in a [dedicated guide](https://docs.envio.dev/docs/HyperIndex/preload-optimization). It might be a new mental model for you, but this is what can make indexing thousands of times faster. ```typescript // src/handlers/UniswapV3Factory.ts import { indexer } from "envio"; import { getTokenMetadata } from "../tokenMetadata"; indexer.onEvent( { contract: "UniswapV3Factory", event: "PoolCreated" }, async ({ event, context }) => { // Create Pool entity context.Pool.set({ id: `${event.chainId}_${event.block.number}_${event.logIndex}`, token0_id: event.params.token0, token1_id: event.params.token1, fee: event.params.fee, tickSpacing: event.params.tickSpacing, pool: event.params.pool, }); // Fetch and store token0 information try { const tokenMetadata0 = await context.effect(getTokenMetadata, { tokenAddress: event.params.token0, chainId: event.chainId, }); context.Token.set({ id: event.params.token0, name: tokenMetadata0.name, symbol: tokenMetadata0.symbol, decimals: tokenMetadata0.decimals, }); } catch (error) { context.log.error("Failed to fetch token0 metadata", { tokenAddress: event.params.token0, chainId: event.chainId, pool: event.params.pool, err: error, }); return; } // Fetch and store token1 information try { const tokenMetadata1 = await context.effect(getTokenMetadata, { tokenAddress: event.params.token1, chainId: event.chainId, }); context.Token.set({ id: event.params.token1, name: tokenMetadata1.name, symbol: tokenMetadata1.symbol, decimals: tokenMetadata1.decimals, }); } catch (error) { context.log.error("Failed to fetch token1 metadata", { tokenAddress: event.params.token1, chainId: event.chainId, pool: event.params.pool, err: error, }); return; } }, ); ``` ### Step 4: Create the Token Metadata Effect This is where the magic happens. We need to: 1. Make RPC calls to token contracts 2. Use multicall to batch multiple calls for efficiency 3. Handle edge cases like non-standard ERC20 implementations 4. Cache results to avoid redundant calls ```typescript // src/tokenMetadata.ts import { createPublicClient, http, hexToString } from "viem"; import { mainnet } from "viem/chains"; import { createEffect, S } from "envio"; import { getERC20BytesContract, getERC20Contract } from "./utils"; const RPC_URL = process.env.ENVIO_RPC_URL; const client = createPublicClient({ chain: mainnet, batch: { multicall: true }, // Enable multicall batching for efficiency transport: http(RPC_URL, { batch: true }), // Thanks to automatic Effect API batching, we can also enable batching for Viem transport level }); // Use Sury library to define the schema const tokenMetadataSchema = S.schema({ name: S.string, symbol: S.string, decimals: S.number, }); // Infer the type from the schema type TokenMetadata = S.Infer; export const getTokenMetadata = createEffect( { name: "getTokenMetadata", input: { tokenAddress: S.string, chainId: S.number, }, output: tokenMetadataSchema, rateLimit: { calls: 5, per: "second", }, // Enable caching to avoid duplicated calls cache: true, }, async ({ input, context }) => { const { tokenAddress, chainId } = input; // Prepare contract instances for different token standard variations const erc20 = getERC20Contract(tokenAddress as `0x${string}`); const erc20Bytes = getERC20BytesContract(tokenAddress as `0x${string}`); let results: [number, string, string]; try { // Try standard ERC20 interface first (most common) results = await client.multicall({ allowFailure: false, contracts: [ { ...erc20, functionName: "decimals", }, { ...erc20, functionName: "name", }, { ...erc20, functionName: "symbol", }, ], }); } catch (error) { try { // Some tokens use bytes32 for name/symbol instead of string const alternateResults = await client.multicall({ allowFailure: false, contracts: [ { ...erc20Bytes, functionName: "decimals", }, { ...erc20Bytes, functionName: "name", }, { ...erc20Bytes, functionName: "symbol", }, ], }); results = [ alternateResults[0], hexToString(alternateResults[1]).replace(/\u0000/g, ""), // Remove null byte padding hexToString(alternateResults[2]).replace(/\u0000/g, ""), // Remove null byte padding ]; } catch (alternateError) { results = [0, "unknown", "unknown"]; // Fallback for completely non-standard tokens } } const [decimals, name, symbol] = results; return { name, symbol, decimals, }; } ); ``` > **Important:** The `hexToString` method from Viem adds byte padding to the string. We remove this padding with `replace(/\u0000/g, '')` to avoid errors when writing to the database. > **Note:** Read more about Effect API and caching in the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api) guide. ## Key Considerations ### Understanding Current vs. Historical State A call without a block number reads the **current state** of a contract, not the state when the event was emitted. For token metadata (name, symbol, decimals), this isn't typically an issue since these values rarely change. If you need historical state, such as a balance at the event's block, pass `blockNumber` to viem's `readContract` or `multicall`, and make the block number part of the effect's input so each block gets its own cache entry: ```typescript const balance = await client.readContract({ address: input.tokenAddress as `0x${string}`, abi: erc20Abi, functionName: "balanceOf", args: [input.account as `0x${string}`], blockNumber: BigInt(input.blockNumber), }); ``` Reading old blocks needs an archive node, so check that your RPC provider serves archive state. ### Handling Rate Limiting RPC providers often limit the number of requests per time period. To avoid hitting rate limits: 1. **Use multicall** (as shown in our example) to batch multiple contract calls into a single RPC request 2. **Learn about Preload Optimization** to make your indexer thousands of times faster 3. **Enable caching** to avoid redundant requests 4. **Use a paid, unthrottled RPC provider** for production indexers 5. **Implement request throttling** to space out requests when needed 6. **Use multiple RPC providers** and rotate between them for high-volume indexing ## Conclusion Accessing contract state from your event handlers opens up powerful possibilities for enriching your indexed data. By following the patterns in this guide, you can efficiently retrieve and store contract state while maintaining good performance. For more advanced techniques, explore: - Implementing retry logic for failed RPC calls - Handling complex contract interactions beyond basic ERC20 tokens --- # Indexing IPFS Data with Envio > Learn how to fetch and index NFT metadata from IPFS using Envio for complete on-chain and off-chain data. > **Example Repository:** The complete code for this guide can be found [here](https://github.com/enviodev/bored-ape-yacht-club-indexer) ## Introduction This guide demonstrates how to fetch and index data stored on IPFS within your Envio indexer. We'll use the [Bored Ape Yacht Club](https://www.boredapeyachtclub.com/) NFT collection as a practical example, showing you how to retrieve and store token metadata from IPFS. IPFS (InterPlanetary File System) is commonly used in blockchain applications to store larger data like images and metadata that would be prohibitively expensive to store on-chain. By integrating IPFS fetching capabilities into your indexers, you can provide a more complete data model that combines on-chain events with off-chain metadata. ## Implementation Overview Our implementation will follow these steps: 1. Create a basic indexer for Bored Ape Yacht Club NFT transfers 2. Extend the indexer to fetch and store metadata from IPFS 3. Handle IPFS connection issues with fallback gateways ## Step 1: Setting Up the Basic NFT Indexer First, let's create a basic indexer that tracks NFT ownership: ### Initialize the Indexer ```bash pnpx envio init ``` When prompted, enter the Bored Ape Yacht Club contract address: `0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D` ### Configure the Indexer Modify the configuration to focus on the Transfer events: ```yaml # config.yaml name: bored-ape-yacht-club-nft-indexer chains: - id: 1 start_block: 0 end_block: 12299114 # Optional: limit blocks for development contracts: - name: BoredApeYachtClub address: - "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D" events: - event: Transfer(address indexed from, address indexed to, uint256 indexed tokenId) ``` ### Define the Schema Create a schema to store NFT ownership data: ```graphql # schema.graphql type Nft { id: ID! # tokenId owner: String! } ``` ### Implement the Event Handler Track ownership changes by handling Transfer events: ```typescript // src/handlers/BoredApeYachtClub.ts import { indexer } from "envio"; const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"; indexer.onEvent( { contract: "BoredApeYachtClub", event: "Transfer" }, async ({ event, context }) => { if (event.params.from === ZERO_ADDRESS) { // mint context.Nft.set({ id: event.params.tokenId.toString(), owner: event.params.to, }); } else { // transfer const nft = await context.Nft.getOrThrow(event.params.tokenId.toString()); context.Nft.set({ ...nft, owner: event.params.to, }); } }, ); ``` Run your indexer with `pnpm dev` and visit http://localhost:8080 to see the ownership data: ![Basic NFT ownership data](https://docs.envio.dev/docs-assets/ipfs-screenshot.jpg) ## Step 2: Fetching IPFS Metadata Now, let's enhance our indexer to fetch metadata from IPFS: ### Update the Schema Extend the schema to include metadata fields: ```graphql # schema.graphql type Nft { id: ID! # tokenId owner: String! image: String! attributes: String! # JSON string of attributes } ``` ### Create IPFS Effect **Important!** Preload optimization makes your handlers run **twice**. So instead of direct RPC calls, we're doing it through the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api). Learn how Preload Optimization works in a [dedicated guide](https://docs.envio.dev/docs/HyperIndex/preload-optimization). It might be a new mental model for you, but this is what can make indexing thousands of times faster. Let's create the `getIpfsMetadata` effect in the `src/utils/ipfs.ts` file: ```typescript import { createEffect, S, type EffectContext } from "envio"; // Define the schema for the IPFS metadata // It uses Sury library to define the schema const nftMetadataSchema = S.schema({ image: S.string, attributes: S.string, }); // Infer the type from the schema type NftMetadata = S.Infer; // Unique identifier for the BoredApeYachtClub IPFS tokenURI const BASE_URI_UID = "QmeSjSinHpPnmXmspMjwiXyN6zS4E9zccariGR3jxcaWtq"; const endpoints = [ // Try multiple endpoints to ensure data availability // Optional paid gateway (set in .env) ...(process.env.PINATA_IPFS_GATEWAY ? [process.env.PINATA_IPFS_GATEWAY] : []), "https://gateway.pinata.cloud/ipfs", "https://ipfs.io/ipfs", ]; async function fetchFromEndpoint( context: EffectContext, endpoint: string, tokenId: string ): Promise { try { const response = await fetch(`${endpoint}/${BASE_URI_UID}/${tokenId}`); if (response.ok) { const metadata: any = await response.json(); return { image: metadata.image, attributes: JSON.stringify(metadata.attributes), }; } else { context.log.warn(`IPFS didn't return 200`, { tokenId, endpoint }); return null; } } catch (e) { context.log.warn(`IPFS fetch failed`, { tokenId, endpoint, err: e }); return null; } } export const getIpfsMetadata = createEffect( { name: "getIpfsMetadata", input: S.string, output: nftMetadataSchema, rateLimit: { calls: 5, per: "second", }, }, async ({ input: tokenId, context }) => { for (const endpoint of endpoints) { const metadata = await fetchFromEndpoint(context, endpoint, tokenId); if (metadata) { return metadata; } } // ⚠️ Dangerous: Sometimes it's better to crash, to prevent corrupted data // But we're going to use a fallback value, to keep the indexer process running. // Both approaches have their pros and cons. context.log.warn( "Unable to fetch IPFS. Continuing with fallback metadata.", { tokenId, } ); return { attributes: `["unknown"]`, image: "unknown" }; } ); ``` ### Update the Event Handler Let's modify the event handler to fetch and store metadata using the `getIpfsMetadata` effect: ```typescript // src/handlers/BoredApeYachtClub.ts import { indexer } from "envio"; import { getIpfsMetadata } from "../utils/ipfs"; const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"; indexer.onEvent( { contract: "BoredApeYachtClub", event: "Transfer" }, async ({ event, context }) => { if (event.params.from === ZERO_ADDRESS) { // mint const metadata = await context.effect( getIpfsMetadata, event.params.tokenId.toString() ); context.Nft.set({ id: event.params.tokenId.toString(), owner: event.params.to, image: metadata.image, attributes: metadata.attributes, }); } else { // transfer const nft = await context.Nft.getOrThrow(event.params.tokenId.toString()); context.Nft.set({ ...nft, owner: event.params.to, }); } }, ); ``` When you run the indexer now, it will populate both ownership data and token metadata: ![NFT ownership and metadata](https://docs.envio.dev/docs-assets/ipfs-screenshot-2.jpg) ## Best Practices for IPFS Integration When working with IPFS in your indexers, consider these best practices: ### 1. Use Multiple Gateways IPFS gateways can be unreliable, so always implement multiple fallback options: ```typescript const endpoints = [ ...(process.env.PINATA_IPFS_GATEWAY ? [process.env.PINATA_IPFS_GATEWAY] : []), "https://gateway.pinata.cloud/ipfs", "https://ipfs.io/ipfs", ]; ``` ### 2. Handle Failures Gracefully Always include error handling and provide fallback values: ```typescript try { // IPFS fetch logic } catch (error) { context.log.error(`Failed to fetch from IPFS`, error as Error); return { attributes: "[]", image: "default-image-url" }; } ``` ### 3. Implement Local Caching (For Local Development) Follow the [Effect API Persistence](https://docs.envio.dev/docs/HyperIndex/effect-api#persistence) guide to implement caching for local development. This should allow you to avoid repeatedly fetching the same data. ```typescript export const getIpfsMetadata = createEffect( { name: "getIpfsMetadata", input: S.string, output: nftMetadataSchema, rateLimit: { calls: 5, per: "second", }, cache: true, // Enable caching }, async ({ input: tokenId, context }) => {...} ); ``` > **Important:** While the example repository includes SQLite-based caching, this approach is outdated and leads to many indexing issues. > **Note:** We're working on a better integration with Envio Cloud. Currently, due to the cache size, it's not recommended to commit the `.envio/cache` directory to the GitHub repository. ### 4. Learn about Preload Optimization Learn how Preload Optimization works and the [Double-Run Footgun](https://docs.envio.dev/docs/HyperIndex/preload-optimization#double-run-footgun) in a [dedicated guide](https://docs.envio.dev/docs/HyperIndex/preload-optimization). It might be a new mental model for you, but this is what can make indexing thousands of times faster. ## Understanding IPFS ### What is IPFS? IPFS (InterPlanetary File System) is a distributed system for storing and accessing files, websites, applications, and data. It works by: 1. Splitting files into chunks 2. Creating content-addressed identifiers (CIDs) based on the content itself 3. Distributing these chunks across a network of nodes 4. Retrieving data based on its CID rather than its location ### Common Use Cases with Smart Contracts IPFS is frequently used alongside smart contracts for: - **NFTs**: Storing images, videos, and metadata while the contract manages ownership - **Decentralized Identity Systems**: Storing credential documents and personal information - **DAOs**: Maintaining governance documents, proposals, and organizational assets - **dApps**: Hosting front-end interfaces and application assets ### IPFS Challenges IPFS integration comes with several challenges: 1. **Slow Retrieval Times**: IPFS data can be slow to retrieve, especially for less widely replicated content 2. **Gateway Reliability**: Public gateways can be inconsistent in their availability 3. **Data Persistence**: Content may become unavailable if nodes stop hosting it To mitigate these issues: - Use pinning services like Pinata or Infura to ensure data persistence - Implement multiple gateway fallbacks - Consider paid gateways for production applications --- # Using HyperSync as Your Indexing Data Source > Learn how HyperSync is used in HyperIndex to fetch raw blockchain data. > **"Beam me up, Scotty!"** πŸ–– - Just like the Star Trek transporter, HyperSync delivers your blockchain data at warp speed. ## What is HyperSync? HyperSync is a purpose built data-node that helps powers the exceptional performance of HyperIndex. It's a specialized data source optimized for indexing that provides: - **2000x faster sync speeds** compared to traditional RPC methods - **Cost-effective data retrieval** with optimized resource usage - **Flexibility** with the ability to fetch multiple data points in a single round trip with more complex filtering ## How HyperSync Powers Your Indexers ### The Performance Advantage Traditional blockchain indexing relies on RPC (Remote Procedure Call) endpoints to query blockchain data. While functional, RPCs become highly inefficient when: - Indexing millions of events - Processing historical blockchain data - Extracting data across multiple chains - Working with thousands of contracts HyperSync addresses these limitations by providing a streamlined data access layer that dramatically reduces sync times from days to minutes. ### Default Enablement **HyperSync is used by default** as the data source for every chain it supports. This means: - No additional configuration is required to benefit from its speed - No need to worry about RPC rate limiting - No management of multiple RPC providers - No costs for external RPC services :::info Starting in V3, HyperSync requires an API token. Create a free token at [envio.dev/app/api-tokens](https://envio.dev/app/api-tokens) and expose it to your indexer as `ENVIO_API_TOKEN`: ```bash export ENVIO_API_TOKEN=your_token_here ``` Without a token, the indexer stops with `An Envio API token is required for using HyperSync as a data-source.` A rejected token logs `Your ENVIO_API_TOKEN was rejected by HyperSync (401 Unauthorized)` once, and the indexer keeps retrying, so a token that is re-activated starts working on its own. To use a different token, update `ENVIO_API_TOKEN` and restart the indexer. ::: ## Using HyperSync in Your Projects ### Configuration To use HyperSync (the default), simply don't set an RPC for historical sync in your config. HyperIndex will automatically use HyperSync for supported chains: ```yaml name: Greeter description: Greeter indexer chains: - id: 137 # Polygon start_block: 0 # With HyperSync, you can use 0 regardless of contract deployment time contracts: - name: PolygonGreeter abi_file_path: abis/greeter-abi.json address: "0x9D02A17dE4E68545d3a58D3a20BbBE0399E05c9c" events: - event: NewGreeting - event: ClearGreeting ``` ### Smart Block Detection When using HyperSync, you can specify `start_block: 0` in your configuration. HyperSync will automatically: 1. Detect the first block where your contract was deployed 2. Begin indexing from that block 3. Skip unnecessary processing of earlier blocks This feature eliminates the need to manually determine the deployment block of your contract, saving setup time and reducing configuration errors. ### Custom Endpoint By default HyperIndex uses `https://.hypersync.xyz` for every chain HyperSync supports. To use a different endpoint, set `hypersync_config.url` on the chain: ```yaml chains: - id: 1 start_block: 0 hypersync_config: url: https://1.hypersync.xyz ``` A chain can't combine `hypersync_config` with an RPC marked `for: sync`. For a chain with no default endpoint and no `for: sync` RPC, codegen fails with `Failed to automatically find HyperSync endpoint for the chain `. ## Hosting and Support HyperSync is maintained and hosted by Envio for all supported chains. We handle the infrastructure, allowing you to focus on building your indexer logic. ### Supported Chains HyperSync supports numerous EVM chains including Ethereum, Unichain, Arbitrum, Optimism, and more. For a complete and up-to-date list of supported chains, see the [HyperSync Supported Networks](https://docs.envio.dev/docs/HyperSync/hypersync-supported-networks) documentation. ### Alternative Data Sources HyperSync data source is vendorlock-free. While HyperSync is **recommended for optimal performance**, you can always switch to RPCs without the need to change your indexer code. For information on configuring RPC-based indexing, visit the [RPC Data Source](https://docs.envio.dev/docs/HyperIndex/rpc-sync.md) documentation. ### Improving Resilience with RPC fallback For production deployments, it’s recommended to use HyperSync as the primary data source and have RPCs as fallback to improve reliability.You can read more about it in the [RPC Fallback](https://docs.envio.dev/docs/HyperIndex/rpc-sync#improving-resilience-with-rpc-fallback) section. ## Performance Comparison | Metric | Traditional RPC | HyperSync | | --- | --- | --- | | Indexing 1M Events | Hours to days | Minutes | | Resource Usage | High | Optimized | | Network Calls | Many individual calls | Batched for efficiency | | Rate Limiting | Common issue | Not applicable | | Cost | Pay per API call | Included with Envio Cloud | ## Summary HyperSync provides a significant competitive advantage for Envio indexers by dramatically reducing sync times, lowering costs, and simplifying configuration. By using HyperSync as your default data source, you'll experience: - Faster indexing performance - Support for previously impossible indexing cases - Enhanced reliability - Reduced operational complexity To learn more about HyperSync's underlying technology, visit the [HyperSync documentation](https://docs.envio.dev/docs/HyperSync/overview). --- # Using RPC as Your Indexing Data Source > Learn how to index any EVM blockchain using RPC and optimize performance with HyperIndex HyperIndex supports indexing any EVM blockchain using RPC (Remote Procedure Call) as the data source. This page explains when and how to use RPC for your indexing needs. ## When to Use RPC While [HyperSync](https://docs.envio.dev/docs/HyperIndex/hypersync) is the recommended and default data source for optimal performance, there are scenarios where you might need to use RPC instead: 1. **Unsupported Chains**: When indexing a blockchain that isn't yet supported by HyperSync 2. **Custom Requirements**: When you need specific RPC functionality not available in HyperSync 3. **Private Chains**: When working with private or development EVM chains > **Note**: For chains that HyperSync supports, we strongly recommend using HyperSync rather than RPC. HyperSync provides significantly faster indexing performance (up to 100x) and doesn't require managing RPC endpoints or worrying about rate limits. ## Configuring RPC in Your Indexer ### Basic Configuration In V3 the V2 `rpc_config` field has been replaced with `rpc`, which accepts a single URL, a single `Rpc` object, or a list of `Rpc` objects. Each entry can declare what it's `for`: `sync` (historical), `realtime` (head), or `fallback`. When `for` is omitted, it defaults to `fallback` on chains HyperSync supports and to `sync` on other chains. To use RPC as the primary historical data source, add an `rpc` entry with `for: sync` to your chain configuration in `config.yaml`: ```yaml chains: - id: 1 # Ethereum Mainnet rpc: - url: https://eth-mainnet.your-rpc-provider.com # Your RPC endpoint for: sync start_block: 15000000 contracts: - name: MyContract address: "0x1111111111111111111111111111111111111111" # Additional contract configuration... ``` The presence of an RPC marked `for: sync` tells HyperIndex to use RPC instead of HyperSync for historical sync on this chain. You can also add a `for: realtime` RPC to follow the head. Its `ws` field takes a WebSocket endpoint that streams new block heights; `url` must stay an `http://` or `https://` URL: ```yaml chains: - id: 1 start_block: 15000000 rpc: - url: https://eth-mainnet.your-rpc-provider.com for: sync - url: https://eth-mainnet.your-rpc-provider.com ws: wss://eth-mainnet.your-rpc-provider.com for: realtime ``` ### Advanced RPC Configuration For more control over how your indexer interacts with the RPC endpoint, you can configure additional parameters: ```yaml chains: - id: 1 rpc: - url: https://eth-mainnet.your-rpc-provider.com for: sync initial_block_interval: 10000 # Initial number of blocks to fetch in each request backoff_multiplicative: 0.8 # Factor to scale back block request size after errors acceleration_additive: 2000 # How many more blocks to request when successful interval_ceiling: 10000 # Maximum blocks to request in a single call backoff_millis: 5000 # Milliseconds to wait after an error query_timeout_millis: 20000 # Milliseconds before timing out a request start_block: 15000000 # Additional chain configuration... ``` ### Configuration Parameters Explained | Parameter | Description | Default | Recommended Value | | --- | --- | --- | --- | | `url` | Your RPC endpoint URL | - | Depends on provider | | `initial_block_interval` | Starting block batch size | 10,000 | 1,000 - 10,000 | | `backoff_multiplicative` | How much to reduce batch size after errors | 0.8 | 0.5 - 0.9 | | `acceleration_additive` | How much to increase batch size on success | 500 | 500 - 2,000 | | `interval_ceiling` | Maximum blocks per request | 10,000 | 5,000 - 10,000 | | `backoff_millis` | Wait time after errors (ms) | 2,000 | 1,000 - 10,000 | | `query_timeout_millis` | Request timeout (ms) | 20,000 | 10,000 - 30,000 | | `polling_interval` | How often to check for new blocks at the head (ms) | 1,000 | Block time or less | The optimal values depend on your RPC provider's performance and limits, as well as the complexity of your contracts and the data being indexed. The environment variables `ENVIO_RPC_INITIAL_BLOCK_INTERVAL`, `ENVIO_RPC_BACKOFF_MULTIPLICATIVE`, `ENVIO_RPC_ACCELERATION_ADDITIVE` and `ENVIO_RPC_INTERVAL_CEILING` override the matching option for every RPC in the indexer, taking precedence over `config.yaml`. ### Custom HTTP Headers Some providers gate their endpoints behind an `Authorization` header or a custom API-key header rather than putting the key in the URL. Since v3.3, `headers` sets arbitrary HTTP headers on every request to an RPC endpoint: ```yaml chains: - id: 1 rpc: - url: https://eth-mainnet.your-rpc-provider.com for: sync headers: Authorization: "Bearer ${ENVIO_RPC_API_KEY}" X-Custom-Header: "my-value" start_block: 15000000 ``` Header values support `${ENV_VAR}` interpolation, so keep credentials in [environment variables](https://docs.envio.dev/docs/HyperIndex/environment-variables) rather than committing them to `config.yaml`. ### Event Filtering on RPC RPC sources support the same [`where` filtering](https://docs.envio.dev/docs/HyperIndex/wildcard-indexing#topic-filtering) as HyperSync, and since v3.3 that includes: - **`OR` conditions** - passing an array to `params` matches an event if any entry in the array matches. See [Multiple Filters](https://docs.envio.dev/docs/HyperIndex/wildcard-indexing#multiple-filters). - **Multiple wildcard events** - an RPC-backed indexer can register more than one [wildcard](https://docs.envio.dev/docs/HyperIndex/wildcard-indexing) event. Earlier versions allowed only one. ## RPC Best Practices ### Selecting an RPC Provider When choosing an RPC provider, consider: - **Rate limits**: Most providers have limits on requests per second/minute - **Node performance**: Some providers offer faster nodes for premium tiers - **Archive nodes**: Required if you need historical state (e.g., balances at past blocks) - **Geographic location**: Choose nodes closest to your indexer deployment ### Performance Optimization To get the best performance when using RPC: 1. **Start from a recent block** if possible, rather than indexing from genesis 2. **Tune batch parameters** based on your provider's capabilities 3. **Use a paid service** for better reliability and higher rate limits 4. **Consider multiple fallback RPCs** for redundancy ### Improving resilience with RPC fallback HyperIndex allows you to configure additional RPC providers as fallback data sources. This redundancy is **recommended** for production deployments to ensure continuous operation of your indexer. If HyperSync experiences any interruption, your indexer will automatically switch to the fallback RPC provider. Adding an RPC fallback provides these benefits: - **High availability**: Your indexer continues to function even during temporary HyperSync outages - **Automatic failover**: The system detects issues and switches to fallback RPC without manual intervention - **Operational control**: You can specify which RPC providers to use as fallbacks based on your requirements Configure a fallback RPC by adding the `rpc` field to your chain configuration: ```diff name: Greeter description: Greeter indexer chains: - id: 137 # Polygon + rpc: https://polygon.your-rpc-provider.com?API_KEY=${ENVIO_POLYGON_API_KEY} start_block: 0 # With HyperSync, you can use 0 regardless of contract deployment time contracts: - name: PolygonGreeter abi_file_path: abis/greeter-abi.json address: 0x9D02A17dE4E68545d3a58D3a20BbBE0399E05c9c events: - event: NewGreeting - event: ClearGreeting ``` On a chain HyperSync supports, an RPC without `for` defaults to `fallback`. To add several, use the list form: ```yaml chains: - id: 137 # Polygon start_block: 0 rpc: - url: https://polygon.your-rpc-provider.com?API_KEY=${ENVIO_POLYGON_API_KEY} for: fallback - url: https://polygon.your-free-rpc-provider.com for: fallback initial_block_interval: 1000 ``` :::info The fallback RPC takes over when the primary source fails, or when it reports no new block for 20 seconds at the chain head (60 seconds during historical sync). HyperIndex tries the primary source again 60 seconds after switching away from it. ::: ## Choosing an RPC Provider If you need an RPC endpoint for a chain that HyperSync does not cover, [Dwellir](https://www.dwellir.com/networks?utm_source=envio.dev) is an Envio RPC partner that offers endpoints across a broad range of EVM chains. You can check whether your chain is supported on the [Dwellir networks page](https://www.dwellir.com/networks?utm_source=envio.dev), then use the URL they provide in your `config.yaml`. Base is supported by HyperSync, so the block below only illustrates the generic RPC syntax. Use it for chains that HyperSync does not cover. ```yaml chains: - id: 8453 # Base start_block: 0 rpc: - url: https://your-dwellir-endpoint # Endpoint from your Dwellir dashboard for: sync ``` Any provider that implements the standard EVM JSON-RPC API works with HyperIndex, so this is one option among several. For automatic failover across multiple providers, see eRPC below. ## Enhanced RPC with eRPC For more robust RPC usage, you can implement [eRPC](https://github.com/erpc/erpc) - a fault-tolerant EVM RPC proxy with advanced features like caching and failover. ### What eRPC Provides - **Permanent caching**: Stores historical responses to reduce redundant requests - **Auto failover**: Automatically switches between multiple RPC providers - **Re-org awareness**: Properly handles blockchain reorganizations - **Auto-batching**: Optimizes requests to minimize network overhead - **Load balancing**: Distributes requests across multiple providers ### Setting Up eRPC 1. **Create your eRPC configuration file** (`erpc.yaml`): ```yaml logLevel: debug projects: - id: main upstreams: # Add HyperRPC as primary source - endpoint: evm+envio://rpc.hypersync.xyz # Add fallback RPC endpoints - endpoint: https://eth-mainnet-provider1.com - endpoint: https://eth-mainnet-provider2.com - endpoint: https://eth-mainnet-provider3.com ``` 2. **Run eRPC using Docker**: ```bash docker run -v $(pwd)/erpc.yaml:/root/erpc.yaml -p 4000:4000 -p 4001:4001 ghcr.io/erpc/erpc:latest ``` Or add it to your existing Docker Compose setup: ```yaml services: # Your existing services... erpc: image: ghcr.io/erpc/erpc:latest platform: linux/amd64 volumes: - "${PWD}/erpc.yaml:/root/erpc.yaml" ports: - 4000:4000 - 4001:4001 restart: always ``` 3. **Configure HyperIndex to use eRPC** in your `config.yaml`: ```yaml chains: - id: 1 rpc: - url: http://erpc:4000/main/evm/1 # eRPC endpoint for Ethereum Mainnet for: sync start_block: 15000000 # Additional chain configuration... ``` For more detailed configuration options, refer to the [eRPC documentation](https://docs.erpc.cloud/config/example). ## Comparing HyperSync and RPC | Feature | HyperSync | RPC | | --- | --- | --- | | Speed | 10-100x faster | Baseline | | Configuration | Minimal | Requires tuning | | Rate Limits | None | Depends on provider | | Cost | Included with Envio Cloud | Pay per request/subscription | | Chain Support | [Supported chains](https://docs.envio.dev/docs/HyperSync/hypersync-supported-networks) | Any EVM chain | | Maintenance | Managed by Envio | Self-managed | ## Summary While RPC provides the flexibility to index any EVM blockchain, it comes with performance limitations and configuration complexity. For supported chains, we recommend using HyperSync as your data source for optimal performance. If you must use RPC: - Choose a reliable provider - Configure your indexer for optimal performance - Consider implementing eRPC for enhanced reliability and performance - Start from recent blocks when possible to reduce indexing time For any questions about using RPC with HyperIndex, please contact the Envio team. --- # Understanding and Handling Chain Reorganizations > HyperIndex detects chain reorgs and rolls back indexed data automatically. It's on by default, with no rollback logic needed in your handlers. :::info Short answer HyperIndex detects chain reorganizations and rolls back your indexed data automatically. It's on by default (`rollback_on_reorg: true`) and covers reorgs up to `max_reorg_depth` blocks below the chain head. That's 200 on most chains and 0 on Arbitrum and OP Mainnet (see the [defaults](#default-confirmation-thresholds)). You don't need any rollback logic in your handlers. Detection is guaranteed when you read from [HyperSync](#guaranteed-detection) and has some [edge cases on RPC](#rpc-limitations). Side effects outside the database, such as calls to external APIs, are [not rolled back](#scope-of-rollbacks). ::: ## What Are Chain Reorganizations? Chain reorganizations (reorgs) occur when the blockchain temporarily forks and then resolves to a single chain, causing some previously confirmed blocks to be replaced by different blocks. This is a normal part of blockchain consensus mechanisms, especially in proof-of-work chains. When a reorg happens: - Transactions that were previously considered confirmed may be dropped - New transactions may be added to the blockchain - The order of transactions might change For indexers, this presents a challenge: data that was previously indexed may no longer be valid, requiring a rollback and reprocessing of the affected blocks. ## Automatic Reorg Handling in HyperIndex HyperIndex includes built-in support for handling chain reorganizations, ensuring your indexed data remains consistent with the blockchain's canonical state. This feature is **enabled by default** to protect your data integrity. ## Configuration Options ### Enabling or Disabling Reorg Support You can control reorg handling through the `rollback_on_reorg` flag in your `config.yaml` file: Enable reorg handling (the default): ```yaml rollback_on_reorg: true chains: # chain configurations... ``` Or disable it (not recommended for production): ```yaml rollback_on_reorg: false chains: # chain configurations... ``` ### Configuring Confirmation Thresholds You can customize the number of blocks required before considering a block "confirmed" and no longer subject to reorgs: ```yaml rollback_on_reorg: true chains: - id: 137 # Polygon start_block: 0 max_reorg_depth: 250 - id: 1 # Ethereum start_block: 0 # Using default threshold ``` The `max_reorg_depth` field (renamed from V2's `confirmed_block_threshold`) defines how many blocks below the chain head are considered safe from reorganizations. Any reorg deeper than this threshold won't trigger a rollback in your indexer. ## Default Confirmation Thresholds Most chains default to a threshold of **200 blocks**. Arbitrum and OP Mainnet networks default to **0**, which means HyperIndex doesn't track reorgs on those chains, so a reorg there is not detected or rolled back. Set `max_reorg_depth` on those chains if you want rollbacks there. | Chains | Default Threshold | | --- | --- | | Arbitrum One, Arbitrum Nova, OP Mainnet | 0 blocks (no rollback) | | Arbitrum and OP testnets, Citrea Testnet, Citrea Devnet | 0 blocks (no rollback) | | All other chains | 200 blocks | ## Technical Details and Limitations ### Guaranteed Detection Reorg detection is guaranteed when using [HyperSync](https://docs.envio.dev/docs/HyperIndex/hypersync.md) as your data source. HyperSync returns the logs and blocks for a queried range atomically, so block hashes and parent hashes always match the data returned, and any reorganization is detected and handled. ### RPC Limitations When using a [custom RPC endpoint](https://docs.envio.dev/docs/HyperIndex/rpc-sync.md) as your data source, there are some edge cases where reorgs might go undetected. RPC queries aren't atomic, so if the logs come from a reorged block but the block header comes from the canonical block, the indexer may not see that the logs came from a reorged block. ### Scope of Rollbacks During a reorg-triggered rollback: βœ… **What is rolled back:** - All entities defined in your schema - All data that your handlers read or write to the database ❌ **What is not rolled back:** - Side effects in your handler code (API calls, external services) - Custom caching mechanisms outside of HyperIndex - Logs or external files written by your handlers ## Best Practices 1. **Keep reorg support enabled** for production indexers 2. **Use HyperSync** when possible for guaranteed reorg detection 3. **Avoid external side effects** in your handlers that cannot be rolled back 4. **Consider higher thresholds** for high-value applications or chains with historically deep reorgs ## Example Configuration Here's a complete example showing reorg handling configuration for multiple chains: ```yaml rollback_on_reorg: true chains: - id: 1 # Ethereum Mainnet start_block: 0 # Using default threshold (200) # other chain config... - id: 137 # Polygon start_block: 0 max_reorg_depth: 250 # Higher threshold for Polygon # other chain config... - id: 42161 # Arbitrum One start_block: 0 max_reorg_depth: 200 # Arbitrum defaults to 0, so set it to enable rollbacks # other chain config... ``` By properly configuring reorg support, you ensure that your indexed data remains consistent with the blockchain, even when the chain reorganizes. ## Using HyperSync Directly? Handle Reorgs with the Rollback Guard If you use [HyperSync](https://docs.envio.dev/docs/HyperSync/hypersync-query#rollback-guard) directly, without HyperIndex, you have to handle reorg detection and rollback yourself using the optional **rollback guard** that HyperSync returns with query responses near the chain head. HyperSync validates block parent hashes internally and re-syncs when it detects a fork, so it always serves canonical chain data. Data you have already fetched can still go stale after a reorg, though. To detect that, compare the `first_parent_hash` of the current response against the `hash` you stored from the previous response. If they differ, a reorg has occurred and you need to re-fetch the affected range. For full details, including a pseudocode example, see the [HyperSync Rollback Guard documentation](https://docs.envio.dev/docs/HyperSync/hypersync-query#rollback-guard). :::tip HyperIndex automates all of this: it fetches recent block hashes to pinpoint exactly where a reorg occurred and automatically rolls back database state. Unless you need the full flexibility of raw HyperSync, HyperIndex saves significant implementation effort. ::: --- --- # Understanding Generated Indexing Files > Learn how generated files handle type-safe data access, event processing, and runtime indexing. ## Overview In V3, the local `generated` package is gone. Code generation now writes a single ambient declaration file at `.envio/types.d.ts` (git-ignored by `.envio/.gitignore`) and wires it into your project through a small `envio-env.d.ts` file at the project root. Everything you used to import from `generated` is now exported from the `envio` package. These generated declarations form the type-level backbone of your blockchain indexer, translating your configuration, schema, and event handlers into the strongly-typed runtime values exposed by `envio`. > **Important:** The contents of `.envio/` should never be manually edited. Any changes will be overwritten the next time code generation runs. ## What V3 Emits | File / location | Purpose | | --- | --- | | `.envio/types.d.ts` | Ambient TypeScript declarations describing your contracts, events, entities, enums, and chains. | | `envio-env.d.ts` (root) | Tiny shim that references `.envio/types.d.ts` so the compiler picks it up. | | `.envio/.gitignore` | Written once and never overwritten. Ignores `types.d.ts` only. | | `src/Indexer.res` | ReScript projects only. Exposes the indexer to ReScript handlers. | | `.envio/cache/` (optional) | Local cache of [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api) results, populated via the dev console. | The `generated/` directory used by V2 (with ReScript sources, JS shims, and a per-project `package.json`) is no longer produced. ## Purpose of Generated Files Generated files serve several critical functions: 1. **Type-Safe Data Access** - They provide strongly-typed interfaces to interact with your defined entities through `envio`. 2. **Event Processing** - They describe each contract's events so `indexer.onEvent({ contract, event }, ...)` is fully type-checked. 3. **Database Interactions** - They generate the entity types and helper signatures used by `context.` and `indexer.`. 4. **Runtime Orchestration** - They feed into the `indexer` value (chains, contracts, entities) that orchestrates indexing. ## Real-World Example: Uniswap V4 Indexer Let's examine how specific elements from a real Uniswap V4 indexer translate into generated declarations. ### From Schema to Generated Types For a schema entity like this: ```graphql type Pool { id: ID! chainId: BigInt! currency0: String! currency1: String! fee: BigInt! tickSpacing: BigInt! hooks: String! numberOfSwaps: BigInt! @index createdAtTimestamp: BigInt! createdAtBlockNumber: BigInt! } ``` The codegen process emits a TypeScript type you can import from `envio`: ```typescript import type { Entity } from "envio"; // Equivalent to importing the `Pool` named type directly. type Pool = Entity<"Pool">; // Shape of the generated entity: // { // id: string; // chainId: bigint; // currency0: string; // currency1: string; // fee: bigint; // tickSpacing: bigint; // hooks: string; // numberOfSwaps: bigint; // createdAtTimestamp: bigint; // createdAtBlockNumber: bigint; // } ``` You read and write `Pool` entities through the type-safe `context` and `indexer` APIs: ```typescript // Inside a handler const pool = await context.Pool.get(id); context.Pool.set({ id, chainId, currency0, currency1, fee, tickSpacing, hooks, numberOfSwaps, createdAtTimestamp, createdAtBlockNumber }); // Inside a test, on a test indexer from createTestIndexer() indexer.Pool.set({ /* ... */ }); const stored = await indexer.Pool.getOrThrow(id); ``` ### From Config to Generated Event Handlers Given a contract event in `config.yaml`: ```yaml contracts: - name: PoolManager events: - event: Swap(bytes32 indexed id, address indexed sender, int128 amount0, int128 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint24 fee) ``` Codegen widens the `indexer.onEvent` overloads so that the following call is fully typed end-to-end (event params, return type, `context.chain`, etc.): ```typescript import { indexer } from "envio"; import type { EvmEvent } from "envio"; indexer.onEvent( { contract: "PoolManager", event: "Swap" }, async ({ event, context }) => { const { id, sender, amount0, amount1, sqrtPriceX96, liquidity, tick, fee } = event.params; // ... }, ); // The full event payload type is also available as a generic: type PoolManagerSwapEvent = EvmEvent<"PoolManager", "Swap">; type PoolManagerSwapBlock = EvmEvent<"PoolManager", "Swap">["block"]; ``` ### From Multi-Chain Config to Generated Chain Handlers Your config has multiple chains: ```yaml chains: - id: 1 # Ethereum Mainnet # ... - id: 10 # Optimism # ... - id: 42161 # Arbitrum # ... ``` Codegen turns the chain set into a literal `EvmChainId` union (`FuelChainId` and `SvmChainId` on other ecosystems) and exposes per-chain helpers under `indexer.chains`: ```typescript import { indexer } from "envio"; import type { EvmChainId } from "envio"; // EvmChainId is `1 | 10 | 42161` const mainnet = indexer.chains[1]; const optimism = indexer.chains[10]; const arbitrum = indexer.chains[42161]; // `chain.id` is also typed inside handler/where callbacks: indexer.onBlock( { name: "Heartbeat", where: ({ chain }) => { // chain.id is narrowed to the configured EvmChainId union return chain.id === 1; }, }, async ({ block, context }) => { // context.chain.id is typed as well }, ); ``` `getGeneratedByChainId(...)` from V2 has been replaced by `indexer.chains[chainId]`. ## When to Run Code Generation You should run code generation using the Envio CLI whenever you: ```bash pnpm envio codegen ``` Codegen should be run after: 1. Modifying your `config.yaml` file 2. Changing your GraphQL schema 3. Switching to a new contract or ABI 4. After pulling changes from version control Handler files are not an input to codegen, so editing them doesn't need it. > Note: changes to handler files in V3 no longer trigger automatic codegen on `pnpm dev`. ## Troubleshooting Generation Errors When code generation fails, the error points to an issue in `config.yaml`, `schema.graphql` or an ABI. It reads `Failed parsing config`, followed by the specific cause. ### Configuration Errors A YAML syntax error, a missing required field, an unknown field or a malformed address in `config.yaml` stops codegen. Add the `# yaml-language-server: $schema=./node_modules/envio/evm.schema.json` comment at the top of the file so your editor flags these as you type. See the [Configuration File](https://docs.envio.dev/docs/HyperIndex/configuration-file) guide for every field. ### Schema Errors Schema errors name the entity and field. Common ones: - `No 'id' field found on entity Pool` - every entity needs an `id`. - `The [Swap!]! field type requires an explicit @derivedFrom` - a list of entities needs `@derivedFrom`. - `No type definition 'Int8' exists in schema` - the type isn't a supported scalar, an entity or an enum. - `Schema contains the following reserved keywords: ...` - rename the entity, enum or enum value. See the [Schema](https://docs.envio.dev/docs/HyperIndex/schema) guide for the full rules. ### Handler Errors Codegen doesn't read your handlers. Mistakes in them, such as a wrong entity field or an unselected `event.transaction` field, are TypeScript errors. Run `pnpm tsc --noEmit` to see them. From v3.14 the indexer also runs this check on start and won't start until handler files type-check. If `typescript` or a `tsconfig.json` is missing, it logs a warning and skips the check. Import everything from `envio`. ## Relationship with Setup Files The generated declarations directly reflect the structure defined in your setup files: - **config.yaml** β†’ Determines which chains, contracts, and events are indexed - **schema.graphql** β†’ Defines the entities and relationships that are generated - **handlers in `src/handlers/`** β†’ Provide the business logic that the generated types describe ## Best Practices 1. **Never modify generated files directly** - Always change the source files 2. **Run codegen before starting your indexer** - Ensure all declarations are up to date 3. **Check error messages carefully** - They often pinpoint issues in your setup files 4. **Commit `envio-env.d.ts` and `.envio/.gitignore`** - The shim is part of the project. The `.gitignore` codegen writes keeps `.envio/types.d.ts` out of git and leaves `.envio/cache/` trackable, so you choose whether to commit a saved effect cache. ## Summary Generated declarations form the critical bridge between your indexing specifications and the actual runtime execution. While you shouldn't modify them directly, understanding their structure and purpose can help you debug issues and optimize your indexing process. If you encounter persistent errors related to generated files, ensure your configuration, schema, and handlers follow Envio's best practices, or contact support for assistance. --- --- # HyperIndex Terminology & Key Concepts > Explore key terms for fast reference and blockchain indexer development. This comprehensive glossary explains the key terms and concepts used throughout the Envio documentation and ecosystem. Terms are organized by category for easier reference. ## Table of Contents - [Blockchain Fundamentals](#blockchain-fundamentals) - [Smart Contract Concepts](#smart-contract-concepts) - [Indexing & Data](#indexing--data) - [Development Tools](#development-tools) - [Programming Languages](#programming-languages) - [Envio Platform](#envio-platform) - [Mathematical Concepts](#mathematical-concepts) ## Blockchain Fundamentals ### Address A unique identifier representing an account or entity within a blockchain network. Addresses are typically represented as hexadecimal strings (e.g., `0x1234...abcd`) and used to send, receive, or interact with blockchain resources. ### Block A collection of data containing a set of transactions that are bundled together and added to the blockchain. Blocks are linked together chronologically to form the blockchain. ### EVM **Ethereum Virtual Machine (EVM)** is a runtime environment that executes smart contracts on the Ethereum blockchain. It provides a sandboxed and deterministic execution environment for smart contract code. ### EVM Compatible The ability for a blockchain to run the EVM and execute Ethereum smart contracts. In the context of Envio, it's the ability to deploy a unified API to retrieve data from multiple EVM-compatible blockchains (e.g., Ethereum, BSC, Arbitrum, Polygon, Avalanche, Optimism, Fantom, Cronos, etc.). ### Node A device or computer that participates in a blockchain network, maintaining a copy of the blockchain and validating transactions. ### Transaction An action or set of actions recorded on the blockchain, typically involving the transfer of assets, execution of smart contracts, or other network interactions. Once confirmed, transactions become a permanent part of the blockchain. ## Smart Contract Concepts ### Event A specific occurrence or action within a blockchain system that is specified in smart contracts and used to emit data from the blockchain. Smart contracts can emit events to essentially communicate that something has happened on the blockchain. Web applications or any kind of application (e.g., mobile app, backend job, etc.) can listen to events and take actions when they occur. Events are typically data that are not stored on-chain as it would be considerably more expensive to store. **Example:** Declaring an event: ```solidity event Deposit(address indexed _from, bytes32 indexed _id, uint _value); ``` Emitting an event: ```solidity emit Deposit(msg.sender, _id, msg.value); ``` ### Event Handler A function that listens for a specific event from a smart contract and either updates or inserts new data into your Envio API. Event handlers define the business logic for processing blockchain events. ### Smart Contract A self-executing program with the terms of an agreement directly written into code that runs on the blockchain. Smart contracts are not controlled by a user but are deployed to the network and run as programmed. User accounts can interact with smart contracts by submitting transactions that execute defined functions. ### Tokens Digital representations of assets or utilities within a blockchain system that follow a specific standard. Common token standards include: - **ERC-20**: Standard for fungible tokens (identical and interchangeable) - **ERC-721**: Standard for non-fungible tokens (unique and non-interchangeable) - **ERC-1155**: Multi-token standard supporting both fungible and non-fungible tokens ## Indexing & Data ### API **Application Programming Interface** is a set of protocols and tools for building software applications. APIs define how different software components should interact with each other. ### Endpoint A URL that can be used to query an Envio custom API. Endpoints provide a structured way to request specific data from the indexer. ### GraphQL A query language for interacting with APIs, commonly used in blockchain systems for retrieving specific data from blockchain platforms. As an alternative to REST, GraphQL lets developers construct requests that pull data from multiple data sources in a single API call. ### GraphQL API The data presentation part of an Envio indexer. Typically, it's a GraphQL API auto-generated from the schema file, allowing flexible and efficient data queries. ### Blockchain Indexer A specialized database management system (DBMS) that indexes and organizes blockchain data, making it easier for developers to efficiently query, retrieve, and utilize on-chain data. Web2 apps usually rely on indexers like Google to pre-sort information into indices for data retrieval and filtering. In blockchain and Web3, applications need blockchain indexers to achieve similar data retrieval capabilities. ### Query A request for data. In the context of Envio, a query is a request for data from an Envio API that will be answered by an Envio Indexer. ### Schema File A file that defines entities based on events emitted from smart contracts and specifies the data types for these entities. The schema serves as the blueprint for your indexed data structure. ## Development Tools ### Codegen The process of automatically generating code based on a given input. In blockchain development, codegen is often used for generating client libraries, interfaces, or type-safe data access layers from schemas or specifications. ### Envio CLI A command line interface tool for building and deploying Envio indexers. The CLI provides commands for initializing, developing, and managing your indexer projects. ### SDK **Software Development Kit** is a collection of tools, libraries, and documentation that facilitates the development of applications for a specific platform or system. ## Programming Languages ### JavaScript A high-level, interpreted programming language primarily used for client-side scripting in web browsers. It is the de facto language for web development, enabling developers to create interactive and dynamic web applications. ### ReScript A robustly typed language that compiles to efficient and human-readable JavaScript. ReScript aims to bring the power and expressiveness of functional programming to JavaScript development. It offers seamless integration with JavaScript and provides features like static typing, pattern matching, and immutable data structures. ### TypeScript A superset of JavaScript that adds static typing and other advanced features to the language. It compiles down to plain JavaScript, making it compatible with existing JavaScript codebases. TypeScript helps developers catch errors during development by providing type-checking and improved tooling support. It enhances JavaScript by adding features like interfaces, classes, modules, and generics. ## Envio Platform ### Envio Cloud A managed service platform for building, hosting, and querying Envio's Indexers with guaranteed uptime and performance service level agreements. Envio Cloud removes the operational burden of running blockchain indexers. ### Ploffen Ploffen (meaning "Pop" in Dutch) is a fun game based on an ERC20 token contract, where users can deposit a game token (i.e., make a contribution) into a savings pool. The last user to add a contribution to the savings pool has a chance of winning the entire pool if no other user deposits a contribution within 1 hour of the previous contribution. For example, if 30 persons play the game, and each person contributes a small amount, the last person can win the _total contributions_ made by all 30 persons in the savings pool. The Ploffen project demonstrates a Hardhat framework example. It includes a sample contract, a test for that contract, a deployment script, and the Envio integration to index emitted events from the Ploffen smart contract. ## Mathematical Concepts ### Commutative Property A fundamental property of certain binary operations in mathematics. An operation is said to be commutative if the order in which you apply the operation to two operands does not affect the result. In other words, for a commutative operation: a + b = b + a **Examples of commutative operations:** 1. **Addition**: 2 + 3 = 3 + 2 2. **Multiplication**: 2 Γ— 3 = 3 Γ— 2 **Examples of non-commutative operations:** 1. **Subtraction**: 5 - 3 β‰  3 - 5 2. **Division**: 8 / 4 β‰  4 / 8 3. **String Concatenation**: "Hello" + "World" β‰  "World" + "Hello" The commutative property is a property of the operation itself, not necessarily the numbers involved. If an operation is commutative, you can switch the order of the operands without changing the result. --- # Using WebSockets with GraphQL > Connect to a HyperIndex GraphQL endpoint over WSS or WS for real-time subscriptions, with a graphql-ws example and the level of support on each hosting plan. > **⚠️ Important**: WebSocket support is available but should be used at your own risk on plans other than dedicated. ## Overview By default, HyperIndex provides GraphQL endpoints over HTTP/HTTPS. However, you can also connect to your GraphQL endpoint using WebSocket connections (WSS/WS) for real-time subscriptions and persistent connections. ## WebSocket Support Status WebSocket connections are available with different levels of support depending on your hosting plan: - **Dedicated**: WebSockets are fully supported. The dedicated package includes additional infrastructure such as connection pooling which enables proper WebSocket support. - **Other Plans**: WebSocket support is available but should be used at your own risk. These plans do not have the same infrastructure support for WebSockets as dedicated. We don't recommend relying on WebSockets for more than 10 concurrent connections. ## How to Use WebSockets To use WebSockets with your HyperIndex GraphQL endpoint, simply swap the protocol in your endpoint URL: ### Protocol Mapping - **HTTPS β†’ WSS**: Change `https://` to `wss://` in your GraphQL endpoint URL - **HTTP β†’ WS**: Change `http://` to `ws://` in your GraphQL endpoint URL ### Example If your GraphQL endpoint is: ``` https://indexer.hyperindex.xyz/123abcd/graphql ``` You can connect via WebSocket using: ``` wss://indexer.hyperindex.xyz/123abcd/graphql ``` Similarly, for HTTP endpoints: ``` http://localhost:8080/v1/graphql ``` Becomes: ``` ws://localhost:8080/v1/graphql ``` ## Usage Example Here's a TypeScript example using the `graphql-ws` library to subscribe to real-time updates from your indexer: ```typescript import { createClient } from 'graphql-ws'; // Define the entity you are subscribing to (must match your schema definition) interface Swap { id: string; } interface SubscriptionData { data?: { Swap?: Swap[]; }; } const client = createClient({ url: 'ws://localhost:8080/v1/graphql', }); console.log('Connecting to WebSocket...'); client.subscribe( { query: ` subscription { Swap(order_by: { id: desc }, limit: 10) { id } } `, }, { next: (data) => { console.log('\nπŸ“₯ New event received:'); console.log(JSON.stringify(data, null, 2)); }, error: (err) => { console.error('❌ Error:', err); }, complete: () => { console.log('βœ… Subscription completed'); }, } ); ``` ### Installation To use this example, install the required dependencies: ```bash npm install graphql-ws ws # or yarn add graphql-ws ws ``` ## Getting Support For any questions about WebSocket usage, contact the Envio team via [Telegram](https://t.me/envio) or [Discord](https://discord.gg/envio). --- # Query Conversion > Learn how to convert queries from TheGraph's custom GraphQL syntax to Envio's standard GraphQL syntax. Envio uses standard GraphQL query language, while TheGraph uses a custom GraphQL syntax. While the queries are very similar, there are some important differences to be aware of when migrating. This guide covers all the differences between TheGraph's query syntax and Envio's query syntax, with examples for each conversion rule. ## Converter Tool We've built a [query converter tool](https://github.com/enviodev/subgraph-to-hyperindex-query-converter) that automatically converts TheGraph queries to Envio's GraphQL syntax. You can: - **Convert and execute**: Provide your Envio GraphQL endpoint and a query written in TheGraph syntax. The tool will convert it, execute it against your endpoint, and return the results - **Convert only**: Use the tool to convert queries and view the converted output without executing them. To convert queries without executing them, add `/debug` to the converter endpoint and send your query. The response will contain only the converted query without actually running it. **Repository**: [subgraph-to-hyperindex-query-converter](https://github.com/enviodev/subgraph-to-hyperindex-query-converter) :::info Availability The query converter tool is only available to users on paid tiers. ::: :::info Setup Assistance If you'd like to use the query converter tool for your indexer, please reach out to our team and we can add an instance of the converter tool to be deployed with your indexer. ::: :::tip Best Practice **We strongly recommend converting your queries to use Envio's standard GraphQL syntax** rather than relying on the query converter tool. This ensures better performance, maintainability, and avoids potential conversion limitations. The converter tool is primarily intended for backwards compatibility in cases where you might have external-facing APIs which depend on TheGraph's query syntax. ::: :::warning Beta Status This converter tool is still very much in beta. We're actively working on it and discovering new query conversions that need to be handled. **If you encounter any conversion failures or incorrect conversions, please [file a GitHub issue](https://github.com/enviodev/subgraph-to-hyperindex-query-converter/issues) in the repository so we can address it.** ::: ### Converter Tool Limitations The query converter tool has several limitations to be aware of: - **Rate limits**: The rate limits of your associated tier will still apply when using the converter tool. - **Beta status and incomplete coverage**: Since the tool is in beta there is a possibility we have missed some conversion patterns. Some queries may still fail to convert correctly or may not be handled at all. If you encounter any conversion failures or incorrect conversions, please [file a GitHub issue](https://github.com/enviodev/subgraph-to-hyperindex-query-converter/issues) in the repository so we can address it. - **WebSocket subscriptions**: WebSocket subscriptions are not supported. The converter only works with standard HTTP GraphQL queries. - **Directives not supported**: GraphQL directives (such as `@skip`, `@include`, etc.) are not supported because the converter uses simple string parsing rather than a full GraphQL parser. Directives are ignored or may break parsing. - **Variables in orderBy/orderDirection**: Variables used in `orderBy` and `orderDirection` parameters are ignored because HyperIndex requires literal field names in `order_by` clauses, and variable values are unknown at conversion time. Queries using variables for ordering will return unordered results. - **Array filter operators**: The `_containsAny` and `_containsAll` filters are TheGraph-specific array operators that don't have direct Hasura equivalents. The converter explicitly rejects these and returns an `UnsupportedFilter` error. Use `_in` for array matching instead. - **Meta queries**: Meta queries only support `_meta { block { number } }` because HyperIndex exposes block information differently. Other `_meta` fields (hash, timestamp, deployment, hasIndexingErrors) are not available in HyperIndex's schema and will return a `ComplexMetaQuery` error. - **Introspection queries**: Introspection queries only work if they use the operation name `"IntrospectionQuery"`. Other introspection queries (like querying `__schema` directly) will fail because they go through normal conversion which doesn't understand introspection syntax. For production applications, we recommend migrating your queries to Envio's standard GraphQL syntax to avoid these limitations. --- ### 1. Entity Name Conversion **Rule**: TheGraph uses pluralized entity names (e.g., `pools`, `factories`, `tokens`), while Envio uses the entity name as-is from the schema (singular, PascalCase). When converting, plural entity names are automatically singularized and capitalized to match Envio's schema. **Example**: ```graphql # TheGraph query { pools { id } factories { id } tokens { id } } # Envio query { Pool { id } Factory { id } Token { id } } ``` Single entity queries use `EntityName_by_pk` (by primary key) in Envio. Alternatively, you could use a `where` clause with the primary key field: ```graphql # TheGraph query { pool(id: "0x123") { value } } # Envio query { Pool_by_pk(id: "0x123") { value } } ``` With `disable_default_cross_chain: true` in `config.yaml`, an entity's primary key is `id` plus `chainId`, so `_by_pk` takes both: `Pool_by_pk(id: "0x123", chainId: 1)`. Or using a `where` clause: ```graphql # Envio query { Pool(where: {id: {_eq: "0x123"}}) { value } } ``` ### 2. Pagination Parameters #### First β†’ Limit **Rule**: The `first` parameter is converted to `limit`. **Example**: ```graphql # TheGraph query { pools(first: 10) { id } } # Envio query { Pool(limit: 10) { id } } ``` #### Skip β†’ Offset **Rule**: The `skip` parameter is converted to `offset`. **Example**: ```graphql # TheGraph query { pools(skip: 20) { id } } # Envio query { Pool(offset: 20) { id } } ``` ### 3. Ordering Parameters #### OrderBy and OrderDirection β†’ Order_by **Rule**: The `orderBy` and `orderDirection` parameters are combined into a single `order_by: {field: direction}` clause. **Example**: ```graphql # TheGraph query { pools(orderBy: name, orderDirection: desc) { id name } # Use orderDirection: asc for ascending order } # Envio query { Pool(order_by: {name: desc}) { id name } # Use asc for ascending order, e.g., order_by: {name: asc} } ``` ### 4. Filter Operators #### Equality Filter **Rule**: Simple equality filters are converted to `where: {field: {_eq: value}}` format. **Example**: ```graphql # TheGraph query { pools(name: "test") { id name } } # Envio query { Pool(where: {name: {_eq: "test"}}) { id name } } ``` #### Comparison Filters **Rule**: Comparison filters (`_not`, `_gt`, `_gte`, `_lt`, `_lte`, `_in`, `_not_in`) are converted to their Hasura equivalents. **Examples**: ```graphql # TheGraph query { pools(id_not: "0x123") { id } pools(amount_gt: 100) { id amount } pools(amount_gte: 100) { id amount } pools(timestamp_lt: 1650000000) { id timestamp } pools(timestamp_lte: 1650000000) { id timestamp } pools(id_in: ["1", "2", "3"]) { id name } pools(id_not_in: ["1", "2", "3"]) { id name } } # Envio query { Pool(where: {id: {_neq: "0x123"}}) { id } Pool(where: {amount: {_gt: 100}}) { id amount } Pool(where: {amount: {_gte: 100}}) { id amount } Pool(where: {timestamp: {_lt: 1650000000}}) { id timestamp } Pool(where: {timestamp: {_lte: 1650000000}}) { id timestamp } Pool(where: {id: {_in: ["1", "2", "3"]}}) { id name } Pool(where: {id: {_nin: ["1", "2", "3"]}}) { id name } } ``` #### String Filters **Rule**: String filters (`_contains`, `_starts_with`, `_ends_with`, and their `_not` and `_nocase` variants) are converted to `_ilike` with appropriate wildcards. The `%` symbol represents any text at that position in the pattern. **Examples**: ```graphql # TheGraph query { pools(name_contains: "test") { id name } pools(name_not_contains: "test") { id name } pools(symbol_starts_with: "ABC") { id symbol } pools(symbol_ends_with: "XYZ") { id symbol } pools(name_not_starts_with: "A") { id name } pools(name_not_ends_with: "x") { id name } pools(name_contains_nocase: "test") { id name } pools(name_starts_with_nocase: "test") { id name } pools(name_ends_with_nocase: "test") { id name } } # Envio query { Pool(where: {name: {_ilike: "%test%"}}) { id name } Pool(where: {_not: {name: {_ilike: "%test%"}}}) { id name } Pool(where: {symbol: {_ilike: "ABC%"}}) { id symbol } Pool(where: {symbol: {_ilike: "%XYZ"}}) { id symbol } Pool(where: {_not: {name: {_ilike: "A%"}}}) { id name } Pool(where: {_not: {name: {_ilike: "%x"}}}) { id name } Pool(where: {name: {_ilike: "%test%"}}) { id name } Pool(where: {name: {_ilike: "test%"}}) { id name } Pool(where: {name: {_ilike: "%test"}}) { id name } } ``` ### 5. Variable Type Conversions #### ID β†’ String **Rule**: Variable types `ID` and `ID!` are converted to `String` and `String!` respectively. **Example**: ```graphql # TheGraph query getPoolValue($id: ID!) { pool(id: $id) { value } } # Envio query getPoolValue($id: String!) { Pool_by_pk(id: $id) { value } } ``` #### Bytes β†’ String **Rule**: Variable types `Bytes` and `Bytes!` are converted to `String` and `String!` respectively. **Example**: ```graphql # TheGraph query getTokens($id: Bytes) { tokens(where: { id: $id }) { id timestamp } } # Envio query getTokens($id: String) { Token(where: {id: {_eq: $id}}) { id timestamp } } ``` #### BigInt β†’ numeric **Rule**: Variable types `BigInt` and `BigInt!` are converted to `numeric` and `numeric!` respectively. **Example**: ```graphql # TheGraph query GetTokens($amount: BigInt) { tokens(where: { amount: $amount }) { id amount } } # Envio query GetTokens($amount: numeric) { Token(where: {amount: {_eq: $amount}}) { id amount } } ``` #### BigDecimal β†’ numeric **Rule**: Variable types `BigDecimal` and `BigDecimal!` are converted to `numeric` and `numeric!` respectively. **Example**: ```graphql # TheGraph query GetValue($value: BigDecimal!) { pools(where: { value: $value }) { id } } # Envio query GetValue($value: numeric!) { Pool(where: {value: {_eq: $value}}) { id } } ``` --- ## Summary Table | Category | TheGraph | Envio | Example | | --- | --- | --- | --- | | **Entity Names** | Plural camelCase | Singular PascalCase (as-is from schema) | `pools` β†’ `Pool` | | **Pagination** | `first`, `skip` | `limit`, `offset` | `first: 10, skip: 20` β†’ `limit: 10, offset: 20` | | **Ordering** | `orderBy`, `orderDirection` | `order_by: {field: direction}` | `orderBy: name, orderDirection: desc` β†’ `order_by: {name: desc}` | | **Equality Filter** | `field: value` | `field: {_eq: value}` | `name: "test"` β†’ `name: {_eq: "test"}` | | **Comparison Filters** | `field_gt`, `field_gte`, etc. | `field: {_gt: value}`, etc. | `amount_gt: 100` β†’ `amount: {_gt: 100}` | | **String Filters** | `_contains`, `_starts_with`, etc. | `_ilike` with `%` wildcards | `name_contains: "test"` β†’ `name: {_ilike: "%test%"}` | | **Variable Types** | `ID`, `Bytes`, `BigInt`, `BigDecimal` | `String`, `numeric` | `$id: ID!` β†’ `$id: String!` | --- ## Getting Help If you encounter any issues with query conversion or have questions: - **Converter Issues**: File a [GitHub issue](https://github.com/enviodev/subgraph-to-hyperindex-query-converter/issues) for the converter tool - **General Questions**: Join our [Discord community](https://discord.gg/envio) for support --- # MCP Server > Connect Claude Code, Cursor and other MCP clients to the Envio docs MCP server to search and fetch pages, or use the same tools through the Envio CLI from 3.1. Envio provides a Model Context Protocol (MCP) server that lets AI coding assistants search and retrieve documentation directly. This means tools like Claude Code, Cursor, and other MCP-compatible clients can access Envio docs without you needing to copy-paste context manually. ## Endpoint ``` https://docs.envio.dev/mcp ``` ## Available Tools The MCP server exposes two tools: | Tool | Description | | --- | --- | | `docs_search` | Full-text search across all documentation. Returns matching pages with titles, URLs, and content snippets. | | `docs_fetch` | Retrieves the full content of a documentation page as markdown. | ## Envio CLI Tools Starting from Envio `3.1`, the same documentation search and retrieval is also available directly through the Envio CLI - no MCP server setup required. AI agents can call these tools out of the box: | Tool | Description | | --- | --- | | `envio tools search-docs ` | Full-text search across all documentation, equivalent to the `docs_search` MCP tool. | | `envio tools fetch-docs ` | Retrieves the full content of a documentation page as markdown, equivalent to the `docs_fetch` MCP tool. | ## Setup ### Claude Code ```bash claude mcp add --transport http envio-docs https://docs.envio.dev/mcp ``` ### Cursor / VS Code Add the following to your MCP configuration (`.cursor/mcp.json` or VS Code MCP settings): ```json { "mcpServers": { "envio-docs": { "url": "https://docs.envio.dev/mcp" } } } ``` ### Other MCP Clients Point any MCP-compatible client to the endpoint URL above using the **Streamable HTTP** transport. ---