# Rich Media: p5.js & three.js Over the On-Chain Floor

ChainRender supports **rich, dynamic, GPU-accelerated visuals** — p5.js sketches and three.js scenes — while
staying trustless. The trick is the **floor principle** applied to rendering libraries: the on-chain floor renders
first and always; the library runs as an *enhancement* over it, and the library itself is stored **on-chain**, not
fetched from a CDN.

## How it works

A rich-media component carries a **scene binding** — the library (by DependencyRegistry content hash), a seed, and
the sketch to run (by SourceStore id).
When it renders:

1. **The floor renders immediately.** `renderFloor(id)` is a pure `eth_call` — a complete, fully on-chain SVG that
   needs nothing but the chain. This is what you always see; it's Grade A.
2. **The viewer then *attempts* the enhancement.** It reads the binding, fetches the named library from the
   on-chain **`DependencyRegistry`** by hash, **verifies `keccak` at every stage**, gunzips it, and runs the sketch
   in a **sandboxed iframe** (`sandbox="allow-scripts"`, CSP `default-src 'none'`).
3. **It fails closed to the floor** on *any* failure — no library, a hash mismatch, a script error, a strict CSP.
   You never get a broken render; worst case, you get the on-chain floor.

A rich-media app is graded **⚙ Above-floor**: the floor is Grade A, the sketch is a client-side enhancement over
it. Show both — never the floor's letter alone for a rich-media app (`grade(tree)` returns the letter plus
`aboveFloor` for exactly this).

## Building one (the tree, the check, the deploy)

**1. The tree.** A rich-media app is an image node with `bind: "p5"` or `bind: "three"` carrying a `scene` — the
builder's Scene panel writes exactly this shape:

```ts
import { checkNode, grade, type Node } from "@chainrender/client";

const app = {
  type: "box",
  children: [
    { type: "text", role: "heading", content: "Harbor Nocturne" },
    {
      type: "image",
      bind: "three",               // or "p5"
      alt: "Night circuit",
      scene: {
        source: SKETCH_SOURCE,     // the sketch code: p5 global mode, or three via the GLOBAL `THREE` — never `import`
        seed: "0x…",               // bytes32 — the sketch's ONLY entropy source (window.CR_SEED); empty = 0x…01
        libHash: "",               // empty = the deployed on-chain library (discovered by name); or its DependencyRegistry hash
        mobile: true,              // CR-Stage mobile-ready full page
      },
    },
  ],
} as unknown as Node;

checkNode(app, { authoring: true }).ok;   // true — validates scene's fields, the p5/three bind, and libHash
grade(app);                               // { letter: "A", …, aboveFloor: { kinds: ["three"], word: "Above-floor", locks: "⚙" } }
```

`checkNode(tree, { authoring: true })` rejects what the builder would ignore or the viewer could not run: unknown
`scene` keys, a missing `source`, a scene on an image without a p5/three `bind`, an `import` in the source, and a
zero `libHash` (that is the canvas-only tier: a p5/three sketch would have no library). The fields are in
**[Node Fields → `image.scene`](../reference/node-fields.md)**.

**2. Deploy.** The builder's Deploy for a rich-media app sends three transactions:
1. **The component registry** the chain's `RenderRouter` reads (`registry()`), `register(bytes,bytes32)` — the tree itself, compiled (its `scene` is dropped by
   `compile()`). Its content hash is what a subname binds to.
2. **SourceStore** — the sketch `source`, gzipped (native `CompressionStream`). A sketch too large for one storage
   pointer is split into chunk blobs plus a `CRCHUNKS1|<id>,<id>,…` manifest blob; the chunk size follows the chain's
   code-size ceiling and per-transaction gas cap (`chains.json`). The id (keccak of the stored bytes) is the
   sketch's on-chain identity.
3. **SceneComponentRegistry** `register(floorContract, floorSelector, seed, binding)` — the floor is **SceneFloor**'s
   `sigilFloor(seed)` (a seed-derived on-chain SVG poster, what `renderFloor(id)` returns) and
   `binding = encodeSceneBinding({ kind, libHash, seed, entry: <SourceStore id>, meta })`, where `meta` is the app
   metadata JSON (`appmeta.encodeAppMeta`, with `grade: "gear"`, `gradeWord: "Above-floor"`).

The scene id is `sceneIdOf(floor, selector, seed, binding)`; the full-page viewer URL carries `sketch`, `lib`,
`seed` and `kind`, and [Explore](./apps-directory.md) lists the app automatically.

All of these encoders are exported from `@chainrender/client` (0.11.0): `encodeSceneBinding`,
`decodeSceneBinding`, `sceneIdOf`, `SCENE_FLOOR_SELECTORS`, `sceneNamespaceId`.

**3. Rules a rich-media app must keep** (they are what the grade and the user rely on):
- Everything the app says about itself must be true in the code. If the text says "the seed sets the track", the
  sketch must derive the track from `window.CR_SEED`.
- Live chain data only through `window.CR_CHAIN`, labelled live only when `CR_CHAIN.live === true` (below).
- Don't display a grade for a tree that is not deployed. Say "would be A (floor) + ⚙ above-floor once deployed",
  with the hash it would have.
- Off-chain parts of an app (a server, a database, a peer-to-peer room) are outside the component: name them as
  such, and never fold them into the component's grade.

## The library lives on-chain

This is the key difference from a normal web app that loads `three.js` from a CDN. Here, the library is **stored
on-chain** in the `DependencyRegistry`:

- **Content-addressed & chunked.** A gzipped library is split into ≤72KB parts, each stored on-chain, registered as
  a content-addressed manifest, and round-trip-verified.
- **Immutable & pinned once.** You upload p5/three once (via `scripts/upload-dependency.ts`); components then
  reference it by hash forever — no re-upload per deploy.
- **Verifiable at render.** The viewer keccak-verifies every chunk as it reassembles the library. You're running
  *exactly* the pinned bytes, not whatever a CDN happens to serve.

> A gzipped modern p5 + three core is on the order of ~$20 to pin at sub-1-gwei gas — a one-time cost, after which
> every scene that references it is free to render.

## The two tiers

- **Library-free tier** (`libHash: ZERO`) — canvas-only sketches that call no p5/three API (plain `<canvas>` 2D or
  WebGL). No library upload. A p5 or three sketch is **never** in this tier: with a zero `libHash` the viewer has no
  library to load, and `checkNode` reports it.
- **Library tier** — p5.js or three.js sketches, with the library pinned on-chain as above. Leave `libHash` empty in
  the builder and Deploy uses the deployed library.

## Why this preserves trustlessness

A naive "on-chain three.js" would fetch the library from a CDN — reintroducing a trusted host and dropping the
grade. ChainRender's version doesn't:

- The **floor is always fully on-chain and Grade A** — the rich enhancement can vanish entirely and you still see a
  complete, correct, trustless render.
- The **library is on-chain and content-addressed** — no CDN, no trusted host. Each stored chunk is keyed by the
  keccak256 of its bytes and the chunk list under a library hash never changes, so a pinned library is always the same
  bytes. (The registry key itself is the hash its uploader declared: neither `DependencyRegistry` nor the viewer yet
  re-hashes the reassembled library against it.)
- The sketch runs **sandboxed** (`allow-scripts` only, `default-src 'none'`) — it can't reach the network, read
  storage, or escape its frame.

This is the floor principle at its most powerful: **you get real p5/three richness *and* absolute trustlessness,
because the rich layer is an enhancement over an on-chain floor, and even the library is on-chain.** See
**[The Floor](../concepts/the-floor.md)**.

## Honest boundaries

- **Rendering the enhancement needs a capable client.** three.js/p5 run client-side (that's the point of an
  enhancement). A client without JS/WebGL, or under a stricter CSP than the sandbox needs, gets the floor. That's
  by design — fail-closed, never broken.
- **three.js is ESM-heavy.** The viewer decodes a *complete, self-contained* three.js (core + module + addons) and
  runs it via `eval` (no dynamic `import` of blob URLs, so it works under strict CSPs). Pin a *bundled complete
  build* — `three.module.min.js` alone isn't self-contained (it imports `three.core`).
- **This is a rich-media viewer capability.** The `renderFloor` path is universal; the library enhancement requires
  the rich-media viewer (or your own client implementing the fetch-verify-sandbox flow).

## Loading the library (the operational reality)

Both libraries load **from chain, as plain script tags** -- sandbox-safe and CSP-safe (no CDN):
- **p5** is **p5.js 2.3.2**, the only p5 registered on every ChainRender chain (`deployment/genesis-libraries*.json`). It
  is a UMD build; it loads as a plain script and sets `window.p5`. Write sketches for the **p5 2.x API** (see below).
- **three.js** must also be the **UMD build (r160, `three.min.js`)** -- it sets `window.THREE`. Modern three (r161+)
  is ESM-only with no global, which does **not** work loaded as a plain script in a strict-CSP sandboxed iframe.
  Sketches use the **global `THREE`** (not `import`). The r160 UMD is the last version with a global build; it is
  ample for generative/artistic 3D.

### Write for p5 2.x, not 1.x

Most examples on the web, and most AI models, still write the p5 **1.x** API. On the deployed p5 2.3.2 these calls
throw, or (`preload`) silently never run. Each was checked in Chromium against p5 2.3.2 and 1.9.0 (docs/194):

| p5 1.x | On p5 2.3.2 | Write instead |
|---|---|---|
| `bezierVertex(x2,y2, x3,y3, x4,y4)` | throws at `endShape` ("reading 'position'") | one point per call: `bezierVertex(x2,y2); bezierVertex(x3,y3); bezierVertex(x4,y4);` |
| `curveVertex`, `curvePoint`, `curveTangent` | not defined | `splineVertex`, `splinePoint`, `splineTangent` (same arguments) |
| `curveTightness(t)` | not defined | `splineProperty('tightness', t)` |
| `quadraticVertex(cx,cy, x,y)` | not defined | `bezierOrder(2); bezierVertex(cx,cy); bezierVertex(x,y);` |
| `bezierDetail(n)` | not defined | remove it |
| `function preload() { … }` | **never called**, so nothing it loads is loaded | `window.setup = async function () { img = await loadImage(url); … }` |

A global variable named after a p5 function (`log`, `text`, `color`, …) also fails on 2.x ("Cannot redefine property").
The review (`chainrender_review`, `npx @chainrender/mcp review`, the builder's Review tab) reports the calls in the
table as the `p5-v1-api` error, with the line of each.

The viewer discovers each library by name in the DependencyRegistry (**newest-wins**, so a re-uploaded UMD library
supersedes an older one), fetches the gzipped chunks via `eth_call`, decompresses with the browser's **native
`DecompressionStream`** (no external gzip library), and injects the source. No importmaps, no blob URLs, no CDN --
which is what keeps it working under a strict Content-Security-Policy.

### Large sketches — chunked SourceStore uploads

The *library* isn't the only thing that can exceed a single storage blob — so can your own **sketch**. When a
sketch is larger than one SourceStore entry, the builder splits it into chunk blobs and writes one extra
**manifest** blob whose payload is `CRCHUNKS1|<id>,<id>,…` (the ordered chunk ids). The SourceStore id the app
references is that manifest. At load, the viewer reads the entry: if it begins with `CRCHUNKS1|` it fetches each
listed chunk and concatenates them; otherwise it uses the entry as-is (a single blob). It then gunzips if the
bytes carry the gzip magic, and runs the sketch. Fully backward-compatible: a small, raw, single-blob sketch has
no manifest header and no gzip magic, so it's used verbatim. This is a deploy + runtime mechanism (builder writes,
viewer reassembles) — the authoring SDK only estimates chunk count (`buildManifest().chunkEstimate`); it never
needs to know how a large asset was split.

## The full-page viewer

A deployed rich-media app runs in the **full-page viewer** (`chainrender-viewer.html`), which takes the scene's
`sketch` (SourceStore id), `lib` (DependencyRegistry libHash), `seed`, and `kind` as URL params, loads them from
chain, and runs the sketch full-viewport over the floor. Every deploy produces a complete shareable viewer URL, and
[Explore](../concepts/apps-directory.md) lists deployed rich-media apps automatically (read from
`SceneComponentRegistry`).

## Reading live on-chain data from a sketch (`window.CR_CHAIN`)

A rich-media sketch runs sandboxed and **cannot reach the network** — but it *can* read real, live on-chain data
through a single injected bridge: **`window.CR_CHAIN`**. This is how a p5/three sketch shows real balances, blocks,
gas, token metadata, logs, and ENS names without a CDN, an API, or a trusted host. Every read is a plain JSON-RPC
call to the chain.

> **Grade note.** A sketch that reads `CR_CHAIN` is still a **client-side enhancement over the on-chain floor**
> (Grade ⚙). The floor renders first and always; `CR_CHAIN` enriches the enhancement with *real* numbers instead
> of fabricated ones. The rule is simple: **never fake chain data.** If you show a block number, a balance, a price,
> or a transfer, it must come from `CR_CHAIN` — never from `random()` or a hardcoded literal presented as live.

### The snapshot (auto-polled)

`CR_CHAIN` exposes a live snapshot that refreshes every few seconds. Read these fields directly:

```js
window.CR_CHAIN.blockNumber    // latest block (number) or null until loaded
window.CR_CHAIN.gasPriceGwei   // current gas price in gwei
window.CR_CHAIN.baseFeeGwei    // current base fee in gwei
window.CR_CHAIN.blockHash      // latest block hash
window.CR_CHAIN.txCount        // tx count in the latest block
window.CR_CHAIN.chainId        // e.g. "11155111" (Sepolia)
window.CR_CHAIN.live           // true ONLY when real data has loaded
window.CR_CHAIN.source         // "live" | "loading" | "unavailable"
```

**Critical timing:** the snapshot loads **asynchronously** (~1–2s after start) — it is **not** ready in `setup()`.
Register a callback with `window.CR_CHAIN.onReady(fn)`, or check `window.CR_CHAIN.live` each frame in `draw()` and
only switch from a `"Loading…"` state to real numbers once `live === true`. Never read once in `setup()` and fall
back to fake data.

```js
window.setup = function () {
  createCanvas(800, 500);
  if (window.CR_CHAIN) window.CR_CHAIN.onReady(function () { /* real data is ready */ });
};
window.draw = function () {
  background(10, 12, 18);
  var live = window.CR_CHAIN && window.CR_CHAIN.live;
  text(live ? ("Block " + window.CR_CHAIN.blockNumber) : "Loading live data…", 20, 40);
};
```

### The read helpers (all Promise-returning, all fail-closed to `null`)

For anything beyond the snapshot, `CR_CHAIN` exposes async helpers. Each returns a Promise, guards for nulls, and
**fails closed** — on any RPC error it resolves to `null` rather than throwing, so your sketch degrades to a labeled
fallback instead of breaking. Prefer these over hand-rolling `eth_call` encoding.

**Generic:**

```js
CR_CHAIN.read(method, params)   // any read-only RPC method, returns the raw result
CR_CHAIN.call(to, data)         // eth_call to a contract (hex selector + args)
CR_CHAIN.balanceOf(addr)        // NATIVE ETH balance (in ether), NOT a token balance
CR_CHAIN.logs(filter)           // eth_getLogs with a raw filter object
CR_CHAIN.tx(hash)               // a transaction by hash
CR_CHAIN.block(numOrTag)        // a block (with transactions)
```

**Tokens** — read metadata and balances the honest way (never guess decimals):

```js
CR_CHAIN.erc20(tokenAddr)                 // -> { name, symbol, decimals, decimalsStatus, totalSupply, totalSupplyFloat, error }
CR_CHAIN.tokenBalanceOf(tokenAddr, holder)// -> decimal string of an ERC-20 balance
CR_CHAIN.tokenDecimals(tokenAddr)         // -> the token's decimals (number)
CR_CHAIN.native                           // -> { symbol, decimals: 18 }: the chain's gas token (ETH, or USDC on Arc)
CR_CHAIN.formatUnits(raw, decimals, 6)    // -> "1,234.5" exact; a nonzero dust amount is "<0.000001", never "0.000000"
```

`decimalsStatus` says why `decimals` is missing, so an app never has to guess:

| `decimalsStatus` | Meaning | Show |
|---|---|---|
| `"ok"` | `decimals` was read on-chain | the scaled amount |
| `"absent"` | the address answered no `decimals()` (it reverted, returned nothing, or not a uint8): not a token with decimals | the raw amount, labelled raw |
| `"failed"` | the read itself failed; `error` says why (e.g. `HTTP 429`) | "unavailable", and try again later |

`CR_CHAIN.read` (and every helper built on it) retries a rate limit, a timeout, a network error or an HTTP 5xx three
times (after 0.4 s, 1.2 s and 3 s); a revert or a range refusal is answered at once. `CR_CHAIN.readOnce` makes one
attempt. Token names and symbols are decoded as UTF-8 (`USD₮0`, not `USDâ‚®0`).

> **Always scale token amounts by the real `decimals`.** Call `erc20()` (or `tokenDecimals()`) once, cache it, and
> divide raw amounts by `10 ** decimals`. Hardcoding `/ 1e6` or `/ 1e18` will render a *real* number at the wrong
> scale — which is a data-honesty violation exactly like fabricating one.

**Transactions & accounts** — including whether a tx actually succeeded:

```js
CR_CHAIN.receipt(hash)  // -> { status: "success" | "reverted", gasUsed, effectiveGasPriceGwei, blockNumber, logs }
CR_CHAIN.nonceOf(addr)  // -> the address's transaction count
```

> `tx()` alone can’t tell you if a transaction reverted — use `receipt()` and read `status` before showing any
> “confirmed”/“success” state.

**Code & storage:**

```js
CR_CHAIN.isContract(addr)      // -> boolean (guards a hardcoded address before you read it)
CR_CHAIN.codeSize(addr)        // -> bytecode size in bytes
CR_CHAIN.storageAt(addr, slot) // -> raw storage slot (advanced)
```

**Gas fee history** — a real gas chart in one call (prefer over sampling `gasPriceGwei` over wall-clock time):

```js
CR_CHAIN.feeHistory(nBlocks, percentiles)
// -> { baseFeeGwei: [...], gasUsedRatio: [...], oldestBlock, reward: [[...]] }
```

**Event logs** — the honest source for *historical activity* (transfers, mints, swaps), with decode helpers:

```js
CR_CHAIN.logsBetween(addr, topic, fromBlock, toBlock)  // an explicit range
CR_CHAIN.recentLogs(addr, topic, lookbackBlocks)       // auto-ranges from the current block
CR_CHAIN.decodeTransfer(log)  // -> { from, to, valueRaw, tokenId, blockNumber, txHash } (handles ERC-20 vs ERC-721)
CR_CHAIN.topicAddr(topic32)   // extract an address from a 32-byte indexed topic
```

> When decoding events, **verify the shape** (`topics[0]` matches the event signature, `topics.length` matches the
> indexed-parameter count) — an ERC-721 `Transfer` indexes `tokenId` and has no `data`, unlike ERC-20. And when you
> show a bounded window, **disclose it** ("last ~2000 blocks"), never imply a complete history.

**ENS** — human-readable names instead of raw hex (see the [ENS guide](../guides/ens-integration.md)):

```js
CR_CHAIN.ensName(addr)       // reverse-resolve an address -> "vitalik.eth" (or null)
CR_CHAIN.ensAddr(name)       // forward-resolve a name -> address (or null)
CR_CHAIN.ensText(name, key)  // read a text record (avatar, url, com.twitter, …)
```

**Activity feeds** — recent NFT or token transfers across a contract, or chain-wide, without writing a log scanner:

```js
CR_CHAIN.feed({ kind: "nft-transfers", blocks: 2000, limit: 24, onPage: (p) => redraw(p) })
  .then((r) => { rows = r.events; caption = r.caption; });   // show r.caption — it says what was read
```

`kind` is `nft-transfers`, `nft-mints`, `nft-all`, `erc20-transfers`, `token-transfers` (ERC-20 and ERC-721, no native),
`native-transfers`, `transfers` or `logs`. Add `address` to read one
contract. `feed` pages **adaptively** (docs/196): public RPCs refuse a large `eth_getLogs` (by block range, result count
or response size), and a chain-wide Transfer query over even 2,000 blocks is refused on a busy chain. So it starts with
small pages (250 blocks chain-wide, 5,000 for one contract), halves a page the RPC refuses, never widens back to a
refused size, and waits out rate limits. `limit` stops it as soon as the newest N matching events are found. The
result's `window` is the range **actually read** (`{fromBlock, toBlock, scanned, requested}`), and `caption` states it
("last 2000 blocks (blocks …)", or "partial: last 600 of 2000 blocks requested" when it had to stop early).

The result, exactly (an AI stress test on 2026-11-01 guessed these, so they are spelled out):

| Field | Meaning |
|---|---|
| `events[]` | newest first: `{ contract, from, to, standard, tokenId, valueRaw, decimals, symbol, isMint, isBurn, block, logIndex, txHash }` |
| `standard` | `"erc20"`, `"erc721"` or `"native"`, lowercase with no hyphen |
| `tokenId` | the ERC-721 token id as a decimal string; `null` otherwise |
| `valueRaw` | the amount as 0x-hex (32 bytes) for ERC-20 and native; `null` for ERC-721. Scale an ERC-20 with `CR_CHAIN.erc20(contract).decimals`, a native transfer with `decimals` |
| `decimals` | `18` for native; `null` otherwise (an ERC-20 reads its own) |
| `symbol` | native: the chain's gas token (`CR_CHAIN.native.symbol`: `ETH` on Sepolia, `USDC` on Arc); `null` otherwise |
| `window` | `{ fromBlock, toBlock, scanned, requested }`: the range actually read |
| `complete` | `true` when the whole requested window was read |
| `reason` | `null` when complete; `"limit"` when it stopped because it found `limit` events (normal, not an error); otherwise the RPC error that stopped it early |
| `caption` | show it as is |

**Native transfers (EIP-7708).** On chains that emit them (Sepolia, and Arc, which ships its own implementation),
every native-coin transfer is a `Transfer(from, to, value)` log from `0xfffffffffffffffffffffffffffffffffffffffe`:
the same topic and shape as an ERC-20 transfer, but there is no contract at that address, so `decimals()` returns
nothing. The feed labels these `standard: "native"` with `decimals: 18` and the gas token's `symbol`. Never call
`erc20()` on them. `transfers` includes them, `erc20-transfers` and `token-transfers` leave them out, and `native-transfers` is only
them. For a filtered view, ask for the matching kind: the feed then pages until it has `limit` of them.

`onPage(p)`: `p.scannedFrom`–`p.scannedTo` is this page; `p.readFrom`–`p.readTo` is everything read so far (cumulative,
so don't add pages up); `p.count` is this page's logs, and `p.total` / `p.matched` are the events so far (all, and of your
kind).

### The honesty rules (enforced by the builder, expected of every sketch)

- **Gate the "LIVE" label on `CR_CHAIN.live === true`.** Until then, show `"Loading…"`. If `CR_CHAIN` is missing or
  `live` is false, label the display `"Offline / Simulated"` and suffix any placeholder with `(SIM)` — never a fake
  number under a LIVE label.
- **Label each data region by its own read.** A successful `blockNumber` does *not* mean your `erc20()` or
  `feeHistory()` call succeeded — gate each region on its own result, not one global flag.
- **Cache one-time reads** (`erc20` metadata, `decimals`, `isContract`) and **throttle repeating reads** — never call
  a helper every frame; gate on a frame counter or a several-second interval.
- **Null-guard everything** and `.catch()` every call, falling back to a clearly-labeled state.
- **Only `CR_CHAIN` is reachable.** The sandbox blocks all other network access by design — do not attempt to `fetch`
  any other URL or CDN.

## Icons in rich-media (and any) apps

On-chain [icons](../concepts/icons.md) are available to rich-media and standard apps alike -- discovered by name,
injected, theme-adaptive. The viewer loads them the same CSP-safe way as p5/three.

## Related
- **[The Floor](../concepts/the-floor.md)** — the principle this is built on.
- **[Visual & Media Capabilities](../concepts/visual-media.md)** — the on-chain floors (SDF, generative art) these
  enhance.
- **[What's Fully On-Chain](../concepts/fully-on-chain.md)** — including the on-chain library storage.
