# Envio docs: HyperIndex examples and tutorials > Example indexers (Uniswap v4, Sablier, Velodrome and Aerodrome) and EVM tutorials. Generated at build time from the pages of https://docs.envio.dev. Each page below is the full markdown of one docs page, after a `` line. Append `.md` to that URL to fetch the page on its own. The index of every page is https://docs.envio.dev/llms.txt. Context files, one per product area: - [llms-hyperindex.txt](https://docs.envio.dev/llms-hyperindex.txt): HyperIndex core, about 47k tokens. Build, run and test an indexer: getting started, config.yaml, schema, handlers, CLI, testing, troubleshooting. - [llms-hyperindex-advanced.txt](https://docs.envio.dev/llms-hyperindex-advanced.txt): HyperIndex advanced features, about 32k tokens. Factories, the Effect API, wildcard indexing, preload, contract state, IPFS, HyperSync and RPC sources, reorgs, WebSockets. - [llms-hyperindex-reference.txt](https://docs.envio.dev/llms-hyperindex-reference.txt): HyperIndex performance and reference, about 27k tokens. Config schema reference, observability, performance tuning, benchmarks, supported chains and licensing. - llms-hyperindex-examples.txt (this file): 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: - How to Index Uniswap v4 Swaps - Sablier streams and airdrops indexer examples - Velodrome and Aerodrome DEX indexer example - How to Index ERC20 Token Transfers - Indexing Optimism Bridge Deposits - Getting Price Data in Your Indexer - Indexing Greeter Contract Using Envio - Scaffold-Eth-2 Envio Extension --- # How to Index Uniswap v4 Swaps > Index Uniswap v4 swaps and pools from the PoolManager singleton with Envio HyperIndex, with a config, schema and handler you can copy, plus the production indexer behind v4.xyz. Uniswap v4 keeps every pool inside one contract. There is no pool contract per pair and no factory to follow, so indexing v4 means indexing a single address, the `PoolManager`, and reading the pool id carried on each event. This page has both routes. Build a minimal indexer yourself, which is the walkthrough below, or start from the [official Uniswap V4 indexer](https://github.com/enviodev/uniswap-v4-indexer), the production implementation that powers [v4.xyz](https://v4.xyz), which is described further down. In a hurry, skip to [the agent prompt](#hand-this-to-your-coding-agent). ## Prerequisites - Node.js 22.15.0 or higher - [Docker](https://www.docker.com/products/docker-desktop/), which `envio dev` uses for Postgres and Hasura - An [API token](https://docs.envio.dev/docs/HyperSync/api-tokens) ## PoolManager addresses Two of the deployments, from [Uniswap's own deployment list](https://github.com/Uniswap/docs/blob/main/content/protocols/v4/deployments.mdx): | Chain | Chain ID | PoolManager | | --- | --- | --- | | Ethereum | 1 | `0x000000000004444c5dc75cB358380D2e3dE08A90` | | Base | 8453 | `0x498581fF718922c3f8e6A244956aF099B2652b2b` | ## Set up ```bash mkdir uniswap-v4-swaps && cd uniswap-v4-swaps pnpm init pnpm pkg set type=module pnpm add envio ``` `config.yaml` ```yaml # yaml-language-server: $schema=./node_modules/envio/evm.schema.json name: uniswap-v4-swaps contracts: - name: PoolManager handler: src/EventHandlers.ts events: - event: "Initialize(bytes32 indexed id, address indexed currency0, address indexed currency1, uint24 fee, int24 tickSpacing, address hooks, uint160 sqrtPriceX96, int24 tick)" - event: "Swap(bytes32 indexed id, address indexed sender, int128 amount0, int128 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint24 fee)" chains: - id: 8453 # Base start_block: 25350000 contracts: - name: PoolManager address: "0x498581fF718922c3f8e6A244956aF099B2652b2b" ``` The signatures come from [`IPoolManager.sol`](https://github.com/Uniswap/v4-core/blob/main/src/interfaces/IPoolManager.sol). Solidity declares `id` as `PoolId`, the currencies as `Currency` and the hook as `IHooks`, which are `bytes32`, `address` and `address` underneath, so that is what the config uses. The `Swap` signature above hashes to `0x40e9cecb9f5f1f1c5b9c97dec2917b7ee92e57ba5563708daca94dd84ad7112f`, which is the topic the PoolManager emits. `schema.graphql` ```graphql type Pool { id: ID! currency0: String! currency1: String! fee: Int! tickSpacing: Int! hooks: String! swapCount: Int! } type Swap { id: ID! pool_id: String! sender: String! amount0: BigInt! amount1: BigInt! tick: Int! blockNumber: Int! blockTimestamp: Int! } ``` `src/EventHandlers.ts` ```typescript import { indexer } from "envio"; indexer.onEvent( { contract: "PoolManager", event: "Initialize" }, async ({ event, context }) => { context.Pool.set({ id: event.params.id, currency0: event.params.currency0, currency1: event.params.currency1, fee: Number(event.params.fee), tickSpacing: Number(event.params.tickSpacing), hooks: event.params.hooks, swapCount: 0, }); }, ); indexer.onEvent( { contract: "PoolManager", event: "Swap" }, async ({ event, context }) => { context.Swap.set({ id: `${event.chainId}_${event.block.number}_${event.logIndex}`, pool_id: event.params.id, sender: event.params.sender, amount0: event.params.amount0, amount1: event.params.amount1, tick: Number(event.params.tick), blockNumber: event.block.number, blockTimestamp: event.block.timestamp, }); const pool = await context.Pool.get(event.params.id); if (pool) { context.Pool.set({ ...pool, swapCount: pool.swapCount + 1 }); } }, ); ``` Every numeric event parameter arrives as a BigInt, including the small ones like `fee`, `tickSpacing` and `tick`. Writing one of those straight into an `Int!` field fails with `cannot cast type bigint to integer[]`, so wrap them in `Number()`, and keep `BigInt!` for the amounts. Put your [API token](https://docs.envio.dev/docs/HyperSync/api-tokens) in a `.env` file in the project root, which is where the indexer reads it from: ```bash ENVIO_API_TOKEN=your_token_here ``` Then start it: ```bash pnpm envio dev ``` ## Querying the result Busiest pools, from the counter the handler keeps: ```graphql query BusiestPools { Pool(limit: 3, order_by: { swapCount: desc }) { id currency0 currency1 fee swapCount } } ``` Indexing Base from block 25,350,000 to 26,418,699 gave 4,344 pools and 750,230 swaps, and the busiest pool came back like this: ```json { "id": "0x7af84d60777413f90cc511a83cf702b128bc885f84d6ca8be4b60063328d907a", "currency0": "0x0000000000000000000000000000000000000000", "currency1": "0x000000000D564D5be76f7f0d28fE52605afC7Cf8", "fee": 0, "swapCount": 159420 } ``` Recent swaps for one pool: ```graphql query PoolSwaps { Swap( where: { pool_id: { _eq: "0x96d4b53a38337a5733179751781178a2613306063c511b78cd02684739288c0a" } } order_by: { blockNumber: desc } limit: 3 ) { sender amount0 amount1 blockNumber } } ``` ```json { "sender": "0x6fF5693b99212Da76ad316178A184AB56D299b43", "amount0": "995365987060141", "amount1": "-2701188", "blockNumber": 26418690 } ``` Amounts are signed and written from the pool's side, so one is negative and the other positive on every swap. ## Reading v4 data - **Native ETH is the zero address.** v4 handles ETH directly rather than through WETH. Currencies are sorted numerically in the pool key, and the zero address sorts first, so a pool that trades ETH always carries it as `currency0` and never as `currency1`. In the run above, 723 of the 4,344 pools had native ETH as `currency0` - **Most pools carry hooks.** `hooks` is the address of the contract attached to the pool, and it is the zero address when there is none. In the same run, 3,107 of the 4,344 pools had one - **`fee` is in millionths**, capped at 1,000,000, so `3000` is 0.30% and `500` is 0.05%. A fee of exactly `0x800000` means the pool sets its fee dynamically, which [`PoolKey.sol`](https://github.com/Uniswap/v4-core/blob/main/src/types/PoolKey.sol) describes as the highest bit being set. A fee of `0` is a pool whose LP fee is zero, which is common where a hook charges instead - **`Swap` carries its own `fee`**, which is the fee taken on that swap rather than the pool's LP fee from `Initialize`. The handler above ignores it, so do not confuse the two if you add it to the schema - **The pool id is a hash**, not an address. `Initialize` is the only event that maps it to the currencies, fee, tick spacing and hook, which is why this indexer stores pools as well as swaps ## Adding more chains Add another entry under `chains` with that chain's id, start block and PoolManager address. The contract and handler are already shared, so nothing else changes. See [multichain indexing](https://docs.envio.dev/docs/HyperIndex/multichain-indexing). ## Hand this to your coding agent ```text Set up an Envio HyperIndex indexer for Uniswap v4 swaps on Base. - pnpm init, pnpm pkg set type=module, pnpm add envio - config.yaml: contract PoolManager at 0x498581fF718922c3f8e6A244956aF099B2652b2b on chain 8453, with the Initialize and Swap event signatures from IPoolManager.sol. PoolId is bytes32, Currency is address and IHooks is address in the signature - schema.graphql: a Pool entity (currencies, fee, tickSpacing, hooks, swapCount) and a Swap entity (pool_id, sender, amount0, amount1, tick, block number and timestamp) - src/EventHandlers.ts: import { indexer } from "envio" and register both events with indexer.onEvent. Wrap fee, tickSpacing and tick in Number(), since every numeric param arrives as a BigInt, and keep the amounts as BigInt - Put ENVIO_API_TOKEN in a .env file in the project root - Run it with pnpm envio dev, which needs Docker Docs: https://docs.envio.dev/docs/HyperIndex/example-uniswap-v4-multi-chain-indexer ``` ## The production indexer The [official Uniswap V4 indexer](https://github.com/enviodev/uniswap-v4-indexer) goes much further than the walkthrough above. It is the same indexer that powers the [v4.xyz](https://v4.xyz) website, providing real-time data for the Uniswap V4 interface. ### Key Features - **Multichain Support**: Indexes Uniswap V4 across the 18 chains listed in its `config.yaml`, in real time - **Complete Pool Metrics**: Tracks pool statistics including volume, TVL, fees, and other critical metrics - **Swap Analysis**: Monitors swap events and liquidity changes with high precision - **Hook Stats**: Tracks every hook with the pools and swaps it touches and its TVL, volume and fees - **Production Ready**: Powers the official v4.xyz interface with production-grade reliability - **Fast Syncing**: HyperIndex reading HyperSync leads most scenarios in our [benchmarks](https://docs.envio.dev/docs/HyperIndex/benchmarks), which run in CI and check each tool's output against ground truth ![V4 gif](https://docs.envio.dev/img/v4.gif) ### Technical Overview This indexer is built using TypeScript and provides a unified GraphQL API for accessing Uniswap V4 data across all supported chains. The architecture is designed to handle high throughput and maintain consistency across different chains. #### Performance Advantages - **Reads from HyperSync rather than RPC**, which is where the speed comes from. The [benchmarks](https://docs.envio.dev/docs/HyperIndex/benchmarks) page has the measured figures per scenario - **Real-time Updates**: Maintains low latency for new blocks while efficiently managing historical data ### Use Cases - Power analytics dashboards and trading interfaces - Monitor DeFi positions and protocol health - Track historical performance of Uniswap V4 pools - Build custom notifications and alerts - Analyze hook interactions and their impact ### Getting Started To use this indexer, you can: 1. Clone the [repository](https://github.com/enviodev/uniswap-v4-indexer) 2. Follow the installation instructions in the README 3. Run the indexer locally or deploy it to a production environment 4. Access indexed data through the GraphQL API ### Contribution The Uniswap V4 indexer is actively maintained and welcomes contributions from the community. If you'd like to contribute or report issues, please visit the [GitHub repository](https://github.com/enviodev/uniswap-v4-indexer). :::note This is an official reference implementation that powers the v4.xyz website. While extensively tested in production, remember to validate the data for your specific use case. The indexer is continuously updated to support the latest Uniswap V4 features and optimizations. ::: --- # Sablier Protocol Indexers > Sablier's official HyperIndex indexers for Lockup and Flow streams and Merkle airdrops across many EVM chains, used in production and useful as reference code. The following blockchain indexers serve as exceptional reference implementations for the Sablier protocol, showcasing professional development practices and efficient multichain data processing. ## Overview [Sablier](https://sablier.com/) is a token streaming protocol that enables real-time finance on the blockchain, allowing tokens to be streamed continuously over time. These official Sablier indexers track streaming activity across many EVM-compatible chains, providing comprehensive data through a unified GraphQL API. ## Professional Indexer Suite Sablier maintains two public indexers, each targeting a specific part of their protocol: ### 1. [Streams Indexer](https://github.com/sablier-labs/indexers/tree/main/envio/streams) Tracks Sablier's payment-stream data across both the Lockup and Flow products. Lockup covers streams with fixed durations and amounts (creation, cancellation, and withdrawal events), while Flow covers open-ended streaming with dynamic flow rates. For more detail, see the [Lockup indexer docs](https://docs.sablier.com/api/lockup/indexers) and the [Flow indexer docs](https://docs.sablier.com/api/flow/indexers). ### 2. [Airdrops Indexer](https://github.com/sablier-labs/indexers/tree/main/envio/airdrops) Tracks Sablier's Merkle airdrop campaigns, which enable efficient batch stream creation using cryptographic proofs. This indexer captures data about campaign creation, claims, and related activity, powering both Airstreams and Instant Airdrops. For more detail, see the [Airdrops indexer docs](https://docs.sablier.com/api/airdrops/indexers). ## Key Features - **Comprehensive Multichain Support**: Indexes data across many EVM-compatible chains - **Professionally Maintained**: Used in production by the Sablier team and their partners - **Extensive Test Coverage**: Includes comprehensive testing to ensure data accuracy - **Optimized Performance**: Implements efficient data processing techniques - **Well-Documented**: Clear code structure with extensive comments - **Backward Compatibility**: Carefully manages schema evolution and contract upgrades - **Cross-chain Architecture**: Envio promotes efficient cross-chain indexing where all chains share the same indexer endpoint ## Best Practices Showcase These blockchain indexers demonstrate several development best practices: - **Modular Code Structure**: Well-organized code with clear separation of concerns - **Consistent Naming Conventions**: Professional and consistent naming throughout - **Efficient Event Handling**: Optimized processing of blockchain events - **Comprehensive Entity Relationships**: Well-designed data model with proper relationships - **Thorough Input Validation**: Robust error handling and input validation - **Detailed Changelogs**: Documentation of breaking changes and migrations - **Preload Optimization**: Envio indexers benefit from always-on [Preload Optimization](https://docs.envio.dev/docs/HyperIndex/preload-optimization), which batches entity reads and runs external calls in parallel through the Effect API ## Getting Started To use these indexers as a reference for your own development: 1. Clone the indexer that matches your needs: - [Streams Indexer](https://github.com/sablier-labs/indexers/tree/main/envio/streams) - [Airdrops Indexer](https://github.com/sablier-labs/indexers/tree/main/envio/airdrops) 2. Review the file structure and implementation patterns 3. Examine the event handlers for efficient data processing techniques 4. Study the schema design for effective entity modeling For complete API documentation and usage examples, see: - [Sablier API Overview](https://docs.sablier.com/api/overview#envio) :::note These are official indexers maintained by the Sablier team and represent production-quality implementations. They serve as an excellent example of professional blockchain indexer development and are regularly updated to support the latest protocol features. ::: --- # Velodrome & Aerodrome DEX Indexer > A reference HyperIndex indexer for Velodrome and Aerodrome that tracks pools, swaps and liquidity across Superchain chains through a single GraphQL API. This blockchain indexer provides a comprehensive implementation for tracking data from the popular Velodrome and Aerodrome decentralized exchanges across multiple chains. ## Overview The [Velodrome & Aerodrome Indexer](https://github.com/enviodev/velodrome-indexer) demonstrates how to: - Create a **multichain indexer** that works across Superchain chains - Index core DEX functionality including pools, swaps, and liquidity positions - Unify data access through a single GraphQL API - Build efficient handlers using TypeScript ## Key Features - Complete tracking of liquidity pools and trading activity - Real-time synchronization across multiple chains - Well-documented codebase suitable as a starting point for similar DEX indexers - Making ad-hoc RPC requests for additional data (use with caution) For implementation details, usage examples, and setup instructions, see the project's [README](https://github.com/enviodev/velodrome-indexer/blob/main/README.md). :::note This indexer was built by Envio partners and community builders and serves as a valuable reference implementation. As with any indexer, perform appropriate testing and data validation before using in production environments. ::: --- # How to Index ERC20 Token Transfers > Index ERC20 token transfers with Envio HyperIndex. Copy the config, schema and handler, run the indexer on Base, and query transfers and balances over GraphQL. ## Introduction This tutorial indexes ERC20 token transfers with Envio HyperIndex, using USDC on Base as the example. You end up with every `Transfer` event in a database, a running total per account, and a GraphQL API over both. There are two ways to get there. Write the three files yourself, which is below and takes a copy and paste, or generate them from the contract address with [contract import](https://docs.envio.dev/docs/HyperIndex/quickstart), which is the rest of the page. ## The short version Three files and a handful of commands. Everything in this section was run against Base before it was written, and the handler keeps a running total per account as well as the raw transfers. ```bash mkdir usdc-base-transfers && cd usdc-base-transfers pnpm init pnpm pkg set type=module pnpm add envio ``` The handlers are ES modules, so `type` has to be set before the indexer will load them. Indexing reads from HyperSync, which needs an [API token](https://docs.envio.dev/docs/HyperSync/api-tokens). Put it in a `.env` file in the project root, or nothing will sync: ```bash ENVIO_API_TOKEN=your_token_here ``` `config.yaml` ```yaml # yaml-language-server: $schema=./node_modules/envio/evm.schema.json name: usdc-base-transfers contracts: - name: USDC handler: src/EventHandlers.ts events: - event: "Transfer(address indexed from, address indexed to, uint256 value)" chains: - id: 8453 # Base start_block: 28000000 contracts: - name: USDC address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" ``` `schema.graphql` ```graphql type Transfer { id: ID! from: String! to: String! value: BigInt! blockNumber: Int! blockTimestamp: Int! } type Account { id: ID! sent: BigInt! received: BigInt! transferCount: Int! } ``` `src/EventHandlers.ts` ```typescript import { indexer } from "envio"; indexer.onEvent( { contract: "USDC", event: "Transfer" }, async ({ event, context }) => { context.Transfer.set({ id: `${event.chainId}_${event.block.number}_${event.logIndex}`, from: event.params.from, to: event.params.to, value: event.params.value, blockNumber: event.block.number, blockTimestamp: event.block.timestamp, }); const sender = await context.Account.get(event.params.from); context.Account.set({ id: event.params.from, sent: (sender?.sent ?? 0n) + event.params.value, received: sender?.received ?? 0n, transferCount: (sender?.transferCount ?? 0) + 1, }); const receiver = await context.Account.get(event.params.to); context.Account.set({ id: event.params.to, sent: receiver?.sent ?? 0n, received: (receiver?.received ?? 0n) + event.params.value, transferCount: (receiver?.transferCount ?? 0) + 1, }); }, ); ``` Then start it: ```bash pnpm envio dev ``` If you have run another indexer on this machine before, run `pnpm envio stop` first so it starts from a clean database. Indexing starts from the block in `config.yaml`, and Hasura opens at [http://localhost:8080](http://localhost:8080) with the password `testing`. ### Querying what you indexed The largest transfers: ```graphql query LargestTransfers { Transfer(limit: 3, order_by: { value: desc }) { from to value blockNumber } } ``` ```json { "from": "0xBBBBBbbBBb9cC5e90e3b3Af64bdAF62C37EEFFCb", "to": "0xadaa772e1EEc300C1bb62D8342b69E8c627172a6", "value": "28060166801788", "blockNumber": 28000952 } ``` USDC has 6 decimals, so that value is about 28.06 million USDC. The accounts that received the most, which comes from the `Account` entity the handler keeps updated: ```graphql query TopReceivers { Account(limit: 3, order_by: { received: desc }) { id received transferCount } } ``` ```json { "id": "0xb2cc224c1c9feE385f8ad6a55b4d94E92359DC59", "received": "2521096268603014", "transferCount": 24430 } ``` An aggregate like that is why you index rather than call an RPC. It is one row, kept current as new transfers arrive. ## Prefer to generate it from the contract? The rest of this page does the same job with `envio init contract-import`, which reads the ABI from a block explorer and writes the three files for you. ## Prerequisites Before starting, ensure you have the following installed: - **[Node.js](https://nodejs.org/en/download/current)** _(22.15.0 or newer, which `envio` requires)_ - **[pnpm](https://pnpm.io/installation)** _(recommended but not required)_ - **[Docker Desktop](https://www.docker.com/products/docker-desktop/)** _(required to run the Envio indexer locally)_ > **Note:** Docker is specifically required to run your blockchain indexer locally. You can skip Docker installation if you plan only to use Envio Cloud. ## Step 1: Initialize Your Indexer `envio init` on its own prints what to do next, aimed at a coding agent as much as a person. With no token set yet it opens with that (trimmed): ```text Welcome to Envio Indexer! Let's set up an indexer that will become a reliable blockchain backend you trust, love, and own. Leave the rest to your favorite agent: 1. ENVIO_API_TOKEN is not set. Ask the user to create one at https://envio.dev/app/api-tokens and provide it to the session before continuing. 2. Prompt the user for the project intent if it is missing from context (what should the indexer track and surface?). 3. Determine the chain, contract, and addresses needed to produce that result. Use web search or block-explorer tool calls when the user hasn't supplied them. 4. To continue, call: pnpx envio init contract-import explorer \ -n ${indexer-name} \ -c ${address} \ -b ${chainId} \ --single-contract \ --all-events \ -d ${directory} ``` Create the token first at [envio.dev/app/api-tokens](https://envio.dev/app/api-tokens) and export it, because contract import refuses to run without one: ```bash export ENVIO_API_TOKEN=your_token_here ``` ## Step 2: Import the USDC Token Contract Fill those in for USDC on Base and run it: ```bash pnpx envio init contract-import explorer \ --name usdc-base-transfer-indexer \ --contract-address 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 \ --blockchain base \ --single-contract \ --all-events \ --directory usdc-base-transfer-indexer ``` The ABI comes from the block explorer, so you only need the address. [View the contract on BaseScan](https://basescan.org/address/0x833589fcd6edb6e08f4c7c32d4f71b54bda02913). Drop `--all-events` to pick events yourself, and `--single-contract` to add more contracts, addresses or chains in the same pass. It finishes with: ```text Your indexer is ready! Pick how you'd like to run it: 1. cd usdc-base-transfer-indexer && pnpm test # run the tests (recommended for AI) 2. cd usdc-base-transfer-indexer && pnpm dev # run locally 3. cd usdc-base-transfer-indexer && pnpm start # run in production ``` ## Step 3: Start Your Indexer 1. Move into the project, and stop any indexer already running there: ```bash cd usdc-base-transfer-indexer pnpm envio stop ``` > **Note:** You can skip this step if this is your first time running an indexer. 2. Start your new indexer: ```bash pnpm dev ``` This command: - Starts the required Docker containers - Sets up your database - Launches the indexing process - Opens the Hasura GraphQL interface ## Step 4: Understanding the Generated Code Contract import writes a whole project, including tests, a `.env` and a git repo. These are the three files you will actually edit, shown here for USDC and trimmed to the `Transfer` event. `config.yaml` holds the chain, the start block, the contract address and the events to index: ```yaml # yaml-language-server: $schema=./node_modules/envio/evm.schema.json name: usdc-base-transfer-indexer disable_default_cross_chain: true chains: - id: 8453 start_block: 0 contracts: - name: FiatTokenProxy address: - "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" events: - event: Transfer(address indexed from, address indexed to, uint256 value) ``` `schema.graphql` holds an entity per event, named after the contract: ```graphql type FiatTokenProxy_Transfer { id: ID! from: String! to: String! value: BigInt! } ``` `src/handlers/FiatTokenProxy.ts` holds a handler per event, writing one row per log: ```typescript import { indexer } from "envio"; import type { FiatTokenProxy_Transfer } from "envio"; indexer.onEvent({ contract: "FiatTokenProxy", event: "Transfer" }, async ({ event, context }) => { const entity: FiatTokenProxy_Transfer = { id: `${event.chainId}_${event.block.number}_${event.logIndex}`, from: event.params.from, to: event.params.to, value: event.params.value, }; context.FiatTokenProxy_Transfer.set(entity); }); ``` The entity name comes from the contract name in `config.yaml`, so renaming the contract renames the entity and the GraphQL field with it. ## Step 5: Exploring Your Indexed Data Now you can interact with your indexed USDC transfer data: ### Accessing Hasura 1. Open Hasura at [http://localhost:8080](http://localhost:8080) 2. When prompted, enter the admin password: `testing` ### Monitoring Indexing Progress Progress lives in two places. The **Data** tab tracks `chain_metadata`, a view with one row per chain, where `latest_processed_block` is how far indexing has reached and `block_height` is the head: ```text chain_id | start_block | block_height | latest_processed_block | num_events_processed ----------+-------------+--------------+------------------------+---------------------- 8453 | 28000000 | 51661447 | 28272195 | 6160136 ``` The numbers above come from the hand written indexer earlier on this page. The `envio_chains` table holds the same thing with different column names, but Hasura does not track it, so read that one from Postgres directly. > **Note:** Thanks to Envio's [HyperSync](https://docs.envio.dev/docs/hypersync), you index from the chain's own data layer rather than paging an RPC node. ### Querying Indexed Events 1. Click the **API** tab 2. Construct a GraphQL query to explore your data Here's an example query to fetch the 10 largest USDC transfers: ```graphql query LargestTransfers { FiatTokenProxy_Transfer(limit: 10, order_by: { value: desc }) { from to value } } ``` 3. Click the **Play** button to execute your query ## Hand this to your coding agent ```text Set up an Envio HyperIndex indexer for ERC20 Transfer events. - pnpm init, pnpm pkg set type=module, pnpm add envio, files config.yaml, schema.graphql, src/EventHandlers.ts - Put ENVIO_API_TOKEN in a .env file in the project root, indexing fails without it - config.yaml: top-level contracts block with the Transfer event signature, then a chains block with the chain id, start_block and the token address - schema.graphql: a Transfer entity, plus an Account entity holding sent, received and transferCount - src/EventHandlers.ts: import { indexer } from "envio" and register with indexer.onEvent({ contract, event }, handler). Read the account with context.Account.get before writing it back with context.Account.set - Run it with pnpm envio dev, which needs Docker Docs: https://docs.envio.dev/docs/HyperIndex/tutorial-erc20-token-transfers ``` ## Common follow-ups ### How do I index more than one token? Add another address under the same contract in `config.yaml`, or a second contract with its own handler. The [configuration file guide](https://docs.envio.dev/docs/HyperIndex/configuration-file) covers both. ### How do I index the same token on several chains? Add another entry to `chains` with that chain's id, start block and token address. One indexer covers them all, see [multichain indexing](https://docs.envio.dev/docs/HyperIndex/multichain-indexing). ### How do I index every ERC20 rather than a list of them? Index the `Transfer` event across all contracts with [wildcard indexing](https://docs.envio.dev/docs/HyperIndex/wildcard-indexing), or register tokens as they are deployed with [dynamic contracts](https://docs.envio.dev/docs/HyperIndex/dynamic-contracts). ### How do I get balances rather than transfers? Keep the running total in the handler, as the `Account` entity above does. Reading a balance then becomes one row rather than a call per holder. ## Conclusion You now have an indexer for USDC transfers on Base, either written by hand or generated from the contract, with a GraphQL API over the results. ### What You've Learned - How to initialize an indexer using Envio's contract import feature - How to index ERC20 token transfers on the Base chain - How to query and analyze token transfer data using GraphQL ### Next Steps - Try customizing the event handlers to add additional logic - Create aggregated statistics about token transfers - Add more tokens or events to your indexer - Deploy your indexer to Envio Cloud For more tutorials and advanced features, see the [documentation](https://docs.envio.dev). --- # Indexing Optimism Bridge Deposits > Learn to quickly index Optimism Bridge deposits and explore OP Bridge event data. ## Introduction This tutorial will guide you through indexing Optimism Standard Bridge deposits in under 5 minutes using Envio HyperIndex's no-code [contract import](https://docs.envio.dev/docs/HyperIndex/quickstart) feature. The Optimism Standard Bridge enables the movement of ETH and ERC-20 tokens between Ethereum and Optimism. We'll index bridge deposit events by extracting `DepositFinalized` logs on Optimism and `ETHDepositInitiated` logs on Ethereum Mainnet. [Video](https://www.youtube.com/watch?v=9U2MTFU9or0) ## Prerequisites Before starting, ensure you have the following installed: - **[Node.js](https://nodejs.org/en/download/current)** _(22.15.0 or newer)_ - **[pnpm](https://pnpm.io/installation)** _(recommended but not required)_ - **[Docker Desktop](https://www.docker.com/products/docker-desktop/)** _(required to run the Envio indexer locally)_ > **Note:** Docker is specifically required to run your blockchain indexer locally. You can skip Docker installation if you plan only to use Envio Cloud. ## Step 1: Initialize Your Indexer 1. Open your terminal in an empty directory and run: ```bash pnpx envio init ``` 2. Enter a folder name for your indexer (we'll use "optimism-bridge-indexer" in this example). The indexer takes its name from the folder. ``` ? Specify a folder name (ENTER to skip): (.) optimism-bridge-indexer ``` The indexer is generated in TypeScript by default. ## Step 2: Import the Optimism Bridge Contract 1. Select **Evm** → **From Address - Lookup ABI from block explorer** → **optimism** (type to filter the chain list) 2. Enter the Optimism bridge contract address: ``` 0x4200000000000000000000000000000000000010 ``` [View on Optimistic Etherscan](https://optimistic.etherscan.io/address/0x4200000000000000000000000000000000000010) 3. Select only the `DepositFinalized` event. All events start selected, so: - Press ← to clear all - Move to `DepositFinalized` with the arrow keys (↑↓) - Press spacebar to select it, then Enter > **Tip:** You can select multiple events to index simultaneously. ## Step 3: Add the Ethereum Mainnet Bridge Contract 1. When prompted, select **Add a new contract (with a different ABI)** 2. Choose **Block Explorer** → **ethereum-mainnet** 3. Enter the Ethereum Mainnet gateway contract address: ``` 0x99C9fc46f92E8a1c0deC1b1747d010903E884bE1 ``` [View on Etherscan](https://etherscan.io/address/0x99C9fc46f92E8a1c0deC1b1747d010903E884bE1) 4. Select only the `ETHDepositInitiated` event (press ← to clear all, then space on `ETHDepositInitiated`, then Enter) 5. When finished adding contracts, select **I'm finished** 6. Add your Envio API token. Pick **Create a new API token** to open the token page, or **Add an existing API token**, then paste it at the `? Add your API token:` prompt: ``` ? Add an Envio API token to your .env file? > Create a new API token (Opens https://envio.dev/app/api-tokens) Add an existing API token ``` ## Step 4: Start Your Indexer 1. If you have any running indexers, stop them first: ```bash pnpm envio stop ``` 2. Start your new indexer: ```bash pnpm dev ``` This command: - Starts the required Docker containers - Sets up your database - Launches the indexing process - Opens the Hasura GraphQL interface ## Step 5: Understanding the Generated Code Let's examine the key files that Envio generated: ### 1. `config.yaml` This configuration file defines: - Chains to index (Optimism and Ethereum Mainnet) - Starting blocks for each chain - Contract addresses and ABIs - Events to track ```yaml title="config.yaml" # yaml-language-server: $schema=./node_modules/envio/evm.schema.json name: optimism-bridge-indexer disable_default_cross_chain: true chains: - id: 1 start_block: 0 contracts: - name: L1ChugSplashProxy address: - "0x99C9fc46f92E8a1c0deC1b1747d010903E884bE1" events: - event: ETHDepositInitiated(address indexed from, address indexed to, uint256 amount, bytes extraData) - id: 10 start_block: 0 contracts: - name: Proxy address: - "0x4200000000000000000000000000000000000010" events: - event: DepositFinalized(address indexed l1Token, address indexed l2Token, address indexed from, address to, uint256 amount, bytes extraData) ``` ### 2. `schema.graphql` This schema defines the data structures for our selected events: - Entity types based on event data - Field types matching the event parameters - Relationships between entities (if applicable) ```graphql title="schema.graphql" type L1ChugSplashProxy_ETHDepositInitiated { id: ID! from: String! to: String! amount: BigInt! extraData: String! } type Proxy_DepositFinalized { id: ID! l1Token: String! l2Token: String! from: String! to: String! amount: BigInt! extraData: String! } ``` ### 3. `src/handlers` This folder has one file per contract (`Proxy.ts` and `L1ChugSplashProxy.ts`) containing the business logic for processing events: - Functions that execute when events are detected - Data transformation and storage logic - Entity creation and relationship management ```typescript title="src/handlers/Proxy.ts" /* * Please refer to https://docs.envio.dev for a thorough guide on all Envio indexer features */ import { indexer } from "envio"; import type { Proxy_DepositFinalized, } from "envio"; indexer.onEvent({ contract: "Proxy", event: "DepositFinalized" }, async ({ event, context }) => { const entity: Proxy_DepositFinalized = { id: `${event.chainId}_${event.block.number}_${event.logIndex}`, l1Token: event.params.l1Token, l2Token: event.params.l2Token, from: event.params.from, to: event.params.to, amount: event.params.amount, extraData: event.params.extraData, }; context.Proxy_DepositFinalized.set(entity); }); ``` ## Step 6: Exploring Your Indexed Data Now you can interact with your indexed data: ### Accessing Hasura 1. Open Hasura at [http://localhost:8080](http://localhost:8080) 2. When prompted, enter the admin password: `testing` ### Monitoring Indexing Progress In the **API** tab, run this query to see which blocks each chain has processed: ```graphql query IndexingProgress { _meta { chainId progressBlock sourceBlock eventsProcessed isReady } } ``` > **Note:** Thanks to Envio's [HyperSync](https://docs.envio.dev/docs/hypersync), indexing happens significantly faster than with standard RPC methods. ### Querying Indexed Events 1. Click the **API** tab 2. Construct a GraphQL query to explore your data Entity names follow the `_` pattern. The block explorer names the Optimism contract `Proxy` and the Ethereum Mainnet contract `L1ChugSplashProxy`, so the tables are `Proxy_DepositFinalized` and `L1ChugSplashProxy_ETHDepositInitiated`. Here's an example query to fetch the 10 largest bridge deposits: ```graphql query LargestDeposits { Proxy_DepositFinalized(limit: 10, order_by: { amount: desc }) { l1Token l2Token from to amount } } ``` 3. Click the **Play** button to execute your query ## Conclusion Congratulations! You've successfully created an indexer for Optimism Bridge deposits across both Ethereum and Optimism. ### What You've Learned - How to initialize a multi-network indexer using Envio - How to import contracts from different blockchains - How to query and explore indexed blockchain data ### Next Steps - Try customizing the event handlers to add additional logic - Create relationships between events on different networks - Deploy your indexer to Envio Cloud For more tutorials and advanced features, check out our [documentation](https://docs.envio.dev) or watch our [video walkthroughs](https://www.youtube.com/watch?v=9U2MTFU9or0) on YouTube. --- # Getting Price Data in Your Indexer > Learn how to fetch and integrate token price data in your indexer using oracles, DEX pools, and APIs. ## Introduction Many blockchain applications require price data to calculate values such as: - Historical token transfer values in USD - Total value locked (TVL) in DeFi protocols over time - Portfolio valuations at specific points in time This tutorial explores three different approaches to incorporating price data into your Envio indexer, using a real-world example of tracking ETH deposits into a Uniswap V3 liquidity pool on the Blast blockchain. > **TL;DR:** The complete code for this tutorial is available in [this GitHub repository](https://github.com/enviodev/price-data). ## What You'll Learn In this tutorial, you'll: - Compare three different methods for accessing token price data - Analyze the tradeoffs between accuracy, decentralization, and performance - Implement a multi-source price feed in an Envio indexer - Build a practical example indexing Uniswap V3 liquidity events with price context ## Price Data Methods Compared There are three primary methods to access price data within your indexer: | Method | Description | Speed | Accuracy | Decentralization | | --- | --- | --- | --- | --- | | Oracles | On-chain price feeds (e.g., API3, Chainlink) | Fast | Medium | Medium | | DEX Pools | Swap events from decentralized exchanges | Fast | Medium-High | High | | Off-chain APIs | External services (e.g., CoinGecko) | Slow | High | Low | Let's explore each method in detail. ## Method 1: Using Oracle Price Feeds Oracle networks provide on-chain price data through specialized smart contracts. For this tutorial, we'll use [API3](https://api3.org/) price feeds on Blast. ### How Oracles Work Oracle services like API3 maintain a network of data providers that push price updates to on-chain contracts. These updates typically occur: - At regular time intervals - When price deviations exceed a predefined threshold (e.g., 1%) - When manually triggered by network participants ### Finding the Right Oracle Feed To locate the ETH/USD price feed using API3 on Blast: 1. Identify the API3 contract address: [`0x709944a48cAf83535e43471680fDA4905FB3920a`](https://blastscan.io/address/0x709944a48cAf83535e43471680fDA4905FB3920a) 2. Find the data feed ID for ETH/USD: - The dAPI name "ETH/USD" as bytes32: `0x4554482f55534400000000000000000000000000000000000000000000000000` - Using the [`dapiNameToDataFeedId`](https://blastscan.io/address/0x709944a48cAf83535e43471680fDA4905FB3920a#readContract#F8) function, this maps to `0x3efb3990846102448c3ee2e47d22f1e5433cd45fa56901abe7ab3ffa054f70b5` 3. Monitor the `UpdatedBeaconSetWithBeacons` events with this data feed ID to get price updates > **Note:** API3 later moved ETH/USD on Blast to new data feed IDs, and stopped publishing it on Blast in May 2026. This feed ID stops updating after block 11,692,092 (November 2024), so the oracle price stays flat after that block. The same approach works on any chain where an API3 feed is live: look up the current data feed ID with `dapiNameToDataFeedId` before you index. ### Oracle Advantages and Limitations **Advantages:** - Fast indexing (no external API calls required) - Moderate decentralization - Generally reliable data **Limitations:** - Updates only on significant price changes - Limited token coverage (mainly high-liquidity pairs) - Minor accuracy tradeoffs ## Method 2: Using DEX Pool Swap Events Decentralized exchanges like Uniswap provide price data through swap events. We'll use the USDB/WETH pool on Blast to derive ETH pricing. ### Locating the Right DEX Pool First, we need to find the specific Uniswap V3 pool for USDB/WETH: ```typescript import { createPublicClient, http, parseAbi, getContract } from "viem"; import { blast } from "viem/chains"; const usdb = "0x4300000000000000000000000000000000000003"; const weth = "0x4300000000000000000000000000000000000004"; const factoryAddress = "0x792edAdE80af5fC680d96a2eD80A44247D2Cf6Fd"; const factoryAbi = parseAbi([ "function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool)", ]); const providerUrl = "https://rpc.blast.io"; const poolBips = 3000; // 0.3%. This is measured in hundredths of a bip const client = createPublicClient({ chain: blast, transport: http(providerUrl), }); const factoryContract = getContract({ abi: factoryAbi, address: factoryAddress, client: client, }); (async () => { const poolAddress = await factoryContract.read.getPool([ usdb, weth, poolBips, ]); console.log(poolAddress); })(); ``` > **Tip:** You can also manually find the pool address using the [`getPool`](https://blastscan.io/address/0x792edAdE80af5fC680d96a2eD80A44247D2Cf6Fd#readContract#F2) function on a block explorer. Running this code reveals the USDB/WETH pool is at [`0xf52B4b69123CbcF07798AE8265642793b2E8990C`](https://blastscan.io/address/0xf52B4b69123CbcF07798AE8265642793b2E8990C). ### Getting Price Data From Swap Events Uniswap V3 emits `Swap` events containing price information in the `sqrtPriceX96` field. To convert this to a price, we'll use a formula in our event handler. ### DEX Advantages and Limitations **Advantages:** - Very decentralized - High update frequency - Wide token coverage **Limitations:** - Susceptible to price impact and manipulation (especially in low-liquidity pools) - Requires extra calculations to derive prices - May require multiple pools for cross-pair calculations ## Method 3: Using Off-chain APIs External price APIs like [CoinGecko](https://www.coingecko.com/en/api) provide comprehensive token price data but require HTTP calls from your indexer. ### Making API Requests Here's an effect that fetches historical ETH prices from CoinGecko. Save it as `src/handlers/request.ts`: ```typescript title="src/handlers/request.ts" import { createEffect, S } from "envio"; const COIN_GECKO_API_KEY = process.env.COIN_GECKO_API_KEY; // Convert a unix timestamp to the dd-mm-yyyy date format CoinGecko expects export function unixToDate(unix: number): string { return new Date(unix * 1000) .toISOString() .slice(0, 10) .split("-") .reverse() .join("-"); } export const getEthPrice = createEffect( { name: "getEthPrice", input: S.string, // date as dd-mm-yyyy output: S.nullable(S.number), rateLimit: { calls: 5, per: "minute", }, cache: true, }, async ({ input: date, context }) => { try { const res = await fetch( `https://api.coingecko.com/api/v3/coins/ethereum/history?date=${date}&localization=false`, { headers: { accept: "application/json", ...(COIN_GECKO_API_KEY ? { "x-cg-demo-api-key": COIN_GECKO_API_KEY } : {}), }, } ); const data: any = await res.json(); const usdPrice = data?.market_data?.current_price?.usd; if (typeof usdPrice !== "number") { throw new Error(`HTTP ${res.status}: ${JSON.stringify(data).slice(0, 200)}`); } context.log.info(`ETH price on ${date}: ${usdPrice}`); return usdPrice; } catch (err) { context.log.error(`Failed to fetch ETH price for ${date}: ${err}`); // Don't cache failed responses so they are retried on the next run context.cache = false; return null; } } ); ``` The call is wrapped in the [Effect API](https://docs.envio.dev/docs/HyperIndex/effect-api), so each date is fetched once and cached, and the rate limit keeps you inside CoinGecko's free tier. Add your CoinGecko key to `.env` as `COIN_GECKO_API_KEY=`. > **Note:** The free CoinGecko API only provides daily price data (at 00:00 UTC), not block-by-block precision, and only returns history for the past 365 days. For older blocks or production use, consider a paid API with more granular historical data. ### Off-chain API Advantages and Limitations **Advantages:** - Highest accuracy (with paid APIs) - Most comprehensive token coverage - No susceptibility to on-chain manipulation **Limitations:** - Significantly slows indexing speed due to API calls - Centralized data source - May require paid subscriptions for full functionality ## Building a Multi-Source Price Feed Indexer Now let's build an indexer that compares all three methods when tracking Uniswap V3 liquidity pool deposits. ### Step 1: Initialize Your Indexer Create a new Envio indexer project from the Greeter template, then remove the template's Greeter handler and test, since this tutorial replaces them. The init command needs an Envio API token, so create one at [envio.dev/app/api-tokens](https://envio.dev/app/api-tokens) and export it first, or pass `--api-token `. ```bash export ENVIO_API_TOKEN=your_token_here pnpx envio init template -t greeter -l typescript -n envio-indexer -d envio-indexer cd envio-indexer rm src/handlers/Greeter.ts src/indexer.test.ts ``` ### Step 2: Configure Your Indexer Edit your `config.yaml` file to track both the API3 oracle and the Uniswap V3 pool: ```yaml # yaml-language-server: $schema=./node_modules/envio/evm.schema.json name: envio-indexer chains: - id: 81457 start_block: 11000000 contracts: - name: Api3ServerV1 address: - "0x709944a48cAf83535e43471680fDA4905FB3920a" events: - event: UpdatedBeaconSetWithBeacons(bytes32 indexed beaconSetId, int224 value, uint32 timestamp) - name: UniswapV3Pool address: - "0xf52B4b69123CbcF07798AE8265642793b2E8990C" 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" ``` > **Important:** The `field_selection` section is needed to include transaction hashes in your indexed data. ### Step 3: Define Your Schema Create a schema that captures price data from all three sources: ```graphql type OraclePoolPrice { id: ID! value: BigInt! timestamp: BigInt! block: Int! } type UniswapV3PoolPrice { id: ID! sqrtPriceX96: BigInt! timestamp: Int! block: Int! } type EthDeposited { id: ID! timestamp: Int! block: Int! oraclePrice: Float! poolPrice: Float! offChainPrice: Float! offchainOracleDiff: Float! depositedPool: Float! depositedOffchain: Float! depositedOracle: Float! txHash: String! } ``` ### Step 4: Implement Event Handlers Create event handlers to process data from all three sources. Save them as `src/handlers/EventHandlers.ts`: ```typescript title="src/handlers/EventHandlers.ts" import { indexer, type Entity } from "envio"; import { getEthPrice, unixToDate } from "./request"; let latestOraclePrice = 0; let latestPoolPrice = 0; indexer.onEvent( { contract: "Api3ServerV1", event: "UpdatedBeaconSetWithBeacons" }, async ({ event, context }) => { // Handlers run twice (preload, then processing). Only update the // module-level price in the processing run, which follows on-chain order. if (context.isPreload) return; // Filter out the beacon set for the ETH/USD price if ( event.params.beaconSetId != "0x3efb3990846102448c3ee2e47d22f1e5433cd45fa56901abe7ab3ffa054f70b5" ) { return; } const entity: Entity<"OraclePoolPrice"> = { id: `${event.chainId}-${event.block.number}-${event.logIndex}`, value: event.params.value, timestamp: event.params.timestamp, block: event.block.number, }; latestOraclePrice = Number(event.params.value) / Number(10 ** 18); context.OraclePoolPrice.set(entity); }, ); indexer.onEvent( { contract: "UniswapV3Pool", event: "Swap" }, async ({ event, context }) => { if (context.isPreload) return; const entity: Entity<"UniswapV3PoolPrice"> = { id: `${event.chainId}-${event.block.number}-${event.logIndex}`, sqrtPriceX96: event.params.sqrtPriceX96, timestamp: event.block.timestamp, block: event.block.number, }; latestPoolPrice = Number( (2n ** 192n) / (BigInt(event.params.sqrtPriceX96) * BigInt(event.params.sqrtPriceX96)) ); context.UniswapV3PoolPrice.set(entity); }, ); indexer.onEvent( { contract: "UniswapV3Pool", event: "Mint" }, async ({ event, context }) => { const offChainPrice = (await context.effect(getEthPrice, unixToDate(event.block.timestamp))) ?? NaN; const ethDepositedUsdPool = (latestPoolPrice * Number(event.params.amount1)) / 10 ** 18; const ethDepositedUsdOffchain = (offChainPrice * Number(event.params.amount1)) / 10 ** 18; const ethDepositedUsdOracle = (latestOraclePrice * Number(event.params.amount1)) / 10 ** 18; const ethDeposited: Entity<"EthDeposited"> = { id: `${event.chainId}-${event.block.number}-${event.logIndex}`, timestamp: event.block.timestamp, block: event.block.number, oraclePrice: round(latestOraclePrice), poolPrice: round(latestPoolPrice), offChainPrice: round(offChainPrice), depositedPool: round(ethDepositedUsdPool), depositedOffchain: round(ethDepositedUsdOffchain), depositedOracle: round(ethDepositedUsdOracle), offchainOracleDiff: round( ((ethDepositedUsdOffchain - ethDepositedUsdOracle) / ethDepositedUsdOffchain) * 100 ), txHash: event.transaction.hash, }; context.EthDeposited.set(ethDeposited); }, ); function round(value: number) { return Math.round(value * 100) / 100; } ``` ### Step 5: Run Your Indexer Start your indexer with: ```bash pnpm dev ``` This will begin indexing data from block 11,000,000 on Blast. ### Step 6: Analyze the Results After running your indexer, you can query the data in Hasura to compare the three price data sources: ```graphql query ComparePrices { EthDeposited(order_by: { block: desc }, limit: 10) { block timestamp oraclePrice poolPrice offChainPrice depositedPool depositedOffchain depositedOracle offchainOracleDiff txHash } } ``` ## Results Analysis When comparing our three price data sources in our original run, we found: ![Table of indexer results](https://docs.envio.dev/assets/images/image-6c1e35503e3d7c97eb008482bf735877.png) Looking at the `offchainOracleDiff` column, we can see that oracle and off-chain prices typically align closely but can deviate by as much as 17.98% in some cases. For the highlighted transaction ([0xe7e79ddf29ed2f0ea8cb5bb4ffdab1ea23d0a3a0a57cacfa875f0d15768ba37d](https://blastscan.io/tx/0xe7e79ddf29ed2f0ea8cb5bb4ffdab1ea23d0a3a0a57cacfa875f0d15768ba37d)), we can compare our calculated values: - **Actual value** (from block explorer): $2,358.27 - **DEX pool value** (`depositedPool`): $2,117.07 - **Off-chain API value** (`depositedOffchain`): $2,156.15 This demonstrates that even the most accurate methods have limitations. ## Conclusion: Choosing the Right Method Based on our analysis, here are some recommendations for choosing a price data method: ### Use Oracle or DEX Pools when: - Indexing speed is critical - Absolute precision isn't required - You're working with high-liquidity tokens ### Use Off-chain APIs when: - Price accuracy is paramount - Indexing speed is less important - You can implement effective caching ### For maximum accuracy while maintaining performance: - Combine multiple methods and aggregate results - Use high-volume DEX pools on major chains - Cache API results to avoid redundant calls ## Next Steps To further enhance your price data indexing: 1. **Implement caching** for off-chain API calls 2. **Cross-reference multiple DEX pools** for better accuracy 3. **Consider time-weighted average prices (TWAP)** instead of spot prices 4. **Use multichain indexing** to access higher-liquidity pools on major chains By carefully choosing and implementing the right price data strategy, you can build robust indexers that provide accurate financial data for your blockchain applications. --- # Indexing Greeter Contract Using Envio > Learn how to build and run a multi-chain indexer that tracks Greeter contract events using Envio. ## Introduction This tutorial provides a step-by-step guide to indexing a simple Greeter smart contract deployed on multiple blockchains. You'll learn how to set up and run a multichain indexer using Envio's template system. ### What is the Greeter Contract? The [Greeter contract](https://github.com/Float-Capital/hardhat-template) is a straightforward smart contract that allows users to store greeting messages on the blockchain. For this tutorial, we'll be indexing instances of this contract deployed on both **Polygon** and **Linea**. ### What You'll Build By the end of this tutorial, you'll have: - A functioning multichain indexer that tracks greeting events - The ability to query these events through a GraphQL endpoint - Experience with Envio's core indexing functionality ## Prerequisites Before starting, ensure you have the following installed: - **[Node.js](https://nodejs.org/en/download/current)** _(v22.15.0 or newer required)_ - **[pnpm](https://pnpm.io/installation)** _(recommended but not required)_ - **[Docker Desktop](https://www.docker.com/products/docker-desktop/)** _(required to run the Envio indexer locally)_ > **Note:** Docker is specifically required to run your blockchain indexer locally. You can skip Docker installation if you plan only to use Envio Cloud. ## Step 1: Initialize Your Project First, let's create a new project using Envio's Greeter template: 1. Open your terminal and run: ```bash pnpx envio init ``` 2. When prompted for a folder name, press Enter to use the current directory or type another path: ``` ? Specify a folder name (ENTER to skip): (.) ``` 3. Choose the **Evm** ecosystem: ``` ? Choose blockchain ecosystem > Evm Svm Fuel ``` 4. Select the **Greeter** template: ``` ? Choose an initialization option From Address - Lookup ABI from block explorer From ABI File - Use your own ABI file Template: ERC20 > Template: Greeter Feature: External Calls Feature: Factory Contract ``` 5. Add your Envio API token. Pick **Create a new API token** to open the token page, or **Add an existing API token**, then paste it at the `? Add your API token:` prompt: ``` ? Add an Envio API token to your .env file? > Create a new API token (Opens https://envio.dev/app/api-tokens) Add an existing API token ``` After completing these steps, Envio will generate all the necessary files for your indexer project, with event handlers in TypeScript. If you are running this through an AI agent or a script, skip the prompts with the non-interactive equivalent. It needs an Envio API token, so create one at [envio.dev/app/api-tokens](https://envio.dev/app/api-tokens) and export it first, or pass `--api-token `. ```bash export ENVIO_API_TOKEN=your_token_here pnpx envio init template -t greeter -l typescript -d . ``` ## Step 2: Understanding the Generated Files Let's examine the key files that were created: ### `config.yaml` This configuration file defines which chains and contracts to index: ```yaml # Partial example chains: - id: 137 # Polygon # ... Polygon chain settings contracts: - name: Greeter address: "0x9D02A17dE4E68545d3a58D3a20BbBE0399E05c9c" # ... contract settings - id: 59144 # Linea # ... Linea chain settings contracts: - name: Greeter address: "0xdEe21B97AB77a16B4b236F952e586cf8408CF32A" # ... contract settings ``` ### `schema.graphql` This schema defines the data structures for the indexed events: ```graphql type User { id: ID! greetings: [String!]! latestGreeting: String! numberOfGreetings: Int! } ``` ### `src/handlers/Greeter.ts` This file contains the logic to process events emitted by the Greeter contract. ## Step 3: Start Your Indexer > **Important:** Make sure Docker Desktop is running before proceeding. 1. Start the indexer with: ```bash pnpm dev ``` This command: - Launches Docker containers for the database and Hasura - Sets up your local development environment - Begins indexing data from the specified contracts - Opens a terminal UI to monitor indexing progress The indexer will retrieve data from both Polygon and Linea blockchains, starting from the blocks specified in your `config.yaml` file. ## Step 4: Interact with the Contracts To see your indexer in action, you can write new greetings to the blockchain: ### For Polygon: 1. Visit the contract on [Polygonscan](https://polygonscan.com/address/0x9D02A17dE4E68545d3a58D3a20BbBE0399E05c9c#writeContract) 2. Connect your wallet 3. Use the `setGreeting` function to write a new greeting 4. Submit the transaction ### For Linea: 1. Visit the contract on [Lineascan](https://lineascan.build/address/0xdEe21B97AB77a16B4b236F952e586cf8408CF32A#writeContract) 2. Connect your wallet 3. Use the `setGreeting` function to write a new greeting 4. Submit the transaction Since this is a multichain example, you can interact with both contracts to see how Envio handles data from different blockchains simultaneously. ## Step 5: Query the Indexed Data Now you can explore the data your indexer has captured: 1. Open Hasura at [http://localhost:8080](http://localhost:8080) 2. When prompted for authentication, use the password: `testing` 3. Navigate to the **Data** tab to browse the database tables 4. Or use the **API** tab to write GraphQL queries ### Example Query Try this query to see the users with the most greetings: ```graphql query GetUsers { User(limit: 10, order_by: { numberOfGreetings: desc }) { id chainId latestGreeting numberOfGreetings greetings } } ``` ## Step 6: Deploy to Production (Optional) When you're ready to move from local development to production: 1. Visit [Envio Cloud](https://envio.dev/app/login) 2. Follow the steps to deploy your indexer 3. Get a production GraphQL endpoint for your application For detailed deployment instructions, see the [Envio Cloud documentation](https://docs.envio.dev/docs/HyperIndex/hosted-service.md). ## What You've Learned By completing this tutorial, you've learned: - How to initialize an Envio project from a template - How indexers process data from multiple blockchains - How to query indexed data using GraphQL - The basic structure of an Envio indexing project ## Next Steps Now that you've mastered the basics, you can: - Try the [Contract Import](https://docs.envio.dev/docs/HyperIndex/quickstart.md) feature to index any deployed contract - Customize the event handlers to implement more complex indexing logic - Add relationships between entities in your schema - Explore [Preload Optimization](https://docs.envio.dev/docs/HyperIndex/preload-optimization.md) for faster handlers - Create aggregated statistics from your indexed data For more tutorials and examples, visit the [Envio Documentation](https://docs.envio.dev/) or join our [Discord community](https://discord.gg/envio) for support. --- # Scaffold-Eth-2 Envio Extension > Scaffold-ETH Extension: Get a boilerplate indexer for your deployed smart contracts and start tracking events instantly. ## Introduction The [Scaffold-ETH 2](https://scaffoldeth.io/extensions) Envio extension makes indexing your deployed smart contracts as simple as possible. Generate a boilerplate indexer for your deployed contracts with a single click and start indexing their events immediately. With this extension, you get: - 🔍 **Automatic indexer generation** from your deployed contracts - 📊 **Status dashboard** with links to Envio metrics and database - 🔄 **One-click regeneration** to update the indexer when you deploy new contracts - 📈 **GraphQL API** for querying your indexed blockchain data ## Prerequisites Before starting, ensure you have the following installed: - **[Node.js v22](https://nodejs.org/en/download)** _(v22.15.0 or newer required)_ - **[pnpm](https://pnpm.io/installation)** _(for the Envio indexer; install it standalone, for example `npm install -g pnpm`, not through `corepack enable`, because the Scaffold-ETH root pins Yarn)_ - **[Docker Desktop](https://www.docker.com/products/docker-desktop/)** _(required to run the Envio indexer locally)_ - **[Yarn](https://yarnpkg.com/getting-started/install)** _(for Scaffold-ETH; enable it with `corepack enable yarn`)_ ## Step 1: Create a New Scaffold-ETH 2 Project with Envio Extension To create a new Scaffold-ETH 2 project with the Envio extension already integrated: ```bash npx create-eth@latest -e enviodev/scaffold-eth-2-extension ``` The CLI asks for a project name and a Solidity framework (Hardhat or Foundry). The steps below use the project name you choose. ## Step 2: Start the Local Blockchain Navigate to your project directory and start the local blockchain: ```bash cd your-project-name yarn chain ``` This will start a local blockchain node for development. ## Step 3: Deploy Your Contracts In a new terminal window, navigate to your project directory and deploy the default smart contracts: ```bash cd your-project-name yarn deploy ``` This will deploy the default contracts to the local blockchain. This step is optional and can also be done once you've created your own smart contracts and deployed them using `yarn deploy`. ## Step 4: Start Scaffold-ETH Frontend From your project directory, start the Scaffold-ETH frontend: ```bash yarn start ``` This will start the Scaffold-ETH frontend at `http://localhost:3000`. ## Step 5: Generate the Indexer Navigate to the Envio page in your Scaffold-ETH frontend at `http://localhost:3000/envio` and click the **"Generate"** button. This should only be done once you've created a smart contract and ran `yarn deploy`. This will create the boilerplate indexer from your deployed contracts. ![Scaffold-ETH 2 Envio Dashboard](https://docs.envio.dev/img/scaffold-eth-2-envio-page.png) The Envio page also includes a helpful "How to Use" section with step-by-step instructions. ## Step 6: Start the Indexer Navigate to the Envio package directory and start the indexer: ```bash cd packages/envio pnpm dev ``` This will begin indexing your contract events. ## Regenerating the Indexer When you deploy new contracts or make changes to existing ones, you'll need to regenerate the indexer: ### Via Frontend Dashboard 1. Go to the Envio page at `http://localhost:3000/envio` 2. Click "Generate" to regenerate the boilerplate indexer ### Via Command Line ```bash cd packages/envio pnpm run update ``` > **Note:** Regenerating will overwrite any custom handlers, config, and schema changes, creating a fresh boilerplate indexer based on your deployed contracts. After regenerating, you'll need to stop the running indexer (Ctrl+C) and restart it with `pnpm dev` for the changes to take effect. ---