# Guide: Live Data, Events & Local State

Beyond binding a single value, `@chainrender/client/runtime` gives you batched reads, event log access, and
opt-in local state — everything a live, reactive UI needs, while keeping the app itself fully on-chain.

## Batched reads

Read several on-chain values in one round-trip with `batchRead` (Multicall3 `aggregate3`, one `eth_call`). Each
call fails closed on its own: a reverting read comes back `success: false` instead of failing the batch.

```ts
import { batchRead } from "@chainrender/client/runtime";
import { decodeFunctionResult, parseAbi } from "viem";

const results = await batchRead([
    { to: oracle, signature: "latestAnswer()", args: [], slot: "price" },
    { to: token, signature: "balanceOf(address)", args: [user], slot: "balance" },
    { to: token, signature: "totalSupply()", args: [], slot: "supply" },
  ], { rpc }); // opts.multicall overrides the canonical Multicall3 address on a chain without it

// each result is { success, returnData } in the same order; decode with the function's return type
const abi = parseAbi(["function totalSupply() view returns (uint256)"]);
const supply = results[2].success
  ? decodeFunctionResult({ abi, functionName: "totalSupply", data: results[2].returnData })
  : null;
```

## Reading events

`getLogs` / `readEvents` read event history (for feeds, activity, indexing) with a topic helper:

```ts
import { events } from "@chainrender/client/runtime";

const spec = {
  to: token,
  // the full signature with `indexed` names is needed to filter on indexed args (eth_getLogs filters topics only)
  event: "event Transfer(address indexed from, address indexed to, uint256 value)",
  filter: { indexedArgs: { to: holder }, fromBlock: 5_000_000n, toBlock: "latest" as const },
  slot: "activity",
};
const logs = await events.readEvents(spec, { rpc, limit: 50 });   // eth_getLogs: an on-chain data edge (doc 94)
// the same through an explicit source: events.getLogs(rpc).read(spec, { limit: 50 })
const topic0 = events.eventTopic0(spec.event);                    // the event selector
```

`events.indexer(query)` plugs in an off-chain indexer instead (Grade C, labelled as such), and `events.custom(read)`
any other log source.

**Where this sits in the grade.** `getLogs` is an on-chain data edge (an `EventSpec` with `dataEdge: "on-chain"`,
doc 94); `indexer` is off-chain. The read itself, though, is made by *your* page's code at view time, against the RPC
you give it, so it is not part of a component's on-chain render. Inside a ChainRender app, a list of transfers is the
**`transfers` bind**: the viewer reads the logs itself, cross-checks each page across the chain's endpoints, applies
the poisoning defences and labels the result ⚙ Above-floor over the app's floor ([Viewer Reads](./viewer-reads.md)).

For heavier discovery, the runtime exposes an `indexer` hook — but note the **honest boundary**: enumerating "all
of X" at scale needs an indexer, while reading a *specific* value or a bounded range is a direct on-chain call. See
**[The Render Pipeline](../concepts/render-pipeline.md)**.

## Local state (opt-in, client-side)

For client-side preferences (a chosen theme, a saved RPC, UI state), the runtime offers pluggable local stores —
`memory`, `localStorage`, `indexedDB` — so you don't reach for browser APIs directly and can keep behavior
consistent and testable:

```ts
import { local } from "@chainrender/client/runtime";
const store = local.localStorage("myapp");   // or local.memory(), local.indexedDB(…), local.custom(…)
await store.set("theme", "dark");            // every store is async: set / get / list / delete
const theme = await store.get<string>("theme");
```

Local state never affects the app's on-chain identity or grade — it's purely a client convenience.

## Binding data into a rendered component

`bindSlots` resolves an app's data slots against live sources at render time (this is what the interpreter does
on-chain; the runtime mirror lets you drive it client-side for previews):

```ts
import { renderComponent, bindSlots, makeProviderResolvers } from "@chainrender/client/runtime";

const container = document.querySelector("#app")!.attachShadow({ mode: "open" });
container.innerHTML = await renderComponent({ rpc, router }, hash);   // the on-chain render (escaped HTML)
await bindSlots(container, makeProviderResolvers(publicClient));       // fills every [data-cr-bind] slot in place
// publicClient: a viem PublicClient (it has getEnsName / getEnsAvatar / getBalance). These client-side fills are the
// CLIENT_FETCH path — on-chain resolvers fill slots during the render itself and need none of this.
```

## Live data inside a rich-media sketch (`window.CR_CHAIN`)

The reads above are the **declarative** path — data slots resolved on-chain by the interpreter. A **rich-media**
p5/three sketch reads live data a different way: through the injected **`window.CR_CHAIN`** bridge. Same chain, same
honesty rules, but callable imperatively from inside the sketch loop.

```js
// snapshot (auto-polled, ready ~1-2s after start — not in setup()):
CR_CHAIN.blockNumber, CR_CHAIN.gasPriceGwei, CR_CHAIN.baseFeeGwei, CR_CHAIN.live

// async helpers (Promise-returning, fail-closed to null):
await CR_CHAIN.erc20(token)        // { name, symbol, decimals, decimalsStatus: "ok"|"absent"|"failed", totalSupply, totalSupplyFloat, error }
await CR_CHAIN.receipt(txHash)     // { status: "success"|"reverted", gasUsed, ... }
await CR_CHAIN.feeHistory(30)      // real gas curve: { baseFeeGwei:[...], gasUsedRatio:[...], reward:[[...]] }
await CR_CHAIN.recentLogs(addr, transferTopic, 2000)  // recent events, auto-ranged
await CR_CHAIN.ensName(addr)       // "vitalik.eth" or null
```

Use `CR_CHAIN.onReady(fn)` (or gate on `CR_CHAIN.live` in `draw()`) for the initial fetch, scale token amounts by
the token’s **real** `decimals` (never a hardcoded `1e6`/`1e18`), cache one-time reads, throttle repeats, and only
show a "LIVE" label when `CR_CHAIN.live === true`. The full helper reference and honesty rules live in
**[Rich Media → Reading live on-chain data](../concepts/rich-media-p5-three.md)**.

> Same **honest boundary** as above: `erc20`, `receipt`, `feeHistory`, logs, and ENS are all direct on-chain reads;
> enumerating "all holders" or "every historical transfer" at scale still needs an indexer, not a single call.

## Related
- **[Resolvers & Data Binding](../concepts/resolvers.md)** · **[Bind Live On-Chain Data](./bind-data.md)**
