# Folklore Cartridge (`.fkc`) — sprite `.bin` → loadable on-chain cartridge

**Status:** draft spec · **Date:** 2026-06-29 · **Author:** tehironclad
**Scope:** define the cartridge binary format and the full author → run loop on the Folklore CPU, so a sprite drawn in the editor becomes a tradeable on-chain cartridge that any client can load, run, and render. This is the `0xHEX .bin` snippet economy from Maria's day-909 brief, written down.

> Reverse-engineered from the live atropa sources — citations are `atropa_pulsechain/...`:
> `frontend/sprite_editor.html`, `frontend/unix1.yul`, `frontend/sh.yul`,
> `solidity/bin/{folklore,cpu6502}.yul`, `Dysnomia/Lib/FolkloreAssembler.cs`,
> `lore/auncient_cartridge_strategy_lore.md`.

---

## 1. The loop

```
 AUTHOR            COMPILE          PACKAGE          PUBLISH              LOAD            RUN              RENDER
 sprite_editor  →  6502 asm     →  .fkc container →  write_instruction →  sys_exec     →  sys_step ×N   →  peek $E000..$E1FF
 (64×64 grid)      (LDA/STA/RTS)   (header+code)     (on-chain, nameHash) (load by hash)  (CPU executes)   → blit framebuffer
                                                     └─ mint ERC-721 ────┐
                                                        cartridge token  └─ pass nameHash as an argument to any game
```

Today only the first two boxes exist, and even Export only *prints* the opcodes. §6 is the gap list.

---

## 2. Target machine — the Folklore CPU

An on-chain 6502. State lives in contract storage; the contract *is* the RAM.

### Memory map
| Range | Bytes | Purpose |
|---|---|---|
| `$0200`+ | — | Program origin / load address (cartridge code) |
| `$E000`–`$E1FF` | 512 | **Sprite framebuffer** — 1bpp, 64×64, row-major, MSB-first |
| (other) | — | zero-page, stack `$0100`, registers per `cpu6502.yul` |

The 64×64 framebuffer is exactly `64/8 × 64 = 512` bytes (`sprite_editor.html:348`).

### On-chain ABI
| Function | Selector | Role |
|---|---|---|
| `poke(uint256 addr, uint256 val) → uint256` | — | write one RAM byte (raw data path) |
| `peek(uint256 addr) → uint256` (view) | — | read one RAM byte (render path) |
| `write_instruction(nameHash, offset, instruction) → success` | `0x77726974` | upload one byte/opcode of a named binary |
| `sys_exec(pid, binaryHash) → success` | `0x5f2f5361` | load a stored binary as the active program for `pid` |
| `sys_step(pid) → success` | `0x00c71a91` | execute one instruction of the active program |
| `runSteps(uint256 maxSteps) → uint256` | — | execute up to N instructions (batch) |

`sh.yul` "run" = `sys_exec(0, fileHash)` then loop `sys_step(0)`. Reference contract on the editor: `0x52173b6ac069619c206b9A0e75609fC92860AB2A`.

### Opcode subset used by sprite cartridges
| Mnemonic | Byte | Form | Meaning |
|---|---|---|---|
| `LDA #imm` | `0xA9 ii` | 2 bytes | A ← imm |
| `STA abs` | `0x8D ll hh` | 3 bytes | `mem[hh ll]` ← A (little-endian addr) |
| `RTS` | `0x60` | 1 byte | return (end of cartridge) |

Full 6502 set is in `solidity/bin/cpu6502.yul`; games use more (branches, sound-register writes — see `auncient_cartridge_strategy_lore.md`).

---

## 3. Raw sprite payload (the 512-byte bitmap)

Packing (matches `sprite_editor.html:357-368` / `:382-393`):
- 64 rows × 8 bytes/row, row-major top-to-bottom.
- Within a byte, pixel `x` → bit `7-(x mod 8)` (MSB = leftmost). `1` = lit.
- Byte `i` maps to framebuffer address `$E000 + i`.

This raw form is what **Solder Grid** writes directly: `poke($E000+i, byte[i])` for all 512 bytes. Stateful, no code — good for "set the screen now," bad for sharing (it's data, not a runnable artifact).

---

## 4. Cartridge container — `.fkc`

A cartridge is **executable code**, not raw data: a 6502 program that *reconstructs* the sprite into `$E000` and returns. The editor already compiles this (`:395-411`) — `LDA #b / STA $E000+i` per non-zero byte, then `RTS` — but emits headerless, un-downloadable opcodes. This spec adds a 16-byte self-describing header so a loader can identify, version, and run any cartridge.

### Header (16 bytes, little-endian)
| Off | Size | Field | Notes |
|---|---|---|---|
| 0 | 4 | magic | `46 4B 43 01` (`"FKC"`,ver 1) |
| 4 | 1 | version | format version |
| 5 | 1 | type | `01` sprite-loader · `02` game · `03` audio · … |
| 6 | 2 | origin | load address, e.g. `0200` |
| 8 | 2 | entry | first PC, e.g. `0200` |
| 10 | 2 | code_len | payload length in bytes |
| 12 | 2 | fb_base | framebuffer base, e.g. `E000` |
| 14 | 1 | fb_format | `01` = 1bpp 64×64 mono |
| 15 | 1 | flags | bit0 sparse (zero-bytes skipped) |
| 16 | code_len | **payload** | 6502 machine code |

`.bin` = header ‖ payload. A bare-opcode export (no header) is still valid as a *legacy* cartridge if a loader assumes `type=01, origin=entry=$0200, fb_base=$E000`.

### Sparse vs full
The current compiler **skips zero bytes** (`if (bytes[i] !== 0)`), so blank rows cost nothing — set `flags.sparse=1`. A `full` variant (emit all 512 stores) is deterministic-size, useful for animation frames that overwrite.

---

## 5. On-chain storage & the cartridge token

Two storage models; pick per use:

1. **Named binary (executable).** Upload payload byte-by-byte with `write_instruction(nameHash, offset, byte)`, `nameHash = keccak256(name)`. Run with `sys_exec(pid, nameHash)` + `runSteps(code_len)`. This is the canonical "cartridge you can run."
2. **Blob (data).** Store the whole `.fkc` in a `bytes` slot keyed by hash; clients fetch and execute locally or hand to `sys_exec`.

### Cartridge token (the tradeable part)
- Mint an **ERC-721** (or ERC-1155 for editions) whose token id ↔ `nameHash`.
- `tokenURI` → metadata: title, author LAU, `type`, a PNG/SVG preview rendered from the payload, and the `nameHash` + `code_len`.
- **"Passed as an argument"** (Maria's phrase) = the 32-byte `nameHash`: any game can `sys_exec(pid, nameHash)` to splice in a community sprite/NPC/sound routine. A cartridge is thus both a collectible *and* a callable.
- Provenance ties to identity: sign the `.fkc` hash in-wallet (entropy already does in-wallet YI provenance signing — reuse it).

---

## 6. What exists vs. what's missing

| Stage | State | Gap to close |
|---|---|---|
| Author (64×64 editor) | ✅ works | — |
| Compile to 6502 | ✅ works (`:395-411`) | only displayed as hex text |
| **Download `.bin`** | ❌ | wrap opcodes in the §4 header → `Blob` → download |
| **Header / self-describing** | ❌ | add the 16-byte header |
| Solder (poke data) | ✅ works | — |
| **Upload cartridge on-chain** | ❌ | loop `write_instruction(nameHash,i,byte)` |
| **Load a cartridge back** | ❌ | "Import .fkc" → parse header → preview/run |
| **Run + render in-browser** | ❌ | JS 6502 step loop (or `sys_step`) → blit `$E000` to canvas |
| **Mint as token** | ❌ | ERC-721 wrapper keyed by `nameHash` + preview metadata |

---

## 7. Build plan (close the loop)

Smallest path to a working demo, in order:

1. **Real `.bin` export** — add the §4 header, emit a `Blob`, trigger download. (~30 min, editor-only.)
2. **In-browser run+render** — a ~150-line JS 6502 interpreter (LDA/STA/RTS is enough for sprite cartridges) that executes a `.fkc` and blits `$E000` to a canvas. Proves load-back with zero chain. Reusable as the entropy **Cartridge Viewer**.
3. **Import .fkc** in the editor — parse header, load payload, render, allow re-edit.
4. **On-chain upload + run** — `write_instruction` loop + `sys_exec`/`runSteps`, then `peek` the framebuffer to confirm parity with the local render.
5. **Mint** — ERC-721 keyed by `nameHash`, preview PNG in metadata, in-wallet provenance signature.

### Where entropy fits (read-side, on-brand)
Per the lore-layer refocus, entropy doesn't author or mint — **System 1** does the wallet/mint. Entropy ships the **Cartridge Viewer + Gallery**: fetch a `nameHash`/`.fkc`, run it client-side (step 2), render the sprite, show provenance, and — the tie-in — auto-feature new cartridges as a recurring section in the **Lore Zine** (Issue 003 "Insert Coin" already themes this). Authoring/mint links out to System 1.

---

## 8. Worked example (2×2 corner pixel)

Grid: only `(0,0)` lit → row 0 byte 0 = `0x80`, all others `0`.
- Sparse cartridge payload: `A9 80 8D 00 E0 60` (`LDA #$80 ; STA $E000 ; RTS`).
- `.fkc` = `46 4B 43 01 01 01 00 02 00 02 06 00 00 E0 01 01` ‖ `A9 80 8D 00 E0 60`.
- Run: `sys_exec(0, keccak("corner"))`, `runSteps(6)` → `peek($E000) == 0x80` → blit → one lit pixel, top-left.
