> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sqd.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Query builder

> API reference for EvmQueryBuilder

`EvmQueryBuilder` assembles a typed portal query from a field selection and one or more data-request clauses. Pass `.build()` to `outputs` (or to `.pipe()`) on an EVM source. The resulting object is consumed by [`evmPortalStream()`](./source) and by the [evmDecoder](../utility-components/evm-decoder) which composes on top of it.

## `evmQuery()`

Returns a fresh `EvmQueryBuilder`.

```ts theme={"system"}
import { evmQuery } from '@subsquid/pipes/evm'

const query = evmQuery()
  .addFields({
    block: { timestamp: true },
    log: { address: true, topics: true, data: true },
  })
  .addLog({
    range: { from: 20_000_000 },
    request: { topic0: ['0xddf252ad…'] },
  })
  .build()
```

## `EvmQueryBuilder<F>`

```ts theme={"system"}
class EvmQueryBuilder<F extends FieldSelection = {}> {
  addFields<T>(fields: Subset<T, FieldSelection>): EvmQueryBuilder<F & T>
  addLog(options: RequestOptions<LogRequest>): this
  addTransaction(options: RequestOptions<TransactionRequest>): this
  addTrace(options: RequestOptions<TraceRequest>): this
  addStateDiff(options: RequestOptions<StateDiffRequest>): this
  addRange(range: PortalRange): this
  merge(other?: EvmQueryBuilder<F>): this
  build(opts?: { setupQuery?: SetupQueryFn<EvmQueryBuilder<F>> }): QueryAwareTransformer
}
```

The generic parameter `F` narrows the block type produced by the stream — only fields explicitly selected with `.addFields()` appear on the decoded records, at both compile and runtime.

### `RequestOptions<R>`

```ts theme={"system"}
type RequestOptions<R> = { range: PortalRange; request: R }
type PortalRange = { from?: number | string | 'latest' | Date; to?: number | string | Date }
```

`PortalRange.from` defaults to `0`; a `Date` or numeric timestamp is resolved to a block number via the portal at query start. `'latest'` is resolved to the current head.

***

## `.addFields(fields)`

Add to the field selection. Repeated calls are merged recursively. Block hash and number are returned regardless of selection.

### `block`

| Field              | Type                       |
| ------------------ | -------------------------- |
| `number`           | `number` (always returned) |
| `hash`             | `string` (always returned) |
| `parentHash`       | `string`                   |
| `timestamp`        | `number` (Unix seconds)    |
| `transactionsRoot` | `string`                   |
| `receiptsRoot`     | `string`                   |
| `stateRoot`        | `string`                   |
| `logsBloom`        | `string`                   |
| `sha3Uncles`       | `string`                   |
| `extraData`        | `string`                   |
| `miner`            | `string`                   |
| `nonce`            | `string`                   |
| `mixHash`          | `string`                   |
| `size`             | `number`                   |
| `gasLimit`         | `bigint`                   |
| `gasUsed`          | `bigint`                   |
| `difficulty`       | `bigint`                   |
| `totalDifficulty`  | `bigint?`                  |
| `baseFeePerGas`    | `bigint`                   |
| `blobGasUsed`      | `bigint`                   |
| `excessBlobGas`    | `bigint`                   |
| `l1BlockNumber`    | `number?` (L2 only)        |

### `transaction`

| Field                                                                                                        | Type                                 |
| ------------------------------------------------------------------------------------------------------------ | ------------------------------------ |
| `transactionIndex`                                                                                           | `number`                             |
| `hash`                                                                                                       | `string`                             |
| `nonce`                                                                                                      | `bigint`                             |
| `from`                                                                                                       | `string`                             |
| `to`                                                                                                         | `string?`                            |
| `input`                                                                                                      | `string`                             |
| `value`                                                                                                      | `bigint`                             |
| `gas`                                                                                                        | `bigint`                             |
| `gasPrice`                                                                                                   | `bigint`                             |
| `maxFeePerGas`                                                                                               | `bigint?`                            |
| `maxPriorityFeePerGas`                                                                                       | `bigint?`                            |
| `v`, `r`, `s`, `yParity`                                                                                     | `bigint`/`string`/`string`/`number?` |
| `chainId`                                                                                                    | `number?`                            |
| `sighash`                                                                                                    | `string?` (first 4 bytes of `input`) |
| `contractAddress`                                                                                            | `string?` (for create transactions)  |
| `gasUsed`                                                                                                    | `bigint`                             |
| `cumulativeGasUsed`                                                                                          | `bigint`                             |
| `effectiveGasPrice`                                                                                          | `bigint`                             |
| `type`                                                                                                       | `number`                             |
| `status`                                                                                                     | `number` (0 = fail, 1 = success)     |
| `blobVersionedHashes`                                                                                        | `string[]?`                          |
| `l1Fee`, `l1FeeScalar`, `l1GasPrice`, `l1GasUsed`, `l1BlobBaseFee`, `l1BlobBaseFeeScalar`, `l1BaseFeeScalar` | L2 fee metadata                      |

### `log`

| Field              | Type       |
| ------------------ | ---------- |
| `logIndex`         | `number`   |
| `transactionIndex` | `number`   |
| `transactionHash`  | `string`   |
| `address`          | `string`   |
| `data`             | `string`   |
| `topics`           | `string[]` |

### `trace`

Trace records are a tagged union over `type`. Each type has its own action and (optionally) result sub-objects; the field selection is flat with `create…`/`call…`/`suicide…`/`reward…` prefixes. Shared:

| Field              | Type                                          |
| ------------------ | --------------------------------------------- |
| `type`             | `'create' \| 'call' \| 'suicide' \| 'reward'` |
| `transactionIndex` | `number`                                      |
| `traceAddress`     | `number[]`                                    |
| `subtraces`        | `number`                                      |
| `error`            | `string \| null`                              |
| `revertReason`     | `string?`                                     |

Type-specific (appears only on that trace `type`):

| Field                                                                                    | Action/result  | Type                                                                         |
| ---------------------------------------------------------------------------------------- | -------------- | ---------------------------------------------------------------------------- |
| `createFrom`, `createValue`, `createGas`, `createInit`                                   | create action  | `string` / `bigint` / `bigint` / `string`                                    |
| `createResultGasUsed`, `createResultCode`, `createResultAddress`                         | create result  | `bigint` / `string?` / `string`                                              |
| `callCallType`, `callFrom`, `callTo`, `callValue`, `callGas`, `callInput`, `callSighash` | call action    | `string` / `string` / `string` / `bigint?` / `bigint` / `string` / `string?` |
| `callResultGasUsed`, `callResultOutput`                                                  | call result    | `bigint` / `string?`                                                         |
| `suicideAddress`, `suicideRefundAddress`, `suicideBalance`                               | suicide action | `string` / `string` / `bigint`                                               |
| `rewardAuthor`, `rewardValue`, `rewardType`                                              | reward action  | `string` / `bigint` / `string`                                               |

### `stateDiff`

State diffs are a tagged union over `kind` (`'+'` = add, `'-'` = delete, `'*'` = change, `'='` = no-change).

| Field              | Type                                                      |
| ------------------ | --------------------------------------------------------- |
| `transactionIndex` | `number`                                                  |
| `address`          | `string`                                                  |
| `key`              | `'balance' \| 'code' \| 'nonce' \| string` (storage slot) |
| `kind`             | `'+' \| '-' \| '*' \| '='`                                |
| `prev`             | `string` (present for `-`, `*`)                           |
| `next`             | `string` (present for `+`, `*`)                           |

***

## `.addLog(options)`

Filter logs. All list filters AND across fields but OR within a field. Request options:

| Field                        | Type       | Meaning                                                 |
| ---------------------------- | ---------- | ------------------------------------------------------- |
| `address`                    | `string[]` | Emitting contract addresses (lowercase).                |
| `topic0`                     | `string[]` | First topic (typically the event signature hash).       |
| `topic1`, `topic2`, `topic3` | `string[]` | Remaining indexed topics.                               |
| `transaction`                | `boolean`  | Also fetch the parent transaction of each matching log. |
| `transactionTraces`          | `boolean`  | Also fetch traces of parent transactions.               |
| `transactionLogs`            | `boolean`  | Also fetch all logs from parent transactions.           |
| `transactionStateDiffs`      | `boolean`  | Also fetch state diffs caused by parent transactions.   |

An empty `request: {}` matches every log in the range.

```ts theme={"system"}
evmQuery().addLog({
  range: { from: 20_000_000, to: 20_000_100 },
  request: {
    address: ['0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'],
    topic0: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'],
    transaction: true,
  },
})
```

## `.addTransaction(options)`

Filter transactions.

| Field        | Type       | Meaning                                                             |
| ------------ | ---------- | ------------------------------------------------------------------- |
| `from`       | `string[]` | Sender addresses (lowercase).                                       |
| `to`         | `string[]` | Recipient addresses (lowercase).                                    |
| `sighash`    | `string[]` | First 4 bytes of `input` (e.g. `0xa9059cbb` for ERC-20 `transfer`). |
| `type`       | `number[]` | Transaction type (0 legacy, 2 EIP-1559, 3 blob, etc.).              |
| `logs`       | `boolean`  | Also fetch emitted logs.                                            |
| `traces`     | `boolean`  | Also fetch execution traces.                                        |
| `stateDiffs` | `boolean`  | Also fetch state diffs.                                             |

## `.addTrace(options)`

Filter execution traces.

| Field                  | Type                                              | Meaning                                        |
| ---------------------- | ------------------------------------------------- | ---------------------------------------------- |
| `type`                 | `('create' \| 'call' \| 'suicide' \| 'reward')[]` | Restrict to given trace types.                 |
| `createFrom`           | `string[]`                                        | Creator address for `create` traces.           |
| `callFrom`             | `string[]`                                        | Caller address for `call` traces.              |
| `callTo`               | `string[]`                                        | Callee address for `call` traces.              |
| `callSighash`          | `string[]`                                        | `input` sighash for `call` traces.             |
| `suicideRefundAddress` | `string[]`                                        | Refund address for `suicide` traces.           |
| `rewardAuthor`         | `string[]`                                        | Author of `reward` traces.                     |
| `transaction`          | `boolean`                                         | Fetch parent transactions of matching traces.  |
| `transactionLogs`      | `boolean`                                         | Fetch all logs emitted by parent transactions. |
| `subtraces`            | `boolean`                                         | Fetch all subtraces of matching traces.        |
| `parents`              | `boolean`                                         | Fetch parent traces of matching traces.        |

## `.addStateDiff(options)`

Filter storage diffs.

| Field         | Type                           | Meaning                                                   |
| ------------- | ------------------------------ | --------------------------------------------------------- |
| `address`     | `string[]`                     | Contract or account addresses (lowercase).                |
| `key`         | `string[]`                     | Storage keys or pseudo-keys (`balance`, `code`, `nonce`). |
| `kind`        | `('+' \| '-' \| '*' \| '=')[]` | Type of change.                                           |
| `transaction` | `boolean`                      | Fetch parent transactions.                                |

## `.addRange(range)`

Push a range-only request with no filters. Mostly useful to bound the stream or in combination with `includeAllBlocks` set elsewhere.

```ts theme={"system"}
evmQuery().addRange({ from: 20_000_000, to: 20_001_000 })
```

## `.merge(other)`

Merge another builder's requests and fields in-place. Overlapping ranges are reconciled at build time.

## `.build(opts?)`

Return a `QueryAwareTransformer` suitable for use as a source output.

```ts theme={"system"}
evmPortalStream({
  portal: 'https://portal.sqd.dev/datasets/ethereum-mainnet',
  outputs: { transfers: evmQuery().addLog({/*…*/}).build() },
})
```

`opts.setupQuery` is an advanced hook called when the query is finalized: it receives `{ query, logger }` and can mutate `query` (e.g. merge additional requests from runtime data). Default behaviour is to merge `this` into the stream's root query.

***

## See also

* [Source](./source) — how queries attach to the stream.
* [evmDecoder](../utility-components/evm-decoder) — typed wrapper that emits a pre-built query plus event/function decoding.
* [Handling contract events](../../guides/basic-development/handling-events) — higher-level guide.
* [Portal API (EVM) OpenAPI](/en/portal/evm/api) — raw wire protocol this builder serialises to.
