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

# Read contract state with eth_call

> Enrich streaming rows with on-chain contract state by calling view functions with _gs_eth_call in a Turbo SQL transform, at the exact block of each event.

## Overview

Events tell you what happened, but often you also need the contract's state at that moment: a holder's token balance after a transfer, a token's `totalSupply`, a pool's reserves, an oracle price. On-chain, you read that state by calling a `view` function with the `eth_call` JSON-RPC method.

The [`_gs_eth_call`](https://docs.goldsky.com/turbo-pipelines/reference/sql-functions#_gs_eth_call) SQL function makes that call from inside a Turbo SQL transform. You give it a Solidity function signature, a contract address, arguments and a block number. It ABI-encodes the call, sends it to an RPC endpoint you choose, and returns the decoded result as a new column. You don't need a separate fetcher service.

This guide builds a pipeline that streams USDC transfers on Ethereum and adds the recipient's USDC balance at the end of the transfer's block, then shows how to read multiple return values, choose the block, batch calls with Multicall3, and keep RPC usage under control.

## How it works

```mermaid actions={false} theme={"dark"}
flowchart LR
    A[Source dataset<br/>ethereum.erc20_transfers] -->|one row per transfer| B[SQL transform<br/>_gs_eth_call]
    B -->|eth_call at the row's block| C[(RPC endpoint<br/>Edge RPC or your own)]
    C -->|decoded return values| B
    B -->|row + contract state| D[(Sink)]
```

For each row that reaches it, `_gs_eth_call`:

1. Encodes the function signature and arguments into call data.
2. Sends an `eth_call` to `rpc_url` against the contract `address` at `block_number`.
3. Decodes the response using the return types in the signature and returns them as an `ARRAY<VARCHAR>`, one element per return value.

If the call for a row fails (bad signature, revert, RPC error, decode error), the function returns `NULL` for that row. A row-level failure never fails the batch or the pipeline.

> [!WARNING]
>
> `rpc_url` must be a valid `http(s)://` URL written as a constant. If it is `NULL`, varies per row, or fails endpoint validation (for example a private or loopback address), the transform raises an execution error instead of returning `NULL` rows.

## Prerequisites

* The [Turbo CLI extension](https://docs.goldsky.com/turbo-pipelines/cli.md#installation) installed, and a Goldsky account logged in to your project.
* An EVM JSON-RPC endpoint for the chain you are reading. We recommend [Edge RPC](https://docs.goldsky.com/edge-rpc/introduction.md). Create an endpoint in the dashboard or with `goldsky edge create`, and use its URL in the form `https://edge.goldsky.com/standard/evm/1?key=YOUR_EDGE_KEY`. Any other public `http(s)://` endpoint works too. Private and loopback addresses are blocked.
* A sink for the results. This guide uses [PostgreSQL](https://docs.goldsky.com/turbo-pipelines/sinks/postgres.md) through a secret named `MY_POSTGRES`. To try the pipeline without a database, swap the sink for a [blackhole sink](https://docs.goldsky.com/turbo-pipelines/sinks/blackhole.md) and watch the output with [live inspect](https://docs.goldsky.com/turbo-pipelines/live-inspect.md).

> [!NOTE]
>
> The pipeline sends the RPC requests with your endpoint, so your RPC provider bills the usage. With Edge that is per request; see [Edge pricing](https://docs.goldsky.com/pricing/summary.md). Every row that reaches `_gs_eth_call` can cost a call, so filter rows down before calling it. See [Keep RPC usage under control](#keep-rpc-usage-under-control).

## Write the function signature

`_gs_eth_call` takes a human-readable Solidity signature that lists both the input types and the return types:

```text theme={"dark"}
functionName(input_types)(output_types)
```

| Function | Signature |
| - | - |
| ERC-20 `balanceOf` | `'balanceOf(address)(uint256)'` |
| ERC-20 `totalSupply` | `'totalSupply()(uint256)'` |
| ERC-20 `decimals` | `'decimals()(uint8)'` |
| ERC-20 `symbol` | `'symbol()(string)'` |
| ERC-721 `ownerOf` | `'ownerOf(uint256)(address)'` |
| Uniswap V2 `getReserves` | `'getReserves()(uint112,uint112,uint32)'` |

Use only types, with no parameter names and no spaces. The return types are required, because the function uses them to decode the response.

Pass the arguments as an array of strings in the order the signature declares them, for example `ARRAY[recipient]` for `balanceOf(address)`. Cast numeric arguments to text, for example `ARRAY[CAST(token_id AS TEXT)]`. Pass `NULL` for functions that take no arguments.

## Step 1: Create the pipeline

Create a file named `usdc-balances.yaml`. Replace `YOUR_EDGE_KEY` with your Edge key, or replace the whole URL with another provider's Ethereum endpoint.

```yaml usdc-balances.yaml theme={"dark"}
name: usdc-balances
resource_size: s

sources:
  # Every USDC transfer on Ethereum mainnet
  usdc_transfers:
    type: dataset
    dataset_name: ethereum.erc20_transfers
    version: 1.2.0
    start_at: latest
    filter: address = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'

transforms:
  # Call balanceOf(recipient) on the USDC contract at the end of the
  # transfer's block
  transfers_with_balance:
    type: sql
    primary_key: id
    sql: |
      SELECT
        id,
        sender,
        recipient,
        CAST(amount AS TEXT) AS amount,
        block_number,
        to_timestamp(block_timestamp) AS block_time,
        transaction_hash,
        _gs_eth_call(
          'https://edge.goldsky.com/standard/evm/1?key=YOUR_EDGE_KEY',
          'balanceOf(address)(uint256)',
          '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
          ARRAY[recipient],
          CAST(block_number AS BIGINT)
        )[1] AS recipient_balance
      FROM usdc_transfers

sinks:
  postgres_sink:
    type: postgres
    from: transfers_with_balance
    schema: public
    table: usdc_transfers_with_balance
    secret_name: MY_POSTGRES
    primary_key: id
```

> [accordion] What each piece does
>
> * **`sources.usdc_transfers`**: the ERC-20 transfers dataset for Ethereum, filtered at the source to the USDC contract. `start_at: latest` processes only new transfers going forward.
> * **`_gs_eth_call(...)`**: calls `balanceOf(recipient)` on the USDC contract at the end of the transfer's block and returns an array with one element, the decoded `uint256`.
> * **`[1]`**: picks the first (and only) return value. Arrays in Turbo SQL are 1-indexed.
> * **`recipient_balance`**: the balance in USDC base units (6 decimals) as a decimal string, or `NULL` if the call failed. It is the balance at the end of the block, not right after this transfer. If the recipient moves USDC again later in the same block, this value already includes that. See [Choose the block](#choose-the-block).

## Step 2: Deploy and inspect

Validate, then apply:

```bash theme={"dark"}
goldsky turbo validate usdc-balances.yaml
goldsky turbo apply usdc-balances.yaml
```

Watch the enriched rows as they flow through the transform:

```bash theme={"dark"}
goldsky turbo inspect usdc-balances.yaml -n transfers_with_balance
```

If every `recipient_balance` is `NULL`, check the RPC URL and key first, then the function signature.

## Step 3: Query the results

The return values are strings, so cast them before doing arithmetic:

```sql theme={"dark"}
-- Recipient balances in whole USDC at the end of each transfer's block
SELECT recipient,
       recipient_balance::numeric / 1e6 AS usdc_balance,
       block_number,
       block_time
FROM public.usdc_transfers_with_balance
WHERE recipient_balance IS NOT NULL
ORDER BY block_number DESC
LIMIT 20;
```

To do the math inside the pipeline instead, convert the value to a 256-bit integer with `CAST(... AS DECIMAL(78, 0))`. See [Large numbers](https://docs.goldsky.com/turbo-pipelines/reference/sql-functions.md#large-numbers-256-bit-integers-and-wide-decimals).

```sql theme={"dark"}
CAST(
  CAST(
    _gs_eth_call(
      'https://edge.goldsky.com/standard/evm/1?key=YOUR_EDGE_KEY',
      'balanceOf(address)(uint256)',
      '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
      ARRAY[recipient],
      CAST(block_number AS BIGINT)
    )[1] AS DECIMAL(78, 0)
  ) / 1000000 AS TEXT
) AS recipient_balance_usdc
```

## Read multiple return values

When a function returns several values, list every return type in the signature. The result array has one element per type, in the same order. Call the function once in a subquery, then pick the elements you need.

This example reads the reserves of the Uniswap V2 USDC/WETH pair at every new Ethereum block:

```yaml uniswap-v2-reserves.yaml theme={"dark"}
name: uniswap-v2-reserves
resource_size: s

sources:
  blocks:
    type: dataset
    dataset_name: ethereum.raw_blocks
    version: 1.0.0
    start_at: latest

transforms:
  pair_reserves:
    type: sql
    primary_key: id
    sql: |
      SELECT
        id,
        block_number,
        reserves[1] AS reserve_usdc,  -- token0 of the pair
        reserves[2] AS reserve_weth,  -- token1 of the pair
        reserves[3] AS last_updated   -- blockTimestampLast
      FROM (
        SELECT
          id,
          number AS block_number,
          _gs_eth_call(
            'https://edge.goldsky.com/standard/evm/1?key=YOUR_EDGE_KEY',
            'getReserves()(uint112,uint112,uint32)',
            '0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc',
            NULL,  -- no arguments
            CAST(number AS BIGINT)
          ) AS reserves
        FROM blocks
      ) sub
      WHERE reserves IS NOT NULL

sinks:
  postgres_sink:
    type: postgres
    from: pair_reserves
    schema: public
    table: uniswap_v2_usdc_weth_reserves
    secret_name: MY_POSTGRES
    primary_key: id
```

This pipeline makes one RPC call per block.

> [!WARNING]
>
> Each element is stringified on its own. Scalar return types (`uint*`, `int*`, `address`, `bool`, `string`, `bytes`) come back intact. For nested return types such as `string[]` or tuples, commas and brackets inside an element aren't escaped. Prefer one call per scalar field when you need to parse the result reliably.

## Choose the block

The last argument sets the block whose state the call reads:

| `block_number` | State you get |
| - | - |
| `CAST(block_number AS BIGINT)` | At the end of the row's block, after every transaction in it. |
| `CAST(block_number - 1 AS BIGINT)` | At the end of the previous block, before anything in the row's block ran. |
| `NULL` | At the chain head (`latest`) when the call runs. |

Pass the row's block for results that are consistent with the event, including when you backfill from `start_at: earliest`. A call at `NULL` reads whatever the chain head is when the pipeline processes the row, so its result depends on when the row is processed.

> [!NOTE]
>
> Historical calls need an RPC endpoint that serves the state for that block. Calls for old blocks on a node that has pruned that state fail and return `NULL`.

## Batch calls with Multicall3

By default, `_gs_eth_call` sends one `eth_call` request per row. Set the optional sixth argument, `use_multicall`, to `TRUE` to batch eligible rows into Multicall3 calls instead. The optional seventh argument, `max_calls_per_multicall`, sets how many calls go into each batch. The default is `50`.

```sql theme={"dark"}
_gs_eth_call(
  'https://edge.goldsky.com/standard/evm/1?key=YOUR_EDGE_KEY',
  'balanceOf(address)(uint256)',
  '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
  ARRAY[recipient],
  CAST(block_number AS BIGINT),
  TRUE,  -- use_multicall
  50     -- max_calls_per_multicall
)[1] AS recipient_balance
```

> [!WARNING]
>
> With batching on, the Multicall3 contract calls your target contract, so the target sees Multicall3 as `msg.sender` instead of the RPC caller. A view function whose result depends on `msg.sender` can return a different value or revert. Only turn batching on for functions that are independent of the caller, such as `balanceOf(address)`, which takes the account as an argument.

If the whole Multicall3 request fails, for example with an RPC error or because it hits the node's per-request gas limit, Turbo retries every call in that batch as a separate direct `eth_call`. A failed batch therefore costs one request plus one per call in the batch, and takes longer. Individual calls that fail inside a successful batch return `NULL` for their rows.

Only raise the batch size if you have measured RPC throughput as your bottleneck. Larger batches are more likely to hit the gas limit and fall back to direct calls. When in doubt, leave the optional arguments off.

## Keep RPC usage under control

Every row that reaches `_gs_eth_call` costs RPC usage, and a busy dataset can produce thousands of rows per second. Within each batch, Turbo deduplicates calls with the same contract, call data and block, so identical calls are sent once. Distinct calls still cost one each. Reduce the rows before the call:

* **Filter at the source.** A source `filter:` such as `address = '0x...'` limits the stream to the contracts you care about before any transform runs.
* **Filter in SQL.** Put conditions in the `WHERE` clause of the same query, or in an earlier transform, so the call only runs for rows you keep.
* **Watch a changing set of addresses.** Store the addresses in a [dynamic table](https://docs.goldsky.com/turbo-pipelines/transforms/dynamic-tables.md) and filter with `WHERE dynamic_table_check('watched_addresses', recipient)`. You can add and remove addresses without redeploying. The [native balances guide](https://docs.goldsky.com/turbo-pipelines/guides/native-balances.md) shows the full pattern.

## Handle failed calls

A call that reverts, times out, or can't be decoded returns `NULL` for its row instead of failing the pipeline. An invalid `rpc_url` is different: it raises an error for the whole transform. Decide what a `NULL` should mean for your sink:

* To drop rows whose call failed, wrap the call in a subquery and filter with `WHERE result IS NOT NULL`, as the reserves example does.
* If the sink upserts on a key, such as one row per holder, drop failed rows. Otherwise a failed call replaces a good value with `NULL`.
* To keep every event and backfill the value later, keep the row and store the `NULL`.

## Related

* [`_gs_eth_call` reference](https://docs.goldsky.com/turbo-pipelines/reference/sql-functions#_gs_eth_call)
* [Native balances guide](https://docs.goldsky.com/turbo-pipelines/guides/native-balances.md), which uses `_gs_evm_get_balances` for native ETH balances
* [Dynamic tables](https://docs.goldsky.com/turbo-pipelines/transforms/dynamic-tables.md)
* [SQL transforms](https://docs.goldsky.com/turbo-pipelines/transforms/sql.md)
* [Edge RPC](https://docs.goldsky.com/edge-rpc/introduction.md)

Can't find what you're looking for? Reach out to us at [support@goldsky.com](mailto:support@goldsky.com) for help.


## Related topics

- [Pricing: plans, metering, and product costs](https://docs.goldsky.com/pricing/summary.md)
- [eth_call](https://docs.goldsky.com/edge-rpc/evm/methods/eth_call.md)
- [Subgraph performance](https://docs.goldsky.com/subgraphs/guides/performance.md)
- [Use declared eth_calls to increase indexing performance](https://docs.goldsky.com/subgraphs/guides/declared-eth-calls.md)
- [How Boost routes requests](https://docs.goldsky.com/boost/how-it-works.md)
