### Local Docker Example for Envio Indexer Setup Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Demonstrates a minimal Dockerfile and docker-compose.yaml for setting up the Envio indexer alongside PostgreSQL and Hasura. This configuration includes services for the database, GraphQL engine, and the indexer itself, with explanations of environment variables for customization. ```yaml services: envio-postgres: image: postgres:14 restart: always volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_PASSWORD: "envio" graphql-engine: image: hasura/graphql-engine:v2.15.0 ports: - "8080:8080" depends_on: - envio-postgres environment: HASURA_GRAPHQL_DATABASE_URL: "postgres://envio:envio@envio-postgres:5432/postgres" HASURA_GRAPHQL_ENABLE_CONSOLE: "true" HASURA_GRAPHQL_ADMIN_SECRET: "my-admin-secret" restart: always envio-indexer: build: context: . dockerfile: Dockerfile ports: - "5000:5000" depends_on: - envio-postgres - graphql-engine environment: ENVIO_PG_PASSWORD: "envio" ENVIO_PG_USER: "postgres" ENVIO_PG_HOST: "envio-postgres" ENVIO_PG_PORT: "5432" ENVIO_PG_DATABASE: "postgres" HASURA_GRAPHQL_ADMIN_SECRET: "my-admin-secret" ENVIO_API_TOKEN: "YOUR_ENVIO_API_TOKEN" restart: always volumes: postgres_data: ``` -------------------------------- ### Start Envio Indexer Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Starts the Envio indexer, which includes setting up Docker containers, initializing the database, launching the indexing process, and opening the Hasura GraphQL interface. It's recommended to stop any currently running indexers before starting a new one. ```bash pnpm start:optimism-bridge-indexer ``` -------------------------------- ### Start Envio Indexer Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Navigate to the Envio package directory and execute the command to start the indexer. This command initiates the process of indexing contract events. ```bash cd packages/enviopnpm dev ``` -------------------------------- ### Start Local Blockchain for Development Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This command navigates to the project directory and starts a local blockchain node, which is essential for testing contract deployments and interactions during development. ```bash cd your-project-name yarn chain ``` -------------------------------- ### Envio CLI: Docker and Benchmarking Commands Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete These commands manage Docker containers and analyze indexer performance. 'envio local docker up' starts the necessary Docker services for your environment. 'envio start --bench' combined with 'envio benchmark-summary' allows you to run benchmarks and then view a summary of the performance data. ```bash envio local docker up envio start --bench envio benchmark-summary ``` -------------------------------- ### Define Network Configuration for Optimism using Envio Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This configuration snippet details the setup for indexing data from the Optimism network with Envio. It includes the network ID, desired start block, contract information, and event handling configuration. Replace the example values with your project's specific details. ```yaml name: IndexerName # Specify indexer namedescription: Indexer Description # Include indexer descriptionnetworks: - id: 10 # Optimism start_block: START_BLOCK_NUMBER # Specify the starting block contracts: - name: ContractName address: - "0xYourContractAddress1" - "0xYourContractAddress2" handler: ./src/EventHandlers.ts events: - event: Event # Specify event - event: Event ``` -------------------------------- ### Indexing ERC20 Token Transfers on Base Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete A step-by-step guide to indexing ERC20 token transfers on the Base network using Envio HyperIndex. This tutorial covers initializing an indexer, importing contracts, and starting the indexing process. ```APIDOC ## Indexing ERC20 Token Transfers on Base ### Introduction This tutorial demonstrates how to index ERC20 token transfers on the Base network using Envio HyperIndex, focusing on USDC transfers and identifying the largest ones. ### Prerequisites - Node.js (v22+ recommended) - pnpm (v8+) - Docker Desktop (required for local indexing) ### Step 1: Initialize Your Indexer 1. Open your terminal in an empty directory. 2. Run the initialization command (e.g., `envio init`). 3. Name your indexer (e.g., `usdc-base-transfer-indexer`). 4. Choose your preferred language (TypeScript, JavaScript, or ReScript). ### Step 2: Import the USDC Token Contract 1. In the Envio interface, select **Contract Import** → **Block Explorer** → **Base**. 2. Enter the USDC token contract address on Base: `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`. 3. Select the `Transfer` event by navigating with arrow keys and pressing the spacebar. 4. Choose **I'm finished** when done. ### Step 3: Start Your Indexer 1. Stop any running indexers if necessary (e.g., `envio stop`). 2. Start your new indexer: `envio start`. This command starts Docker containers, sets up the database, launches indexing, and opens the Hasura GraphQL interface. ### Step 4: Understanding the Generated Code Examine the key files generated by Envio to understand the indexer's structure and functionality. ``` -------------------------------- ### Initialize Envio Project Using a Template Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Creates a new Envio project from a pre-built template. Templates provide a starting point with common configurations and structures for specific types of indexing tasks. ```bash envio init template ``` -------------------------------- ### Navigating Hasura Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete A guide to using the Hasura console for querying, visualizing, and testing indexed blockchain data, particularly when running a local or self-hosted Envio instance. ```APIDOC ## Navigating Hasura **Note:** This guide is relevant for local development or self-hosted Envio instances using Hasura. ### Introduction Hasura is a GraphQL engine that provides a web interface for interacting with your indexed blockchain data. It is essential for querying data, visualizing tables and relationships, testing API endpoints, and monitoring the indexing process. ### Accessing Hasura Console When running HyperIndex locally, the Hasura Console is available at the following URL: `http://localhost:8080` (Default URL - check your specific setup if different) **Authentication:** When prompted for credentials, use the password: `testing` ### Key Dashboard Areas #### API Tab The API tab allows you to execute GraphQL queries and mutations. It functions as a GraphQL playground. **Features:** * **Explorer Panel:** Displays all entities defined in your `schema.graphql`. * **Query Builder:** Area for writing and executing GraphQL queries. * **Results Panel:** Shows the results of your queries in JSON format. **Available Entities:** * Entities defined in `schema.graphql`. * `dynamic_contracts`. * `raw_events` (Only if `raw_events: true` is set in `config.yaml`). **Example Query:** ```graphql query MyQuery { User(limit: 5) { id latestGreeting numberOfGreetings } } ``` #### Data Tab The Data tab provides direct access to your database tables and relationships, enabling you to view and manage indexed data. **Features:** * **Schema Browser:** Lists all tables in the database. * **Table Data:** Browse and view data within tables. * **Relationship Viewer:** Visualize connections between entities. **Working with Tables:** 1. Select a table from the "public" schema. 2. Use the "Browse Rows" tab to view data. 3. Use the "Insert Row" tab to manually add data for testing. 4. Use the "Modify" tab to view table structure. ``` -------------------------------- ### Create Scaffold-ETH 2 Project with Envio Extension Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This command initializes a new Scaffold-ETH 2 project pre-configured with the Envio extension, simplifying the setup for smart contract indexing. ```bash npx create-eth@latest -e enviodev/scaffold-eth-2-extension ``` -------------------------------- ### Example Reorg Configuration for Multiple Networks (YAML) Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This example demonstrates a comprehensive reorg handling configuration for multiple blockchain networks. It specifies different 'confirmed_block_threshold' values for Ethereum Mainnet, Polygon, and Arbitrum One, highlighting customized settings and default usage. ```yaml rollback_on_reorg: truenetworks: - id: 1 # Ethereum Mainnet confirmed_block_threshold: 250 # Higher threshold for Ethereum # other network config... - id: 137 # Polygon confirmed_block_threshold: 150 # Lower threshold for Polygon # other network config... - id: 42161 # Arbitrum One # Using default threshold (200) # other network config... ``` -------------------------------- ### ReScript Setup Configuration Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This snippet shows the necessary configuration for ReScript projects. It specifies source directories and build dependencies, ensuring correct project structure and build processes. ```json { "sources": [ { "dir": "src", "subdirs": true }, { "dir": "test", "subdirs": true } ], "bs-dependencies": ["rescript-mocha"] } ``` -------------------------------- ### Configure Network Settings in YAML Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Example of defining network configurations in a YAML file. This includes network ID, start and end blocks for data ingestion, and a list of contracts to be indexed. ```yaml networks: - id: 1 start_block: 0 end_block: 19000000 contracts: - name: Greeter address: 0x1111111111111111111111111111111111111111 ``` -------------------------------- ### IPFS Multiple Gateway Configuration Example (JavaScript) Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Demonstrates configuring multiple IPFS gateways to ensure data availability and resilience against single gateway failures. Includes an optional paid gateway. ```javascript const endpoints = [ ...(process.env.PAID_IPFS_GATEWAY ? [process.env.PAID_IPFS_GATEWAY] : []), "https://cloudflare-ipfs.com/ipfs", "https://ipfs.io/ipfs", "https://gateway.pinata.cloud/ipfs", ]; ``` -------------------------------- ### Common Issues and Solutions Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Troubleshooting guide for common errors encountered during Envio development, such as 'Cannot read properties of undefined' and 'Type mismatch'. Includes ReScript setup and debugging tips. ```APIDOC ## Common Issues and Solutions ### Error: "Cannot read properties of undefined" **Description:** This error typically indicates that an entity could not be found in the database. Ensure that the IDs you are using are correct and that the entity exists before attempting to access it. ### Error: "Type mismatch" **Description:** This error occurs when the structure of your entity does not align with the defined schema. Pay close attention to data types, especially when working with numeric types like `BigInt` and `number`. ### ReScript Setup **Description:** If you are using ReScript, you must update your `rescript.json` file to include necessary configurations. **Configuration Example:** ```json { "sources": [ { "dir": "src", "subdirs": true }, { "dir": "test", "subdirs": true } ], "bs-dependencies": ["rescript-mocha"] } ``` ### Debugging Database State **Description:** To help diagnose issues with assertions, you can log the exact state of your entities. **Logging Example:** ```javascript console.log(JSON.stringify(updatedMockDb.entities.User.get(userAddress), null, 2)); ``` **Support:** For further assistance, please reach out on Discord. ``` -------------------------------- ### Install and Use Node.js v22 with NVM Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Envio requires Node.js v22 or newer. This snippet demonstrates how to install and switch to Node.js v22 using Node Version Manager (nvm). If nvm is not available, download Node.js directly from the official website. ```bash # Using nvm (recommended) nvm install 22 nvm use 22 # Or download directly from https://nodejs.org/ ``` -------------------------------- ### Metadata Query Result Example Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Presents a sample JSON response from the '_meta' query, illustrating the structure and typical values for indexing metadata across multiple chains. ```json { "data": { "_meta": [ { "chainId": 1, "progressBlock": 22817138, "eventsProcessed": 2380000, "bufferBlock": 22820499, "firstEventBlock": 21688545, "sourceBlock": 23368264, "readyAt": null, "isReady": false, "startBlock": 0, "endBlock": null }, { "chainId": 10, "progressBlock": 137848820, "eventsProcessed": 2455000, "bufferBlock": 137873621, "firstEventBlock": 130990676, "sourceBlock": 141168975, "readyAt": null, "isReady": false, "startBlock": 0, "endBlock": null } ] } } ``` -------------------------------- ### Initialize Envio Indexer Project Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This snippet demonstrates the command-line interaction for initializing a new Envio indexer project. It covers selecting the project name, programming language (TypeScript), blockchain ecosystem (Fuel), initialization option (Contract Import), ABI file path, events to index, contract name, and contract address. It shows the typical prompts and user selections during the setup process. ```bash pnpm create envio@latest ? Specify a folder name (ENTER to skip): sway-farm-indexer ? Which language would you like to use? JavaScript> TypeScript ReScript[↑↓ to move, enter to select, type to filter] ? Choose blockchain ecosystem Evm> Fuel[↑↓ to move, enter to select, type to filter] ? Choose an initialization option Template> Contract Import[↑↓ to move, enter to select, type to filter] ? What is the path to your json abi file? ./sway-farm/contract/out/debug/contract-abi.json ? Which events would you like to index?> [x] NewPlayer [ ] PlantSeed [x] SellItem [ ] InvalidError [ ] Harvest [ ] BuySeeds [x] LevelUp[↑↓ to move, space to select one, → to all, ← to none, type to filter] ? What is the name of this contract? SwayFarm ? What is the address of the contract? 0xf5b08689ada97df7fd2fbd67bee7dea6d219f117c1dc9345245da16fe4e99111[Use the proxy address if your abi is a proxy implementation] ? Would you like to add another contract?> I'm finished Add a new address for same contract on same network Add a new contract (with a different ABI)[Current contract: SwayFarm, on network: Fuel] Please run `cd sway-farm-indexer` to run the rest of the envio commands ``` -------------------------------- ### Example Environment Variables for Envio Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Demonstrates common environment variables used with Envio, including API tokens, RPC URLs, and batch sizes. These variables help configure indexer behavior and external service integrations. ```shell # Envio API Token (required for continued HyperSync access)ENVIO_API_TOKEN=your-secret-token# Blockchain RPC URLENVIO_RPC_URL=https://arbitrum.direct.dev/your-api-key# Starting block number for indexingENVIO_START_BLOCK=12345678# Coingecko API keyENVIO_COINGECKO_API_KEY=api-key# In-memory batch size (default 5000)MAX_BATCH_SIZE=1 ``` -------------------------------- ### Envio Greeter Project Configuration (`config.yaml`) Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This YAML file defines the networks and contracts to be indexed by Envio. It specifies network names, addresses, and other settings for each contract to be monitored. This example shows configurations for Greeter contracts on Polygon and Linea. ```yaml # Partial exampleenvio_node: networks: - name: polygon # ... Polygon network settings contracts: - name: Greeter address: "0x9D02A17dE4E68545d3a58D3a20BbBE0399E05c9c" # ... contract settings - name: linea # ... Linea network settings contracts: - name: Greeter address: "0xdEe21B97AB77a16B4b236F952e586cf8408CF32A" # ... contract settings ``` -------------------------------- ### Envio CLI: Initialize Indexer from Contract Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This advanced usage example demonstrates how to initialize a new Envio indexer by importing data from an existing smart contract. It specifies the type of indexer ('explorer'), the network ('ethereum-mainnet'), and the contract address. ```bash envio init contract-import explorer -b ethereum-mainnet -c 0x1234... ``` -------------------------------- ### Complete or Add More Contracts Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Final prompt after selecting contract details, offering options to finish the setup, add another contract on the same network, add the same contract on a different network, or add a completely new contract. ```bash ? Would you like to add another contract?> I'm finished Add a new address for same contract on same network Add a new network for same contract Add a new contract (with a different ABI) ``` -------------------------------- ### Configure RPC Settings with HyperSync in YAML Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Example demonstrating how to configure RPC settings for a network, including the RPC endpoint URL and initial block interval. This configuration can leverage HyperSync for enhanced performance. ```yaml networks: - id: 1 rpc_config: url: https://eth.llamarpc.com initial_block_interval: 1000 ``` -------------------------------- ### Migrating from Loaders to Envio Handlers in JavaScript Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This example shows the migration process from the older `handlerWithLoader` pattern to the modern `handler` pattern in Envio. It illustrates how to consolidate loader logic directly into the handler and optionally use `context.isPreload` for single-phase execution. ```javascript // Before: 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! }, }); // After: ERC20.Transfer.handler(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 }); ``` -------------------------------- ### Example YAML Network Configuration Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Illustrates correct and potentially incorrect network ID configurations within a YAML file. This helps in diagnosing 'Config validation failed' errors related to network IDs. ```yaml networks: - id: 1 # Valid Ethereum mainnet - id: 10 # Valid Optimism - id: 999 # Might be invalid if this network ID isn't recognized ``` -------------------------------- ### Control Docker Containers for Envio Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Manages Docker containers used by Envio. This allows for starting, stopping, and managing the lifecycle of necessary containerized services. ```bash envio local docker ``` -------------------------------- ### Envio CLI: Database Migration Commands Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete These commands manage the database schema for your indexer project. 'up' applies the latest schema migrations, 'down' drops the entire schema, and 'setup' resets the database by dropping the schema and then applying migrations. These are essential for managing database states during development and deployment. ```bash envio local db-migrate up envio local db-migrate down envio local db-migrate setup ``` -------------------------------- ### Network Configuration Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Defines the configuration for a blockchain network to be indexed by HyperIndex. This includes network ID, start and end blocks for indexing, and contract details. ```APIDOC ## Network Configuration ### Description Defines the configuration for a blockchain network to be indexed by HyperIndex. This includes network ID, start and end blocks for indexing, and contract details. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (integer) - Required - The public blockchain network ID. - **rpc_config** (object | null) - Optional - RPC configuration for utilizing as the network's data-source. Highly recommended for chains with HyperSync support. - **rpc** (object | null) - Optional - RPC configuration for your indexer. Serves as a fallback for HyperSync-supported networks or primary for others. - **hypersync_config** (object | null) - Optional - Additional HyperSync configuration for fine-tuning. - **confirmed_block_threshold** (integer | null) - Optional - The number of blocks from the head to account for reorgs. - **start_block** (integer) - Required - The block at which the indexer should start ingesting data. - **end_block** (integer | null) - Optional - The block at which the indexer should terminate. - **contracts** (array) - Required - All the contracts that should be indexed on the given network. ### Request Example ```yaml networks: - id: 1 start_block: 0 end_block: 19000000 contracts: - name: Greeter address: 0x1111111111111111111111111111111111111111 ``` ### Response #### Success Response (200) N/A (Configuration) #### Response Example N/A (Configuration) ``` -------------------------------- ### Run Envio Indexer in Development Mode Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Starts the Envio indexer in development mode, enabling hot reloading for faster iteration during development. Changes to code and configuration are reflected automatically. ```bash envio dev ``` -------------------------------- ### Define Network Configuration for Ethereum (Eth) using Envio Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This configuration snippet outlines how to set up Envio for indexing data from the Ethereum mainnet. It specifies the network ID, starting block, contract details, and event handlers. Remember to customize the placeholder values for your specific indexing task. ```yaml name: IndexerName # Specify indexer namedescription: Indexer Description # Include indexer descriptionnetworks: - id: 1 # Eth start_block: START_BLOCK_NUMBER # Specify the starting block contracts: - name: ContractName address: - "0xYourContractAddress1" - "0xYourContractAddress2" handler: ./src/EventHandlers.ts events: - event: Event # Specify event - event: Event ``` -------------------------------- ### IPFS Fetch Error Handling Example (JavaScript) Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Illustrates graceful error handling for IPFS fetch operations. Includes a try-catch block to log errors and return default values, preventing indexer failures. ```javascript try { // IPFS fetch logic } catch (error) { context.log.error(`Failed to fetch from IPFS`, error as Error); return { attributes: [], image: "default-image-url" }; } ``` -------------------------------- ### Querying Indexed Events Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Discover how to query your indexed blockchain data using GraphQL via the Envio API tab. Includes an example for fetching large bridge deposits. ```APIDOC ## Querying Indexed Events ### Description Explore your indexed blockchain data by constructing GraphQL queries. The Envio interface provides an API tab for this purpose. ### How to Query 1. Click on the **API** tab. 2. Construct a GraphQL query to retrieve the desired data. 3. Click the **Play** button to execute your query. ### Example Query: Largest Bridge Deposits ```graphql query LargestDeposits { DepositFinalized(limit: 10, order_by: { amount: desc }) { l1Token l2Token from to amount blockTimestamp } } ``` ``` -------------------------------- ### Envio CLI: Project and Development Commands Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This set of commands facilitates the creation, development, and deployment of Envio indexers. 'init' scaffolds a new project, 'dev' runs the indexer in development mode with hot reloading, 'start' deploys the indexer for production or testing, and 'stop' halts all Envio processes. 'codegen' is used to regenerate code after configuration or schema changes. ```bash envio init envio dev envio start envio stop envio codegen ``` -------------------------------- ### Configure Basic RPC Network in config.yaml Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This YAML configuration snippet demonstrates how to set up a basic RPC data source for a network within the Envio indexer configuration file (`config.yaml`). It specifies the network ID, the RPC endpoint URL, the starting block for indexing, and contract details. The presence of `rpc_config` signals the use of RPC over HyperSync. ```yaml networks: - id: 1 # Ethereum Mainnet rpc_config: url: https://eth-mainnet.your-rpc-provider.com # Your RPC endpoint start_block: 15000000 contracts: - name: MyContract address: "0x1234..." # Additional contract configuration... ``` -------------------------------- ### GraphQL Schema Example with @index Directive Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Demonstrates the correct placement of the '@index' directive within a GraphQL schema definition. This is crucial for resolving 'Schema parsing error' messages related to directives. ```graphql type Pool { id: ID! numberOfSwaps: BigInt! @index # Correct placement of @index directive } ``` -------------------------------- ### Other Language Logging Examples in Envio HyperIndex Handlers Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Illustrates logging practices in Envio HyperIndex handlers for languages other than JavaScript/TypeScript. It covers basic string logging, logging with custom exceptions using `errorWithExn`, and structured logging with parameters. This snippet shows how to integrate Envio's logging system into different language contexts. ```other // Inside your handlerexception ExampleException(string) // Example of an exception// Basic string loggingcontext.log.debug(`Processing event with block hash: ${event.blockHash} (debug)`)context.log.info(`Processing event with block hash: ${event.blockHash} (info)`)context.log.warn(`Potential issue with event: ${event.blockHash} (warn)`)context.log.error(`Failed to process event: ${event.blockHash} (error)`)// With exception:context.log.errorWithExn( `Failed to process event: ${event.blockHash}`, ExampleException("Error processing event"))// You can also provide an object as the second argument for structured logging:context.log.info("Processing blockchain event", ~params={ "type": "info", "extra": "Additional debugging context", "data": { "blockHash": event.blockHash },}); ``` -------------------------------- ### Configure RPC Endpoint for Indexer in YAML Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Example showing how to specify the RPC endpoint for the indexer in a YAML configuration. This can be a single URL or an array of URLs acting as primary and fallback endpoints. ```yaml networks: - id: 1 rpc: - url: https://eth.llamarpc.com for: sync ``` -------------------------------- ### Run Indexer with Custom Environment Variables (Shell) Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Execute the Envio indexer using custom environment variables for network and contract configuration. This example demonstrates setting `ENVIO_CHAIN_ID` and `ENVIO_GREETER_ADDRESS` before running the development server. ```shell ENVIO_CHAIN_ID=optimism ENVIO_GREETER_ADDRESS=0xYourContractAddress pnpm dev ``` -------------------------------- ### Docker Compose for eRPC Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Integrates eRPC into an existing Docker Compose setup. This configuration defines the eRPC service, its image, volume mounts for configuration, port mappings, and restart policy for continuous operation. ```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 ``` -------------------------------- ### Define Network Configuration for Arbitrum using Envio Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This configuration snippet defines settings for indexing data from the Arbitrum network using Envio. It includes the network ID, starting block, contract addresses, and event handlers. Ensure you replace placeholders with your specific project details. ```yaml name: IndexerName # Specify indexer namedescription: Indexer Description # Include indexer descriptionnetworks: - id: 42161 # Arbitrum start_block: START_BLOCK_NUMBER # Specify the starting block contracts: - name: ContractName address: - "0xYourContractAddress1" - "0xYourContractAddress2" handler: ./src/EventHandlers.ts events: - event: Event # Specify event - event: Event ``` -------------------------------- ### Configure HyperIndex with Default HyperSync (YAML) Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This YAML configuration demonstrates how to set up HyperIndex to use HyperSync as the default data source. By omitting an explicit RPC for historical sync, HyperIndex automatically leverages HyperSync. It includes network ID, start block, contract details, and handler information. The `start_block: 0` setting is a key benefit of using HyperSync, allowing indexing from the contract's deployment. ```yaml name: Greeter description: Greeter indexer networks: - 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 handler: ./src/EventHandlers.bs.js events: - event: NewGreeting - event: ClearGreeting ``` -------------------------------- ### Configure Network Indexing with Envio YAML Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This configuration file defines how Envio indexes data from a specific blockchain network. It includes network ID, starting block, contract details, and event handlers. Ensure that the handler path and event names are correctly specified. ```yaml name: IndexerName # Specify indexer name description: Indexer Description # Include indexer description networks: - id: 2741 # Abstract start_block: START_BLOCK_NUMBER # Specify the starting block contracts: - name: ContractName address: - "0xYourContractAddress1" - "0xYourContractAddress2" handler: ./src/EventHandlers.ts events: - event: Event # Specify event - event: Event ``` -------------------------------- ### Envio Indexer Configuration (YAML) Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This YAML configuration file sets up an Envio indexer to track events from specific smart contracts on a given network. It specifies the network ID, start block, and contracts to monitor, including their names, addresses, handler files, and the specific events to subscribe to. It also demonstrates how to select specific transaction fields. ```yaml # yaml-language-server: $schema=./node_modules/envio/evm.schema.json name: envio-indexer preload_handlers: true networks: - id: 81457 start_block: 11000000 contracts: - name: Api3ServerV1 address: - 0x709944a48cAf83535e43471680fDA4905FB3920a handler: src/EventHandlers.ts events: - event: UpdatedBeaconSetWithBeacons(bytes32 indexed beaconSetId, int224 value, uint32 timestamp) - name: UniswapV3Pool address: - 0xf52B4b69123CbcF07798AE8265642793b2E8990C handler: src/EventHandlers.ts events: - event: Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick) - event: Mint(address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1) field_selection: transaction_fields: - "hash" ``` -------------------------------- ### Configure Network Contracts for Indexing Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Defines network contracts to be indexed, including their names, addresses, start blocks, ABI file paths, handlers, and events. This configuration allows for granular control over which contract data is ingested and processed. ```yaml networks: - id: 1 start_block: 0 contracts: - name: Greeter address: - 0x1111111111111111111111111111111111111111 handler: src/EventHandlers.ts events: - event: Transfer(address indexed from, address indexed to, uint256 value) ``` -------------------------------- ### Set Block Range for Data Fetching Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This configuration example demonstrates setting a start and end block for data fetching operations. The end block must be greater than the start block. ```yaml start_block: 10000000 end_block: 20000000 # Must be greater than start_block ``` -------------------------------- ### JavaScript Logging Examples in Envio HyperIndex Handlers Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Demonstrates how to use the context.log object for various logging levels (debug, info, warn, error) within Envio HyperIndex event handlers. It shows basic string logging, logging with exceptions, and structured logging with additional context objects. This code is intended to be run within the Envio handler context. ```javascript context.log.debug( `Processing event with block hash: ${event.blockHash} (debug)`);context.log.info(`Processing event with block hash: ${event.blockHash} (info)`);context.log.warn(`Potential issue with event: ${event.blockHash} (warn)`);context.log.error(`Failed to process event: ${event.blockHash} (error)`);// With exception:context.log.error( `Failed to process event: ${event.blockHash}`, new Error("Error processing event"));// You can also provide an object as the second argument for structured logging:context.log.info("Processing blockchain event", { type: "info", extra: "Additional debugging context", data: { blockHash: event.blockHash },}); ``` -------------------------------- ### Event Handler Registration in HyperIndex LLM Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Shows examples of registering an event handler function in HyperIndex LLM. The handler receives 'event' and 'context' objects for processing blockchain data. It also mentions the 'generated' module for types and the 'pnpm codegen' command. ```javascript ..handler(async ({ event, context }) => { // Your logic here }); ``` ```javascript const { } = require("generated"); ..handler(async ({ event, context }) => { // Your logic here }); ``` ```javascript Handlers...handler(async ({ event, context }) => { // Your logic here }); ``` -------------------------------- ### Initialize a New Indexer Project Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Initializes a new indexer project using the Envio CLI. This command sets up the basic project structure and configuration files required for an indexing project. ```bash envio init ``` -------------------------------- ### Multichain Indexer Configuration (YAML) Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Defines the structure of a `config.yaml` file for multichain indexing. It includes global contract definitions, network-specific configurations with chain IDs and starting blocks, and contract instances referencing global contracts with network-specific addresses. This structure allows for reusable handlers and event definitions across different blockchains. ```yaml # Example structure (simplified) contracts: - name: ExampleContract abi_file_path: ./abis/example-abi.json handler: ./src/EventHandlers.js events: - event: ExampleEvent networks: - id: 1 # Ethereum Mainnet start_block: 0 contracts: - name: ExampleContract address: "0x1234..." - id: 137 # Polygon start_block: 0 contracts: - name: ExampleContract address: "0x5678..." ``` -------------------------------- ### Start Envio Indexer without Code Generation Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Starts the Envio indexer without performing code generation. This command is useful when code generation has already been completed or is not required for the current run. ```bash envio start ``` -------------------------------- ### Initialize Indexer with `pnpx envio init` Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Autogenerate an indexer for a specified contract address by running the envio init command. This process typically involves selecting a blockchain, providing a contract address, and choosing which events to index. ```bash pnpx envio init ``` -------------------------------- ### Handle Fuel Events in a Handler Function Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This JavaScript example demonstrates how to structure a handler function for Fuel events. It shows how to access event parameters, block and transaction information, the source contract address, and the log position. The example also includes storing processed event data using the 'context' object. ```javascript // Example Fuel event handler SwayContract.NewGreeting.handler(async ({ event, context }) => { // Access event parameters const message = event.params.message; // Access block information const blockHeight = event.block.height; const blockTime = event.block.time; const blockId = event.block.id; // Access transaction information const txId = event.transaction.id; // Access source contract address const sourceContract = event.srcAddress; // Access log position const logIndex = event.logIndex; // Store data context.Greeting.set({ id: event.transaction.id, message: message, timestamp: blockTime, }); }); ``` -------------------------------- ### Initialize Envio Project Boilerplate Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Command to generate a boilerplate project structure for Envio. This includes the creation of essential configuration files like `config.yaml` and a basic `schema.graphql` with default handler functions. ```shell npx envio init ``` -------------------------------- ### Update Event Handler Code Migration Example Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This example demonstrates how to migrate event handler code in Envio to accommodate changes in event object field names. It shows the transition from old fields to new fields for various event properties, including data, time, block height, transaction ID, and contract ID. This ensures compatibility with updated Envio versions. ```javascript SwayContract.NewGreeting.handler(async ({ event, context }) => { context.Greeting.set({ - id: event.data.id, - message: event.data.message, - createdAt: event.time, - blockHeight: event.blockHeight, + id: event.params.id, + message: event.params.message, + createdAt: event.block.time, + blockHeight: event.block.height, transaction: event.transaction.id, }); }); ``` -------------------------------- ### Set Console Log Level to Verbose Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Example of how to set the console log level to the most verbose option ('trace') using an environment variable export command. ```shell export LOG_LEVEL="trace" # Set console log level to the most verbose option ``` -------------------------------- ### Deploy Smart Contracts to Local Blockchain Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This command deploys the default smart contracts (or your custom ones) to the locally running blockchain. It's a necessary step before indexing can occur. ```bash cd your-project-name yarn deploy ``` -------------------------------- ### Update Envio Package using npm Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This command updates the Envio package to the latest version locally or globally using npm. Ensure you have npm installed and configured. ```bash pnpm i envio@latest pnpm i -g envio@latest ``` -------------------------------- ### Define DerivedFrom Directive in GraphQL Schema Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This example illustrates the correct usage of the `@derivedFrom` directive in a GraphQL schema. It specifies a field argument to establish a relationship between entities. ```graphql type User { id: ID! orders: [Order!]! @derivedFrom(field: "user") } ``` -------------------------------- ### Initialize Envio Indexer with pnpm Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Initializes a new Envio indexer project in the current directory. Users will be prompted to name the indexer and select a preferred programming language (TypeScript, JavaScript, or ReScript). ```bash pnpm create envio@latest ``` -------------------------------- ### Get or Create Entity using context.Entity.getOrCreate Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Retrieves an entity by its ID, or creates it with default values if it does not exist. This is a shorthand for checking existence and then setting the entity if it's missing. ```javascript const pool = await context.Pool.getOrCreate({ id: poolId, totalValueLockedETH: 0n, });// Which is equivalent to: let pool = await context.Pool.get(poolId); if (!pool) { pool = { id: poolId, totalValueLockedETH: 0n, }; context.Pool.set(pool); } ``` -------------------------------- ### Configure Networks for Indexer Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Configures the blockchain networks on which the indexer is deployed. Each network entry requires an ID, start block, and a list of contract configurations including their names and addresses. ```yaml networks: - id: 1 start_block: 0 contracts: - name: Greeter address: 0x9D02A17dE4E68545d3a58D3a20BbBE0399E05c9c ``` -------------------------------- ### GraphQL Query for Latest Greetings Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete An example GraphQL query to retrieve the latest greetings from the indexed data. It limits results to 10 and orders them by block timestamp in descending order. ```graphql query GetGreetings { Greeting(limit: 10, order_by: { blockTimestamp: desc }) { id user greeting blockNumber blockTimestamp transactionHash } } ``` -------------------------------- ### Rescript/Mocha/Belt Integration Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete This snippet shows how to open namespaces or modules for Rescript, Mocha, and Belt, likely for setting up a testing environment or context. ```rescript open RescriptMocha open Mocha open Belt ``` -------------------------------- ### Importing Test Helpers and Entities Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Demonstrates importing necessary testing utilities and generated entities for use in test files. This includes MockDb, Greeter, Addresses from TestHelpers, and UserEntity. ```typescript const { MockDb, Greeter, Addresses } = TestHelpers; ``` ```typescript const assert = require("assert"); const { UserEntity, TestHelpers } = require("generated"); const { MockDb, Greeter, Addresses } = TestHelpers; ``` -------------------------------- ### Retrieve or Throw Entity using context.Entity.getOrThrow Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Retrieves an entity by its ID or throws an error if it does not exist. This method is available starting from envio@2.22.0. An optional custom error message can be provided. ```javascript const pool = await context.Pool.getOrThrow(poolId);// Will throw: Entity 'Pool' with ID '...' is expected to exist. // Or you can pass a custom message as a second argument: const pool = await context.Pool.getOrThrow( poolId, `Pool with ID ${poolId} is expected.` ); ``` -------------------------------- ### Verify Envio Configuration and Indexer Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Commands to verify the validity of configuration files and ensure the indexer is running correctly. These are essential steps during the migration process from TheGraph to Envio. ```shell pnpm envio codegen pnpm dev ``` -------------------------------- ### Configure HyperIndex to use eRPC Source: https://docs.envio.dev/docs/https:/docs.envio.dev/docs/HyperIndex-LLM/hyperindex-complete Sets up HyperIndex to use the eRPC endpoint for its network connection. This involves specifying the RPC URL pointing to the eRPC service and defining the starting block for indexing. ```yaml networks: - id: 1 rpc_config: url: http://erpc:4000/main/evm/1 # eRPC endpoint for Ethereum Mainnet start_block: 15000000 # Additional network configuration... ```