> For the complete documentation index, see [llms.txt](https://docs.envio.dev/llms.txt).

# Transaction Handlers

Run logic on transactions, whether or not they emit a log.

---

Some activity never shows up in event logs, such as a plain native token transfer from a wallet, a call to a contract that logs nothing, or a reverted call. `indexer.onTransaction` runs your handler on every mined transaction that matches its filter, so you can index that activity too.

It works on EVM chains. If `indexer.onTransaction` isn't available in your project, even one you've just created, upgrade `envio` by running these from the project root:

```bash
pnpm add envio@^3.19.0
pnpm envio skills update
```

The second command refreshes the project's [agent skills](/docs/HyperIndex/quickstart-with-ai#skills-for-your-agent), replacing any edits you made to the ones Envio ships. Skills from older versions can tell your coding assistant that `onTransaction` doesn't exist.

## Track a wallet's transactions

This example records every transaction a wallet sends, including the reverted ones. A transaction handler needs no contract in `config.yaml`, only the chain:

```yaml title="config.yaml"
name: wallet-activity
chains:
  - id: 1
    start_block: 20000000
```

Add an entity to hold each transaction:

```graphql title="schema.graphql"
type WalletTransaction {
  id: ID!
  to: String
  value: BigInt!
  reverted: Boolean!
  blockNumber: Int!
  timestamp: Int!
}
```

Run `pnpm codegen`, then register the handler:

```typescript title="src/handlers/walletActivity.ts"
import { indexer } from "envio";

// Replace with the wallet you want to track.
const WALLET = "0x28C6c06298d514Db089934071355E5743bf21d60";

indexer.onTransaction(
  {
    name: "WalletActivity",
    where: ({ chain }) =>
      chain.id === 1 && {
        transaction: { from: [WALLET], status: [0, 1] },
      },
    fields: {
      transaction: ["hash", "to", "value", "status"],
      block: ["timestamp"],
    },
  },
  async ({ transaction, context }) => {
    context.WalletTransaction.set({
      id: transaction.hash,
      to: transaction.to,
      value: transaction.value,
      reverted: transaction.status === 0,
      blockNumber: transaction.block.number,
      timestamp: transaction.block.timestamp,
    });
  },
);
```

`value` is the native value sent with the transaction. Token transfers are recorded as events, so index those with an [event handler](/docs/HyperIndex/event-handlers).

## Options

`indexer.onTransaction` takes an options object and an `async` handler function.

- `name` (required) - A non-empty name for the handler, used in logs and error messages.
- `where` (required) - A callback that decides which chains the handler runs on and which transactions it matches. See [Filtering transactions](#filtering-transactions).
- `fields` (optional) - The transaction and block fields the handler reads. See [Selecting fields](#selecting-fields).

## Filtering transactions

HyperIndex calls `where` once for each configured chain when the handler is registered. It returns one of three values:

- `false` skips the chain.
- `true` runs the handler on every successful transaction on the chain.
- A filter object runs it on the transactions that match.

Returning anything else makes registration throw, including a promise from an `async` callback or `undefined` from a missing `return`.

The filter object has the shape `{ transaction: { from?, to?, status? } }`. All three keys are optional:

| Key | Type | Matches |
| --- | --- | --- |
| `from` | array of addresses | Transactions sent by any of these addresses. |
| `to` | array of addresses | Transactions sent to any of these addresses. A contract creation has no `to`, so it never matches. |
| `status` | array of `0` and `1` | `1` for successful transactions and `0` for reverted ones. Defaults to `[1]`. |

A transaction has to match every key you give, and any one value within a key. For example, `{ from: [sender], to: [tokenA, tokenB] }` matches a transaction from `sender` to either token.

```typescript
// Successful transactions sent by either wallet
where: () => ({ transaction: { from: [walletA, walletB] } })

// Reverted calls to one contract
where: () => ({ transaction: { to: [contract], status: [0] } })

// A different wallet on each chain
where: ({ chain }) => {
  if (chain.id === 1) return { transaction: { from: [mainnetWallet] } };
  if (chain.id === 10) return { transaction: { from: [optimismWallet] } };
  return false;
}
```

:::warning
A `from` or `to` set to `undefined` is ignored. For example, `{ transaction: { from: walletsByChain[chain.id] } }` matches every successful transaction on a chain that's missing from `walletsByChain`. Return `false` for chains where you have no addresses.
:::

Reverted transactions are opt-in. Use `status: [0, 1]` to run on both outcomes, or `[0]` for reverted transactions alone.

Registration also throws if the filter has the wrong shape or an unknown key, an address isn't 20 bytes, a list is empty, or `status` holds a value other than `0` or `1`. If `where` returns `false` for every chain, HyperIndex logs a warning that the handler matched 0 chains.

Addresses in a filter match in any letter case, as long as they start with a lowercase `0x`. In the handler, `transaction.from` and `transaction.to` are checksummed unless you set [`address_format: lowercase`](/docs/HyperIndex/configuration-file#address-format), so keep that in mind when you compare them.

Filter values are fixed at registration. Reading a contract's `addresses` from `chain` inside `where` throws, because addresses [registered later](/docs/HyperIndex/dynamic-contracts) would never reach the filter. List the addresses yourself instead.

### Matching calls to one function

There's no function selector filter. Filter on `to`, add `input` to `fields`, and check the selector in your handler:

```typescript
if (!transaction.input.startsWith("0xa9059cbb")) return; // transfer(address,uint256)
```

This only sees the transaction's own call.

### Calls and transfers inside a transaction

Filters match a transaction's own sender and recipient. When a contract calls another contract or sends native token during a transaction, such as through a smart wallet or a router, that inner call or transfer isn't a transaction, so the filter doesn't see it. If it emits an event, index that with [`onEvent`](/docs/HyperIndex/event-handlers).

## Selecting fields

`transaction.block.number` is always available. List everything else you read in `fields`, including `hash`, `from`, `to` and `transactionIndex`. Using a field in the filter doesn't make it readable in the handler, and using the value of an unlisted field is a type error. The types mark `from` and `to` as possibly `undefined`.

`fields` takes the same names as an event handler's [`fields` option](/docs/HyperIndex/event-handlers#selecting-block-and-transaction-fields). The `field_selection` setting in `config.yaml` doesn't apply to transaction handlers.

## Handler function

The handler receives `{ transaction, context }`:

- `transaction` - The fields you selected, with block fields under `transaction.block`. It has the same `EvmTransaction` type as `event.transaction`, so one function can accept either.
- `context` - The same [context object](/docs/HyperIndex/event-handlers#context-object) as in event handlers, including entities, effects, `context.log`, `context.chain.id` and `context.isPreload`.

A transaction handler can't register contracts. To add contracts while indexing, use [`contractRegister`](/docs/HyperIndex/dynamic-contracts).

:::note
Like other handlers, transaction handlers run in the [preload pass](/docs/HyperIndex/preload-optimization) too, so each one runs twice.
:::

## Execution order

Within a block, a transaction's `onTransaction` handlers run before the event handlers for that transaction, and after the event handlers for earlier transactions. [Block handlers](/docs/HyperIndex/block-handlers) run last.

If several transaction handlers match the same transaction, each one runs, in the order you registered them.

[Reorg handling](/docs/HyperIndex/reorgs-support), on by default, covers transaction handlers too, so their writes from replaced blocks are rolled back.

## Data sources and performance

With [HyperSync](/docs/HyperIndex/hypersync), transactions are filtered on the server.

[RPC](/docs/HyperIndex/rpc-sync) has no transaction filter, so HyperIndex reads every block in full and filters locally, with up to 100 blocks in each page of requests. It also requests a receipt for each transaction that matches `from` and `to` when it needs the status or another receipt field, such as `gasUsed`. Because the default is `status: [1]`, the status is needed unless you set `status: [0, 1]`. This applies whenever RPC is serving the data, so check your provider's limits before relying on it for a long backfill. A filter with no `from` or `to`, including `where: () => true`, matches across every transaction on the chain.

Receipts from before Byzantium (Ethereum Mainnet block 4,370,000) carry no status. Some RPC nodes fill one in and others don't. If your filter checks status, as the default does, and a transaction matching `from` and `to` has none, HyperIndex stops using that RPC source and logs why. If no other source can serve those blocks, the indexer stops. Use HyperSync for that range, or set `status: [0, 1]`. With `[0, 1]`, `transaction.status` can be `undefined` on those blocks, so don't read that as either success or failure.

## Testing

[`createTestIndexer`](/docs/HyperIndex/testing#simulate-mock-events) can simulate transactions. Give each item a `transaction` object and, if you need one, a `block` object:

```typescript title="src/walletActivity.test.ts"
import { describe, it } from "vitest";
import { createTestIndexer } from "envio";

const WALLET = "0x28C6c06298d514Db089934071355E5743bf21d60";
const OTHER = "0x1111111111111111111111111111111111111111";

describe("WalletActivity", () => {
  it("records the wallet's transactions, reverted ones included", async (t) => {
    const indexer = createTestIndexer();

    await indexer.process({
      chains: {
        1: {
          startBlock: 20_000_000,
          endBlock: 20_000_010,
          simulate: [
            {
              transaction: { from: WALLET, to: OTHER, value: 5n },
              block: { number: 20_000_001, timestamp: 1_717_281_419 },
            },
            { transaction: { from: WALLET, to: OTHER, value: 0n, status: 0 } },
          ],
        },
      },
    });

    const rows = await indexer.WalletTransaction.getAll();
    t.expect(rows.map((row) => [row.value, row.reverted])).toEqual([
      [5n, false],
      [0n, true],
    ]);
  });
});
```

- `status` defaults to `1`. An item without `block.number` takes the previous item's block number, or the call's `startBlock` if it comes first.
- `transactionIndex` defaults to one above the highest index already used in the block, starting at `0`. `hash` is generated from the block number and that index.
- Give every transaction field your filter checks and your handler reads. Apart from the defaults above and what an event in the same transaction provides, transaction fields you leave out aren't filled in, even where the types say they're present.
- Some block fields you leave out get placeholder values, such as `0` for `timestamp`, so give any block field your handler reads.
- As with simulated events, a transaction that reaches no handler makes `process()` reject.

### Events and transactions together

Every simulated event also creates a transaction in its block, even if you leave `transaction` out of the event. Its index is the event's `transaction.transactionIndex`, which defaults to `0`, and its status is `1` unless the event or a transaction item sets it. A transaction handler that matches it runs too, such as one using `where: () => true`.

To pair an event with a simulated transaction, give them the same block number and transaction index. With the default index, list the transaction item first in that block. If it comes after an event and has no `transactionIndex`, it takes the next index, so the two aren't paired. Setting `transactionIndex` on an event type-checks only when the event selects that field. If the event and the transaction item both give a field, the values have to match.

## Limitations

- EVM only. Registering `onTransaction` on [Fuel](/docs/HyperIndex/fuel) or [Solana](/docs/HyperIndex/solana) throws.
- There's no ReScript API for transaction handlers.
- Filters can't see calls or native transfers made inside a transaction.
- There's no block range option in `where`. A handler runs from the chain's `start_block`.
- Filter values are static and can't follow dynamically registered contracts.
- Transaction handlers can't register contracts.
- [`raw_events`](/docs/HyperIndex/configuration-file#raw-events-storage) rows are written for events only.

## Related pages

- [Event Handlers](/docs/HyperIndex/event-handlers) to index the logs contracts emit.
- [Block Handlers](/docs/HyperIndex/block-handlers) to run logic every block or at an interval.
- [Wildcard Indexing](/docs/HyperIndex/wildcard-indexing) to index one event signature across all contracts.
