read_contract_at

Calls a contract function at an explicit block number and returns ABI-decoded SQL values.

Scalar functionLive RPC RPC

Example

Live RPC

-- Chainlink ETH/USD at one block per day
WITH as_of(day) AS (
  SELECT day
  FROM generate_series('2024-01-01'::DATE, '2024-01-07'::DATE, INTERVAL 1 DAY) AS t(day)
)
SELECT
  day,
  format_units(
    (read_contract_at(
      $client,
      '0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419'::ADDRESS,
      '[{"type":"function","name":"latestRoundData","inputs":[],"outputs":[{"name":"roundId","type":"uint80"},{"name":"answer","type":"int256"},{"name":"startedAt","type":"uint256"},{"name":"updatedAt","type":"uint256"},{"name":"answeredInRound","type":"uint80"}]}]'::JSON,
      'latestRoundData',
      block_at($client, day::TIMESTAMPTZ)
    )).answer,
    8
  )::DOUBLE AS eth_usd
FROM as_of;

API reference

read_contract_at(CLIENT, ADDRESS, JSON, VARCHAR, BIGINT, ...args) # RPC required

The non-negative BIGINT block number may vary by row. ABI and function_name must be literal or foldable. Pinned and retained execution CLIENT values reject the explicit selector.

Inputs

Name Type Use
client CLIENT

Live, pinned, or retained execution CLIENT. Pinned and execution state require the resolved block selector to be latest and reject other selectors.

required positional
to ADDRESS

Contract address to call.

required positional
abi JSON

Literal or foldable JSON ABI used for argument encoding and output types.

required positional
function_name VARCHAR

Literal or foldable ABI function name.

required positional
block_number BIGINT

Non-negative BIGINT block number. NULL produces NULL without issuing an RPC call.

required positional
...args dynamic ANY

Pass one SQL value per ABI input. The ABI determines how many values are accepted and how each value is cast. The ABI and function name must be literal or foldable so the return type can be inferred during planning.

positional

Returns

Name Type
result dynamic ABI-derived scalar or STRUCT

A function with one output returns that value directly. A function with multiple outputs returns a STRUCT with fields named from ABI outputs, or output0, output1, and so on for unnamed outputs.

Guidance

Historical contract reads

Use read_contract_at when the block number is already a typed BIGINT value or comes from block_at.

The ABI and function name remain planning-time constants so the exact scalar or STRUCT return type can be inferred.

  • NULL block numbers return NULL without an RPC request.
  • Negative block numbers are rejected locally.
  • Use read_contract options instead when you need a block tag, on_error, or a dynamic return schema.