diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 258b7ae..2ea695e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,8 +20,7 @@ jobs: cache: npm - run: npm ci - run: npm run check + - run: npm run copyrules - run: npm run build # Internal links only (external URLs skipped to avoid flaky runs). - # favicon.svg is skipped: Starlight's default /favicon.svg is missing - # (no public/ dir) -- TODO add a favicon and drop this skip. - run: npm run linkcheck diff --git a/CLAUDE.md b/CLAUDE.md index f1ad30e..3d73546 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,25 +1,61 @@ # CLAUDE.md — MIST.cash Docs +Astro Starlight site for MIST.cash, restyled to the landing design +(`landing/DESIGN.md` is the source of truth). Content describes the EVM +protocol: the gnark Groth16 circuit, the Solidity contracts and +`@mistcash/sdk`. `spec/` in the root repo is the document of record: a spec +claim beats marketing copy. + ## Commands -- `npm run dev` — Start local dev server with HMR -- `npm run build` — Build static site to `dist/` -- `npm run preview` — Preview the production build locally +- `npm run dev` — local dev server with HMR +- `npm run check` — `astro check` +- `npm run copyrules` — holds every page to the MIST copy rules (prose only) +- `npm run build` — static site to `dist/` +- `npm run linkcheck` — internal link check, after a build +- `npm run preview` — preview the production build + +CI runs check, copyrules, build and linkcheck. All four must be green. -## Directory Layout +## Directory layout ``` -├── astro.config.mjs # Astro + Starlight configuration +├── astro.config.mjs # Starlight config: sidebar, component overrides, code themes +├── scripts/copy-rules.mjs # copy-rules check for src/content/docs +├── public/ # self-hosted fonts (Josefin Sans, Sen) and favicons ├── src/ -│ ├── content.config.ts # Content collection schema -│ ├── content/docs/ # Markdown/MDX documentation pages -│ │ ├── index.mdx -│ │ ├── getting-started.mdx -│ │ ├── guides/ # Deposit, withdraw, ZK proofs, Merkle trees -│ │ ├── packages/ # SDK, config, React packages -│ │ └── reference/ # API, types, contract ABI +│ ├── assets/ # wordmark used by the header +│ ├── components/ # SiteTitle, Hero, Footer overrides; RuledIndex, RecordStrip, Icon +│ │ └── diagrams/ # Figure, Cell, Chip, Reserve, NoteLife, Architecture +│ ├── content/docs/ +│ │ ├── index.mdx # Introduction (splash) +│ │ ├── how-it-works.mdx +│ │ ├── architecture.mdx +│ │ ├── circuits/ # index.mdx, then detailed pages +│ │ ├── contracts/ # index.mdx, then detailed pages +│ │ └── sdk/ # index.mdx, then detailed pages │ └── styles/ -│ └── custom.css # Custom Starlight theme overrides -├── tsconfig.json -└── package.json +│ ├── tokens.css # brand tokens and the Starlight variable mapping +│ ├── theme.css # Starlight components restyled +│ ├── diagram.css # the diagram grammar +│ └── code-themes.mjs # syntax themes from the brand palette ``` + +## Adding a page + +Drop an `.mdx` file under `src/content/docs/circuits/`, `contracts/` or `sdk/`. +The sidebar is autogenerated per directory; order with +`sidebar: { order: N }` in frontmatter (each section's `index.mdx` is order 0 +and labelled "
overview"). Link the new page from its section's index. + +## Design rules that bind this repo + +- Three colours only: midnight, azure, coral, plus tints of them. No green or + red for status: say what happened in words. +- Square corners (2px on controls), 1px rules, no shadow, no blur, no gradient. +- Coral is the one action and at most one marker per view. Never a coral word. +- Josefin Sans for headings, Sen for text, system monospace for code. +- Diagrams use the grammar in `src/styles/diagram.css` and the components in + `src/components/diagrams/`, and must read in both themes at 390px. +- Run `npm run copyrules` before pushing: no em-dashes, no `token`, no chain + names, no hype, no "test". diff --git a/README.md b/README.md index 78f35f1..6e8cf3f 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ Astro + Starlight documentation site. npm ci npm run dev # local dev server npm run check # astro check +npm run copyrules # copy rules on every page npm run build # static build to dist/ npm run linkcheck # internal link check (after build) ``` diff --git a/astro.config.mjs b/astro.config.mjs index 69a250e..b38ab75 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -1,56 +1,91 @@ // @ts-check import { defineConfig } from "astro/config"; import starlight from "@astrojs/starlight"; +import { mistFog, mistMidnight } from "./src/styles/code-themes.mjs"; // https://astro.build/config export default defineConfig({ site: "https://docs.mist.cash", integrations: [ starlight({ - title: "MIST.cash SDK", + title: "MIST.cash Docs", description: - "Privacy-focused SDK for zero-knowledge transactions on Starknet", + "Documentation for MIST.cash, a protocol for private stablecoin payments on EVM chains with compliance set per Reserve: the circuit, the contracts and the TypeScript SDK.", + favicon: "/favicon.ico", social: [ { icon: "github", label: "GitHub", - href: "https://github.com/mistcash/sdk", + href: "https://github.com/mistcash", }, ], - customCss: ["./src/styles/custom.css"], - sidebar: [ + customCss: [ + "./src/styles/tokens.css", + "./src/styles/theme.css", + "./src/styles/diagram.css", + ], + components: { + SiteTitle: "./src/components/SiteTitle.astro", + Hero: "./src/components/Hero.astro", + Footer: "./src/components/Footer.astro", + }, + expressiveCode: { + themes: [mistMidnight, mistFog], + styleOverrides: { + borderColor: "var(--mist-line-strong)", + borderRadius: "0", + codeFontSize: "0.8125rem", + codeLineHeight: "1.6", + frames: { + frameBoxShadowCssValue: "none", + }, + }, + }, + head: [ { - label: "Start Here", - items: [ - { label: "Introduction", slug: "" }, - { label: "Getting Started", slug: "getting-started" }, - ], + tag: "link", + attrs: { + rel: "preload", + href: "/fonts/Sen-Variable-latin.woff2", + as: "font", + type: "font/woff2", + crossorigin: "", + }, }, { - label: "Packages", - items: [ - { label: "@mistcash/sdk", slug: "packages/core" }, - { label: "@mistcash/config", slug: "packages/config" }, - { label: "@mistcash/react", slug: "packages/react" }, - ], + tag: "link", + attrs: { + rel: "preload", + href: "/fonts/JosefinSans-Variable-latin.woff2", + as: "font", + type: "font/woff2", + crossorigin: "", + }, }, { - label: "Guides", - items: [ - { label: "Depositing Tokens", slug: "guides/deposit" }, - { label: "Withdrawing Tokens", slug: "guides/withdraw" }, - { label: "Zero-Knowledge Proofs", slug: "guides/zero-knowledge" }, - { label: "Merkle Trees", slug: "guides/merkle-trees" }, - ], + tag: "link", + attrs: { rel: "apple-touch-icon", href: "/apple-touch-icon.png" }, }, { - label: "Reference", + tag: "meta", + attrs: { name: "theme-color", content: "#010511" }, + }, + ], + sidebar: [ + { + label: "Overview", items: [ - { label: "API Reference", slug: "reference/api" }, - { label: "Types", slug: "reference/types" }, - { label: "Contract ABI", slug: "reference/contract" }, + { label: "Introduction", slug: "" }, + { label: "How MIST works", slug: "how-it-works" }, + { label: "Architecture", slug: "architecture" }, ], }, + // Each section below is autogenerated from its directory, so a page + // added under src/content/docs/
/ appears without touching + // this file. Order pages with `sidebar: { order: N }` in frontmatter. + { label: "Circuits", autogenerate: { directory: "circuits" } }, + { label: "Contracts", autogenerate: { directory: "contracts" } }, + { label: "SDK", autogenerate: { directory: "sdk" } }, ], }), ], diff --git a/package.json b/package.json index 7d8d018..d7c533a 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,8 @@ "preview": "astro preview", "astro": "astro", "check": "astro check", - "linkcheck": "linkinator dist --recurse --silent --skip \"^https?://(?!localhost|127\\.0\\.0\\.1)\" --skip \"favicon\\.svg$\"" + "copyrules": "node scripts/copy-rules.mjs", + "linkcheck": "linkinator dist --recurse --silent --skip \"^https?://(?!localhost|127\\.0\\.0\\.1)\"" }, "dependencies": { "@astrojs/starlight": "^0.34.0", diff --git a/public/apple-touch-icon.png b/public/apple-touch-icon.png new file mode 100755 index 0000000..2f08851 Binary files /dev/null and b/public/apple-touch-icon.png differ diff --git a/public/favicon-32x32.png b/public/favicon-32x32.png new file mode 100755 index 0000000..c39a2c4 Binary files /dev/null and b/public/favicon-32x32.png differ diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100755 index 0000000..c35cc28 Binary files /dev/null and b/public/favicon.ico differ diff --git a/public/fonts/JosefinSans-Variable-latin.woff2 b/public/fonts/JosefinSans-Variable-latin.woff2 new file mode 100644 index 0000000..4a3ce05 Binary files /dev/null and b/public/fonts/JosefinSans-Variable-latin.woff2 differ diff --git a/public/fonts/Sen-Variable-latin.woff2 b/public/fonts/Sen-Variable-latin.woff2 new file mode 100644 index 0000000..a2e403d Binary files /dev/null and b/public/fonts/Sen-Variable-latin.woff2 differ diff --git a/scripts/copy-rules.mjs b/scripts/copy-rules.mjs new file mode 100644 index 0000000..aae9cf1 --- /dev/null +++ b/scripts/copy-rules.mjs @@ -0,0 +1,86 @@ +// Holds every docs page to the MIST copy rules (landing/PRODUCT.md, "Copy +// rules"; the same patterns as landing/src/lib/copy-rules.ts). Prose only: +// fenced code, inline code and import lines are skipped, so a code sample may +// say `token` or `test` where the API does. Run: npm run copyrules +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { join } from "node:path"; + +export const RULES = [ + { id: "test", pattern: /\btest(s|ing)?\b/i, why: "never say test" }, + { id: "mainnet", pattern: /\b(testnets?|mainnets?)\b/i, why: "no network status words" }, + { id: "token", pattern: /\btokens?\b/i, why: "say stablecoins or assets" }, + { + id: "chain-name", + pattern: /\b(ethereum|arbitrum|sepolia|starknet|optimism|polygon|solana|avalanche)\b/i, + why: "no chain or network names for our deployment", + }, + { id: "em-dash", pattern: /—/, why: "no em-dashes: use a full stop or a comma" }, + { id: "arrow-glyph", pattern: /[←-↓↗↘]/, why: "arrows are drawn icons, never glyphs" }, + { + id: "privacy-hype", + pattern: /\b(mixers?|untraceable|anonymous|anonymity|shielded|quantum[- ]proof|quantum[- ]safe)\b/i, + why: "banned privacy wording", + }, + { + id: "hype", + pattern: + /\b(seamless(ly)?|unlock(s|ed|ing)?|empower(s|ed|ing)?|revolutionary|next[- ]gen|supercharge[sd]?|world[- ]class)\b/i, + why: "no hype words", + }, + { id: "emoji", pattern: /\p{Extended_Pictographic}/u, why: "no emoji" }, +]; + +/** Blank out fenced code, inline code and import lines, keeping line numbers. */ +export function prose(source) { + let inFence = false; + return source + .split("\n") + .map((line) => { + if (/^\s*(```|~~~)/.test(line)) { + inFence = !inFence; + return ""; + } + if (inFence || /^import\s/.test(line)) return ""; + return line.replace(/`[^`]*`/g, ""); + }) + .join("\n"); +} + +export function findViolations(source) { + const found = []; + prose(source) + .split("\n") + .forEach((text, i) => { + for (const rule of RULES) { + if (rule.pattern.test(text)) found.push({ rule: rule.id, why: rule.why, line: i + 1, text: text.trim() }); + } + }); + return found; +} + +function* walk(dir) { + for (const name of readdirSync(dir)) { + const path = join(dir, name); + if (statSync(path).isDirectory()) yield* walk(path); + else if (/\.mdx?$/.test(name)) yield path; + } +} + +if (import.meta.url === `file://${process.argv[1]}`) { + const root = process.argv[2] ?? "src/content/docs"; + let files = 0; + let bad = 0; + for (const file of walk(root)) { + files++; + for (const v of findViolations(readFileSync(file, "utf8"))) { + bad++; + console.error(`${file}:${v.line} [${v.rule}] ${v.why}: ${v.text}`); + } + } + if (files === 0) { + console.error(`copy rules: no pages found under ${root}`); + process.exit(1); + } + console.log(`copy rules: ${files} pages, ${bad} violations`); + process.exit(bad === 0 ? 0 : 1); +} diff --git a/src/assets/mist.cash-light.svg b/src/assets/mist.cash-light.svg new file mode 100644 index 0000000..875a967 --- /dev/null +++ b/src/assets/mist.cash-light.svg @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/components/Footer.astro b/src/components/Footer.astro new file mode 100644 index 0000000..507a40a --- /dev/null +++ b/src/components/Footer.astro @@ -0,0 +1,11 @@ +--- +// The stock footer (edit link, last updated, pagination) with the record +// strip beneath it, which closes every page as it does on the landing. +import Default from "@astrojs/starlight/components/Footer.astro"; +import RecordStrip from "./RecordStrip.astro"; +--- + + + diff --git a/src/components/Hero.astro b/src/components/Hero.astro new file mode 100644 index 0000000..208b335 --- /dev/null +++ b/src/components/Hero.astro @@ -0,0 +1,34 @@ +--- +// Replaces Starlight's hero: left-aligned copy on a midnight field beside the +// record, with one coral action. Reads the same `hero` frontmatter. +import Icon from "./Icon.astro"; +import RecordField from "./RecordField.astro"; + +const { title = Astro.locals.starlightRoute.entry.data.title, tagline, actions = [] } = + Astro.locals.starlightRoute.entry.data.hero ?? {}; +--- + +
+
+

+ {tagline &&

} + { + actions.length > 0 && ( +

+ {actions.map((a) => ( + + {a.text} + + + ))} +
+ ) + } +

+
+ +
+
diff --git a/src/components/Icon.astro b/src/components/Icon.astro new file mode 100644 index 0000000..33c2654 --- /dev/null +++ b/src/components/Icon.astro @@ -0,0 +1,32 @@ +--- +// Authored icon set from landing/src/components/ui/Icon.tsx: 24px grid, +// 1.5px stroke, square caps, currentColor. Only the icons the docs use. +const paths = { + "arrow-right": "M4 12h15M13 6l6 6-6 6", + "arrow-up-right": "M7 17 17 7M8 7h9v9", + lock: "M5 10.5h14v10H5zM8 10.5v-3a4 4 0 0 1 8 0v3", +} as const; + +interface Props { + name: keyof typeof paths; + size?: number; +} + +const { name, size = 20 } = Astro.props; +--- + + diff --git a/src/components/RecordField.astro b/src/components/RecordField.astro new file mode 100644 index 0000000..7af7fe9 --- /dev/null +++ b/src/components/RecordField.astro @@ -0,0 +1,27 @@ +--- +// The hero's record field: a grid of identical note cells with one coral cell. +// Decorative, so hidden from assistive tech. On phones only the first rows show. +const cols = 10; +const rows = 8; +const filled = [ + "1101110101", + "0111011010", + "1011101110", + "1110101101", + "0101110111", + "1011011010", + "1101101110", + "0111010111", +]; +const hot = { row: 3, col: 4 }; +const cells = filled.flatMap((r, row) => + [...r].map((c, col) => ({ + state: row === hot.row && col === hot.col ? "followed" : c === "1" ? "recorded" : "empty", + phoneHidden: row >= 5, + })), +); +--- + + diff --git a/src/components/RecordStrip.astro b/src/components/RecordStrip.astro new file mode 100644 index 0000000..6d4355c --- /dev/null +++ b/src/components/RecordStrip.astro @@ -0,0 +1,28 @@ +--- +// The site's signature motif: the shared record as a run of identical note +// cells, one of them coral. Ported from landing/src/components/ui/RecordStrip. +// Decorative only, so it is hidden from assistive tech. +interface Props { + cells?: number; + /** Index of the coral cell, or -1 for none. */ + highlight?: number; + /** Cells shown on a phone; the rest are hidden. */ + mobileCells?: number; +} + +const { cells = 48, highlight = 13, mobileCells = 20 } = Astro.props; +const pattern = [1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0]; +const items = Array.from({ length: cells }, (_, i) => ({ + i, + state: i === highlight ? "followed" : pattern[i % pattern.length] === 1 ? "recorded" : "empty", + hideOnPhone: i >= mobileCells, +})); +--- + + diff --git a/src/components/RuledIndex.astro b/src/components/RuledIndex.astro new file mode 100644 index 0000000..465f46e --- /dev/null +++ b/src/components/RuledIndex.astro @@ -0,0 +1,25 @@ +--- +// An index of ruled rows (the landing's blog-index pattern), for pages that +// point at their children. Each row: a title, one sentence, a drawn arrow. +// Use instead of a grid of cards. +import Icon from "./Icon.astro"; + +interface Props { + items: { href: string; title: string; body: string }[]; +} +const { items } = Astro.props; +--- + + diff --git a/src/components/SiteTitle.astro b/src/components/SiteTitle.astro new file mode 100644 index 0000000..c00e82f --- /dev/null +++ b/src/components/SiteTitle.astro @@ -0,0 +1,42 @@ +--- +// Header title: the landing's wordmark with "Docs" beside it. The wordmark is +// the light variant, which is what the landing header uses on midnight. +import logo from "../assets/mist.cash-light.svg"; + +const { siteTitle, siteTitleHref } = Astro.locals.starlightRoute; +--- + + + + + + + diff --git a/src/components/diagrams/Architecture.astro b/src/components/diagrams/Architecture.astro new file mode 100644 index 0000000..a320bcc --- /dev/null +++ b/src/components/diagrams/Architecture.astro @@ -0,0 +1,46 @@ +--- +// The architecture in one drawing: spend proofs go to one Chamber, which holds +// the shared record and no assets. Reserves hold the assets, each under its +// own rules. The example Reserves are the spec's example deployment. +import Figure from "./Figure.astro"; +import Cell from "./Cell.astro"; +import Reserve from "./Reserve.astro"; + +const record = [ + "1101110101110", + "0111011010111", + "1011101110101", +].flatMap((r) => [...r].map((c) => (c === "1" ? "recorded" : "empty") as "recorded" | "empty")); +--- + +
+
+
+ + +

Spend proof, made on the user's device

+
+ +
+

Chamber · one per network · holds no assets

+
+ {record.map((state) => )} +
+
    +
  • Transactions tree
  • +
  • Nullifiers
  • +
  • zkState tree
  • +
  • ChamberVerifier
  • +
+
+ +
+ + + +
+
+
diff --git a/src/components/diagrams/Cell.astro b/src/components/diagrams/Cell.astro new file mode 100644 index 0000000..8ec246b --- /dev/null +++ b/src/components/diagrams/Cell.astro @@ -0,0 +1,14 @@ +--- +// One note: a square cell. States follow DESIGN.md's diagram grammar. +// empty hairline outline +// recorded faint fill, strong border +// followed coral fill (the payment being followed; one per figure) +// hidden a solid redaction bar +// shared coral outline +interface Props { + state?: "empty" | "recorded" | "followed" | "hidden" | "shared"; +} +const { state = "recorded" } = Astro.props; +--- + + diff --git a/src/components/diagrams/Chip.astro b/src/components/diagrams/Chip.astro new file mode 100644 index 0000000..793ffd2 --- /dev/null +++ b/src/components/diagrams/Chip.astro @@ -0,0 +1,6 @@ +--- +// A state or rule inside a diagram: uppercase label in a 1px border, 2px +// corners. Never a pill. +--- + + diff --git a/src/components/diagrams/Figure.astro b/src/components/diagrams/Figure.astro new file mode 100644 index 0000000..e049ef2 --- /dev/null +++ b/src/components/diagrams/Figure.astro @@ -0,0 +1,17 @@ +--- +// Wraps a diagram with its caption. The figure is the unit that scrolls, +// stacks or re-flows; captions sit under it in small text. +interface Props { + caption?: string; + /** Accessible description of what the drawing shows, for screen readers. */ + label: string; +} +const { caption, label } = Astro.props; +--- + +
+ + {caption &&
{caption}
} +
diff --git a/src/components/diagrams/NoteLife.astro b/src/components/diagrams/NoteLife.astro new file mode 100644 index 0000000..242bb1e --- /dev/null +++ b/src/components/diagrams/NoteLife.astro @@ -0,0 +1,45 @@ +--- +// A note's life in three moves: deposit, private payment, withdrawal. +// One coral cell is the note being followed. Moves are vertical stacks at +// phone width and a row of three from the sm breakpoint. +import Figure from "./Figure.astro"; +import Cell from "./Cell.astro"; +import Chip from "./Chip.astro"; +--- + +
+
    +
  1. +

    1 Deposit

    +
    + Public wallet + + Reserve + + +
    +

    Assets move into the Reserve. A note joins the record.

    +
  2. +
  3. +

    2 Private payment

    +
    + + + +
    +

    Two notes are spent and two are created. Nothing leaves the Reserve.

    +
  4. +
  5. +

    3 Withdrawal

    +
    + + + Public address +
    +

    The amount, asset, Reserve and recipient become public.

    +
  6. +
+
diff --git a/src/components/diagrams/Reserve.astro b/src/components/diagrams/Reserve.astro new file mode 100644 index 0000000..fb232ef --- /dev/null +++ b/src/components/diagrams/Reserve.astro @@ -0,0 +1,23 @@ +--- +// A Reserve: a tall panel with a 1px strong border, its name, its rules as +// chips and a lock line saying its funds stay put. +import Icon from "../Icon.astro"; + +interface Props { + name: string; + rules: string[]; + lock?: string; +} +const { name, rules, lock = "Holds its own funds" } = Astro.props; +--- + +
+

{name}

+
    + {rules.map((r) =>
  • {r}
  • )} +
+

+ + {lock} +

+
diff --git a/src/content/docs/architecture.mdx b/src/content/docs/architecture.mdx new file mode 100644 index 0000000..e34bc00 --- /dev/null +++ b/src/content/docs/architecture.mdx @@ -0,0 +1,89 @@ +--- +title: Architecture +description: "The Chamber, Reserves, the verifier and the circuit, the cryptography they use, the roles with power over the protocol, and its known limits." +--- + +import Architecture from "../../components/diagrams/Architecture.astro"; + +MIST has one Chamber per network, any number of Reserves, one circuit and a generated verifier. Funds sit in Reserves. The record of who owns what sits in the Chamber. + + + +## Components + +| Component | Role | File | +| --- | --- | --- | +| Chamber | The state engine. Verifies each spend's proof and applies it. Keeps the transactions trees, the spent nullifiers, the zkState tree and the Reserve registry. Never holds assets | `Chamber.sol` | +| Reserve | Holds the assets of the notes in its custody under one compliance rule set. Keeps its registered users and its admin's permissions. Moves assets only when the Chamber asks | `Reserve.sol` | +| ChamberVerifier | The Groth16 verifier, generated by gnark for the circuit's 14 public inputs | `ChamberVerifier.sol` | +| ManagerSigRegistrar | The registrar. Adds a user to a Reserve on the EIP-712 signature of a holder of its USERS permission | `ManagerSigRegistrar.sol` | +| PrimaryTransactionCircuit | The one circuit. Every spend is a proof of it | `primary.go` | +| Middleware | A contract that owns notes and adds its own rules before it spends them. The Chamber supports middlewares through ordinary note ownership. None exists yet | Not part of core | + +The contracts are in `core/contracts/src` and the circuit is in `core/circuits/src`. [Contracts](/contracts/) and [Circuits](/circuits/) cover each in turn. + +## Separate custody + +A network can have as many Reserves as it needs, each standing for one rule set: for example every user passed KYC, every wallet passes an AML check, or no extra conditions. A note never leaves its Reserve except as a public withdrawal, so funds governed by one rule set stay apart from funds that follow another. + +Funds never touch the Chamber. ERC-20 `Transfer` events show only movements to and from Reserves. Suspicious activity at one Reserve affects that Reserve's funds and no other. + +| | Monolithic contract | Separate Reserves | +| --- | --- | --- | +| Deposit | Full recipient privacy | Full recipient privacy | +| Withdrawal | Sender hidden among every note in MIST | Sender hidden among the notes of its own Reserve | +| Payment inside MIST | Sender and receiver hidden among every note in MIST | Sender and receiver hidden among every note in MIST | + +## State in the Chamber + +- **Transactions trees.** Append-only Merkle trees of notes. Each holds 4^10 notes. When one fills, the next opens, and every root any tree has had stays valid, so a note stays spendable after its tree has moved on. A spend proves both inputs against one root. +- **Nullifier map.** Every nullifier a spend has published. +- **zkState tree.** One leaf per Reserve: `H3(reserve, reserve_config, users_root)`. The current root is valid, and a superseded root stays valid for 10 minutes. +- **Reserve registry.** Each registered Reserve's zkState leaf, deposit screener and asset list. An asset is listed with a minimum deposit, and zero means it cannot be deposited. +- **Pending deposits.** Deposits waiting for a screener, keyed by deposit id, each with an optional refund address. +- **Private transaction records.** The identifier and the six published commitment elements of each spend that has them. +- **Pause state.** The guardian, whether inflows are paused and until when spends are paused. + +The zkState tree and each transactions tree have depth 10 and four children per node. + +## Cryptography + +| Primitive | Choice | +| --- | --- | +| Curve | BN254, the curve behind the EVM's pairing precompiles | +| Proof system | Groth16, with the circuit written in gnark. The keys come from a single-party setup | +| Hash | Poseidon2 over the BN254 scalar field: 8 full rounds, 56 partial rounds, S-box exponent 5 | +| Encryption | Hash-and-Add, a stream cipher on the width-4 Poseidon2 permutation | +| Merkle trees | Depth 10, four children per node. A node hashes its children in sorted order | + +The circuit does no elliptic-curve operations, and no MIST protocol key lives on a curve. + +## Roles + +| Role | Powers | Limits | +| --- | --- | --- | +| Chamber owner | Registers every Reserve and names its admin. Proposes a new verifier, which goes live after 7 days and only if its code is unchanged, and can cancel it. Sets or replaces the guardian, which can also be named at construction. Moves ownership in two steps behind a 7-day timelock | Cannot swap the verifier instantly, and cannot renounce ownership. A verifier that accepts anything would authorise the withdrawal of everything held, so the owner should be a multisig | +| Guardian | Pauses `deposit` and `approveDeposits` until unpaused. Pauses spends for at most 3 days, with 7 days between pauses. The owner can also unpause | Cannot stop `reclaimDeposit` or `rejectDeposits`. A spend pause ends on its own and cannot be chained | +| Reserve admin | Named by the Chamber owner. Holds every permission, grants and revokes them, and hands the role to a new admin in two steps | Cannot move funds. Grants survive a handover until the new admin revokes them. The previous admin loses its implicit permissions at the handover | +| Permission holders | `ASSETS`: list and delist assets and set minimum deposits. `USERS`: add and remove registered users. `METADATA`: update the Reserve's auditor key. `SCREENING`: set the deposit screener | Each permission covers only its own action. None can move funds | +| Registrar | A contract or account holding `USERS`. `ManagerSigRegistrar` registers a user when a `USERS` holder signed it | A signature carries a deadline and binds the signer, the signer's permission epoch and the leaf's nonce. A removal or the signer losing `USERS` voids it. Any `USERS` holder can revoke every outstanding signature for a leaf | +| Deposit screener | Set by a `SCREENING` holder. Decides which deposits enter a transactions tree | Cannot move funds. The depositor can reclaim a pending deposit. A rejected one is refunded to the address the deposit named | +| Relayer | Not a role. Anyone can submit an `auth_done = 1` spend | Cannot change it | + +## Known limits + +- **One zkState root for every Reserve.** A registration, removal or metadata update at any Reserve replaces it. The previous root stays valid for 10 minutes, so a proof in flight survives a change inside that window. The first registration at a Reserve switches messaging on there and retires every older root at once, because older roots have no users root for it. +- **Removal takes effect after the window.** A removed user stays provable until the last root that holds their leaf expires, at most 10 minutes. +- **A removal freezes the removed user's notes.** At a Reserve with members, only members can spend. A removed user's notes there stay unspendable until a `USERS` holder registers the user again. Any single `USERS` holder can make that removal. The exit spend that would let any owner withdraw in public is **Planned**, and core's operations notes say not to deploy to production, or not to let any Reserve remove users, until it lands. +- **Inputs from one tree.** A spend proves both inputs against one transactions root, so it cannot combine notes from different trees. To merge them, the owner first spends one note with a dummy second input, which lands its outputs in the current tree. +- **No solvency ledger.** The circuit's conservation rule and each Reserve's own balance bound what can leave. A Reserve's admin must list only plain assets: never rebasing, fee-on-transfer, blocklisting or upgradeable ones. + +The [specification](https://github.com/mistcash/mist/tree/main/spec) is the document of record, and its implementation status file tracks each limit. + +## Where the code lives + +| Repository | Contents | +| --- | --- | +| [mistcash/core](https://github.com/mistcash/core) | The circuit in Go with gnark, and the Solidity contracts built with Foundry | +| [mistcash/sdk](https://github.com/mistcash/sdk) | `@mistcash/sdk`, the TypeScript SDK | +| [mistcash/mist](https://github.com/mistcash/mist) | The protocol specification | diff --git a/src/content/docs/circuits/index.mdx b/src/content/docs/circuits/index.mdx new file mode 100644 index 0000000..4a957f6 --- /dev/null +++ b/src/content/docs/circuits/index.mdx @@ -0,0 +1,76 @@ +--- +title: Circuits +description: "PrimaryTransactionCircuit, the one Groth16 circuit behind every MIST spend: its shape, public inputs and checks." +sidebar: + label: Circuits overview + order: 0 +--- + +Every MIST spend is one Groth16 proof of one circuit, `PrimaryTransactionCircuit`. It is written in Go with gnark and proven over BN254. + +The circuit enforces the money rules. Nothing is printed or destroyed: value is pooled and moved from one set of notes to another, or withdrawn on-chain. + +## Shape + +A spend has two input notes and two output notes. A zero-amount dummy note pads a spend that has only one real input or output. At least one input must be real. + +Private inputs are the transaction's `chamber` and `reserve`, the two input notes with their Merkle proofs, the two output notes as owner commitments and amounts, and the witnesses for Reserve messaging. + +## Public inputs + +The Chamber decodes the public inputs in this order. The count and order are a contract between the circuit and `Chamber.sol`: changing either changes the verifier. + +| # | Input | Meaning | +| --- | --- | --- | +| 1 | `nullifier_1` | Nullifier of the first spent note | +| 2 | `nullifier_2` | Nullifier of the second spent note | +| 3 | `new_note_1` | First new note hash to append | +| 4 | `new_note_2` | Second new note hash to append | +| 5 | `transactions_root` | The transactions-tree root the inputs are proven against | +| 6 | `state_root` | The zkState root, shared by every Reserve. The Chamber accepts the current root, and a superseded one for 10 minutes | +| 7 | `withdraw_amount` | The optional withdrawal amount, zero without one | +| 8 | `withdraw_asset` | The asset withdrawn | +| 9 | `withdraw_reserve` | The Reserve that pays out | +| 10 | `withdraw_to` | The public recipient | +| 11 | `tx_payload` | Free payload, for middleware | +| 12 | `owner` | The transaction owner | +| 13 | `auth_done` | Whether the proof (1) or the caller (0) authorised the spend | +| 14 | `auditor_commitments` | The fold of the commitments the spend publishes | + +## What the circuit checks + +- **Range.** Every amount is decomposed to 120 bits, so the conservation sum cannot wrap around the field. +- **Conservation.** The input amounts equal the output amounts plus `withdraw_amount`. +- **Membership and nullifiers.** Each real input is in `transactions_root`, and its nullifier is derived from the note. +- **Nullifier distinctness.** `nullifier_1` differs from `nullifier_2`, so one note cannot fill both inputs. +- **One asset, one custody.** A spend moves one asset. Every note commits under the same `H2(chamber, reserve)`, by construction. +- **Owner authorisation.** With `auth_done = 1`, each input's owner is `H2(owner_secret, "owner")`. With `auth_done = 0`, both inputs share one owner and it equals the public `owner`. +- **Withdrawal pinning.** `withdraw_asset` and `withdraw_reserve` are zero without a withdrawal, and the spend's own asset and Reserve with one. +- **Reserve state.** The Reserve's zkState leaf is in `state_root` on every spend. +- **Reserve messaging.** At a Reserve with registered users, the sender is a member and the spend publishes its details encrypted for the key holder. + +The circuit does not check whether a nullifier was already spent. The Chamber does, when it settles the spend. + +:::caution[Soundness] +A witness that solves does not show that a circuit is sound. Every public input must carry a non-zero coefficient in some constraint, or it can be rewritten in calldata without invalidating the proof. +::: + +## Cost + +Costs are R1CS constraints, recorded in the constraint snapshot that core commits. + +| Operation | Constraints | +| --- | --- | +| `H2`, Poseidon2 of two elements | 217 | +| `H3`, of three elements | 241 | +| `H4`, of four elements | 265 | +| One Merkle node | 283 | +| One Merkle membership lookup | 2,821 | + +## Planned + +The specification describes three circuit changes that are not built: a relayer fee leg, exit spends that let any owner leave a Reserve, and sequential messaging identifiers. Each lands as its own circuit version. + +## Source + +The circuit is `core/circuits/src/primary.go`. Its Poseidon2 and Merkle gadgets are in `core/circuits/gadgets`, and the native reference implementations in `core/circuits/lib`. The [specification](https://github.com/mistcash/mist/blob/main/spec/04_circuit_architecture.md) defines each check. diff --git a/src/content/docs/contracts/index.mdx b/src/content/docs/contracts/index.mdx new file mode 100644 index 0000000..e52171e --- /dev/null +++ b/src/content/docs/contracts/index.mdx @@ -0,0 +1,49 @@ +--- +title: Contracts +description: "The Solidity contracts of MIST: Chamber, Reserve, ChamberVerifier and ManagerSigRegistrar." +sidebar: + label: Contracts overview + order: 0 +--- + +MIST's contracts are written in Solidity and built with Foundry. Three kinds of contract carry the protocol: the Chamber, Reserves and middlewares. Two more support them: the verifier and the registrar. + +| Contract | Role | Entry points | +| --- | --- | --- | +| `Chamber` | Verifies each spend and applies it to state. Holds no assets | `deposit`, `handleZkp`, `approveDeposits`, `rejectDeposits`, `reclaimDeposit`, `setDepositRefundTo`. Owner: `registerReserve`, `proposeVerifier`, `executeVerifierUpdate`, `setGuardian`. Guardian: `pauseInflows`, `pauseSpends` | +| `Reserve` | Holds the assets of its notes under one rule set. Moves them only when the Chamber asks | `deposit` and `withdraw` (Chamber only). `addUser` and `removeUser` (`USERS`), `setScreener` (`SCREENING`), `setAssetMinDeposit` (`ASSETS`), `updateAuditorKey` (`METADATA`). Admin: `grantPermission`, `revokePermission`, `transferAdmin` | +| `ChamberVerifier` | The Groth16 verifier, generated by gnark. Accepts compressed and uncompressed proofs and rejects any public input at or above the field order | `verifyProof`, `verifyCompressedProof` | +| `ManagerSigRegistrar` | The registrar for every Reserve. Anyone can submit a registration that carries the signature of a `USERS` holder | `registerUser(reserve, leaf, deadline, signer, signature)`, `revoke(reserve, leaf)` | + +Middlewares are contracts that own notes. A note owned by a middleware is spent with `auth_done = 0`, so only the middleware can submit the spend, and it decides first whether the spend happens. None exists yet. + +## The flows + +1. **Deposit.** `Chamber.deposit(reserve, ownerCommitment, amount, asset)` takes no proof. An overload adds a trailing `refundTo`. Both return `(noteHash, depositId)`, and `depositId` is 0 when the Reserve has no screener. The depositor approves the Reserve, which pulls the asset. The asset must be listed at the Reserve, and the amount the Reserve received must meet its minimum deposit. At a Reserve with a screener the note is queued, and the screener calls `approveDeposits` or `rejectDeposits`. `approveDeposits` skips ids that are not pending and rejects a duplicate note instead of reverting the batch. While the deposit is pending, only the depositor can reclaim it, and the funds return to the depositor. The depositor can change `refundTo` with `setDepositRefundTo` until the screener decides. Once the deposit is rejected, the depositor or `refundTo` can reclaim it, and the funds go to `refundTo`. Reclaiming is never paused. +2. **Transfer.** `Chamber.handleZkp(proof, publicInputs, auditorCommitments)` reverts while spends are paused. Otherwise it verifies the proof, checks the roots and the authorisation, marks both nullifiers spent and appends both new notes. No assets move. +3. **Withdrawal.** The same call with a non-zero `withdraw_amount`. After every state write the Chamber calls `Reserve.withdraw`, which pays the recipient. +4. **Registration.** A member's leaf is `H2(owner, userKeyExchange)`, computed off-chain. `ManagerSigRegistrar.registerUser` checks the EIP-712 signature of a `USERS` holder, by ECDSA or ERC-1271, and calls `Reserve.addUser`. The signed message binds the Reserve, the leaf, a deadline, the signer and the signer's permission epoch, the leaf's nonce, which moves on every registration and removal, and the leaf's revocation count. A removed user therefore cannot return with an older signature, and a signer that lost `USERS` cannot use its old ones. Any `USERS` holder can `revoke` every outstanding signature for a leaf. `Reserve.removeUser(index)` zeroes a user's leaf, and it reverts if that would empty the users tree. + +:::caution[Assets sent to a Reserve directly are lost] +A Reserve takes assets only through `Chamber.deposit`. Assets sent to a Reserve address by a plain transfer are unrecoverable. +::: + +## Timelocks and pauses + +- **Verifier.** `proposeVerifier` queues a new verifier, `executeVerifierUpdate` makes it live after 7 days if its code hash is unchanged, and `cancelVerifierUpdate` drops it. +- **Ownership.** `transferOwnership` queues a new owner, who accepts after 7 days. `renounceOwnership` always reverts. +- **Guardian.** `pauseInflows` stops `deposit` and `approveDeposits` until the guardian or owner unpauses. `pauseSpends` stops `handleZkp` for 3 days, and the next pause can start no sooner than 7 days after the last one ended. + +## Events + +The Chamber emits `NoteAppended` for every note it adds, `TxTreeOpened` when a tree fills and the next opens, and `PrivateTransfer` for a spend with commitments. Deposit screening emits `DepositQueued`, `DepositRefundToSet`, `DepositApproved`, `DepositRejected`, `DepositDuplicateRejected` and `DepositReclaimed`. State changes emit `ReserveRegistered`, `ReserveConfigUpdated`, `ZkStateRootUpdated`, `ZkStateHistoryRetired`, `ReserveScreenerSet`, `ReserveAssetMinDepositSet`, `GuardianSet`, the pause events, `OwnershipTransferQueued` and the `VerifierUpdate` events. A Reserve emits `UserRegistered`, `UserRemoved`, `AuditorKeyUpdated`, `PermissionGranted`, `PermissionRevoked` and the admin transfer events. The registrar emits `SignaturesRevoked`. + +`getTxArray(offset, limit)` returns a page of the note history across every tree. + +## Toolchain + +The contracts are pinned to solc 0.8.35, the Paris EVM and 200 optimizer runs. `ChamberVerifier.sol` is generated by gnark from the circuit and is never edited by hand. + +## Source + +The contracts are in `core/contracts/src`. The [specification](https://github.com/mistcash/mist/blob/main/spec/02_smart_contract.md) defines their state, actions and trusted roles. diff --git a/src/content/docs/getting-started.mdx b/src/content/docs/getting-started.mdx deleted file mode 100644 index 8893602..0000000 --- a/src/content/docs/getting-started.mdx +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Getting Started -description: Install the MIST.cash SDK and run your first privacy transaction. ---- - -import { Tabs, TabItem, Steps, Aside } from "@astrojs/starlight/components"; - -## Installation - - - - ```bash - pnpm add @mistcash/sdk @mistcash/config - ``` - - - ```bash - npm install @mistcash/sdk @mistcash/config - ``` - - - ```bash - yarn add @mistcash/sdk @mistcash/config - ``` - - - -For React applications, also install the React package: - - - - ```bash - pnpm add @mistcash/react - ``` - - - ```bash - npm install @mistcash/react - ``` - - - ```bash - yarn add @mistcash/react - ``` - - - -## Initialization - -The SDK uses a Go-compiled WASM module for cryptographic operations. You must initialize it before calling any hash or proof functions. - -```typescript -import { initCore } from "@mistcash/sdk"; - -// Initialize WASM + Garaga modules -await initCore(); -``` - - - -You can also initialize modules independently: - -```typescript -import { initWasm, initGaraga } from "@mistcash/sdk"; - -// Initialize only what you need -await initWasm(); // Required for hashing and proof generation -await initGaraga(); // Required for proof calldata formatting -``` - -## Quick Example: Hash a Secret - - - 1. **Initialize the SDK** - - ```typescript - import { initCore, hash2, generateClaimingKey } from "@mistcash/sdk"; - await initCore(); - ``` - - 2. **Generate a claiming key** - - ```typescript - const claimingKey = generateClaimingKey(); - console.log("Claiming key:", claimingKey); - ``` - - 3. **Hash the key with a recipient address** - - ```typescript - const recipientAddress = "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7"; - const commitment = await hash2(claimingKey, recipientAddress); - console.log("Commitment:", commitment); - ``` - - -## Quick Example: React Integration - -```tsx -import { useMist } from "@mistcash/react"; - -function PrivacyWallet({ provider, sendTransaction }) { - const mist = useMist(provider, sendTransaction); - - return ( -
-

Chamber: {mist.chamberAddress}

-

Status: {mist.loadingMessage}

- - mist.setKey(e.target.value)} - /> - mist.setTo(e.target.value)} - /> - - - - {mist.asset && ( - - )} -
- ); -} -``` - -## Supported Tokens - -The SDK supports the following tokens on Starknet mainnet: - -| Token | Symbol | Address | -|-------|--------|---------| -| Ether | ETH | `0x049d36...04dc7` | -| Stark | STRK | `0x04718f...0ecb4` | -| USD Coin | USDC | `0x053c91...0b2c2` | -| Tether | USDT | `0x068f5c...36d11` | -| Survivor | SURVIVOR | `0x5dc92...51f86` | - -See [`tokensData`](/packages/config#supported-tokens) in `@mistcash/config` for full addresses and metadata. - -## Next Steps - -- Learn about the [Core SDK](/packages/core) for low-level cryptographic operations -- Set up the [React hook](/packages/react) for building UIs -- Follow the [Deposit guide](/guides/deposit) for a complete deposit flow -- Follow the [Withdraw guide](/guides/withdraw) for a complete withdrawal flow diff --git a/src/content/docs/guides/deposit.mdx b/src/content/docs/guides/deposit.mdx deleted file mode 100644 index e443328..0000000 --- a/src/content/docs/guides/deposit.mdx +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: Depositing Tokens -description: Step-by-step guide to depositing tokens into the MIST.cash privacy pool. ---- - -import { Steps, Aside } from "@astrojs/starlight/components"; - -This guide walks through the complete process of depositing tokens into the MIST.cash Chamber contract. - -## Overview - -A deposit creates a cryptographic commitment from a **claiming key** and a **recipient address**, then locks tokens in the Chamber contract. The commitment is added to a Merkle tree — and only someone who knows the claiming key can later withdraw the tokens. - -## Prerequisites - -```typescript -import { initCore, generateClaimingKey, txHash } from "@mistcash/sdk"; -import { getChamber } from "@mistcash/sdk"; -import { CHAMBER_ADDR_MAINNET, ERC20_ABI, tokensMap } from "@mistcash/config"; -import { Contract } from "starknet"; - -await initCore(); -``` - -## Deposit Flow - - - 1. **Generate a claiming key** - - The claiming key is the secret that allows withdrawal. It must be stored securely — anyone with this key can claim the deposited tokens. - - ```typescript - const claimingKey = generateClaimingKey(); - - // IMPORTANT: Save this key securely! - console.log("Save this key:", claimingKey); - ``` - - - - 2. **Choose the recipient address** - - This is the address that will later withdraw the tokens. It can be any valid Starknet address — including one that doesn't exist yet. - - ```typescript - const recipientAddress = "0x049d36..."; // The future withdrawer's address - ``` - - 3. **Compute the commitment hash** - - ```typescript - const tokenAddress = tokensMap["ETH"].address; - const amount = "1000000000000000000"; // 1 ETH in wei - - const commitment = txHash(claimingKey, recipientAddress, tokenAddress, amount); - ``` - - 4. **Approve the Chamber contract** - - The Chamber needs permission to transfer your tokens: - - ```typescript - const token = new Contract(ERC20_ABI, tokenAddress, account); - await token.approve(CHAMBER_ADDR_MAINNET, amount); - ``` - - 5. **Execute the deposit** - - ```typescript - const chamber = getChamber(provider); - const asset = { addr: tokenAddress, amount }; - - await chamber.connect(account).deposit(commitment, asset); - ``` - - 6. **Share the claiming key with the recipient** - - The recipient needs: - - The **claiming key** (secret) - - Their **own address** (they already know this) - - Share the claiming key through a secure channel. Never post it publicly. - - -## Complete Example - -```typescript -import { initCore, generateClaimingKey, txHash, getChamber } from "@mistcash/sdk"; -import { CHAMBER_ADDR_MAINNET, ERC20_ABI, tokensMap } from "@mistcash/config"; -import { Contract } from "starknet"; - -async function deposit(account, provider, recipientAddress, tokenSymbol, amount) { - await initCore(); - - // 1. Generate secret - const claimingKey = generateClaimingKey(); - - // 2. Get token info - const token = tokensMap[tokenSymbol]; - if (!token) throw new Error(`Unknown token: ${tokenSymbol}`); - - // 3. Compute commitment - const commitment = txHash(claimingKey, recipientAddress, token.address, amount); - - // 4. Approve - const erc20 = new Contract(ERC20_ABI, token.address, account); - await erc20.approve(CHAMBER_ADDR_MAINNET, amount); - - // 5. Deposit - const chamber = getChamber(provider); - await chamber.connect(account).deposit(commitment, { - addr: token.address, - amount, - }); - - return { claimingKey, commitment }; -} -``` - - - -## Security Considerations - -- **Claiming key storage**: Treat the claiming key like a private key. Store it encrypted or in a secure vault. -- **Amount privacy**: The deposit amount is visible on-chain. Privacy comes from breaking the link between depositor and withdrawer. -- **Timing**: Deposits and withdrawals at unusual times with unique amounts can be correlated. Using common amounts (e.g., round numbers) improves privacy. diff --git a/src/content/docs/guides/merkle-trees.mdx b/src/content/docs/guides/merkle-trees.mdx deleted file mode 100644 index 98dc637..0000000 --- a/src/content/docs/guides/merkle-trees.mdx +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Merkle Trees -description: How MIST.cash uses Merkle trees to organize and verify transaction commitments. ---- - -import { Aside } from "@astrojs/starlight/components"; - -MIST.cash uses a binary Merkle tree with Poseidon hashing to organize all transaction commitments. The Merkle tree enables efficient verification that a commitment exists without revealing which one. - -## How It Works - -Every deposit creates a **leaf** (commitment hash) that gets added to the tree. The tree structure allows proving membership of any leaf by providing just a logarithmic-sized proof path, rather than revealing all leaves. - -``` - Root - / \ - H01 H23 - / \ / \ - H0 H1 H2 H3 ← Leaves (commitments) -``` - -To prove leaf `H1` is in the tree, you only need: `[H0, H23]`. The verifier computes `hash(H0, H1) = H01`, then `hash(H01, H23) = Root`, and checks it matches. - -## Computing Roots - -### From Leaves - -```typescript -import { calculateMerkleRoot } from "@mistcash/sdk"; - -const leaves = [leaf0, leaf1, leaf2, leaf3]; // bigint[] -const root = calculateMerkleRoot(leaves); -``` - -### With Proof - -```typescript -import { calculateMerkleRootAndProof } from "@mistcash/sdk"; - -// Get root AND the proof for leaf at index 1 -const [root, ...proof] = calculateMerkleRootAndProof(leaves, 1); -// proof = [H0, H23] — the sibling hashes needed to reconstruct root from H1 -``` - -## Verifying Proofs - -Given a leaf and its proof path, recompute the root: - -```typescript -import { merkleRootFromPath } from "@mistcash/sdk"; - -const computedRoot = merkleRootFromPath(leaf, proofPath); -const isValid = computedRoot === expectedRoot; -``` - -## Custom Hashers - -By default, the Merkle tree uses `merkleHasher` (Poseidon-based). You can provide a custom hasher: - -```typescript -import { calculateMerkleRoot, merkleHasher } from "@mistcash/sdk"; - -// Default (Poseidon) -const root = calculateMerkleRoot(leaves); - -// Custom hasher -const customHasher = (a: bigint, b: bigint): bigint => { - // Your custom hash function - return a ^ b; // Example only -}; -const root2 = calculateMerkleRoot(leaves, customHasher); -``` - -## Leaf Filtering - -The optional `leafFilter` parameter processes each leaf before insertion into the tree: - -```typescript -import { calculateMerkleRoot, evenLeafFilter } from "@mistcash/sdk"; - -// Apply even leaf filter -const root = calculateMerkleRoot(leaves, undefined, evenLeafFilter); -``` - -## Working with the Contract - -The Chamber contract maintains the authoritative Merkle tree. Fetch its state: - -```typescript -import { getChamber } from "@mistcash/sdk"; - -const chamber = getChamber(provider); - -// Get all leaves -const leaves = await chamber.tx_array(); - -// Get the on-chain root -const contractRoot = await chamber.merkle_root(); - -// Get an on-chain proof for a specific index -const onChainProof = await chamber.merkle_proof(leafIndex); -``` - -### Client-Side vs On-Chain - -You can compute roots and proofs client-side or fetch them from the contract: - -| Operation | Client-Side | On-Chain | -|-----------|-------------|----------| -| Merkle root | `calculateMerkleRoot(leaves)` | `chamber.merkle_root()` | -| Merkle proof | `calculateMerkleRootAndProof(leaves, index)` | `chamber.merkle_proof(index)` | -| Verification | `merkleRootFromPath(leaf, proof)` | Done by ZK verifier | - - - -## Tree Properties - -| Property | Value | -|----------|-------| -| Hash function | Poseidon (ZK-friendly) | -| Tree type | Binary Merkle tree | -| Leaf format | `hash(txSecret, tokenAddress, amount)` | -| Proof size | `O(log n)` where `n` is the number of leaves | diff --git a/src/content/docs/guides/withdraw.mdx b/src/content/docs/guides/withdraw.mdx deleted file mode 100644 index 3c215d1..0000000 --- a/src/content/docs/guides/withdraw.mdx +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: Withdrawing Tokens -description: Step-by-step guide to withdrawing tokens from the MIST.cash privacy pool using zero-knowledge proofs. ---- - -import { Steps, Aside } from "@astrojs/starlight/components"; - -This guide covers the complete withdrawal flow — from looking up a transaction to generating a zero-knowledge proof and claiming tokens. - -## Overview - -Withdrawal proves you know a valid commitment in the Merkle tree **without revealing which one**. The proof is generated client-side using Groth16 (via WASM) and verified on-chain. - -## Prerequisites - -You need: -- A **claiming key** (received from the depositor) -- Your **Starknet address** (the recipient specified during deposit) -- A **Starknet wallet** to sign the withdrawal transaction - -```typescript -import { - initCore, - txSecret, - txHash, - fetchTxAssets, - getTxIndexInTree, - calculateMerkleRootAndProof, - full_prove, - getChamber, -} from "@mistcash/sdk"; - -await initCore(); -``` - -## Withdrawal Flow - - - 1. **Look up the transaction** - - First, verify the deposit exists and get its asset details: - - ```typescript - const chamber = getChamber(provider); - const asset = await fetchTxAssets(chamber, claimingKey, myAddress); - - console.log("Token:", asset.addr); - console.log("Amount:", asset.amount.toString()); - ``` - - - - 2. **Get the Merkle tree state** - - Fetch all transaction leaves and find the index of your transaction: - - ```typescript - const leaves = await chamber.tx_array(); - - const txIndex = await getTxIndexInTree( - leaves, - claimingKey, - myAddress, - asset.addr, - asset.amount.toString() - ); - ``` - - 3. **Compute the Merkle proof** - - ```typescript - const [root, ...proof] = calculateMerkleRootAndProof(leaves, txIndex); - ``` - - 4. **Build the witness** - - The witness contains everything the ZK circuit needs to generate a proof: - - ```typescript - const witness = { - ClaimingKey: claimingKey, - Owner: myAddress, - TxAsset: asset.addr, - Withdraw: { - Amount: asset.amount.toString(), - }, - MerkleRoot: root.toString(), - MerkleProof: proof.map(String), - Tx1Secret: txSecret(claimingKey, myAddress), - }; - ``` - - 5. **Generate the proof and submit** - - ```typescript - const calldata = await full_prove(witness); - await chamber.connect(account).handle_zkp(calldata); - ``` - - This generates a Groth16 proof in WASM and formats it as Starknet calldata using Garaga. - - -## Complete Example - -```typescript -async function withdraw(account, provider, claimingKey, myAddress) { - await initCore(); - - const chamber = getChamber(provider); - - // 1. Look up transaction - const asset = await fetchTxAssets(chamber, claimingKey, myAddress); - - // 2. Get tree state - const leaves = await chamber.tx_array(); - const txIndex = await getTxIndexInTree( - leaves, claimingKey, myAddress, asset.addr, asset.amount.toString() - ); - - // 3. Compute Merkle proof - const [root, ...proof] = calculateMerkleRootAndProof(leaves, txIndex); - - // 4. Build witness - const witness = { - ClaimingKey: claimingKey, - Owner: myAddress, - TxAsset: asset.addr, - Withdraw: { Amount: asset.amount.toString() }, - MerkleRoot: root.toString(), - MerkleProof: proof.map(String), - Tx1Secret: txSecret(claimingKey, myAddress), - }; - - // 5. Generate proof and withdraw - const calldata = await full_prove(witness); - await chamber.connect(account).handle_zkp(calldata); -} -``` - -## Using the React Hook - -The `useMist` hook handles this entire flow automatically: - -```tsx -import { useMist } from "@mistcash/react"; - -function WithdrawUI({ provider, sendTx }) { - const mist = useMist(provider, sendTx); - - const handleWithdraw = async () => { - const asset = await mist.fetchAsset(); - await mist.handleWithdraw(asset); - }; - - return ( -
- mist.setKey(e.target.value)} - /> - mist.setTo(e.target.value)} - /> - -
- ); -} -``` - - diff --git a/src/content/docs/guides/zero-knowledge.mdx b/src/content/docs/guides/zero-knowledge.mdx deleted file mode 100644 index 8d1e3a3..0000000 --- a/src/content/docs/guides/zero-knowledge.mdx +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Zero-Knowledge Proofs -description: Understanding the ZK proof system used in MIST.cash. ---- - -import { Aside } from "@astrojs/starlight/components"; - -MIST.cash uses **Groth16** zero-knowledge proofs to enable private transactions on Starknet. This guide explains the proof system architecture and how to work with it. - -## How ZK Proofs Work in MIST.cash - -A zero-knowledge proof allows you to prove a statement is true without revealing any information beyond the statement itself. In MIST.cash, the statement is: - -> "I know a valid commitment in the Merkle tree, and I know its secret key." - -The proof convinces the contract to release tokens without revealing **which** commitment you're claiming. - -## Architecture - -``` -┌─────────────────────────────────────────────────────┐ -│ Client (Browser) │ -│ │ -│ ┌──────────┐ ┌────────────┐ ┌──────────────┐ │ -│ │ Witness │───▶│ Gnark │───▶│ Garaga │ │ -│ │ Builder │ │ (WASM) │ │ (Calldata) │ │ -│ └──────────┘ └────────────┘ └──────────────┘ │ -│ │ │ │ -│ Groth16 Proof Starknet │ -│ Calldata │ -└─────────────────────────────────┬───────────────────┘ - │ - ▼ - ┌─────────────────────────┐ - │ Starknet (On-Chain) │ - │ │ - │ Chamber Contract │ - │ └── Garaga Verifier │ - │ └── Groth16 Check │ - └─────────────────────────┘ -``` - -### Components - -| Component | Role | Technology | -|-----------|------|------------| -| **Gnark** | Circuit definition and proof generation | Go, compiled to WASM | -| **Garaga** | Proof formatting for Starknet verification | TypeScript | -| **Chamber** | On-chain verification and token release | Cairo (Starknet) | - -## The Witness - -The witness is the private input to the proof. It contains everything the prover knows but doesn't want to reveal: - -```typescript -interface Witness { - ClaimingKey: string; // The secret key - Owner: string; // Recipient address - TxAsset: string; // Token address - Withdraw: { - Amount: string; // Withdrawal amount - }; - MerkleRoot: string; // Current tree root (public) - MerkleProof: string[]; // Path from leaf to root - Tx1Secret: string; // Derived: txSecret(key, owner) -} -``` - -The circuit verifies: -1. `hash(ClaimingKey, Owner)` produces a valid `TxSecret` -2. `hash(TxSecret, TxAsset, Amount)` produces a valid leaf -3. The leaf exists in the Merkle tree (verified via `MerkleProof` against `MerkleRoot`) -4. The nullifier derived from this proof hasn't been spent - -## Generating Proofs - -### Low-Level API - -Use `prove_groth16` for just the proof, or `full_prove` for proof + Starknet calldata: - -```typescript -import { prove_groth16, full_prove } from "@mistcash/sdk"; - -// Just the proof -const result = await prove_groth16(witness); -if (result.status === "ok") { - console.log("Raw proof:", result.proof); -} - -// Proof + formatted calldata for Starknet -const calldata = await full_prove(witness); -// calldata is bigint[] ready for chamber.handle_zkp() -``` - -### Using FIXTURES for Testing - -The SDK includes pre-built fixtures for testing without generating real proofs: - -```typescript -import { FIXTURES } from "@mistcash/sdk"; - -// Use in tests -const testWitness = FIXTURES.witness; -const testProof = FIXTURES.proof; -``` - -## Performance - -Proof generation runs entirely client-side in the browser via WASM. Performance varies by device: - - - -## Proof Verification - -Proofs are verified on-chain by the Garaga verifier integrated into the Chamber contract. The verification checks: - -1. The proof is mathematically valid (Groth16 pairing check) -2. The Merkle root matches the current contract state -3. The nullifier hasn't been used before - -If all checks pass, the contract releases the tokens to the specified recipient. - -## Security Properties - -| Property | Guarantee | -|----------|-----------| -| **Soundness** | Cannot forge a proof without knowing the claiming key | -| **Zero-knowledge** | The proof reveals nothing about which commitment is being claimed | -| **Non-malleability** | Proofs cannot be modified or replayed (nullifier prevents double-spend) | -| **Completeness** | A valid witness always produces a valid proof | diff --git a/src/content/docs/how-it-works.mdx b/src/content/docs/how-it-works.mdx new file mode 100644 index 0000000..ba70bf2 --- /dev/null +++ b/src/content/docs/how-it-works.mdx @@ -0,0 +1,87 @@ +--- +title: How MIST works +description: "Notes, owners and nullifiers, the three moves of a MIST payment, what a proof states, and what each party can see." +--- + +import NoteLife from "../../components/diagrams/NoteLife.astro"; + +A payment in MIST has three moves: a deposit into a Reserve, a private payment inside MIST, and an optional withdrawal to a public address. + + + +## Notes + +Value lives in notes, as in a UTXO chain. A spend consumes notes and creates new ones. Nothing is updated in place. A note commits to six fields. + +| Field | Meaning | +| --- | --- | +| `chamber` | The Chamber ID, `H2(chainId, chamberAddress)`, so notes from different networks stay apart | +| `reserve` | The address of the Reserve that holds the note's assets | +| `blinding` | A random nonce | +| `owner` | Who may spend the note | +| `asset` | The address of the asset contract | +| `amount` | Below 2^120 | + +The note hash combines them. `H2` and `H4` are Poseidon2 compressions of two and four field elements. + +```text +note_hash = H4( H2(chamber, reserve), H2(blinding, owner), asset, amount ) +``` + +Only the owner commitment `H2(blinding, owner)` enters a new note. A note hash never reveals the recipient's address or identity, and whoever creates a note does not need the recipient's blinding or owner. + +### Owners + +A note has one of two kinds of owner, and the kind decides who authorises the spend. + +- **A wallet or contract address**, including a middleware. The spend carries `auth_done = 0` and the Chamber requires `msg.sender` to equal the owner. The spend publishes `owner`, so it links to that address. +- **A MIST Address**, `H2(p, "owner")` for a secret `p`. The spend carries `auth_done = 1` and the proof itself shows knowledge of `p`. Anyone, a relayer for example, can submit the spend. + +### Nullifiers + +A spend marks each input note as spent by publishing its nullifier: the note hash computed with the blinding incremented by one. + +```text +nullifier = H4( H2(chamber, reserve), H2(blinding + 1, owner), asset, amount ) +``` + +The Chamber rejects a nullifier it has seen before. Anyone who knows a note's fields can compute its nullifier and watch for the spend, though that does not let them spend it. A wallet that derives blindings sequentially links its notes, because one note's nullifier equals the hash of the note with the next blinding. Blindings must be derived independently. + +## A note's life + +1. **Deposit.** The depositor approves the Reserve, not the Chamber, to move the asset. They then call `Chamber.deposit` with the Reserve, an owner commitment, an amount and the asset, and can name a refund address. No proof is needed. The asset must be listed at the Reserve, and the amount the Reserve receives must meet its minimum deposit. The Reserve pulls the asset and the Chamber appends the note to a transactions tree. At a Reserve with a deposit screener, the note waits in a queue until the screener approves it, and `deposit` returns the queue's deposit id. The transfer into the Reserve is public. The owner of the note is not. +2. **Private payment.** The owner proves a spend of up to two notes into two new notes, for any owners, in the same Reserve and asset. Observers see two nullifiers and two new note hashes. Who paid stays hidden when the notes are owned by a MIST Address. A wallet or contract owner is public, because the Chamber checks it as the caller. +3. **Withdrawal.** The same kind of spend can pay part of the value to a public address. The withdrawal reveals its amount, asset, Reserve and recipient. + +Every spend has the same shape, two inputs and two outputs. A zero-amount dummy note pads a spend that has only one real input or one real output, so spends look alike. + +A transactions tree holds 4^10 notes. When one fills, the Chamber opens the next, and every root any tree has had stays valid. A spend proves both inputs against one root, so they come from the same tree. + +## What a proof states + +Each spend is one Groth16 proof over BN254, generated on the user's device. The prover also builds to WebAssembly, so it runs in a browser. The proof states that: + +- the input notes are in a transactions tree, at a root the Chamber has produced; +- the nullifiers are derived from those notes; +- the inputs sum to the outputs plus the withdrawal, with every amount range checked to 120 bits; +- the spend moves one asset, within one Chamber and one Reserve; +- the spend is authorised by the notes' owner; +- the Reserve is in the zkState tree, at a root the Chamber still accepts: the current root, or a superseded one for 10 minutes. + +[Circuits](/circuits/) lists each check. + +## Who sees what + +| Party | Sees | Does not see | +| --- | --- | --- | +| Observer: anyone reading the chain | Deposits: depositor, Reserve, asset and amount. For a spend: both nullifiers, both new note hashes, both tree roots, `owner` and `auth_done`, and whether a withdrawal happened with its amount, asset, Reserve and recipient | Which notes were spent, the input amounts and how the outputs split them, the output owners, and the asset and Reserve of a private payment | +| Key holder, at a Reserve with members: whoever holds the members' key exchanges | For each member spend: the sender, the asset, both output amounts and both output owner commitments | Who the recipients are: they appear only as commitments | +| Reviewer: an outside party handed one payment's key | That payment's asset, both output amounts and both output owner commitments | Everything else, including other payments and the sender | + +## Limits + +- **Withdrawals are public.** Amount, asset, Reserve and recipient are published. +- **A wallet or contract owner is public** on every spend of its notes. +- **Note discovery is not specified.** Nothing in the protocol tells a recipient that a note was created for them. Wallets learn of their notes out of band. +- **The proofs are not post-quantum.** They are Groth16. Registration signatures are ECDSA, or ERC-1271 for a contract signer. Records are sealed with a symmetric, hash-based cipher under a key from an off-chain key exchange, and the protocol does not fix that exchange. +- **No relayer is paid.** Anyone can submit an `auth_done = 1` spend, but nothing in the contracts pays them. The withdrawing user then funds gas from a wallet, which links that wallet to the withdrawal. Relayer fees are Planned. diff --git a/src/content/docs/index.mdx b/src/content/docs/index.mdx index 676f945..2190492 100644 --- a/src/content/docs/index.mdx +++ b/src/content/docs/index.mdx @@ -1,64 +1,57 @@ --- title: Introduction -description: Privacy-focused SDK for zero-knowledge transactions on Starknet. +description: "MIST.cash is a protocol for private stablecoin payments on EVM chains. A zero-knowledge proof moves value between private notes, and each Reserve enforces its own compliance rules." +template: splash +hero: + title: Private payments under each Reserve's rules + tagline: MIST moves ERC-20 assets between private notes on an EVM chain. A zero-knowledge proof authorises each move. Each Reserve enforces its own compliance rules. + actions: + - text: How MIST works + link: /how-it-works/ + variant: primary + - text: Architecture + link: /architecture/ + variant: secondary --- -import { Card, CardGrid, LinkCard } from "@astrojs/starlight/components"; +import RuledIndex from "../../components/RuledIndex.astro"; -MIST.cash SDK is a TypeScript toolkit for building privacy-preserving applications on [Starknet](https://starknet.io). It enables zero-knowledge proof-based private transactions using Groth16 proofs, Poseidon hashing, and Merkle trees. +## What MIST is -## Why MIST.cash? +MIST is a protocol for private payments of ERC-20 assets on EVM chains. Value lives in private notes. A note is a hash that commits to an amount of one asset, its owner and the Reserve that holds it. Nobody can read a note from the chain. Its owner proves facts about it in zero knowledge. -Traditional blockchain transactions are fully transparent — sender, receiver, and amount are all publicly visible. MIST.cash breaks this link using zero-knowledge cryptography, allowing users to deposit, transfer, and withdraw tokens without revealing the connection between sender and receiver. +A spend consumes up to two notes and creates two new ones. It can also pay part of the value out to a public address. Observers see two nullifiers and two new note hashes. They do not see who was paid, which asset or how much. -## Architecture +## Separate custody, one shared record -The SDK is organized as a monorepo with three packages: +Two kinds of contract split the work. - - - Core cryptographic engine — WASM-powered Poseidon hashing, Groth16 proof - generation, Merkle tree operations, and Chamber contract utilities. - - - Shared configuration — contract ABIs, addresses, supported token - definitions, and TypeScript types. - - - React integration — the `useMist` hook for managing deposits, withdrawals, - and proof generation from React applications. - - +- A **Reserve** holds the assets of the notes in its custody and stands for one compliance rule set. Its admin grants the permissions that run it: registering users, screening deposits, listing assets and updating metadata. +- The **Chamber** keeps the record of every note, the spent markers and the list of Reserves. It verifies each proof and holds no assets. -## How It Works +Funds under different rules never mix. Private payments from every Reserve are recorded in the same Chamber, so they look alike. -1. **Deposit** — A user deposits tokens into the Chamber contract along with a cryptographic commitment (hash of a secret). -2. **Privacy** — The deposit is added to a Merkle tree. The link between depositor and the commitment is the only public information. -3. **Withdraw** — A different address generates a zero-knowledge proof showing knowledge of a valid commitment in the tree, without revealing which one. Tokens are sent to the new address. +## Compliance per Reserve -The zero-knowledge proof is generated client-side using a Go-compiled WASM module (Gnark) and verified on-chain via the [Garaga](https://garaga.dev) verifier. +A Reserve can switch on four rules. -## Quick Links +- **Asset list.** A Reserve accepts only the assets its admin lists, each with a minimum deposit. +- **Registration.** At a Reserve with members, only registered users can spend. A registered user can later be removed. +- **Deposit screening.** A screener approves or rejects each deposit before its note joins the record. A depositor can always reclaim a pending deposit. A rejected deposit is refunded to the address the depositor named, the depositor by default. +- **Key-holder visibility.** At a Reserve with members, every spend publishes its details encrypted for whoever holds the members' key exchanges: the sender, the asset and the amounts. Recipients appear only as commitments. - - - - - - +:::note[Scope of these docs] +These pages follow the protocol specification, which is the document of record, and the contracts in mistcash/core `main`. Where the specification describes something that is not built yet, the page says Planned. The protocol is pre-production: its keys come from a single-party setup. +::: + +## Where to go next + + diff --git a/src/content/docs/packages/config.mdx b/src/content/docs/packages/config.mdx deleted file mode 100644 index 5c847d5..0000000 --- a/src/content/docs/packages/config.mdx +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: "@mistcash/config" -description: Shared configuration, ABIs, and token definitions for MIST.cash. ---- - -import { Aside } from "@astrojs/starlight/components"; - -The config package provides shared constants, contract ABIs, token metadata, and TypeScript types used across the SDK. - -## Installation - -```bash -pnpm add @mistcash/config -``` - -## Contract Addresses - -### `CHAMBER_ADDR_MAINNET` - -The mainnet Chamber contract address on Starknet. - -```typescript -import { CHAMBER_ADDR_MAINNET } from "@mistcash/config"; - -console.log(CHAMBER_ADDR_MAINNET); -// "0x06f8dcc500131b6be6b33f4534ec6d33df33e61083ec2b051555d52e75654444" -``` - -## ABIs - -### `CHAMBER_ABI` - -The full ABI for the Chamber smart contract, used to create typed contract instances. - -```typescript -import { CHAMBER_ABI } from "@mistcash/config"; -import { Contract } from "starknet"; - -const chamber = new Contract(CHAMBER_ABI, CHAMBER_ADDR_MAINNET, provider); -``` - -### `ERC20_ABI` - -Standard ERC20 ABI for interacting with token contracts. - -```typescript -import { ERC20_ABI } from "@mistcash/config"; -import { Contract } from "starknet"; - -const token = new Contract(ERC20_ABI, tokenAddress, provider); -const balance = await token.balance_of(address); -``` - -## Supported Tokens - -### `tokensData` - -Array of all supported tokens with their metadata. - -```typescript -import { tokensData } from "@mistcash/config"; - -for (const token of tokensData) { - console.log(token.name, token.address, token.decimals); -} -``` - -Each token object has the following shape: - -```typescript -interface Token { - name: string; // Human-readable name (e.g., "Ether") - symbol: string; // Symbol (e.g., "ETH") - address: string; // Starknet contract address - decimals: number; // Token decimals (e.g., 18) - image?: string; // Optional icon URL -} -``` - -**Available tokens:** - -| Name | Symbol | Decimals | -|------|--------|----------| -| Ether | ETH | 18 | -| Stark | STRK | 18 | -| USD Coin | USDC | 6 | -| Tether | USDT | 6 | -| Survivor | SURVIVOR | 18 | - -### `tokensMap` - -Lookup tokens by contract address. - -```typescript -import { tokensMap } from "@mistcash/config"; - -const eth = tokensMap["0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7"]; -console.log(eth.symbol); // "ETH" -``` - -### `tokenNamesMap` - -Lookup tokens by name. - -```typescript -import { tokenNamesMap } from "@mistcash/config"; - -const usdc = tokenNamesMap["USDC"]; -console.log(usdc.address); -``` - -## Types - -### `ChamberTypedContract` - -TypeScript type for the typed Chamber contract instance. Use this for type-safe contract interactions. - -```typescript -import type { ChamberTypedContract } from "@mistcash/config"; - -function doSomething(chamber: ChamberTypedContract) { - // Full type safety for all contract methods - const root = await chamber.merkle_root(); -} -``` - -### `Token` - -Interface for token metadata. - -```typescript -import type { Token } from "@mistcash/config"; - -function renderToken(token: Token) { - return `${token.symbol}: ${token.address}`; -} -``` - - diff --git a/src/content/docs/packages/core.mdx b/src/content/docs/packages/core.mdx deleted file mode 100644 index 0d502d3..0000000 --- a/src/content/docs/packages/core.mdx +++ /dev/null @@ -1,295 +0,0 @@ ---- -title: "@mistcash/sdk" -description: Core cryptographic engine for privacy transactions on Starknet. ---- - -import { Tabs, TabItem, Aside, Steps } from "@astrojs/starlight/components"; - -The core package provides all cryptographic primitives needed for private transactions: Poseidon hashing via Go WASM, Groth16 zero-knowledge proof generation, Merkle tree operations, and Chamber contract interaction utilities. - -## Installation - - - - ```bash - pnpm add @mistcash/sdk @mistcash/config - ``` - - - ```bash - npm install @mistcash/sdk @mistcash/config - ``` - - - -## Initialization - -The SDK relies on a Go-compiled WASM module for cryptographic operations. Initialize before use: - -```typescript -import { initCore } from "@mistcash/sdk"; - -await initCore(); -``` - -Or initialize modules independently: - -```typescript -import { initWasm, initGaraga } from "@mistcash/sdk"; - -await initWasm(); // Hashing + proof generation -await initGaraga(); // Proof calldata formatting for Starknet -``` - - - -## Hashing - -The SDK uses Poseidon hashing — a ZK-friendly hash function. All hash functions are powered by the Go WASM module. - -### `hash2(a, b)` - -Two-input Poseidon hash. Returns a hex string. - -```typescript -const commitment = await hash2(claimingKey, ownerAddress); -``` - -### `hash2Sync(a, b)` - -Synchronous version. Use when you know WASM is already initialized. - -```typescript -const commitment = hash2Sync(claimingKey, ownerAddress); -``` - -### `hash3(a, b, c)` - -Three-input Poseidon hash. - -```typescript -const hash = await hash3(secret, tokenAddress, amount); -``` - -### `hash3Sync(a, b, c)` - -Synchronous three-input hash. - -```typescript -const hash = hash3Sync(secret, tokenAddress, amount); -``` - -### `txSecret(key, to)` - -Derives a transaction secret from a claiming key and recipient address. - -```typescript -const secret = txSecret(claimingKey, recipientAddress); -``` - -### `hash_with_asset(secret, asset, amount)` - -Hashes a transaction secret with asset details to create a commitment leaf. - -```typescript -const leaf = hash_with_asset(secret, tokenAddress, amount); -``` - -### `txHash(key, owner, tokenAddr, amount)` - -Computes the full transaction hash used as a Merkle leaf. Returns a `bigint`. - -```typescript -const hash = txHash(claimingKey, ownerAddress, tokenAddress, amount); -// Returns: bigint -``` - -### `generateClaimingKey()` - -Generates a cryptographically random claiming key. - -```typescript -const key = generateClaimingKey(); -// Returns: "0x..." (hex string) -``` - -## Zero-Knowledge Proofs - -### `prove_groth16(witness)` - -Generates a Groth16 proof from a witness. The proof is computed entirely client-side in WASM. - -```typescript -import { prove_groth16 } from "@mistcash/sdk"; -import type { Witness } from "@mistcash/sdk"; - -const witness: Witness = { - ClaimingKey: claimingKey, - Owner: recipientAddress, - TxAsset: tokenAddress, - Withdraw: { - Amount: amount, - }, - MerkleRoot: root.toString(), - MerkleProof: proof.map(String), - Tx1Secret: txSecret(claimingKey, recipientAddress), -}; - -const result = await prove_groth16(witness); - -if (result.status === "ok") { - console.log("Proof:", result.proof); -} else { - console.error("Proof failed:", result.error); -} -``` - -### `full_prove(witness)` - -Generates a proof and formats it as Starknet calldata using Garaga. Returns an array of `bigint` values ready to submit on-chain. - -```typescript -import { full_prove } from "@mistcash/sdk"; - -const calldata = await full_prove(witness); -// Returns: bigint[] — ready for contract call -``` - - - -### `FIXTURES` - -Pre-built test fixtures for development: - -```typescript -import { FIXTURES } from "@mistcash/sdk"; - -console.log(FIXTURES.witness); // Example witness -console.log(FIXTURES.proof); // Example proof -console.log(FIXTURES.verifyingKey); // Verification key -``` - -## Merkle Trees - -The SDK implements a binary Merkle tree using Poseidon hashing. - -### `calculateMerkleRoot(leaves, hasher?, leafFilter?)` - -Compute the Merkle root from an array of leaves. - -```typescript -import { calculateMerkleRoot } from "@mistcash/sdk"; - -const leaves = [leaf1, leaf2, leaf3]; // bigint[] -const root = calculateMerkleRoot(leaves); -// Returns: bigint -``` - -### `calculateMerkleRootAndProof(leaves, index, hasher?, leafFilter?)` - -Compute both the Merkle root and the proof path for a specific leaf index. - -```typescript -import { calculateMerkleRootAndProof } from "@mistcash/sdk"; - -const [root, ...proof] = calculateMerkleRootAndProof(leaves, targetIndex); -``` - -### `merkleRootFromPath(element, path, hasher?, leafFilter?)` - -Verify a Merkle proof by recomputing the root from an element and its proof path. - -```typescript -import { merkleRootFromPath } from "@mistcash/sdk"; - -const computedRoot = merkleRootFromPath(leaf, proofPath); -const isValid = computedRoot === expectedRoot; -``` - -### `merkleHasher(left, right)` - -The default Poseidon-based hasher used in Merkle tree operations. - -```typescript -import { merkleHasher } from "@mistcash/sdk"; - -const parentHash = merkleHasher(leftChild, rightChild); -``` - -## Contract Utilities - -### `getChamber(provider?)` - -Returns a typed instance of the Chamber contract. - -```typescript -import { getChamber } from "@mistcash/sdk"; - -const chamber = getChamber(provider); -``` - -### `fetchTxAssets(contract, valKey, valTo)` - -Fetches the assets associated with a transaction from the contract. - -```typescript -const asset = await fetchTxAssets(chamber, claimingKey, recipientAddress); -// Returns: { addr: string, amount: string | bigint } -``` - - - -### `checkTxExists(contract, valKey, valTo, tokenAddr, amount)` - -Check whether a specific transaction exists in the contract. - -```typescript -const exists = await checkTxExists(chamber, key, to, tokenAddr, amount); -// Returns: boolean -``` - -### `getTxIndexInTree(leaves, valKey, valTo, tokenAddr, amount)` - -Find the index of a transaction in the Merkle tree leaves. - -```typescript -const index = await getTxIndexInTree(leaves, key, to, tokenAddr, amount); -// Returns: number -``` - -## Formatting Utilities - -### `fmtAmount(amount, decimals)` - -Format a `bigint` amount with decimal places for display. - -```typescript -import { fmtAmount } from "@mistcash/sdk"; - -fmtAmount(1000000n, 6); // "1.0" -``` - -### `fmtAmtToBigInt(amountStr, decimals)` - -Parse a decimal string into a `bigint` with the given precision. - -```typescript -import { fmtAmtToBigInt } from "@mistcash/sdk"; - -fmtAmtToBigInt("1.5", 18); // 1500000000000000000n -``` - -### `getHashParams()` - -Parse URL hash parameters (useful for sharing transaction links). - -```typescript -const params = getHashParams(); -// Returns: Record -``` diff --git a/src/content/docs/packages/react.mdx b/src/content/docs/packages/react.mdx deleted file mode 100644 index d10fe40..0000000 --- a/src/content/docs/packages/react.mdx +++ /dev/null @@ -1,205 +0,0 @@ ---- -title: "@mistcash/react" -description: React hook for integrating MIST.cash privacy transactions into your app. ---- - -import { Tabs, TabItem, Aside, Steps } from "@astrojs/starlight/components"; - -The React package provides the `useMist` hook — a single hook that manages the full lifecycle of privacy transactions including key input, asset fetching, proof generation, and withdrawal. - -## Installation - - - - ```bash - pnpm add @mistcash/react @mistcash/sdk @mistcash/config - ``` - - - ```bash - npm install @mistcash/react @mistcash/sdk @mistcash/config - ``` - - - -**Peer dependencies:** `react@^19.1.0` - -The React package also depends on `@starknet-react/core` and `@starknet-react/chains` for Starknet wallet integration. - -## `useMist` Hook - -### Signature - -```typescript -function useMist( - provider: ProviderInterface | undefined, - sendTx: (calls: Call[]) => void -): UseMistResult; -``` - -**Parameters:** - -| Parameter | Type | Description | -|-----------|------|-------------| -| `provider` | `ProviderInterface \| undefined` | Starknet provider instance from your wallet connection | -| `sendTx` | `(calls: Call[]) => void` | Function to send transactions (from `@starknet-react/core`) | - -### Return Value - -The hook returns an object with the following properties: - -#### Contract State - -| Property | Type | Description | -|----------|------|-------------| -| `chamberAddress` | `string` | The Chamber contract address | -| `contract` | `ChamberTypedContract` | Typed contract instance | -| `txLeaves` | `bigint[]` | Current Merkle tree leaves | - -#### Loading State - -| Property | Type | Description | -|----------|------|-------------| -| `loadingStatus` | `"FINDING_TX" \| "READY"` | Current loading state | -| `loadingMessage` | `string` | Human-readable loading message | - -#### Transaction Inputs - -| Property | Type | Description | -|----------|------|-------------| -| `valKey` | `string` | Current claiming key input | -| `setKey` | `(val: string) => void` | Set the claiming key | -| `valTo` | `string` | Current recipient address input | -| `setTo` | `(val: string) => void` | Set the recipient address | - -#### Asset State - -| Property | Type | Description | -|----------|------|-------------| -| `asset` | `Asset \| undefined` | Found asset details | -| `setAsset` | `(asset: Asset \| undefined) => void` | Set asset manually | -| `setAssetAddr` | `(addr: string) => void` | Set asset token address | -| `setAssetAmt` | `(amount: bigint) => void` | Set asset amount | - -#### Actions - -| Property | Type | Description | -|----------|------|-------------| -| `send` | `(calls?: Call[]) => void` | Send a transaction | -| `fetchAsset` | `() => Promise` | Fetch asset for current key/to | -| `updateTxLeaves` | `() => Promise` | Refresh Merkle tree leaves | -| `handleWithdraw` | `(asset: Asset, newTxAmount?: string) => Promise` | Execute withdrawal with ZK proof | - -#### Transaction Status - -| Property | Type | Description | -|----------|------|-------------| -| `isPending` | `boolean` | Transaction in progress | -| `error` | `string \| null` | Error message | -| `txError` | `Error \| null` | Transaction error object | - -#### Seek and Hide (Re-hiding) - -| Property | Type | Description | -|----------|------|-------------| -| `valSnHTo` | `string` | Seek-and-hide recipient | -| `setSnHTo` | `(val: string) => void` | Set seek-and-hide recipient | -| `valSnHKey` | `string` | Seek-and-hide key | -| `setSnHKey` | `(val: string) => void` | Set seek-and-hide key | -| `valSnHAmt` | `string` | Seek-and-hide amount | -| `setSnHAmt` | `(val: string) => void` | Set seek-and-hide amount | - -## Usage Example - - - 1. **Set up your Starknet provider** - - ```tsx - import { useAccount, useProvider } from "@starknet-react/core"; - - function App() { - const { provider } = useProvider(); - const { account } = useAccount(); - - const sendTx = (calls) => { - account?.execute(calls); - }; - - return ; - } - ``` - - 2. **Use the `useMist` hook** - - ```tsx - import { useMist } from "@mistcash/react"; - - function PrivacyWallet({ provider, sendTx }) { - const mist = useMist(provider, sendTx); - - return ( -
-

MIST.cash Privacy Wallet

-

Status: {mist.loadingMessage}

- - - - - - - - {mist.asset && ( -
-

Found: {mist.asset.amount.toString()} of {mist.asset.addr}

- -
- )} - - {mist.error &&

{mist.error}

} -
- ); - } - ``` -
- -## Withdrawal Flow - -When `handleWithdraw` is called, the hook performs the following steps internally: - -1. Fetches the current Merkle tree leaves from the contract -2. Finds the transaction index in the tree -3. Computes the Merkle root and proof path -4. Constructs the witness object -5. Generates a Groth16 zero-knowledge proof (WASM) -6. Formats the proof as Starknet calldata (Garaga) -7. Submits the withdrawal transaction via `sendTx` - - - - diff --git a/src/content/docs/reference/api.mdx b/src/content/docs/reference/api.mdx deleted file mode 100644 index 8e2abe6..0000000 --- a/src/content/docs/reference/api.mdx +++ /dev/null @@ -1,168 +0,0 @@ ---- -title: API Reference -description: Complete function signatures for all MIST.cash SDK exports. ---- - -import { Aside } from "@astrojs/starlight/components"; - -## @mistcash/sdk - -### Initialization - -```typescript -function initCore(): Promise -function initWasm(): Promise -function initGaraga(): Promise -``` - -### Hashing - -```typescript -function hash2(a: string, b: string): Promise -function hash2Sync(a: string, b: string): string -function hash3(a: string, b: string, c: string): Promise -function hash3Sync(a: string, b: string, c: string): string -function txSecret(key: string, to: string): string -function hash_with_asset(secret: string, asset: string, amount: string): string -function txHash(key: string, owner: string, tokenAddr: string, amount: string): bigint -function generateClaimingKey(): string -``` - -### Zero-Knowledge Proofs - -```typescript -function prove_groth16(witness: Witness): Promise -function full_prove(witness: Witness): Promise - -const FIXTURES: { - witness: Witness - proof: string - verifyingKey: string -} -``` - -### Merkle Trees - -```typescript -function calculateMerkleRoot( - leaves: bigint[], - hasher?: (a: bigint, b: bigint) => bigint, - leafFilter?: (leaf: bigint) => bigint -): bigint - -function calculateMerkleRootAndProof( - leaves: bigint[], - index: number, - hasher?: (a: bigint, b: bigint) => bigint, - leafFilter?: (leaf: bigint) => bigint -): bigint[] - -function merkleRootFromPath( - element: bigint, - path: bigint[], - hasher?: (a: bigint, b: bigint) => bigint, - leafFilter?: (leaf: bigint) => bigint -): bigint - -function get_next_level( - tree: bigint[], - hasher?: (a: bigint, b: bigint) => bigint -): bigint[] - -function merkleHasher(left: bigint, right: bigint): bigint -function evenLeafFilter(leaf: bigint): bigint -``` - -### Contract Utilities - -```typescript -function getChamber(provider?: ProviderInterface): ChamberTypedContract - -function fetchTxAssets( - contract: ChamberTypedContract, - valKey: string, - valTo: string -): Promise - -function checkTxExists( - contract: ChamberTypedContract, - valKey: string, - valTo: string, - tokenAddr: string, - amount: string -): Promise - -function getTxIndexInTree( - leaves: bigint[], - valKey: string, - valTo: string, - tokenAddr: string, - amount: string -): Promise -``` - -### Formatting - -```typescript -function fmtAmount(amount: bigint, decimals: number): string -function fmtAmtToBigInt(amountStr: string, decimals: number): bigint -function getHashParams(): Record -``` - -### Development - -```typescript -function devVal(val: T, defaultVal?: T): T -function devStr(val: string): string -``` - ---- - -## @mistcash/config - -### Constants - -```typescript -const CHAMBER_ADDR_MAINNET: string -const CHAMBER_ABI: Abi -const ERC20_ABI: Abi -``` - -### Token Data - -```typescript -const tokensData: Token[] -const tokensMap: Record -const tokenNamesMap: Record -``` - -### Types - -```typescript -interface Token { - name: string - symbol: string - address: string - decimals: number - image?: string -} - -type ChamberTypedContract = TypedContractV2 -``` - ---- - -## @mistcash/react - -### Hook - -```typescript -function useMist( - provider: ProviderInterface | undefined, - sendTx: (calls: Call[]) => void -): UseMistResult -``` - - diff --git a/src/content/docs/reference/contract.mdx b/src/content/docs/reference/contract.mdx deleted file mode 100644 index 866bbd1..0000000 --- a/src/content/docs/reference/contract.mdx +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Contract ABI -description: Chamber smart contract interface and methods. ---- - -import { Aside } from "@astrojs/starlight/components"; - -The Chamber contract is the on-chain component of MIST.cash. It manages a Merkle tree of transaction commitments and verifies zero-knowledge proofs for private withdrawals. - -## Contract Address - -**Starknet Mainnet:** - -``` -0x06f8dcc500131b6be6b33f4534ec6d33df33e61083ec2b051555d52e75654444 -``` - -## Core Methods - -### `deposit(hash, asset)` - -Deposits tokens into the Chamber and adds a commitment to the Merkle tree. - -```typescript -// The commitment hash -const hash = txHash(claimingKey, ownerAddress, tokenAddress, amount); - -// The asset to deposit -const asset = { addr: tokenAddress, amount: depositAmount }; - -await chamber.deposit(hash, asset); -``` - - - -### `handle_zkp(proof)` - -Processes a zero-knowledge proof to execute a private withdrawal. The proof demonstrates knowledge of a valid commitment in the Merkle tree without revealing which one. - -```typescript -const calldata = await full_prove(witness); -await chamber.handle_zkp(calldata); -``` - -### `withdraw_no_zk(claiming_key, owner, asset, proof)` - -Withdraws tokens without a zero-knowledge proof. Requires revealing the claiming key. - - - -### `seek_and_hide_no_zk(...)` - -Transfers tokens within the privacy pool without full ZK. Allows re-hiding tokens under a new commitment. - -## Read Methods - -### `tx_array()` - -Returns all transaction commitment leaves in the Merkle tree. - -```typescript -const leaves = await chamber.tx_array(); -// Returns: bigint[] -``` - -### `merkle_root()` - -Returns the current Merkle root of the transaction tree. - -```typescript -const root = await chamber.merkle_root(); -// Returns: bigint -``` - -### `merkle_proof(index)` - -Returns the Merkle proof path for a leaf at the given index. - -```typescript -const proof = await chamber.merkle_proof(leafIndex); -// Returns: bigint[] -``` - -### `assets_from_secret(tx_secret)` - -Looks up the asset associated with a transaction secret. - -```typescript -const secret = txSecret(claimingKey, recipientAddress); -const asset = await chamber.assets_from_secret(secret); -// Returns: { addr: string, amount: bigint } -``` - -### `nullifiers_spent(nullifiers)` - -Checks whether a set of nullifiers have been spent (used in withdrawals). - -```typescript -const spent = await chamber.nullifiers_spent([nullifier1, nullifier2]); -// Returns: boolean[] -``` - -### `transactions_exist(transactions)` - -Checks whether a set of transaction hashes exist in the tree. - -```typescript -const exists = await chamber.transactions_exist([hash1, hash2]); -// Returns: boolean[] -``` diff --git a/src/content/docs/reference/types.mdx b/src/content/docs/reference/types.mdx deleted file mode 100644 index 55bfaa2..0000000 --- a/src/content/docs/reference/types.mdx +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: Types -description: TypeScript type definitions used across the MIST.cash SDK. ---- - -## Asset - -Represents a token asset with an address and amount. - -```typescript -interface Asset { - addr: string; - amount: string | bigint; -} -``` - -**Usage:** -```typescript -const asset: Asset = { - addr: "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7", - amount: 1000000000000000000n, // 1 ETH -}; -``` - -## Witness - -Input to the zero-knowledge proof generator. Contains all data needed to prove knowledge of a valid transaction without revealing which one. - -```typescript -interface Witness { - ClaimingKey: string; - Owner: string; - TxAsset: string; - Withdraw: { - Amount: string; - }; - MerkleRoot: string; - MerkleProof: string[]; - Tx1Secret: string; -} -``` - -**Fields:** - -| Field | Description | -|-------|-------------| -| `ClaimingKey` | The secret key that proves ownership of the deposit | -| `Owner` | The address that will receive the withdrawn tokens | -| `TxAsset` | The token contract address | -| `Withdraw.Amount` | The amount to withdraw (as string) | -| `MerkleRoot` | The current Merkle root of the transaction tree | -| `MerkleProof` | Array of sibling hashes forming the proof path | -| `Tx1Secret` | Derived from `txSecret(ClaimingKey, Owner)` | - -## ProofResponse - -Response from the Groth16 proof generation. - -```typescript -interface ProofResponse { - status: "ok" | "error"; - proof?: string; - error?: string; - message?: string; -} -``` - -**Success case:** -```typescript -{ status: "ok", proof: "..." } -``` - -**Error case:** -```typescript -{ status: "error", error: "invalid witness", message: "..." } -``` - -## Token - -Token metadata from `@mistcash/config`. - -```typescript -interface Token { - name: string; - symbol: string; - address: string; - decimals: number; - image?: string; -} -``` - -## ChamberTypedContract - -A typed contract instance for the Chamber smart contract. Provides full TypeScript autocomplete for all contract methods. - -```typescript -type ChamberTypedContract = TypedContractV2; -``` - -**Key contract methods:** - -| Method | Returns | Description | -|--------|---------|-------------| -| `deposit(hash, asset)` | `void` | Deposit tokens with commitment | -| `withdraw_no_zk(key, owner, asset, proof)` | `void` | Withdraw without ZK (testing) | -| `handle_zkp(proof)` | `void` | Process ZK proof withdrawal | -| `tx_array()` | `bigint[]` | Get all transaction leaves | -| `merkle_root()` | `bigint` | Get current Merkle root | -| `merkle_proof(index)` | `bigint[]` | Get proof for leaf index | -| `assets_from_secret(secret)` | `Asset` | Lookup asset by tx secret | -| `nullifiers_spent(nullifiers)` | `boolean[]` | Check if nullifiers are spent | - -## UseMistResult - -Full return type of the `useMist` hook. See the [@mistcash/react documentation](/packages/react#return-value) for a detailed breakdown of each property. - -```typescript -interface UseMistResult { - // Contract - chamberAddress: string; - contract: ChamberTypedContract; - txLeaves: bigint[]; - - // Loading - loadingStatus: "FINDING_TX" | "READY"; - loadingMessage: string; - - // Inputs - valTo: string; - setTo: (val: string) => void; - valKey: string; - setKey: (val: string) => void; - - // Asset - asset: Asset | undefined; - setAsset: (asset: Asset | undefined) => void; - setAssetAddr: (addr: string) => void; - setAssetAmt: (amount: bigint) => void; - - // Actions - send: (calls?: Call[]) => void; - fetchAsset: () => Promise; - updateTxLeaves: () => Promise; - handleWithdraw: (asset: Asset, newTxAmount?: string) => Promise; - - // Status - isPending: boolean; - error: string | null; - txError: Error | null; - - // Seek and Hide - valSnHTo: string; - setSnHTo: (val: string) => void; - valSnHKey: string; - setSnHKey: (val: string) => void; - valSnHAmt: string; - setSnHAmt: (val: string) => void; -} -``` diff --git a/src/content/docs/sdk/index.mdx b/src/content/docs/sdk/index.mdx new file mode 100644 index 0000000..b3b58a3 --- /dev/null +++ b/src/content/docs/sdk/index.mdx @@ -0,0 +1,58 @@ +--- +title: SDK +description: "@mistcash/sdk, the TypeScript SDK for MIST on EVM: proving on the user's device and a client for the Chamber and Reserve contracts." +sidebar: + label: SDK overview + order: 0 +--- + +`@mistcash/sdk` is the TypeScript SDK for MIST on EVM. It builds spend proofs on the user's device, in Node or in a browser, and wraps the calls to the Chamber and Reserve contracts. + +## Install + +```bash +npm install @mistcash/sdk@beta viem +``` + +Version 0.6 is a rewrite and ships on the `beta` tag. The `latest` tag is the legacy 0.5 SDK, which has a different API. + +## Entry points + +| Import | Contents | +| --- | --- | +| `@mistcash/sdk` | `MistClient`, the types, the contract ABIs and the note, proving and key-exchange helpers. Safe to import during server-side rendering: it loads no WebAssembly | +| `@mistcash/sdk/prover` | `loadProver` and `createWorkerProver`, which run the prover from `mist.wasm`, about 20 MB, in Node or in a Web Worker | +| `@mistcash/sdk/prover/webgpu` | The same prover on gnark's WebGPU backend. It falls back to the CPU when there is no GPU | +| `@mistcash/sdk/mist.wasm` | The prover binary, with its proving key embedded | +| `@mistcash/sdk/circuit.json` | The circuit description the prover was built from | + +## What the client does + +`MistClient` takes an address book, a chain adapter and a prover. It covers each role in the protocol. + +- **Depositor.** `deposit` approves a Reserve and deposits into a private note. `refreshScreening` and `reclaimDeposit` follow a deposit through a screener. +- **Member.** `join` runs the key exchange with the Reserve's key holder and registers the member. `spend` builds the proof and submits a private payment or a withdrawal. +- **Reserve operator.** `registerReserve`, `setReserveScreener` and `updateAuditorKey` administer a Reserve. `openPayload` reads a member's spend. +- **Screener.** `queuedDeposits`, `approveDeposits` and `rejectDeposits` decide the deposits waiting at a Reserve. + +```ts +// Deposit into a private note, then withdraw it back to the public account. +await client.deposit({ reserve, id: "me (MIST)", amount, blinding: rand() }); +await client.spend({ id: "me (MIST)", amount: 0n, withdraw: amount, withdrawTo: "me", reserve }); +``` + +Registration uses a post-quantum key exchange. The SDK ships X-Wing, a hybrid of ML-KEM-768 and X25519, as `encapsulate`, `decapsulate` and `deriveUkx`. The protocol does not fix the exchange, so a Reserve can use another. + +## Caveats + +:::caution[The published beta predates the contract hardening] +`0.6.0-beta.1` was built against the earlier contract interface. It calls `Chamber.setVerifier`, `Chamber.setReserveScreener(reserve, screener)`, `Reserve.setRegistrar` and a three-argument `registerUser`. None of these exist in the contracts in mistcash/core `main`: the verifier changes through a timelock, a Reserve sets its own screener, the registrar holds a permission, and `registerUser` takes a deadline and a signer. Calls such as `join` and `setReserveScreener` fail against them until an SDK release follows the contracts. +::: + +:::caution[Before building on the SDK] +- `secretOf` derives a MIST secret from a private key and is for development only. A browser wallet never exposes its key, so an application must derive the secret from a wallet signature. +- The prover's note amount is a `uint64`, so one note holds at most about 18.4 units of an asset with 18 decimals. The protocol allows amounts below 2^120. Larger amounts split across notes. +- With a `StorageAdapter`, call `restoreKeyIndices()` once at startup. Without it, a reload can reuse a key index and the Chamber reverts the spend. +::: + +The repository's [README](https://github.com/mistcash/sdk) has the full setup, including bundler configuration for Vite and webpack. diff --git a/src/styles/code-themes.mjs b/src/styles/code-themes.mjs new file mode 100644 index 0000000..2779da0 --- /dev/null +++ b/src/styles/code-themes.mjs @@ -0,0 +1,43 @@ +// Syntax themes for code blocks, drawn from the brand palette only. +// landing/DESIGN.md allows three hues, so highlighting uses azure for +// structure, coral for literals and tints of the surface text for the rest. +// Contrast: every token colour is at least 4.5:1 on its code background. + +const scopes = (dark) => { + const text = dark ? "#EEF2FF" : "#010511"; + const soft = dark ? "#B0B4C1" : "#3F434F"; // punctuation, operators + const quiet = dark ? "#8A8E9B" : "#5B5F6B"; // comments + const structure = dark ? "#8FB0FF" : "#0046DE"; // keywords, constants + const literal = dark ? "#FE8192" : "#A8283B"; // strings, numbers + return [ + { scope: ["comment", "punctuation.definition.comment"], settings: { foreground: quiet } }, + { scope: ["keyword", "storage", "storage.type", "storage.modifier"], settings: { foreground: structure } }, + { scope: ["constant.language", "constant.other", "support.constant"], settings: { foreground: structure } }, + { scope: ["string", "string.quoted", "punctuation.definition.string"], settings: { foreground: literal } }, + { scope: ["constant.numeric", "constant.character.escape"], settings: { foreground: literal } }, + { scope: ["entity.name.function", "support.function", "meta.function-call"], settings: { foreground: text, fontStyle: "bold" } }, + { scope: ["entity.name.type", "entity.name.class", "support.class", "support.type"], settings: { foreground: text } }, + { scope: ["variable", "variable.other", "variable.parameter"], settings: { foreground: text } }, + { scope: ["variable.other.property", "meta.object-literal.key", "support.type.property-name"], settings: { foreground: text } }, + { scope: ["keyword.operator", "punctuation", "meta.brace"], settings: { foreground: soft } }, + { scope: ["markup.heading"], settings: { foreground: structure, fontStyle: "bold" } }, + { scope: ["markup.inline.raw", "markup.fenced_code"], settings: { foreground: literal } }, + ]; +}; + +const theme = (dark) => ({ + name: dark ? "mist-midnight" : "mist-fog", + type: dark ? "dark" : "light", + colors: { + "editor.background": dark ? "#060F2A" : "#F7F9FF", + "editor.foreground": dark ? "#EEF2FF" : "#010511", + }, + settings: [ + { settings: { foreground: dark ? "#EEF2FF" : "#010511", background: dark ? "#060F2A" : "#F7F9FF" } }, + ...scopes(dark), + ], + tokenColors: scopes(dark), +}); + +export const mistMidnight = theme(true); +export const mistFog = theme(false); diff --git a/src/styles/custom.css b/src/styles/custom.css deleted file mode 100644 index 9764aaa..0000000 --- a/src/styles/custom.css +++ /dev/null @@ -1,28 +0,0 @@ -/* Custom styles for MIST.cash SDK docs */ - -:root { - --sl-color-accent-low: #1a1a2e; - --sl-color-accent: #6c63ff; - --sl-color-accent-high: #c4c1ff; - --sl-color-white: #ffffff; - --sl-color-gray-1: #eceef2; - --sl-color-gray-2: #c0c2c7; - --sl-color-gray-3: #888b96; - --sl-color-gray-4: #545861; - --sl-color-gray-5: #353841; - --sl-color-gray-6: #24272f; - --sl-color-black: #17181c; - --sl-font-system: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, - "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif; -} - -:root[data-theme="light"] { - --sl-color-accent-low: #e8e6ff; - --sl-color-accent: #5b52e0; - --sl-color-accent-high: #2a2366; -} - -/* Code block styling */ -.expressive-code pre { - border-radius: 0.5rem; -} diff --git a/src/styles/diagram.css b/src/styles/diagram.css new file mode 100644 index 0000000..dc2c930 --- /dev/null +++ b/src/styles/diagram.css @@ -0,0 +1,314 @@ +/* MIST.cash docs: the diagram grammar. + * + * One diagram language, from landing/DESIGN.md ("The Record"): + * note or payment a square cell (empty, recorded, followed, hidden, shared) + * reserve a tall panel, 1px strong border, name, rule chips, lock line + * shared record an azure field holding cells, labelled in uppercase + * movement a 1px lane; a coral square is the payment being followed + * labels uppercase label at the top-left of their region + * Square corners, 1px rules, no shadow, no gradient. Horizontal sequences + * become vertical stacks at phone width instead of shrinking type. + * Everything reads colours from the --mist-* surface variables, so the same + * markup holds in both themes and on the azure field. + */ + +/* Cells */ +.mist-cell { + display: block; + aspect-ratio: 1; + width: var(--cell, 1.5rem); + flex: none; + border: 1px solid var(--mist-line); +} +.mist-cell[data-state="recorded"] { + background: var(--mist-line); + border-color: var(--mist-line-strong); +} +.mist-cell[data-state="followed"] { + background: var(--mist-coral); + border-color: var(--mist-coral); +} +.mist-cell[data-state="shared"] { + border-color: var(--mist-coral); +} +.mist-cell[data-state="hidden"] { + background: var(--mist-fg); + border-color: var(--mist-fg); +} + +/* The record strip that closes every page */ +.mist-strip { + display: flex; + gap: 6px; + width: 100%; + overflow: hidden; +} +.mist-strip .mist-cell { + width: auto; + flex: 1; + min-width: 10px; +} +@media (max-width: 36rem) { + .mist-strip [data-phone-hidden] { + display: none; + } +} +.mist-footer-record { + max-width: var(--sl-content-width); + margin-top: 3rem; +} +@media (min-width: 72rem) { + .mist-footer-record { + margin-inline: var(--sl-content-margin-inline, auto); + } +} + +/* Labels name things inside a diagram. Never a kicker above a heading. */ +.mist-label { + margin: 0; + font-family: var(--mist-font-text); + font-size: var(--mist-t-label); + font-weight: 600; + line-height: 1.3; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--mist-fg-3); +} + +/* Chips: states and rules inside a diagram */ +.mist-chip { + display: inline-block; + margin: 0; + padding: 0.25rem 0.5rem; + border: 1px solid var(--mist-line-strong); + border-radius: var(--mist-radius); + font-family: var(--mist-font-text); + font-size: var(--mist-t-label); + font-weight: 600; + line-height: 1.3; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--mist-fg); + list-style: none; +} + +/* Movement lanes: a 1px rule */ +.mist-lane { + display: block; + flex: 1; + min-width: 1.25rem; + height: 0; + border-top: 1px solid var(--mist-line-strong); +} + +/* Figure and stage */ +.mist-figure { + margin: 2rem 0 2.5rem; +} +.mist-figure figcaption { + margin-top: 0.75rem; + font-size: var(--mist-t-small); + line-height: 1.55; + color: var(--mist-fg-3); + max-width: 65ch; +} +.mist-diagram { + padding: 1.5rem; + border: 1px solid var(--mist-line); + background: var(--mist-panel); + color: var(--mist-fg); +} +@media (min-width: 50rem) { + .mist-diagram { + padding: 2rem 2.25rem; + } +} + +/* Three moves of a note's life */ +.mist-moves { + display: grid; + gap: 2rem; + margin: 0; + padding: 0; + list-style: none; +} +.mist-moves > li { + margin: 0; +} +.mist-move { + display: grid; + gap: 1rem; + align-content: start; + grid-template-rows: auto auto 1fr; +} +.mist-move__stage { + display: flex; + align-items: center; + gap: 0.625rem; + min-height: 3rem; +} +.mist-move .mist-lane { + min-width: 0.75rem; +} +.mist-pair { + display: flex; + flex-direction: column; + gap: 6px; +} +.mist-move__note { + margin: 0; + font-size: var(--mist-t-small); + line-height: 1.55; + color: var(--mist-fg-2); +} +@media (min-width: 40rem) { + .mist-moves { + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 0; + } + .mist-moves > li + li { + padding-left: 1.5rem; + margin-left: 1.5rem; + border-left: 1px solid var(--mist-line); + } +} +@media (max-width: 39.99rem) { + .mist-moves > li + li { + padding-top: 2rem; + border-top: 1px solid var(--mist-line); + } +} + +/* The shared record: an azure field that owns its region */ +.mist-record { + --mist-fg: var(--mist-fog); + --mist-fg-2: rgb(238 242 255 / 0.84); + --mist-fg-3: rgb(238 242 255 / 0.84); + --mist-line: rgb(238 242 255 / 0.26); + --mist-line-strong: rgb(238 242 255 / 0.6); + display: grid; + gap: 1rem; + padding: 1.25rem; + background: var(--mist-azure); + color: var(--mist-fog); +} +@media (min-width: 50rem) { + .mist-record { + padding: 1.5rem 1.75rem; + } +} +.mist-record .mist-cells { + display: flex; + flex-wrap: wrap; + gap: 6px; + --cell: 1.25rem; +} +.mist-record__parts { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + margin: 0; + padding: 0; + list-style: none; +} + +/* Architecture */ +.mist-arch { + display: grid; + gap: 0; +} +.mist-arch__proof { + display: flex; + align-items: center; + gap: 0.75rem; + margin-bottom: 1.25rem; +} +.mist-arch__proof .mist-lane { + flex: none; + min-width: 2rem; +} +.mist-arch__reserves { + display: grid; + gap: 1rem; + margin-top: 2.25rem; + position: relative; +} +/* A 1px lane from each Reserve up to the record */ +.mist-arch__reserves .mist-reserve::before { + content: ""; + position: absolute; + top: -2.25rem; + left: 50%; + height: 2.25rem; + border-left: 1px solid var(--mist-line-strong); +} +@media (min-width: 40rem) { + .mist-arch__reserves { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } +} +@media (max-width: 39.99rem) { + .mist-arch__reserves { + margin-top: 1rem; + } + .mist-arch__reserves .mist-reserve::before { + display: none; + } +} + +/* Reserve: a tall panel */ +.mist-reserve { + position: relative; + display: grid; + gap: 0.875rem; + align-content: start; + min-height: 9rem; + padding: 1.25rem; + border: 1px solid var(--mist-line-strong); + background: transparent; +} +.mist-reserve__name { + margin: 0; + font-family: var(--mist-font-display); + font-size: 1.25rem; + font-weight: 600; + line-height: 1.18; + letter-spacing: -0.01em; + color: var(--mist-fg); +} +.mist-reserve__rules { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + margin: 0; + padding: 0; + list-style: none; +} +.mist-lock { + display: flex; + align-items: center; + gap: 0.5rem; + margin: 0; + align-self: end; + font-size: var(--mist-t-small); + color: var(--mist-fg-2); +} +.mist-lock svg { + flex: none; +} + +/* Hero record field */ +.mist-field { + display: grid; + grid-template-columns: repeat(var(--cols), 1fr); + gap: 6px; + width: 100%; +} +.mist-field .mist-cell { + width: auto; +} +@media (max-width: 49.99rem) { + .mist-field [data-phone-hidden] { + display: none; + } +} diff --git a/src/styles/theme.css b/src/styles/theme.css new file mode 100644 index 0000000..269ea6f --- /dev/null +++ b/src/styles/theme.css @@ -0,0 +1,710 @@ +/* MIST.cash docs: Starlight restyled to the landing design (landing/DESIGN.md). + * + * Swiss and editorial: flat fields, 1px rules, square corners (2px on + * controls), no shadow, no glow, no gradient text. Josefin Sans sets headings, + * Sen sets everything read, the system monospace sets code. Coral is the one + * action and at most one marker per view; light mode swaps the marker to azure + * because coral on fog is under 3:1. Tokens live in tokens.css. + * + * These rules are unlayered, so they win over Starlight's layered defaults. + */ + +/* ---------------------------------------------------------------- Base */ + +html { + overflow-x: clip; + background: var(--mist-midnight); + scrollbar-color: rgb(238 242 255 / 0.28) var(--mist-midnight); + -webkit-text-size-adjust: 100%; +} +:root[data-theme="light"] { + background: var(--mist-fog); + scrollbar-color: rgb(1 5 17 / 0.3) var(--mist-fog); +} + +body { + background: var(--sl-color-bg); + color: var(--sl-color-text); + font-family: var(--mist-font-text); + font-feature-settings: "kern"; + caret-color: var(--mist-coral); + overflow-x: clip; +} + +::selection { + background: var(--mist-coral); + color: var(--mist-midnight); +} + +h1, +h2, +h3, +h4 { + text-wrap: balance; +} +p, +li, +dd { + text-wrap: pretty; +} + +:focus-visible { + outline: 2px solid var(--mist-focus); + outline-offset: 3px; +} + +@media (prefers-reduced-motion: reduce) { + html { + scroll-behavior: auto; + } + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +} + +/* -------------------------------------------------------------- Header */ + +.page > .header { + border-bottom: 1px solid var(--mist-line); + background: var(--mist-midnight); +} + +/* Search trigger reads as an input: 40px, 1px strong border, 2px corners. */ +site-search button[data-open-modal] { + min-height: 2.5rem; + border: 1px solid var(--mist-line-strong); + border-radius: var(--mist-radius); + background: transparent; + color: var(--mist-fg-2); + font-family: var(--mist-font-text); + font-size: 0.9375rem; + transition: + border-color 160ms var(--mist-ease), + color 160ms var(--mist-ease); +} +site-search button[data-open-modal]:hover { + border-color: var(--mist-fg); + color: var(--mist-fg); +} +site-search button[data-open-modal] kbd { + border: 1px solid var(--mist-line-strong); + border-radius: var(--mist-radius); + font-family: var(--mist-font-text); + font-size: 0.75rem; +} +@media (min-width: 50rem) { + site-search button[data-open-modal] { + min-width: 12rem; + padding-inline: 0.875rem; + } +} + +/* Search modal: flat, framed, no shadow. */ +site-search dialog { + border: 1px solid var(--mist-line-strong); + border-radius: 0; + background: var(--sl-color-bg); + box-shadow: none; +} +site-search dialog .pagefind-ui__search-input, +site-search dialog input { + border-radius: var(--mist-radius); +} +site-search dialog .pagefind-ui__result-link { + color: var(--mist-fg); +} +site-search dialog .pagefind-ui__result-inner > a::after { + content: none; +} +site-search .pagefind-ui__result { + border-top-color: var(--mist-line); +} +site-search .pagefind-ui__result-excerpt mark { + background: transparent; + color: var(--mist-fg); + font-weight: 700; + text-decoration: underline; +} + +/* The scrim dims the page. It does not blur it. */ +site-search dialog::backdrop { + -webkit-backdrop-filter: none; + backdrop-filter: none; + background: var(--sl-color-backdrop-overlay); +} + +/* Mobile menu toggle: a square control, not Starlight's circle. */ +starlight-menu-button button { + border: 1px solid var(--mist-line-strong); + border-radius: var(--mist-radius); + background: transparent; + color: var(--mist-fg); + box-shadow: none; + padding: 0; +} +@media (max-width: 49.99rem) { + starlight-menu-button button { + display: grid; + place-items: center; + } +} +starlight-menu-button button svg { + width: 1.5rem; + height: 1.5rem; +} +starlight-menu-button[aria-expanded="true"] button { + background: color-mix(in srgb, var(--mist-fg) 8%, transparent); +} + +/* Theme select and social icons keep the header's dark surface. */ +starlight-theme-select select { + border-radius: var(--mist-radius); + border: 1px solid var(--mist-line-strong); + background-color: transparent; +} +.social-icons a { + border-radius: var(--mist-radius); +} + +/* ------------------------------------------------------------- Sidebar */ + +.sidebar-pane { + background: var(--sl-color-bg-sidebar); + border-inline-end: 1px solid var(--mist-line); +} +@media (min-width: 50rem) { + .sidebar-pane { + top: var(--sl-nav-height); + } +} + +/* Group headings are column labels, as in the landing footer. */ +.sidebar-content .large { + font-family: var(--mist-font-text); + font-size: var(--mist-t-label); + font-weight: 600; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--mist-fg-3); +} +.sidebar-content summary { + padding-block: 0.375rem; +} + +.sidebar-content a { + border-radius: 0; + padding: 0.4375rem 0.75rem; + font-size: 0.9375rem; + line-height: 1.4; + color: var(--mist-fg-2); + text-decoration: none; + transition: color 160ms var(--mist-ease); +} +.sidebar-content a:hover { + color: var(--mist-fg); +} +/* The current page: full text colour and a 2px rule in the text colour. Coral + is kept for the one action and the one marker of a view. */ +.sidebar-content a[aria-current="page"], +.sidebar-content a[aria-current="page"]:hover, +.sidebar-content a[aria-current="page"]:focus { + background: transparent; + color: var(--mist-fg); + font-weight: 600; + box-shadow: inset 2px 0 0 var(--mist-fg); +} + +/* Table of contents */ +.right-sidebar { + border-inline-start: 1px solid var(--mist-line); +} +.right-sidebar h2 { + font-size: var(--mist-t-label); + font-weight: 600; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--mist-fg-3); +} +starlight-toc a, +mobile-starlight-toc a { + border-radius: 0; + font-size: 0.875rem; + color: var(--mist-fg-2); +} +starlight-toc a:hover, +mobile-starlight-toc a:hover { + color: var(--mist-fg); +} +starlight-toc a[aria-current="true"], +mobile-starlight-toc a[aria-current="true"] { + color: var(--mist-fg); + font-weight: 600; +} +mobile-starlight-toc nav { + border-color: var(--mist-line); + background: var(--sl-color-bg); +} + +/* ------------------------------------------------------------- Content */ + +/* The title is the one display line on a content page. */ +.content-panel h1, +.content-panel #_top { + font-family: var(--mist-font-display); + font-size: var(--mist-t-h1); + font-weight: 700; + line-height: 1.04; + letter-spacing: -0.025em; + color: var(--mist-fg); +} +main > .content-panel:first-of-type { + padding-top: clamp(2rem, 1.4rem + 2vw, 3.5rem); + padding-bottom: 0; + border: 0; +} +[data-has-hero] main > .content-panel:first-of-type { + padding-top: 1.5rem; +} +main > .content-panel + .content-panel { + border-top: 0; + padding-top: 1.5rem; +} + +.sl-markdown-content { + font-size: var(--mist-t-body); + line-height: 1.65; +} + +.sl-markdown-content :is(h2, h3, h4):not(:where(.not-content *)) { + font-family: var(--mist-font-display); + color: var(--mist-fg); + text-wrap: balance; +} +.sl-markdown-content h2:not(:where(.not-content *)) { + font-size: var(--mist-t-h2); + font-weight: 700; + line-height: 1.08; + letter-spacing: -0.02em; +} +.sl-markdown-content h3:not(:where(.not-content *)) { + font-size: var(--mist-t-h3); + font-weight: 600; + line-height: 1.18; + letter-spacing: -0.01em; +} +.sl-markdown-content h4:not(:where(.not-content *)) { + font-size: 1.1875rem; + font-weight: 600; + line-height: 1.25; +} +/* Space above a heading is always larger than space below it. */ +.sl-markdown-content + :not(h1, h2, h3, h4, h5, h6) + + :is(h2, h3, h4):not(:where(.not-content *)) { + margin-top: clamp(2.5rem, 2rem + 2vw, 3.5rem); +} +.sl-markdown-content :is(h2, h3, h4) + *:not(:where(.not-content *)) { + margin-top: 0.875rem; +} +.sl-heading-wrapper .anchor-link { + color: var(--mist-fg-3); +} + +/* Prose runs at 65ch maximum. */ +.sl-markdown-content :is(p, li, dd):not(:where(.not-content *)) { + max-width: 65ch; +} +/* The paragraph under a title is the lede. */ +.sl-markdown-content > p:first-child { + max-width: 46ch; + font-size: var(--mist-t-lede); + line-height: 1.5; + color: var(--mist-fg-2); +} + +.sl-markdown-content strong { + color: var(--mist-fg); + font-weight: 700; +} + +.sl-markdown-content a:not(:where(.not-content *)) { + color: var(--mist-accent-text); + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 0.22em; + text-decoration-color: color-mix(in srgb, var(--mist-accent-text) 45%, transparent); + transition: text-decoration-color 160ms var(--mist-ease); +} +.sl-markdown-content a:hover:not(:where(.not-content *)) { + color: var(--mist-fg); + text-decoration-color: var(--mist-marker); +} + +.sl-markdown-content ::marker { + color: var(--mist-fg-3); +} +.sl-markdown-content hr { + border: 0; + border-top: 1px solid var(--mist-line); +} +.sl-markdown-content blockquote { + margin-inline: 0; + padding-inline-start: 1.25rem; + border-inline-start: 2px solid var(--mist-line-strong); + color: var(--mist-fg-2); +} + +/* Inline code is data: the system monospace on a panel, 1px hairline. */ +.sl-markdown-content code:not(:where(.not-content *)) { + padding: 0.0625rem 0.375rem; + border: 1px solid var(--mist-line); + border-radius: 0; + background: var(--mist-panel); + color: var(--mist-fg); + font-family: var(--mist-font-mono); + font-size: 0.875em; + font-variant-numeric: tabular-nums; +} +.sl-markdown-content :is(h1, h2, h3, h4) code:not(:where(.not-content *)) { + font-size: 0.8em; + font-weight: 400; +} +.sl-markdown-content pre code:not(:where(.not-content *)) { + border: 0; + padding: 0; + background: none; +} + +/* ---------------------------------------------------------- Code blocks */ +/* Expressive Code takes its colours from the config's themes; the frame is + squared here. */ +.expressive-code .frame, +.expressive-code pre, +.expressive-code .frame .header { + border-radius: 0; +} +/* Terminal blocks drop the window bar and its three dots: a code block is a + flat panel with a 1px border, like every other panel. */ +.expressive-code .frame.is-terminal .header { + display: none; +} +.expressive-code .copy button { + border-radius: var(--mist-radius); +} + +/* -------------------------------------------------------------- Tables */ + +.sl-markdown-content table:not(:where(.not-content *)) { + display: block; + width: 100%; + overflow-x: auto; + border-collapse: collapse; + border: 1px solid var(--mist-line); + font-size: 0.9375rem; + line-height: 1.5; +} +/* Wide tables scroll inside their frame on phones; from 40rem they fill it. */ +@media (min-width: 40rem) { + .sl-markdown-content table:not(:where(.not-content *)) { + display: table; + } +} +.sl-markdown-content :is(th, td):not(:where(.not-content *)) { + padding: 0.75rem 1rem; + border: 0; + border-bottom: 1px solid var(--mist-line); + text-align: start; + vertical-align: top; +} +.sl-markdown-content td:not(:where(.not-content *)) { + min-width: 8rem; +} +.sl-markdown-content :is(td:first-child, th) code:not(:where(.not-content *)) { + white-space: nowrap; +} +.sl-markdown-content td code:not(:where(.not-content *)) { + overflow-wrap: anywhere; +} +.sl-markdown-content tr:last-child td { + border-bottom: 0; +} +.sl-markdown-content thead th:not(:where(.not-content *)) { + background: var(--mist-panel); + border-bottom: 1px solid var(--mist-line-strong); + font-size: var(--mist-t-label); + font-weight: 600; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--mist-fg-3); + white-space: nowrap; +} +.sl-markdown-content tbody td:first-child:not(:where(.not-content *)) { + color: var(--mist-fg); +} +.sl-markdown-content tbody tr:nth-child(even) td { + background: transparent; +} + +/* --------------------------------------------------------------- Asides */ +/* Square panels with a 2px rule. Status is said in the title, not in a hue: + information takes azure, a warning takes coral. */ + +.starlight-aside { + padding: 1.25rem 1.5rem; + border: 1px solid var(--mist-line); + border-inline-start: 2px solid var(--sl-color-asides-border); + border-radius: 0; + background: var(--mist-panel); + color: var(--mist-fg-2); +} +.starlight-aside--note, +.starlight-aside--tip { + --sl-color-asides-text-accent: var(--mist-fg); + --sl-color-asides-border: var(--mist-accent-text); + background: var(--mist-panel); +} +.starlight-aside--caution, +.starlight-aside--danger { + --sl-color-asides-text-accent: var(--mist-fg); + --sl-color-asides-border: var(--sl-color-orange); + background: var(--mist-panel); +} +.starlight-aside--danger { + border-color: var(--sl-color-orange); +} +.starlight-aside__icon { + display: none; +} +.starlight-aside__title { + font-family: var(--mist-font-text); + font-size: var(--mist-t-label); + font-weight: 600; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--mist-fg-3); +} +.starlight-aside__content { + font-size: 1rem; +} +.starlight-aside__content a { + color: var(--mist-accent-text); +} + +/* ------------------------------------------------- Steps, tabs, cards */ + +.sl-steps > li { + --bullet-size: 1.75rem; +} +.sl-steps > li::before { + border-radius: 0; + border: 1px solid var(--mist-line-strong); + background: transparent; + color: var(--mist-fg); + font-family: var(--mist-font-text); + font-weight: 600; + box-shadow: none; +} +.sl-steps > li::after { + background: var(--mist-line); +} + +starlight-tabs [role="tab"] { + border-radius: 0; + font-weight: 600; + color: var(--mist-fg-2); +} +starlight-tabs [role="tab"][aria-selected="true"] { + color: var(--mist-fg); + border-bottom-color: var(--mist-fg); +} + +.sl-markdown-content .card, +.sl-markdown-content .sl-link-card { + border: 1px solid var(--mist-line); + border-radius: 0; + background: var(--mist-panel); + box-shadow: none; +} + +/* ------------------------------------------------------ Pagination */ + +.pagination-links a { + border: 1px solid var(--mist-line-strong); + border-radius: 0; + background: transparent; + box-shadow: none; + transition: border-color 160ms var(--mist-ease); +} +.pagination-links a:hover { + border-color: var(--mist-fg); +} +.pagination-links .link-title { + font-family: var(--mist-font-display); + font-weight: 600; + letter-spacing: -0.01em; + color: var(--mist-fg); +} +.pagination-links span { + color: var(--mist-fg-3); +} +footer.sl-flex { + font-size: var(--mist-t-small); +} + +/* ------------------------------------------------------------- Buttons */ + +.mist-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0.625rem; + min-height: 3rem; + padding: 0 1.375rem; + border: 1px solid var(--btn-border, var(--mist-line-strong)); + border-radius: var(--mist-radius); + background: var(--btn-bg, transparent); + color: var(--btn-fg, var(--mist-fg)); + font-family: var(--mist-font-text); + font-size: 1rem; + font-weight: 600; + line-height: 1; + white-space: nowrap; + text-decoration: none; + transition: + background-color 160ms var(--mist-ease), + border-color 160ms var(--mist-ease), + color 160ms var(--mist-ease); +} +.mist-btn svg { + flex: none; + transition: transform 320ms var(--mist-ease); +} +.mist-btn:hover svg[data-icon="arrow-right"] { + transform: translateX(3px); +} +/* One coral action per view. */ +.mist-btn--primary { + --btn-bg: var(--mist-coral); + --btn-fg: var(--mist-midnight); + --btn-border: var(--mist-coral); +} +.mist-btn--primary:hover { + --btn-bg: var(--mist-fog); + --btn-border: var(--mist-fog); +} +.mist-btn--secondary:hover { + --btn-border: var(--mist-fg); + --btn-bg: color-mix(in srgb, var(--mist-fg) 8%, transparent); +} + +/* ---------------------------------------------------------------- Hero */ +/* A midnight field in both themes, full bleed, with the record beside the + copy. Starlight puts the hero inside the content panel, so the field is + a pseudo-element that extends past it. */ + +.mist-hero { + position: relative; + isolation: isolate; + display: grid; + gap: 2.5rem; + align-items: center; + margin-top: -1.5rem; + padding-block: clamp(3rem, 2.2rem + 3.3vw, 5.5rem); + color: var(--mist-fg); +} +.mist-hero::before { + content: ""; + position: absolute; + z-index: -1; + inset: 0 -100vw; + background: var(--mist-midnight); + border-bottom: 1px solid var(--mist-line); +} +.mist-hero__copy { + display: grid; + gap: 1.5rem; + justify-items: start; +} +.mist-hero h1 { + max-width: 14ch; + margin: 0; + font-family: var(--mist-font-display); + font-size: clamp(2.5rem, 1.75rem + 3.1vw, 4.5rem); + font-weight: 700; + line-height: 1; + letter-spacing: -0.03em; + color: var(--mist-fg); +} +.mist-hero__tagline { + max-width: 40ch; + margin: 0; + font-size: var(--mist-t-lede); + line-height: 1.5; + color: var(--mist-fg-2); +} +.mist-hero__actions { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + margin-top: 0.5rem; +} +@media (min-width: 50rem) { + .mist-hero { + grid-template-columns: minmax(0, 7fr) minmax(0, 5fr); + gap: 4rem; + } +} + +/* -------------------------------------------------------- Ruled index */ + +.mist-index { + margin: 1.5rem 0 0; + padding: 0; + list-style: none; + border-top: 1px solid var(--mist-line-strong); +} +.mist-index li { + margin: 0; + border-bottom: 1px solid var(--mist-line); +} +.mist-index a { + display: grid; + grid-template-columns: 1fr auto; + gap: 0.25rem 1.5rem; + align-items: center; + padding: 1.25rem 0; + color: var(--mist-fg); + text-decoration: none; +} +.mist-index__title { + font-family: var(--mist-font-display); + font-size: var(--mist-t-h3); + font-weight: 600; + line-height: 1.18; + letter-spacing: -0.01em; +} +.mist-index__body { + grid-column: 1; + max-width: 60ch; + font-size: 1rem; + line-height: 1.5; + color: var(--mist-fg-2); +} +.mist-index svg { + grid-column: 2; + grid-row: 1 / span 2; + transition: transform 320ms var(--mist-ease); +} +.mist-index a:hover svg { + transform: translateX(3px); +} +.mist-index a:hover .mist-index__title { + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 0.22em; + text-decoration-color: var(--mist-marker); +} diff --git a/src/styles/tokens.css b/src/styles/tokens.css new file mode 100644 index 0000000..45c5f4e --- /dev/null +++ b/src/styles/tokens.css @@ -0,0 +1,220 @@ +/* MIST.cash docs: design tokens. + * + * Mirrors landing/DESIGN.md and landing/src/app/globals.css. Three colours + * carry the brand (midnight, azure, coral) and every neutral is a tint of + * them, so nothing here introduces a fourth hue. Starlight's variables are + * mapped onto these tokens at the bottom, which is what restyles the + * stock components. + * + * Dark mode is the landing's midnight surface. Light mode is its fog reading + * surface. The header is midnight in both, as it is on the landing. + */ + +@font-face { + font-family: "Josefin Sans"; + src: url("/fonts/JosefinSans-Variable-latin.woff2") format("woff2"); + font-weight: 100 700; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: "Sen"; + src: url("/fonts/Sen-Variable-latin.woff2") format("woff2"); + font-weight: 400 800; + font-style: normal; + font-display: swap; +} + +:root { + /* Brand */ + --mist-midnight: #010511; + --mist-azure: #0046de; + --mist-coral: #fe8192; + + /* Neutrals and tints, from landing globals.css */ + --mist-fog: #eef2ff; + --mist-paper: #f7f9ff; + --mist-deep: #060f2a; + --mist-azure-soft: #8fb0ff; + --mist-azure-deep: #0037b0; + --mist-coral-deep: #e86a7c; + --mist-coral-ink: #a8283b; + + --mist-radius: 2px; + --mist-font-display: "Josefin Sans", ui-sans-serif, Futura, sans-serif; + --mist-font-text: "Sen", ui-sans-serif, system-ui, sans-serif; + --mist-font-mono: ui-monospace, "SFMono-Regular", "JetBrains Mono", Menlo, Consolas, monospace; + + --mist-ease: cubic-bezier(0.16, 1, 0.3, 1); + + /* Type scale, landing --t-* (fluid between 390px and 1440px) */ + --mist-t-display-xl: clamp(2.75rem, 1.55rem + 4.95vw, 6rem); + --mist-t-h1: clamp(2.25rem, 1.6rem + 2.4vw, 3.375rem); + --mist-t-h2: clamp(1.625rem, 1.35rem + 1.1vw, 2.25rem); + --mist-t-h3: clamp(1.25rem, 1.15rem + 0.45vw, 1.5rem); + --mist-t-lede: clamp(1.125rem, 1.04rem + 0.36vw, 1.375rem); + --mist-t-body: 1.0625rem; + --mist-t-small: 0.875rem; + --mist-t-label: 0.75rem; + + --mist-gutter: clamp(1.25rem, 0.6rem + 2.7vw, 3.5rem); +} + +/* Dark: the midnight surface. The header and the mobile menu sheet reuse this + block in both themes, so every derived variable is redeclared here. */ +:root, +::backdrop, +.page > .header, +starlight-menu-button, +.mist-dark { + --mist-fg: var(--mist-fog); + --mist-fg-2: rgb(238 242 255 / 0.74); + --mist-fg-3: rgb(238 242 255 / 0.58); + --mist-line: rgb(238 242 255 / 0.14); + --mist-line-strong: rgb(238 242 255 / 0.36); + --mist-panel: var(--mist-deep); + --mist-accent-text: var(--mist-azure-soft); + --mist-marker: var(--mist-coral); + --mist-focus: var(--mist-coral); + + --sl-color-white: var(--mist-fog); + --sl-color-gray-1: rgb(238 242 255 / 0.92); + --sl-color-gray-2: rgb(238 242 255 / 0.74); + --sl-color-gray-3: rgb(238 242 255 / 0.58); + --sl-color-gray-4: rgb(238 242 255 / 0.36); + --sl-color-gray-5: rgb(238 242 255 / 0.22); + --sl-color-gray-6: var(--mist-deep); + --sl-color-black: var(--mist-midnight); + + --sl-color-accent-low: color-mix(in srgb, var(--mist-azure) 24%, var(--mist-midnight)); + --sl-color-accent: var(--mist-azure); + --sl-color-accent-high: var(--mist-azure-soft); + + /* Starlight's four status hues fold into the brand: azure for information, + coral for warnings. Status is also said in words (the aside title). */ + --sl-color-blue-low: color-mix(in srgb, var(--mist-azure) 20%, var(--mist-midnight)); + --sl-color-blue: var(--mist-azure-soft); + --sl-color-blue-high: var(--mist-azure-soft); + --sl-color-purple-low: var(--sl-color-blue-low); + --sl-color-purple: var(--sl-color-blue); + --sl-color-purple-high: var(--sl-color-blue-high); + --sl-color-green-low: var(--sl-color-blue-low); + --sl-color-green: var(--sl-color-blue); + --sl-color-green-high: var(--sl-color-blue-high); + --sl-color-orange-low: color-mix(in srgb, var(--mist-coral) 14%, var(--mist-midnight)); + --sl-color-orange: var(--mist-coral); + --sl-color-orange-high: var(--mist-coral); + --sl-color-red-low: var(--sl-color-orange-low); + --sl-color-red: var(--sl-color-orange); + --sl-color-red-high: var(--sl-color-orange-high); + + --sl-color-text: var(--mist-fg-2); + --sl-color-text-accent: var(--mist-accent-text); + --sl-color-text-invert: var(--mist-midnight); + --sl-color-bg: var(--mist-midnight); + --sl-color-bg-nav: var(--mist-midnight); + --sl-color-bg-sidebar: var(--mist-midnight); + --sl-color-bg-inline-code: var(--mist-deep); + --sl-color-bg-accent: var(--mist-coral); + --sl-color-hairline-light: var(--mist-line); + --sl-color-hairline: var(--mist-line); + --sl-color-hairline-shade: var(--mist-line); + --sl-color-backdrop-overlay: rgb(1 5 17 / 0.72); + + /* The Flat Rule: no shadows. */ + --sl-shadow-sm: none; + --sl-shadow-md: none; + --sl-shadow-lg: none; + + color-scheme: dark; +} + +/* Light: the fog reading surface, paper for raised panels. */ +:root[data-theme="light"], +[data-theme="light"] ::backdrop { + --mist-fg: var(--mist-midnight); + --mist-fg-2: rgb(1 5 17 / 0.74); + --mist-fg-3: rgb(1 5 17 / 0.62); + --mist-line: rgb(1 5 17 / 0.13); + --mist-line-strong: rgb(1 5 17 / 0.4); + --mist-panel: var(--mist-paper); + --mist-accent-text: var(--mist-azure); + --mist-marker: var(--mist-azure); + --mist-focus: var(--mist-azure); + + --sl-color-white: var(--mist-midnight); + --sl-color-gray-1: rgb(1 5 17 / 0.9); + --sl-color-gray-2: rgb(1 5 17 / 0.74); + --sl-color-gray-3: rgb(1 5 17 / 0.62); + --sl-color-gray-4: rgb(1 5 17 / 0.4); + --sl-color-gray-5: rgb(1 5 17 / 0.24); + --sl-color-gray-6: var(--mist-paper); + --sl-color-gray-7: var(--mist-paper); + --sl-color-black: var(--mist-fog); + + --sl-color-accent-low: color-mix(in srgb, var(--mist-azure) 10%, var(--mist-fog)); + --sl-color-accent: var(--mist-azure); + --sl-color-accent-high: var(--mist-azure-deep); + + --sl-color-blue-low: color-mix(in srgb, var(--mist-azure) 8%, var(--mist-paper)); + --sl-color-blue: var(--mist-azure); + --sl-color-blue-high: var(--mist-azure-deep); + --sl-color-purple-low: var(--sl-color-blue-low); + --sl-color-purple: var(--sl-color-blue); + --sl-color-purple-high: var(--sl-color-blue-high); + --sl-color-green-low: var(--sl-color-blue-low); + --sl-color-green: var(--sl-color-blue); + --sl-color-green-high: var(--sl-color-blue-high); + --sl-color-orange-low: color-mix(in srgb, var(--mist-coral) 14%, var(--mist-paper)); + --sl-color-orange: var(--mist-coral-deep); + --sl-color-orange-high: var(--mist-coral-ink); + --sl-color-red-low: var(--sl-color-orange-low); + --sl-color-red: var(--sl-color-orange); + --sl-color-red-high: var(--sl-color-orange-high); + + --sl-color-text: var(--mist-fg-2); + --sl-color-text-accent: var(--mist-accent-text); + --sl-color-text-invert: var(--mist-fog); + --sl-color-bg: var(--mist-fog); + --sl-color-bg-nav: var(--mist-midnight); + --sl-color-bg-sidebar: var(--mist-fog); + --sl-color-bg-inline-code: var(--mist-paper); + --sl-color-bg-accent: var(--mist-azure); + --sl-color-hairline-light: var(--mist-line); + --sl-color-hairline: var(--mist-line); + --sl-color-hairline-shade: var(--mist-line); + --sl-color-backdrop-overlay: rgb(1 5 17 / 0.5); + + color-scheme: light; +} + +/* Layout and type metrics Starlight reads */ +:root { + --sl-font: var(--mist-font-text); + --sl-font-mono: var(--mist-font-mono); + --sl-text-body: var(--mist-t-body); + --sl-text-code: 0.8125rem; + --sl-text-code-sm: 0.8125rem; + --sl-line-height: 1.65; + --sl-line-height-headings: 1.1; + --sl-text-h1: var(--mist-t-h1); + --sl-text-h2: var(--mist-t-h2); + --sl-text-h3: var(--mist-t-h3); + --sl-text-h4: 1.1875rem; + + --sl-nav-height: 4rem; + --sl-nav-pad-x: var(--mist-gutter); + --sl-content-pad-x: var(--mist-gutter); + --sl-content-width: 46rem; + --sl-sidebar-width: 18rem; + --sl-sidebar-pad-x: 1.25rem; + --sl-menu-button-size: 2.75rem; +} + +@media (min-width: 72rem) { + :root { + --sl-nav-height: 4.5rem; + --sl-content-pad-x: 3rem; + } +}