From e5ba96f47c6b93881c6414d62cc475817a5fe2c5 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:10:05 +0530 Subject: [PATCH 01/14] docs(sdk): add install and setup page Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/install.mdx | 116 +++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 src/content/docs/sdk/install.mdx diff --git a/src/content/docs/sdk/install.mdx b/src/content/docs/sdk/install.mdx new file mode 100644 index 0000000..0717719 --- /dev/null +++ b/src/content/docs/sdk/install.mdx @@ -0,0 +1,116 @@ +--- +title: Install and setup +description: "Installing @mistcash/sdk, its package exports, the Node and browser prover entry points, the wasm assets and circuit.json." +sidebar: + order: 1 +--- + +`@mistcash/sdk` installs from npm with `viem` as a peer dependency. Node runs it with no configuration. A browser app passes the prover's WebAssembly file to the loader explicitly. + +```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. The package needs Node `^20.19.0` or `>=22.12.0` and `viem` `^2`. + +## Package exports + +| Import | Contents | +| --- | --- | +| `@mistcash/sdk` | `MistClient`, the types, the ABIs and the note, proving, identity and key-exchange helpers. ESM and CommonJS. Loads no WebAssembly | +| `@mistcash/sdk/prover` | `loadProver` and `createWorkerProver`. The `node` build reads the wasm from disk, the default build fetches it | +| `@mistcash/sdk/prover/webgpu` | `loadWebGPUProver` and `hasWebGPU`, for browsers | +| `@mistcash/sdk/mist.wasm` | The CPU prover with its proving key embedded. Also served as `@mistcash/sdk/wasm/mist.wasm` | +| `@mistcash/sdk/mist-webgpu.wasm` | The WebGPU build of the same prover. Also served as `@mistcash/sdk/wasm/mist-webgpu.wasm` | +| `@mistcash/sdk/circuit.json` | The record of what the wasm was built from | + +The root entry exports these groups. + +| Group | Exports | +| --- | --- | +| Client | `MistClient`, `MistClientOpts`, `DepositOpts`, `SpendOpts`, `ManagerApproval` | +| Contracts | `CORE_ABI`, `SCREENING_ABI`, `ABIS`, `PUBLIC_INPUTS`, `RESERVE_ROLES`, `ReserveRole`, `AddressBook` | +| Identity | `secretOf`, `ownerOf`, `rand`, `account`, `isMist`, `nameOf`, `OWNER_KEYWORD` | +| Key exchange | `managerKeys`, `encapsulate`, `decapsulate`, `deriveUkx`, `fingerprint`, `SIZES` | +| Notes | `unspent`, `total`, `pick`, `plan` | +| Proving | `buildSpendRequest`, `serializeSpendRequest`, `proveSpend`, `foldCiphertext`, `randomKeyIndex`, `pickUnusedKeyIndex`, `ProverAdapter` | +| Types | `Hex`, `Note`, `PendingDeposit`, `DepositStatus`, `ChainAdapter`, `SentTx`, `TxReceipt`, `MistCallbacks`, `StorageAdapter` | + +`ABIS` holds the ABI of each of the five contracts as human-readable signatures. `CORE_ABI` is the subset a host's chain adapter needs, with the deposit-screening functions included. + +## Prover entry points + +`loadProver` returns a `FullProverAdapter`: `{ hash2, hash3, spend, decrypt }`. Its source argument is one of four things. + +| Source | Call | Use when | +| --- | --- | --- | +| Nothing | `loadProver()` | Node, and browsers where the package's file layout is served as it is | +| A path | `loadProver("/abs/path/mist.wasm")` | Node, with a custom build output | +| A URL | `loadProver(url)` | Browsers, with the URL the bundler emits | +| Bytes | `loadProver(bytes)` | Anywhere, including bytes read from OPFS or IndexedDB | + +```ts +import { loadProver } from "@mistcash/sdk/prover"; + +const prover = await loadProver(); +console.log(await prover.hash2("1", "2")); +``` + +The default source resolves `new URL("../wasm/mist.wasm", import.meta.url)` at runtime. A bundler cannot see that string, so in a built app the file is usually not emitted and the request returns 404. A bundled app passes the URL or the bytes. + +```ts +// Vite +import wasmUrl from "@mistcash/sdk/wasm/mist.wasm?url"; +import { loadProver } from "@mistcash/sdk/prover"; + +const prover = await loadProver(wasmUrl); +``` + +```ts +// Any bundler: fetch the file and pass the bytes +import { loadProver } from "@mistcash/sdk/prover"; + +declare const wasmUrl: string; // the URL the bundler emits for mist.wasm + +const bytes = new Uint8Array(await (await fetch(wasmUrl)).arrayBuffer()); +const prover = await loadProver(bytes); +``` + +On Vite, either pass the URL as above or exclude the SDK from dependency pre-bundling with `optimizeDeps: { exclude: ["@mistcash/sdk"] }`. On webpack 5 and Next.js, a static import of the wasm file yields a hashed URL to pass to `loadProver`. Load the prover in a client-side effect, not during render and not on the server. + +If loading fails, the error names the path or URL it tried and says to pass a source. + +The SDK does not inline the wasm as base64. That would add about 26 MB to every bundle, tie the wasm's cache lifetime to the JavaScript's and force a full decode in memory in place of streaming instantiation. A self-contained bundle base64-encodes the file itself and passes the decoded bytes. + +## Server-side rendering + +`import { MistClient } from "@mistcash/sdk"` is safe during server-side rendering: the root entry pulls in no wasm and no Go runtime. `@mistcash/sdk/prover` is imported from client code only. The `node` export condition keeps `node:fs` out of browser bundles. + +## One prover per page + +The Go runtime registers as `globalThis.Go`, and the prover's exports land on `globalThis`. Two provers in one page collide, and that includes `mist.wasm` next to `mist-webgpu.wasm`. `loadProver` memoizes one instance, so a second call returns the first and ignores its source. A failed load clears the memo and a retry can succeed. + +## The wasm assets and circuit.json + +The wasm files embed the proving key. The proving key must match the verifier deployed on the target chain. A mismatched wasm still produces proofs, and the Chamber rejects each one at `handleZkp`. + +`circuit.json` records what the shipped wasm was built from. + +| Field | Meaning | +| --- | --- | +| `sha256`, `size` | Checksum and byte size of `mist.wasm`, about 19.6 MB | +| `webgpu.sha256`, `webgpu.size` | The same for `mist-webgpu.wasm`, about 21.5 MB | +| `go`, `gnark` | The Go toolchain and the gnark version the wasm links | +| `core.commit` | The mistcash/core commit the proving key was built from | +| `builtFrom.commit` | The mist commit the wasm was built in | +| `timestamp` | When it was built | + +```ts +import circuit from "@mistcash/sdk/circuit.json" with { type: "json" }; + +console.log(circuit.core.commit, circuit.sha256); +``` + +The SDK's pack step refuses to publish a wasm whose checksum or circuit commit differs from `circuit.json`. The sizes above come from the `circuit.json` in the SDK repository. + +On Node, `loadProver()` took about 0.15 s on a development laptop (Node 25.2.1, macOS, four runs between 0.14 s and 0.16 s). That was measured for these pages and is not a browser figure. From 41399fed09bb153c52a4cbf351df2ae35d91cf8a Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:10:05 +0530 Subject: [PATCH 02/14] docs(sdk): add quick start Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/quick-start.mdx | 128 +++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 src/content/docs/sdk/quick-start.mdx diff --git a/src/content/docs/sdk/quick-start.mdx b/src/content/docs/sdk/quick-start.mdx new file mode 100644 index 0000000..150b68f --- /dev/null +++ b/src/content/docs/sdk/quick-start.mdx @@ -0,0 +1,128 @@ +--- +title: Quick start +description: "Join a Reserve, deposit and withdraw with @mistcash/sdk in Node, against a local chain." +sidebar: + order: 2 +--- + +This page runs the whole flow in one Node script: join a Reserve, deposit into a private note, and withdraw it to the public account. It uses a local development chain, where the deployer is the Reserve admin. + +## Before running + +- A local chain with core deployed by core-deploy (`scripts/deploy.sh deploy`). At core `fa7b92d` the Chamber's runtime code is over the EIP-170 limit of 24,576 bytes, so the local chain runs with `--disable-code-size-limit`, which `deploy.sh` sets. +- The deployment's address book, `core-deploy/dist/deployments/.json`. The deploy script creates the fixture Reserve and lists the asset only on chain 31337 and one public development chain. Without fixtures `reserve` and `token` in the book are the zero address, and every other chain is treated as production. +- On the local deployment, dev account 0 is the Chamber owner and the fixture Reserve's admin, the registrar holds `USERS`, and the asset is listed with a minimum deposit of 1. Dev account 5 is the guardian. +- `PRIVATE_KEY` set to dev account 0's key. + +## The script + +Steps below form one file. Run them in order. + +### Chain adapter + +The adapter is the SDK's only link to the chain. It reads contracts, sends transactions and returns events. [Client and address book](/sdk/client/) states what each member must return. + +```ts +import { readFile } from "node:fs/promises"; +import { createPublicClient, createWalletClient, http, keccak256, parseAbi, type WalletClient } from "viem"; +import { privateKeyToAccount } from "viem/accounts"; +import { anvil } from "viem/chains"; +import { loadProver } from "@mistcash/sdk/prover"; +import { + CORE_ABI, + MistClient, + decapsulate, + deriveUkx, + managerKeys, + rand, + type AddressBook, + type ChainAdapter, + type Hex, +} from "@mistcash/sdk"; + +const PRIVATE_KEY = process.env.PRIVATE_KEY as Hex; +const account = privateKeyToAccount(PRIVATE_KEY); +const publicClient = createPublicClient({ chain: anvil, transport: http() }); +const walletClient = createWalletClient({ chain: anvil, transport: http(), account }); + +// Every read, write and event the client uses: Chamber, Reserve, registrar, asset, screening. +const abi = parseAbi(CORE_ABI); + +function chainAdapter(wallet: WalletClient): ChainAdapter { + return { + readContract: (address, functionName, args) => + publicClient.readContract({ address, abi, functionName: functionName as never, args: args as never }), + sendTransaction: async (tx) => { + const hash = await wallet.sendTransaction({ account: wallet.account!, chain: anvil, to: tx.to, data: tx.data, value: tx.value }); + const receipt = await publicClient.waitForTransactionReceipt({ hash }); + // Pass the logs through: deposit() and spend() read NoteAppended and DepositQueued from them. + return { hash, receipt: { transactionHash: hash, gasUsed: receipt.gasUsed, status: receipt.status, logs: receipt.logs } }; + }, + // UserRegistered and UserRemoved (the users tree a spend proves against), and DepositQueued. + getEvents: (address, eventName, fromBlock) => + publicClient.getLogs({ + address, + event: abi.find((item) => item.type === "event" && item.name === eventName) as never, + fromBlock, + }), + }; +} +``` + +### Prover and client + +```ts +const book = JSON.parse(await readFile("core-deploy/dist/deployments/31337.json", "utf8")) as AddressBook; + +const prover = await loadProver(); // reads wasm/mist.wasm from disk in Node +const client = new MistClient({ + book, + chainId: anvil.id, + chain: chainAdapter(walletClient), + prover, + // "me" is the public account, "me (MIST)" its private MIST identity. + addressOf: () => account.address, + // Development only: a real app derives the secret from a wallet signature. + secretOf: () => (BigInt(keccak256(PRIVATE_KEY)) >> 8n).toString(), +}); +``` + +### Join the Reserve + +A Reserve with members lets only members spend. The Reserve's half of the join normally runs in the key holder's service, signed by a `USERS` holder. Here the deployer is the Reserve admin, which holds every permission, so one script plays both sides. + +```ts +const keys = managerKeys(PRIVATE_KEY); + +await client.join({ + id: "me (MIST)", + reserve: book.reserve, + managerPublicKey: keys.publicKey, + managerSide: async ({ cipherText, reserve, mistAddr }) => { + const ukx = deriveUkx(decapsulate(cipherText, keys.secretKey), reserve, mistAddr); + const leaf = BigInt(await prover.hash2(mistAddr, ukx)); + // The last valid second, in chain time. Read the digest just before signing. + const deadline = (await publicClient.getBlock()).timestamp + 3600n; + const digest = await publicClient.readContract({ + address: book.registrar, + abi, + functionName: "registerUserDigest", + args: [reserve, leaf, account.address, deadline], + }); + return { ukx, signer: account.address, deadline, signature: await account.sign({ hash: digest }) }; + }, +}); +``` + +[Joining a Reserve](/sdk/joining-a-reserve/) explains each value. + +### Deposit and withdraw + +```ts +const amount = 10n ** 18n; // amounts are uint64, so one note holds at most about 18.4 units at 18 decimals + +await client.deposit({ reserve: book.reserve, id: "me (MIST)", amount, blinding: rand() }); +await client.spend({ id: "me (MIST)", amount: 0n, withdraw: amount, withdrawTo: "me", reserve: book.reserve }); +``` + +`deposit` approves the Reserve and deposits into a note owned by `me (MIST)`. `spend` proves the withdrawal on this machine, then submits it. The withdrawal pays the public account `me`. From 07f28450a61bbc02216035aed8161b1d80f15408 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:10:05 +0530 Subject: [PATCH 03/14] docs(sdk): document the client, address book and chain adapter Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/client.mdx | 107 ++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 src/content/docs/sdk/client.mdx diff --git a/src/content/docs/sdk/client.mdx b/src/content/docs/sdk/client.mdx new file mode 100644 index 0000000..a7c0e8e --- /dev/null +++ b/src/content/docs/sdk/client.mdx @@ -0,0 +1,107 @@ +--- +title: Client and address book +description: "MistClient configuration, the address book, and what each member of the chain adapter must return." +sidebar: + order: 3 +--- + +`MistClient` is a stateful gateway. The host injects the addresses, the chain transport, the prover and the key lookups, and the client turns them into deposits, spends, registrations and Reserve administration. + +## Address book + +```ts +interface AddressBook { + chamber: Hex; + registrar: Hex; + reserve: Hex; + token: Hex; + verifier: Hex; +} +``` + +This is the shape of `core-deploy/dist/deployments/.json`, which `Deploy.s.sol` writes. Without dev fixtures, `reserve` and `token` are the zero address. + +| Field | Used for | +| --- | --- | +| `chamber` | Every Chamber call: deposits, spends, screening and tree reads | +| `registrar` | `join` and `revokeRegistration`. The registrar holds `USERS` on each Reserve it serves | +| `reserve` | The Reserve a script works with. Client methods take the Reserve as an argument | +| `token` | The one asset a client deposits, spends and withdraws. Another asset needs another address book | +| `verifier` | Held for reference. The client makes no call to it | + +## Configuration + +```ts +new MistClient({ book, chainId, chain, prover, callbacks, store, secretOf, addressOf }); +``` + +| Option | Type | Purpose | +| --- | --- | --- | +| `book` | `AddressBook` | The addresses above | +| `chainId` | `number` or `string` | Bound into the proof's note hashes | +| `chain` | `ChainAdapter` | Reads, writes and events | +| `prover` | `ProverAdapter` | `hash2`, `spend` and, for `openPayload`, `decrypt` | +| `callbacks` | `MistCallbacks` | Optional hooks, below | +| `store` | `StorageAdapter` | Optional. Persists used key indices only | +| `secretOf` | `(id) => string` | The MIST secret of an identity. Without it, a call that needs one throws `MistClient: secretOf not configured` | +| `addressOf` | `(name) => Hex` | The address behind a public account name. Without it, a call that needs one throws `MistClient: addressOf not configured` | + +An identity is a name. `alice` is a public account, owned by its address. `alice (MIST)` is a private MIST identity, owned by a MIST Address derived from `secretOf`. [Notes and keys](/sdk/notes-and-keys/) covers both. + +The client's public state is `book`, `chainId`, `chain`, `prover`, `callbacks`, `store`, `notes`, `ukx` and `usedKeyIndices`. + +## Chain adapter + +```ts +interface ChainAdapter { + readContract(address: Hex, functionName: string, args?: unknown[]): Promise; + sendTransaction(tx: { to: Hex; data: Hex; value?: bigint }): Promise; + getEvents?(address: Hex, eventName: string, fromBlock?: bigint): Promise }>>; +} +``` + +| Member | Must return | +| --- | --- | +| `readContract` | The decoded result of a view call. Every function name the client reads is in `CORE_ABI` | +| `sendTransaction` | `{ hash?, result?, receipt }` once the transaction is confirmed. `receipt` carries `transactionHash` and `logs`, and optionally `gasUsed` and `status` | +| `getEvents` | Decoded events with `args`. Optional, but `queuedDeposits`, `registeredUserLeaves` and every `spend` at a Reserve with members need it | + +### sendTransaction + +The host owns signing, simulation, gas and waiting. The client calls `sendTransaction` for every write and never reads `receipt.status`, so an adapter throws when a transaction reverts. Otherwise the client records a membership or a spend that never happened. + +`receipt.logs` is required. + +- `deposit` reads its own `NoteAppended` or `DepositQueued` event from the logs. `spend` reads `NoteAppended`. +- An adapter that cannot return logs returns the deposit call's `(noteHash, depositId)` as `result` instead. +- With neither, `deposit` stops after the approve and before any funds move. +- When one receipt carries several Chamber notes, as a bundled transaction does, `result` picks this deposit's note. Without a `result` in that case, `deposit` refuses to guess. + +The adapter also decides who submits. [Private transfers and withdrawals](/sdk/transfers/) shows a spend sent from a relayer account. + +### getEvents + +`getEvents` serves three events. + +- `UserRegistered` and `UserRemoved` on a Reserve, which build the users tree a spend proves against. A Reserve with members needs every one of them. `registeredUserLeaves` throws on a missing registration, and `spend` refuses before proving when it holds fewer leaves than the Reserve's `registeredUsersCount`. +- `DepositQueued` on the Chamber, which `queuedDeposits` reads. + +## Callbacks + +| Hook | Fires | Use | +| --- | --- | --- | +| `onProgress(stage)` | At each stage: `Approving`, `Depositing`, `Exchanging keys`, `Registering`, `Proving in your browser`, `Relayer submitting` or `Submitting` | Progress display. The strings are for people, not for matching | +| `onBeforeSend({ to, data, functionName })` | Before each `sendTransaction` | Return `false` to veto. The call throws `MistClient: send of vetoed by onBeforeSend` | +| `onTx({ functionName, receipt })` | After each confirmed write | Logging and fan-out | +| `onProof({ kind: "spend", secs })` | After proving | Timing | + +## Storage adapter + +```ts +interface StorageAdapter { + get(key: string): string | null | Promise; + set(key: string, value: string): void | Promise; +} +``` + +`localStorage`, a `Map` wrapper or a database wrapper all fit. The client writes one key, `mist:keyIndices`. It does not store notes or key exchanges. From 5561823d1659599de86e9ee29a5e06cf411d5c04 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:10:05 +0530 Subject: [PATCH 04/14] docs(sdk): document identities, notes and what the host persists Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/notes-and-keys.mdx | 105 ++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 src/content/docs/sdk/notes-and-keys.mdx diff --git a/src/content/docs/sdk/notes-and-keys.mdx b/src/content/docs/sdk/notes-and-keys.mdx new file mode 100644 index 0000000..edc35ba --- /dev/null +++ b/src/content/docs/sdk/notes-and-keys.mdx @@ -0,0 +1,105 @@ +--- +title: Notes and keys +description: "Identities, the note model, key indices and what the host must persist." +sidebar: + order: 4 +--- + +The client holds a wallet's notes and key exchanges in memory and nothing more. A host that keeps either across sessions persists them itself. + +## Identities + +An identity is a name that decides who owns a note. + +| Identity | Owner | Spend authorised by | +| --- | --- | --- | +| `alice` | The address `addressOf("alice")` returns, as a decimal field string | The wallet, as the caller of `handleZkp` | +| `alice (MIST)` | A MIST Address, `H2(secret, "owner")`, where `secret` is `secretOf("alice (MIST)")` | The proof, which shows knowledge of the secret | + +`isMist(id)` tells the two apart, `account(id)` strips the `(MIST)` suffix, and `ownerOf` computes the owner. [Private transfers and withdrawals](/sdk/transfers/) covers what each kind means for who submits. + +`secretOf` is a synchronous `(id) => string` and returns a decimal string below the field order. The SDK's helper returns `keccak256(privateKey) >> 8`, which is for development only. A browser wallet never exposes its private key, so an application derives the secret from a wallet signature. The signature call is asynchronous, so the host obtains it first and the callback returns the stored value. The same identity must always yield the same secret, or its notes become unspendable. + +## The note model + +```ts +interface Note { + reserve: Hex; + id: string; + blinding: string; + amount: bigint; + hash?: string; + txIndex?: number; + spent?: boolean; + nullifier?: string; + kind?: string; + screening?: "pending" | "rejected" | "reclaimed"; + depositId?: string; +} +``` + +| Field | Meaning | +| --- | --- | +| `reserve`, `id` | The Reserve holding the assets and the owning identity | +| `blinding`, `amount` | The two secrets a note hash hides. Nothing on the chain gives either back, so a lost value is a lost note | +| `hash` | The note hash. Set from the deposit result or the proof output | +| `txIndex` | The note's global index in the Chamber's transaction array. It fixes the tree the note sits in, and the client looks it up from `hash` when unset | +| `spent`, `nullifier` | Set after a spend of the note is submitted | +| `kind` | `deposit`, `received` or `change`, set by the client | +| `screening`, `depositId` | Set while a deposit waits at a screened Reserve, or after the screener rejected it or it was reclaimed. [Deposits](/sdk/deposits/) covers them | + +A note is spendable when it is not `spent`, has no `screening` and belongs to the identity at the Reserve. `client.unspent(reserve, id)` lists those notes and `client.total()` sums the unspent ones. + +Reserve addresses compare as strings, in `notes` and in the `ukx` keys. The host passes each Reserve in one casing throughout. + +A spend records the notes it creates in `client.notes`: the change note and the recipient's note, each under its own identity. The SDK has no way to find a note created for someone else, because the protocol defines no note discovery. A recipient in another client needs the sender to pass the note's `blinding` and `amount` over a channel of its own, and adds a `Note` to its `client.notes`. + +## Key exchanges + +At a Reserve with members, a member's `join` produces a key exchange, `ukx`. The client keeps it as `client.ukx[":"]`. `isMember(reserve, id)` is true when that entry exists. Without it the client cannot prove membership, and the member joins again. Notes are unaffected, because a note's owner is the MIST Address and not the key exchange. + +A key holder's client reads the same map. `openPayload` tries each `ukx` entry of a Reserve, so the key holder fills the map with the members' key exchanges. + +## Key indices + +Each member spend carries a key index from 0 to 255, and the Chamber files the spend under a private transaction key derived from the key exchange and that index. The Chamber rejects a key it has seen, so an index is used once per key exchange. + +- `spend` draws an index at random from those not yet used for the key exchange. The indices live in `client.usedKeyIndices`. +- A key exchange allows 256 member spends. After that the draw throws `All 256 key indices used for this ukx`, and the member joins again to get a fresh key exchange. +- A spend by a non-member at a Reserve without members uses no recorded index. +- Used indices persist through the `store`, under `mist:keyIndices`. The client merges into the stored map and never overwrites it, so two clients sharing one store do not erase each other's indices. + +Call `restoreKeyIndices()` once at startup when a `store` is passed. `spend` also re-reads the store before it draws. Without the startup call, a reload begins with an empty set and can draw an index already spent, and the Chamber reverts the spend. + +```ts +import { MistClient } from "@mistcash/sdk"; + +declare const client: MistClient; + +await client.restoreKeyIndices(); +``` + +## What the host persists + +| State | Lives in | Persisted by | +| --- | --- | --- | +| Notes | `client.notes`, in memory | The host | +| Key exchanges | `client.ukx`, in memory | The host | +| Used key indices | `client.usedKeyIndices`, mirrored to `store` | The client, through the `store` | +| The MIST secret | `secretOf` | The host's wallet derivation | + +`notes` holds `bigint` amounts, which `JSON.stringify` rejects. A host converts them on the way out and back. + +```ts +import type { MistClient, Note } from "@mistcash/sdk"; + +declare const client: MistClient; + +const saved = JSON.stringify({ notes: client.notes, ukx: client.ukx }, (_key, value) => + typeof value === "bigint" ? value.toString() : value, +); + +const restored = JSON.parse(saved) as { notes: Array & { amount: string }>; ukx: Record }; +client.notes = restored.notes.map((note) => ({ ...note, amount: BigInt(note.amount) })); +Object.assign(client.ukx, restored.ukx); +``` From 81d09a054689ae5bad68307bb87bfe1d488e4217 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:10:05 +0530 Subject: [PATCH 05/14] docs(sdk): document deposits, refundTo and screening Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/deposits.mdx | 114 ++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 src/content/docs/sdk/deposits.mdx diff --git a/src/content/docs/sdk/deposits.mdx b/src/content/docs/sdk/deposits.mdx new file mode 100644 index 0000000..d0e5a47 --- /dev/null +++ b/src/content/docs/sdk/deposits.mdx @@ -0,0 +1,114 @@ +--- +title: Deposits +description: "Depositing with MistClient: refundTo, the minimum deposit and asset list, screening, and who may reclaim a queued deposit." +sidebar: + order: 5 +--- + +`deposit` approves a Reserve and deposits into a private note. At a Reserve with a screener the note waits in a queue until the screener approves it, and the depositor can reclaim it until then. + +## Depositing + +```ts +import { MistClient, rand, type Hex } from "@mistcash/sdk"; + +declare const client: MistClient; +declare const reserve: Hex; +declare const amount: bigint; + +const note = await client.deposit({ reserve, id: "alice (MIST)", amount, blinding: rand() }); +``` + +`deposit` takes `{ reserve, id, amount, blinding, refundTo? }` and returns the new `Note`, also pushed to `client.notes`. It runs in this order. + +1. It checks the deposit against the Chamber's own rules and refuses, with nothing sent, on a failure in the table below. +2. It sends the approve to `book.token`, naming the Reserve as spender. +3. It sends `Chamber.deposit`, the overload with `refundTo` when one is given. +4. It reads the note from the receipt's `NoteAppended` or `DepositQueued` log, or from the adapter's `(noteHash, depositId)` result. + +| Refusal | Message | +| --- | --- | +| Amount is zero or less | `Enter a whole amount above zero.` | +| Inflows are paused | `Deposits are paused.` | +| The Reserve has not listed the asset | `This reserve does not accept this token.` | +| Amount is below the Reserve's minimum | `The minimum deposit at this reserve is N.` | + +At a Reserve without a screener the note carries `hash` and `txIndex` and is spendable at once. At a screened Reserve it carries `screening: "pending"`, `depositId` and `hash`, and is not spendable until `refreshScreening` sees it approved. + +## The asset list and minimum deposit + +Each Reserve lists the assets it takes, each with a minimum deposit. Nothing is depositable until a holder of `ASSETS` lists the asset with `setAssetMinDeposit`. A minimum of 0 delists it. See [Reserve administration](/sdk/reserve-administration/). The client reads `reserveAssetMinDeposit` for `book.token` before it sends the approve, so a rejected deposit costs no approval. + +## refundTo + +`refundTo` names who a rejected deposit refunds, and who may then reclaim it. It defaults to the sender. A router depositing for a user names the user. + +```ts +import { MistClient, rand, type Hex } from "@mistcash/sdk"; + +declare const client: MistClient; +declare const reserve: Hex; +declare const amount: bigint; +declare const userAddress: Hex; + +const note = await client.deposit({ reserve, id: "alice (MIST)", amount, blinding: rand(), refundTo: userAddress }); +await client.setDepositRefundTo(note.depositId!, userAddress); +``` + +`setDepositRefundTo(depositId, refundTo)` changes the address while the deposit is pending. Only the depositor can call it, and the zero address reverts. At a Reserve without a screener there is no queue, so there is nothing to refund. + +## Screening + +A holder of `SCREENING` names a screener for a Reserve. Deposits into that Reserve are then queued, and their notes enter a transaction tree only after the screener approves them. What the screener checks is the screener's own policy. The SDK carries the decision and the evidence commitment. + +| Method | Does | +| --- | --- | +| `isScreened(reserve)` | Whether the Reserve has a screener. False when the read reverts | +| `pendingDeposit(id)` | One queue entry: `{ depositId, depositor, status, reserve, asset, amount, noteHash }`, with `status` of `none`, `pending` or `rejected`. `none` means settled or unknown | +| `queuedDeposits(reserve?, fromBlock?)` | The pending deposits, oldest first, from `DepositQueued` events checked against the live queue. Needs `getEvents` | +| `refreshScreening(notes?)` | Re-reads this client's screened notes | +| `approveDeposits(ids, evidence)`, `rejectDeposits(ids, evidence)` | The screener's decision for a batch | +| `reclaimDeposit(id)` | Takes a queued deposit back | + +`refreshScreening` moves each local note by what it finds. An approved note, which is in a tree, loses its `screening` flag and gets its `txIndex`. A note still queued keeps or takes `pending` or `rejected`. A pending note that left the queue without entering a tree is `reclaimed`. A rejected deposit that leaves the queue is `reclaimed` too, since rejection is final. + +```ts +import { keccak256, toHex } from "viem"; +import { MistClient, type Hex } from "@mistcash/sdk"; + +declare const client: MistClient; +declare const reserve: Hex; +declare const isAllowed: (depositor: Hex) => boolean; // the screener's own policy + +const queue = await client.queuedDeposits(reserve); +const approved = queue.filter((deposit) => isAllowed(deposit.depositor)); +const rejected = queue.filter((deposit) => !isAllowed(deposit.depositor)); + +// evidence is a bytes32 commitment to the off-chain screening record +const evidence = keccak256(toHex(JSON.stringify({ approved, rejected }, (_key, value) => (typeof value === "bigint" ? value.toString() : value)))); +await client.approveDeposits(approved.map((deposit) => deposit.depositId), evidence); +await client.rejectDeposits(rejected.map((deposit) => deposit.depositId), evidence); +``` + +- A batch skips ids that are no longer pending, for example one already reclaimed. +- Approval rejects, instead of reverting, a deposit whose note is already in a tree (`DepositDuplicateRejected`). A mined `approveDeposits` therefore does not mean every id was approved. `refreshScreening` reads the outcome. +- The screener is read when a deposit is decided. A new screener decides every deposit still queued. +- Notes with `screening` set are never picked as spend inputs. + +## Reclaiming + +| Deposit status | Who may call `reclaimDeposit` | Who is paid | +| --- | --- | --- | +| Pending | The depositor only | The depositor | +| Rejected | The depositor or `refundTo` | `refundTo`, which is the depositor when none was named | + +Reclaiming is never paused, so a screener or a pause cannot trap a deposit. After a reclaim the client marks the matching local note `reclaimed`. + +```ts +import { MistClient } from "@mistcash/sdk"; + +declare const client: MistClient; +declare const depositId: string; + +await client.reclaimDeposit(depositId); +``` From c6939f0bca53e3491a19bb28effe8581c055c456 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:10:05 +0530 Subject: [PATCH 06/14] docs(sdk): document joining a Reserve and registrar v3 signatures Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/joining-a-reserve.mdx | 103 +++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 src/content/docs/sdk/joining-a-reserve.mdx diff --git a/src/content/docs/sdk/joining-a-reserve.mdx b/src/content/docs/sdk/joining-a-reserve.mdx new file mode 100644 index 0000000..cbf31a2 --- /dev/null +++ b/src/content/docs/sdk/joining-a-reserve.mdx @@ -0,0 +1,103 @@ +--- +title: Joining a Reserve +description: "The X-Wing key exchange, the registrar v3 signature a key holder makes, and what voids it." +sidebar: + order: 6 +--- + +A Reserve with members lets only members spend. `join` runs a key exchange with the Reserve's key holder, then registers the member's leaf through the registrar with a signature from a `USERS` holder. + +## The exchange + +A member's leaf is `H2(mistAddr, ukx)`, where `ukx` is the key exchange shared with the key holder. The leaf goes on-chain. The `ukx` does not. It must stay off-chain and have full entropy, or the leaf can be brute-forced. + +1. **Member.** `join` calls `encapsulate(managerPublicKey)`, which returns a `cipherText` and a shared secret, then derives `ukx = deriveUkx(secret, reserve, mistAddr)`. +2. **Key holder.** `managerSide({ cipherText, reserve, mistAddr })` runs wherever the host provides it, usually a request to the Reserve's service. It calls `decapsulate`, derives the same `ukx`, computes the leaf and has a `USERS` holder sign the registrar digest. It receives the member's MIST Address. +3. **Member.** `join` compares the two `ukx` values. A difference throws `Client and manager derived different ukx values`. Otherwise it sends `registrar.registerUser(reserve, leaf, deadline, signer, signature)` and stores the `ukx` in `client.ukx`. + +`managerKeys(privateKey)` derives the key holder's X-Wing key pair from an account key: `{ publicKey, secretKey }`. The wire sizes are in `SIZES`: 1216 bytes for the public key and 1120 for the ciphertext. + +X-Wing is a hybrid of ML-KEM-768 and X25519, so the key exchange is post-quantum. The proofs are Groth16 and the registration signature is ECDSA or ERC-1271. Neither is post-quantum. + +## The key holder's half + +`managerSide` returns a `ManagerApproval`. + +| Field | Meaning | +| --- | --- | +| `ukx` | The key exchange the key holder derived | +| `signer` | The `USERS` holder that signed, as named in the digest | +| `deadline` | The last valid second, in chain time, inclusive | +| `signature` | 65 bytes `r ++ s ++ v` from an account, or an ERC-1271 signature from a contract | + +```ts +import { createPublicClient, http, parseAbi } from "viem"; +import { privateKeyToAccount } from "viem/accounts"; +import { anvil } from "viem/chains"; +import { CORE_ABI, MistClient, decapsulate, deriveUkx, managerKeys, type AddressBook, type Hex } from "@mistcash/sdk"; +import type { FullProverAdapter } from "@mistcash/sdk/prover"; + +declare const book: AddressBook; +declare const client: MistClient; +declare const prover: FullProverAdapter; +declare const reserve: Hex; +declare const KEY_HOLDER_KEY: Hex; // a key that holds USERS on the Reserve + +const abi = parseAbi(CORE_ABI); +const publicClient = createPublicClient({ chain: anvil, transport: http() }); +const signer = privateKeyToAccount(KEY_HOLDER_KEY); +const keys = managerKeys(KEY_HOLDER_KEY); + +await client.join({ + id: "alice (MIST)", + reserve, + managerPublicKey: keys.publicKey, + managerSide: async ({ cipherText, reserve, mistAddr }) => { + const ukx = deriveUkx(decapsulate(cipherText, keys.secretKey), reserve, mistAddr); + const leaf = BigInt(await prover.hash2(mistAddr, ukx)); + const deadline = (await publicClient.getBlock()).timestamp + 3600n; + // Read the digest just before signing: it binds values that move. + const digest = await publicClient.readContract({ + address: book.registrar, + abi, + functionName: "registerUserDigest", + args: [reserve, leaf, signer.address, deadline], + }); + return { ukx, signer: signer.address, deadline, signature: await signer.sign({ hash: digest }) }; + }, +}); +``` + +The registrar accepts a signature from any holder of `USERS` on the Reserve, and the registrar itself must hold `USERS` there too. Anyone can submit the registration, since the signature names the signer and not the submitter. + +## What the signature binds + +The digest is EIP-712. The domain is `MistReserveRegistrar`, version `3`, with the chain id and the registrar's address. The signed type is: + +```text +RegisterUser(address reserve,uint256 leaf,uint256 leafNonce,uint256 revocations,address signer,uint256 signerEpoch,uint256 deadline) +``` + +Three of those values move on their own, which is why the digest is read just before signing. + +| Value | Read from | Moves when | +| --- | --- | --- | +| `leafNonce` | `Reserve.leafNonce(leaf)` | The leaf is added or removed. A signature works once, and a removed member needs a new one | +| `revocations` | `registrar.revocations(reserve, leaf)` | `revokeRegistration` is called for the leaf | +| `signerEpoch` | `Reserve.permissionEpoch(USERS, signer)` | The signer loses `USERS`, through `revokePermission` or an admin handover | + +## What voids a signature + +| Cause | Result at `registerUser` | +| --- | --- | +| The chain time passes `deadline` | `Registrar: signature expired` | +| The leaf was registered or removed since signing | `Registrar: invalid signature` | +| A `USERS` holder called `revokeRegistration` for the leaf | `Registrar: invalid signature` | +| The signer lost `USERS` through a revoke or a handover | `Registrar: missing users permission` while it holds none, and `Registrar: invalid signature` if it holds the role again | +| The signature does not match the digest | `Registrar: invalid signature` | + +Two more reverts come from the Reserve. `Reserve: missing permission` means the registrar does not hold `USERS`. `Reserve: user already registered` means the leaf is already in the tree. + +When the transaction reverts and the adapter throws, `join` records no membership. A contract signer's ERC-1271 check runs after the ECDSA check. `USERS` should go only to contracts whose ERC-1271 cannot approve arbitrary digests. + +Leaving is the Reserve's act. `removeUser` zeroes a member's leaf. See [Reserve administration](/sdk/reserve-administration/). From 33fc93959cf5c0024020dd295e90e75376496ab6 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:10:05 +0530 Subject: [PATCH 07/14] docs(sdk): document private transfers and withdrawals Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/transfers.mdx | 133 +++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 src/content/docs/sdk/transfers.mdx diff --git a/src/content/docs/sdk/transfers.mdx b/src/content/docs/sdk/transfers.mdx new file mode 100644 index 0000000..fd8044a --- /dev/null +++ b/src/content/docs/sdk/transfers.mdx @@ -0,0 +1,133 @@ +--- +title: Private transfers and withdrawals +description: "spend: note selection, tree-aware leaves, proving, and who submits a private payment or a withdrawal." +sidebar: + order: 7 +--- + +`spend` is the one call for a private payment inside MIST and for a withdrawal to a public address. It selects notes, builds the proof on the host, checks it against the Chamber and submits it. + +## Calling spend + +```ts +import { MistClient, type Hex } from "@mistcash/sdk"; + +declare const client: MistClient; +declare const reserve: Hex; +declare const amount: bigint; + +// A private payment from alice to bob +await client.spend({ id: "alice (MIST)", amount, to: "bob (MIST)", reserve }); + +// A withdrawal to the public account alice +await client.spend({ id: "alice (MIST)", amount: 0n, withdraw: amount, withdrawTo: "alice", reserve }); +``` + +`spend` returns `{ receipt, secs, commitments }`: the receipt, the proving time in seconds, and the commitments for the Reserve's key holder. + +| Option | Meaning | +| --- | --- | +| `id` | The spending identity | +| `amount` | The value sent to `to`. Pass `0n` for a withdrawal, since a non-zero `amount` is a payment and needs `to` | +| `to` | The recipient identity. Unset for a withdrawal | +| `withdraw`, `withdrawTo` | A public payout and the account name that receives it. `withdrawTo` is required when `withdraw` is above zero | +| `reserve` | The Reserve to spend at. Defaults to the Reserve of the first unspent note | +| `notes` | The notes to choose from. Defaults to `client.notes` | +| `blindingA`, `blindingB` | Blindings for the recipient's output and the change output. Random when unset | +| `keyIndex` | An explicit key index. Drawn from the unused ones when unset | +| `state` | Chain state the host fetched itself. Read through the adapter when unset | + +A spend can pay `amount` to `to` and withdraw `withdraw` in one proof. The selected notes cover `amount + withdraw`. The change goes back to `id`. + +## Note selection + +The circuit takes at most two inputs and produces two outputs, and both inputs are proven against one transaction tree. `pick` therefore takes the smallest single note that covers the total, or else the tightest pair from one tree. When no single note and no pair covers it, `spend` throws and the message says so. Sending part of the value to oneself merges notes. + +```ts +import { plan, type Hex, type Note } from "@mistcash/sdk"; + +declare const notes: Note[]; +declare const reserve: Hex; + +const result = plan({ + id: "alice (MIST)", + amount: 5n, + reserve, + reserveUsers: 0n, // registeredUsersCount of the Reserve + isMember: false, + notes, + txTreeCapacity: 4 ** 10, +}); + +if ("error" in result) throw new Error(result.error); +console.log(result.notes, result.change, result.txTree); +``` + +`plan` validates a spend before proving and returns `{ notes, amount, change, submitter, txTree }`, or `{ error }`. At a Reserve with members, a non-member gets `Reserve is members only: join it first.`. + +## Tree-aware leaves + +The Chamber opens a new transaction tree every `txTreeCapacity` leaves, which is 4^10 or 1,048,576. A note's `txIndex` fixes its tree: tree `t` holds `txArray[t * capacity, (t + 1) * capacity)`. + +- `spend` reads each note's `txIndex`, or finds it from the note hash through `noteIndexPlusOne`. With fetched state it spends only notes it can find in a tree. +- It hands the prover that one tree's leaves, from `txTreeLeaves(treeId)`. The client reads them through `getTxArray(offset, limit)` in pages of 1,024 leaves, eight reads at a time, up to `txCount`. +- With the `state` option the host supplies the leaves, and `state.txLeaves` must be the leaves of the one tree that holds the input notes. + +The prover also takes the zkState tree and the Reserve's users tree. `registeredUserLeaves(reserve)` returns the users tree by index with removed members as `"0"`. `zkStateLeaves()` returns the zkState tree. + +## Proving + +1. `spend` refuses with `Spends are paused.` while the guardian has paused spends. +2. It checks that the member's leaf, `H2(owner, ukx)`, is still in the users tree. A removed member gets `This reserve no longer lists you as a member: join it again.`. +3. It builds the request and calls `prover.spend`. The result is 8 proof elements and 14 public inputs, plus commitments at a Reserve with members. +4. It asks the Chamber whether the proof's zkState root is still valid. A superseded root stays valid for 10 minutes. If the Chamber would reject it, `spend` throws `The reserve state changed while proving: spend again.`, and nothing is submitted or recorded. +5. It submits `handleZkp`, marks the inputs `spent` with their `nullifier`, and records the output notes with their `txIndex` from `NoteAppended`. + +`callbacks.onProof` receives the proving time. Proving blocks the thread it runs on, so a browser uses a worker. See [Prover backends](/sdk/prover-backends/). + +## Who submits + +The notes' owner decides who may submit. + +| Owner | `auth_done` | Who may submit | What the observer learns | +| --- | --- | --- | --- | +| A MIST Address, `alice (MIST)` | 1 | Anyone, a relayer for example. The proof shows knowledge of the secret | Two nullifiers and two new note hashes. The sender stays hidden | +| A wallet address, `alice` | 0 | Only that wallet. The Chamber requires `msg.sender` to equal the owner and reverts `only owner caller` otherwise | The spend publishes the owner, so it links to the address | + +The SDK sends every transaction through `chain.sendTransaction`. The adapter decides which account signs. For a MIST identity the progress stage is `Relayer submitting`. For a public identity it is `Submitting`, and the adapter must send from the owner's account. + +```ts +import { createWalletClient, http } from "viem"; +import { privateKeyToAccount } from "viem/accounts"; +import { anvil } from "viem/chains"; +import { MistClient, type AddressBook, type ChainAdapter, type Hex } from "@mistcash/sdk"; +import type { FullProverAdapter } from "@mistcash/sdk/prover"; + +declare const book: AddressBook; +declare const prover: FullProverAdapter; +declare const reserve: Hex; +declare const RELAYER_KEY: Hex; +declare const alice: Hex; // the public address behind the name "alice" +declare const aliceSecret: string; // the secret behind "alice (MIST)" +declare const chainAdapter: (wallet: ReturnType) => ChainAdapter; // from the quick start + +const relayerWallet = createWalletClient({ chain: anvil, transport: http(), account: privateKeyToAccount(RELAYER_KEY) }); + +// Every transaction this client sends is paid for by the relayer account. +const client = new MistClient({ + book, + chainId: anvil.id, + chain: chainAdapter(relayerWallet), + prover, + addressOf: () => alice, + secretOf: () => aliceSecret, +}); + +await client.spend({ id: "alice (MIST)", amount: 0n, withdraw: 1n, withdrawTo: "alice", reserve }); +``` + +## What a spend reveals + +A withdrawal reveals its amount, asset, Reserve and recipient, and hides among its own Reserve's notes. A payment inside MIST hides among every Reserve's notes. Sender privacy holds only for notes owned by a MIST Address. + +At a Reserve with members the key holder sees the sender, the asset and both output amounts of each member spend. Recipients appear only as output commitments. `spend` returns those commitments, and `handleZkp` carries them. [Reserve administration](/sdk/reserve-administration/) covers reading them. From 1b951c899d3691a0b41bb384aa8db55f5c176758 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:10:05 +0530 Subject: [PATCH 08/14] docs(sdk): document Reserve administration Co-Authored-By: Claude Sonnet 5.5 --- .../docs/sdk/reserve-administration.mdx | 129 ++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 src/content/docs/sdk/reserve-administration.mdx diff --git a/src/content/docs/sdk/reserve-administration.mdx b/src/content/docs/sdk/reserve-administration.mdx new file mode 100644 index 0000000..1e4f300 --- /dev/null +++ b/src/content/docs/sdk/reserve-administration.mdx @@ -0,0 +1,129 @@ +--- +title: Reserve administration +description: "Permissions, admin handover, removing members, revoking registrations, the screener and the asset list, as MistClient methods." +sidebar: + order: 8 +--- + +A Reserve has one admin and four permissions. The client wraps each administrative call. Every action is taken on the Reserve, which pushes the result to the Chamber. + +## Permissions + +The admin is named at `registerReserve` and holds all four permissions. Each can also be granted to any number of accounts. `RESERVE_ROLES[role]` is the `bytes32` id, `keccak256(name)`. + +| Role | Lets an account | Client method | +| --- | --- | --- | +| `ASSETS` | List an asset with a minimum deposit, or delist it with 0 | `setAssetMinDeposit(reserve, asset, minDeposit)` | +| `USERS` | Sign registrations and remove members | `removeUser(reserve, index)`, `revokeRegistration(reserve, leaf)` | +| `METADATA` | Rotate the auditor key | `updateAuditorKey(reserve, keyHash, keyInputPoint)` | +| `SCREENING` | Set the deposit screener | `setReserveScreener(reserve, screener)` | + +The admin alone grants and revokes. Granting the zero address reverts. A repeat grant, or a revoke with no grant, is a no-op. The admin's own permissions are implicit and cannot be revoked. + +```ts +import { MistClient, type AddressBook, type Hex } from "@mistcash/sdk"; + +declare const client: MistClient; +declare const book: AddressBook; +declare const reserve: Hex; +declare const signerService: Hex; + +// The registrar needs USERS before anyone can join +await client.grantPermission(reserve, "USERS", book.registrar); +// An account whose registration signatures count +await client.grantPermission(reserve, "USERS", signerService); + +await client.revokePermission(reserve, "USERS", signerService); +console.log(await client.hasPermission(reserve, "USERS", signerService)); // false +``` + +`hasPermission(reserve, role, account)` is true for the admin on every role. A `USERS` revoke moves the account's epoch for that role, which voids every registrar signature the account made. + +## Admin handover + +```ts +import { MistClient, type Hex } from "@mistcash/sdk"; + +declare const client: MistClient; +declare const nextAdminClient: MistClient; +declare const reserve: Hex; +declare const nextAdmin: Hex; + +await client.transferAdmin(reserve, nextAdmin); +await nextAdminClient.acceptAdmin(reserve); +``` + +The handover has two steps. The admin nominates, and the nominee accepts. Nominating the zero address cancels. On acceptance: + +- Explicit grants survive. The new admin reviews them and revokes stale ones. +- The old admin's implicit permissions end, and its epochs move, so the registrar signatures it made stop working. + +## Members + +`removeUser(reserve, index)` zeroes a member's leaf and pushes the new users root to the Chamber. The index comes from the `UserRegistered` event or from `registeredUserLeaves(reserve)`. + +```ts +import { MistClient, type Hex } from "@mistcash/sdk"; +import type { FullProverAdapter } from "@mistcash/sdk/prover"; + +declare const client: MistClient; +declare const prover: FullProverAdapter; +declare const reserve: Hex; +declare const mistAddr: string; // the member's MIST Address +declare const ukx: string; // the member's key exchange + +const leaf = BigInt(await prover.hash2(mistAddr, ukx)); +const leaves = await client.registeredUserLeaves(reserve); +const index = leaves.indexOf(leaf.toString()); +if (index < 0) throw new Error("member not found"); + +await client.removeUser(reserve, BigInt(index)); +``` + +- Removal takes full effect within 10 minutes, the zkState root grace. +- Removing the last user reverts with `Reserve: last user`. +- A removed member's `spend` fails with `This reserve no longer lists you as a member: join it again.` Re-joining needs a new signature, because removal moves the leaf's nonce. +- A spend at a Reserve with members proves against every slot, removed ones included. `getEvents` must serve all of the Reserve's `UserRegistered` and `UserRemoved` events. + +`revokeRegistration(reserve, leaf)` voids every outstanding registrar signature for `leaf`, by any signer. It takes no deadline and needs `USERS`. + +## Screener, assets and key + +`setReserveScreener(reserve, screener)` needs `SCREENING`. It calls `Reserve.setScreener`, which tells the Chamber. The zero address means no screener. [Deposits](/sdk/deposits/) covers the screener's own calls. + +`setAssetMinDeposit(reserve, asset, minDeposit)` needs `ASSETS`. A minimum above 0 lists the asset, and 0 delists it. Nothing is depositable until listed. + +`updateAuditorKey(reserve, keyHash, keyInputPoint)` needs `METADATA`. It rotates the Reserve's auditor key and config. + +```ts +import { MistClient, type AddressBook, type Hex } from "@mistcash/sdk"; + +declare const client: MistClient; +declare const book: AddressBook; +declare const reserve: Hex; +declare const screener: Hex; + +await client.setAssetMinDeposit(reserve, book.token, 10n ** 15n); +await client.setReserveScreener(reserve, screener); +``` + +## Reading a member's spend + +The key holder opens the commitments of a member's spend with `openPayload({ reserve, commitments })`. It tries each key exchange in `client.ukx` for that Reserve against `prover.decrypt`, and returns `{ owner, keyIndex, plaintext }` for the first key exchange that opens them, or `null`. It throws when the prover has no `decrypt`. + +```ts +import { MistClient, type Hex } from "@mistcash/sdk"; + +declare const client: MistClient; +declare const reserve: Hex; +declare const commitments: string[]; // from a spend + +const opened = await client.openPayload({ reserve, commitments }); +console.log(opened?.owner, opened?.plaintext); +``` + +## Chamber owner + +`registerReserve(admin, keyHash, keyInputPoint)` deploys and registers a Reserve, and only the Chamber owner can call it. + +The SDK does not wrap the guardian's pauses, the verifier and ownership timelocks or `setGuardian`. Those are owner and guardian operations, done through a Safe. Their ABIs are in `ABIS.Chamber`, and the client only reads the pause flags. From 1a798da509424f65ebdf59dfb156b791d231802a Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:10:05 +0530 Subject: [PATCH 09/14] docs(sdk): document the CPU and WebGPU prover backends Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/prover-backends.mdx | 92 ++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 src/content/docs/sdk/prover-backends.mdx diff --git a/src/content/docs/sdk/prover-backends.mdx b/src/content/docs/sdk/prover-backends.mdx new file mode 100644 index 0000000..0f6d49b --- /dev/null +++ b/src/content/docs/sdk/prover-backends.mdx @@ -0,0 +1,92 @@ +--- +title: Prover backends +description: "The CPU WebAssembly prover and the WebGPU prover: when to use each, the worker, fallback and load time." +sidebar: + order: 9 +--- + +The SDK proves with one Go prover in two builds: `mist.wasm` on the CPU and `mist-webgpu.wasm`, which runs the heavy steps as WebGPU compute shaders. Both use the same proving key, so both produce proofs the same `ChamberVerifier` accepts. + +## Choosing + +| | CPU | WebGPU | +| --- | --- | --- | +| File | `mist.wasm`, about 19.6 MB | `mist-webgpu.wasm`, about 21.5 MB | +| Entry | `loadProver` | `loadWebGPUProver` | +| Runs in | Node and browsers | Browsers | +| Without a GPU | Not applicable | Proves on the CPU with the same file. `backend` says `cpu` | +| Load time | About 0.15 s in Node, measured for these pages | Up to about 1.5 s longer than the CPU build, per the SDK README: shader compilation and the proving key's one-time upload to the GPU | +| Proof time | About 2.5 s on an Apple M-series laptop in Chromium, per the SDK README | About 0.2 s on the same laptop, per the SDK README | + +The proof times are the SDK README's measurement and were not re-run for these pages. They depend on the device. The file sizes come from `circuit.json`. + +The WebGPU backend is gnark's. gnark marks it experimental and unaudited. It changes how a proof is computed and not what is proven. + +## CPU prover + +```ts +import { loadProver } from "@mistcash/sdk/prover"; + +const prover = await loadProver(); // Node: reads the wasm from disk +``` + +On the main thread, `spend` blocks until the proof is done. A browser app runs the prover in a worker. + +## Worker + +`createWorkerProver` runs the prover in a Web Worker. It returns the adapter, `backend()` and `terminate()`. It is browser-only. + +```ts +import { createWorkerProver } from "@mistcash/sdk/prover"; +import { MistClient, type AddressBook, type ChainAdapter } from "@mistcash/sdk"; + +declare const book: AddressBook; +declare const chain: ChainAdapter; +declare const wasmUrl: string; // the URL the bundler emits for mist.wasm + +const prover = createWorkerProver({ wasmUrl }); +const client = new MistClient({ book, chainId: 1, chain, prover }); + +// ... use the client, then stop the worker. +prover.terminate(); +``` + +- Every method is proxied over `postMessage`, so each returns a promise. `MistClient` already awaits them. +- `wasmUrl` is optional and defaults to the package's own file, which a bundler usually does not emit. See [Install and setup](/sdk/install/). +- The worker holds the roughly 20 MB prover. Without `terminate()` it lives for the page's lifetime. +- `terminate()` rejects every call still in flight. Later calls reject with `prover worker terminated`. + +## WebGPU + +```ts +import { hasWebGPU, loadWebGPUProver } from "@mistcash/sdk/prover/webgpu"; +import { loadProver } from "@mistcash/sdk/prover"; + +declare const wasmUrl: string; // the URL the bundler emits for mist.wasm +declare const webgpuWasmUrl: string; // the URL the bundler emits for mist-webgpu.wasm + +// Load one prover per page: both files install the same globals. +const prover = hasWebGPU() ? await loadWebGPUProver(webgpuWasmUrl) : await loadProver(wasmUrl); +``` + +`loadWebGPUProver(source?)` returns the adapter with two extra fields: `backend`, which is `webgpu` or `cpu`, and `fallbackReason` when it is `cpu`. It takes the same sources as `loadProver`. + +In a worker, pass `webgpu: true`. `wasmUrl` must then point at `mist-webgpu.wasm`. + +```ts +import { createWorkerProver } from "@mistcash/sdk/prover"; + +declare const webgpuWasmUrl: string; // the URL the bundler emits for mist-webgpu.wasm + +const prover = createWorkerProver({ webgpu: true, wasmUrl: webgpuWasmUrl }); +const { backend, fallbackReason } = await prover.backend(); +console.log(backend, fallbackReason); +``` + +The WebGPU loader never fails for want of a GPU. With no `navigator.gpu`, no adapter or a failed upload, the same wasm proves on the CPU and `backend` says `cpu`. `hasWebGPU()` only checks that `navigator.gpu` exists, so an adapter can still be missing. A page that prefers the smaller `mist.wasm` when there is no GPU checks `hasWebGPU()` first, as above. + +Shader sources are inlined into the SDK's JavaScript, so nothing is fetched from a path a bundler never emits. + +## The prover adapter + +`MistClient` needs a `ProverAdapter`: `hash2`, `spend` and, for `openPayload`, `decrypt`. Each may be synchronous or return a promise. The loaders return a `FullProverAdapter`, which adds `hash3`. A host can supply its own adapter, such as one that proves on a server. From 87c680e20a86159f8d6365a944ddb20fb026bbbd Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:10:05 +0530 Subject: [PATCH 10/14] docs(sdk): list errors and pause states Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/errors.mdx | 108 ++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 src/content/docs/sdk/errors.mdx diff --git a/src/content/docs/sdk/errors.mdx b/src/content/docs/sdk/errors.mdx new file mode 100644 index 0000000..3a77775 --- /dev/null +++ b/src/content/docs/sdk/errors.mdx @@ -0,0 +1,108 @@ +--- +title: Errors and pause states +description: "Each refusal and revert message the SDK and the contracts produce, what causes it and what clears it." +sidebar: + order: 10 +--- + +The client refuses a call before it sends anything wherever the Chamber would reject it, so a failure costs no gas. The messages below are exact. The contract reverts reach the host through its chain adapter. + +## Pause states + +The guardian pauses two things separately. `inflowsPaused` stops `deposit` and `approveDeposits` until the guardian or owner unpauses. Spends pause for at most 3 days, and the next spend pause starts no sooner than 7 days after the last one ended. The client reads both flags. + +| State | What the client does | What stays available | +| --- | --- | --- | +| Inflows paused | `deposit` throws `Deposits are paused.` before the approve is sent | `reclaimDeposit` and `rejectDeposits` | +| Spends paused | `spend` throws `Spends are paused.` before proving | `reclaimDeposit`, deposits and screening | + +`approveDeposits` has no client-side check. Sent during a pause, it reverts with `Chamber: inflows paused`. + +## Deposits + +- `Enter a whole amount above zero.` + Amount is zero or less. Pass an amount above zero. +- `Deposits are paused.` + Inflows paused. Wait for the guardian to unpause. +- `This reserve does not accept this token.` + Asset not listed. An `ASSETS` holder lists it with `setAssetMinDeposit`. +- `The minimum deposit at this reserve is N.` + Below the minimum. Deposit at least N. +- `MistClient: deposit() needs sendTransaction to return receipt.logs (or the call result); nothing was deposited` + Adapter returns no logs. Return `receipt.logs`. Raised after the approve and before the deposit. +- `MistClient: deposit sent, but its receipt has no NoteAppended or DepositQueued log and no (noteHash, depositId) result: return receipt.logs from sendTransaction` + Receipt has no deposit event. Return the logs. The deposit is already on-chain. +- `MistClient: the deposit's receipt holds several Chamber notes: return the call's (noteHash, depositId) result to pick this one` + Receipt holds several notes. Return `result` from `sendTransaction`. +- `MistClient: queuedDeposits needs ChainAdapter.getEvents` + Queue read without events. Provide `getEvents`. + +## Spends + +- `withdrawTo is required for withdrawals` + Withdrawal without recipient. Pass `withdrawTo`. +- ``No reserve: pass `reserve` explicitly or deposit first.`` + No Reserve known. Pass `reserve`. +- `Reserve is members only: join it first.` + Members-only Reserve. Call `join`. +- `Your notes here hold N.` + Notes too small. Deposit more, or lower the amount. +- `A spend takes at most two notes from one tx tree and no two of yours cover this. Send some to yourself to merge them.` + No two notes cover it. Merge notes, or split the payment. +- `MistClient: read X of the reserve's Y user leaves: ChainAdapter.getEvents must serve every UserRegistered and UserRemoved` + Missing user leaves. Serve every event of the Reserve. +- `This reserve no longer lists you as a member: join it again.` + Member removed. Call `join` with a new signature. +- `The reserve state changed while proving: spend again.` + Root went stale. Call `spend` again. Nothing was submitted. +- `All 256 key indices used for this ukx` + Key indices used up. Join again for a new key exchange. +- `In.Amount N out of uint64 range`, and the same for `Out.Amount` and `Withdraw` + Amount over uint64. Split across notes. +- The prover's own error, or `Prover rejected the spend` + Prover rejects. Read the message. + +## Joining and configuration + +- `Client and manager derived different ukx values` + Key exchanges differ. The key holder must derive from the same `cipherText`, Reserve and MIST Address. +- `MistClient: secretOf not configured` + No secret lookup. Pass `secretOf`. +- `MistClient: addressOf not configured` + No address lookup. Pass `addressOf`. +- `MistClient: send of vetoed by onBeforeSend` + Send vetoed. The hook returned `false`. +- `Prover predates decrypt: rebuild mist.wasm.` + Prover cannot decrypt. Use a current wasm. +- `MistClient: UserRegistered events are missing for reserve
` + Missing registration. Serve every `UserRegistered` event. +- `prover worker terminated` + Worker stopped. Create a new worker prover. + +## Contract reverts + +| Revert | Cause | +| --- | --- | +| `Registrar: signature expired` | The chain time passed the signature's `deadline` | +| `Registrar: invalid signature` | The signature does not match the digest, or a value it binds moved | +| `Registrar: missing users permission` | The signer, or the caller of `revoke`, holds no `USERS` | +| `Reserve: missing permission` | The caller lacks the permission, such as the registrar without `USERS` | +| `Reserve: only admin` | A grant, revoke or handover from a non-admin | +| `Reserve: only pending admin` | `acceptAdmin` from an account that was not nominated | +| `Reserve: zero account` | `grantPermission` for the zero address | +| `Reserve: user already registered` | The leaf is already in the users tree | +| `Reserve: no user at index` | `removeUser` for an index with no member | +| `Reserve: last user` | `removeUser` would empty the users tree | +| `Chamber: asset not allowed` | The asset is not listed at the Reserve | +| `Chamber: deposit below minimum` | The Reserve received less than its minimum | +| `Chamber: spends paused`, `Chamber: inflows paused` | A pause is active | +| `Chamber: not pending` | `setDepositRefundTo` on a deposit that is not pending | +| `Chamber: only depositor` | A pending deposit reclaimed or re-addressed by someone else | +| `Chamber: only depositor or refundTo` | A rejected deposit reclaimed by someone else | +| `Chamber: zero refundTo` | A zero `refundTo` | +| `Chamber: no queued deposit` | `reclaimDeposit` for an id that is settled or unknown | +| `invalid merkle proof` | The proof's transaction root is not one the Chamber produced | +| `invalid state root` | The proof's zkState root is neither current nor within the 10-minute grace | +| `only owner caller` | A wallet-owned spend submitted by an account other than the owner | +| `transaction is spent` | A nullifier was already used | +| `private tx key used` | The key index was already used for this key exchange | From e79dfb7c8f48f7057abf805b3eb317aeec89ee7a Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:10:05 +0530 Subject: [PATCH 11/14] docs(sdk): list the breaking changes from 0.6.0-beta.1 Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/migrating.mdx | 83 ++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 src/content/docs/sdk/migrating.mdx diff --git a/src/content/docs/sdk/migrating.mdx b/src/content/docs/sdk/migrating.mdx new file mode 100644 index 0000000..bdfb87e --- /dev/null +++ b/src/content/docs/sdk/migrating.mdx @@ -0,0 +1,83 @@ +--- +title: Migrating from 0.6.0-beta.1 +description: "The breaking changes between @mistcash/sdk 0.6.0-beta.1 and the release that targets core fa7b92d." +sidebar: + order: 11 +--- + +The release that follows `0.6.0-beta.1` targets core `fa7b92d`. The prover's request shape and exports are unchanged. The contract surface, `join`, the adapter contract and the leaves passed to a spend all changed. + +## Changes + +| # | Change | Action | +| --- | --- | --- | +| 1 | `join`'s `managerSide` returns `{ ukx, signer, deadline, signature }`, signed over `registerUserDigest(reserve, leaf, signer, deadline)`, EIP-712 version 3 | Sign the new digest and return the four fields | +| 2 | `setRegistrar()` is removed | The Reserve admin calls `grantPermission(reserve, "USERS", registrar)` | +| 3 | `setVerifier()` is removed | The verifier changes through a 7-day owner timelock, `proposeVerifier` and `executeVerifierUpdate` in `ABIS.Chamber`, outside the client | +| 4 | `setReserveScreener()` goes to the Reserve and needs `SCREENING` | Call it as a holder of `SCREENING` | +| 5 | Adapters return `receipt.logs` or the deposit's `(noteHash, depositId)` as `result` | Return logs from `sendTransaction`. Otherwise `deposit` stops after the approve | +| 6 | `SpendOpts.state.txLeaves` is the leaves of the input notes' one transaction tree | Pass `txTreeLeaves(treeId)`, or omit `state` | +| 7 | With fetched state, `spend` spends only notes it can find in a tree | Give each note a `hash` or a `txIndex` | +| 8 | `getEvents` also serves `UserRemoved`, and every user event of a Reserve with members | Return all of them | +| 9 | The contents of `CORE_ABI` and `SCREENING_ABI` changed. `SCREENING_ABI` gains `setDepositRefundTo` and `DepositRefundToSet`, and `DepositQueued` carries `refundTo` | Rebuild any `parseAbi(CORE_ABI)` and event decoding from the new exports | +| 10 | Reclaiming a pending deposit is the depositor's alone and refunds the depositor. `refundTo` is paid only after a rejection | Update any flow that reclaimed a pending deposit as `refundTo` | +| 11 | `revokeRegistration(reserve, leaf)` takes no deadline and voids every signature for the leaf | Drop the deadline argument | + +New in this release: `grantPermission`, `revokePermission`, `transferAdmin`, `acceptAdmin`, `hasPermission`, `setAssetMinDeposit`, `removeUser`, `revokeRegistration`, `setDepositRefundTo`, `txTreeLeaves`, `registeredUserLeaves`, `RESERVE_ROLES` and `ManagerApproval`. `Note` gains `txIndex`, `DepositOpts` gains `refundTo`, `pick` takes a third argument `txTreeCapacity`, and `plan` takes `txTreeCapacity` and returns `txTree`. + +## join + +Before, the key holder returned the key exchange and a signature over the leaf. Now it returns who signed and until when, and the digest binds more. + +```ts +import type { Hex, ManagerApproval } from "@mistcash/sdk"; + +declare const ukx: string; +declare const signer: Hex; +declare const deadline: bigint; +declare const signature: Hex; + +// 0.6.0-beta.1 +const before = { ukx, signature }; + +// Next release +const after: ManagerApproval = { ukx, signer, deadline, signature }; +console.log(before, after); +``` + +[Joining a Reserve](/sdk/joining-a-reserve/) has the full key holder code and what the digest binds. + +## Setting up a Reserve + +Before, `setRegistrar(reserve)` pointed a Reserve at a registrar. Now the registrar is an account with `USERS`, like any signer. + +```ts +import { MistClient, type AddressBook, type Hex } from "@mistcash/sdk"; + +declare const client: MistClient; +declare const book: AddressBook; +declare const reserve: Hex; +declare const screener: Hex; + +await client.grantPermission(reserve, "USERS", book.registrar); +await client.setAssetMinDeposit(reserve, book.token, 1n); +await client.setReserveScreener(reserve, screener); +``` + +## Adapters + +```ts +import type { ChainAdapter } from "@mistcash/sdk"; +import type { TransactionReceipt } from "viem"; + +declare function submit(data: `0x${string}`): Promise; + +const sendTransaction: ChainAdapter["sendTransaction"] = async (tx) => { + const receipt = await submit(tx.data); + // Next release: logs are required + return { hash: receipt.transactionHash, receipt: { transactionHash: receipt.transactionHash, status: receipt.status, logs: receipt.logs } }; +}; +console.log(sendTransaction); +``` + +[Client and address book](/sdk/client/) lists what each adapter member must return. From 5c27561ec8a7b784036267bf14d3e614bab5a74f Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:10:05 +0530 Subject: [PATCH 12/14] docs(sdk): describe the next release and index the SDK pages Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/index.mdx | 82 +++++++++++++++++----------------- 1 file changed, 40 insertions(+), 42 deletions(-) diff --git a/src/content/docs/sdk/index.mdx b/src/content/docs/sdk/index.mdx index b3b58a3..2afac45 100644 --- a/src/content/docs/sdk/index.mdx +++ b/src/content/docs/sdk/index.mdx @@ -1,58 +1,56 @@ --- 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." +description: "@mistcash/sdk, the TypeScript SDK for MIST on EVM: proving on the user's device and a client for the Chamber, Reserve and registrar 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. +import RuledIndex from "../../../components/RuledIndex.astro"; -## Install +`@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, Reserve and registrar contracts. -```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 | +:::caution[These pages document the next SDK release] +They describe the SDK as it will ship, built against mistcash/core `fa7b92d`. The published `@mistcash/sdk@0.6.0-beta.1` predates it and targets an earlier contract interface, so calls such as `join` and `setReserveScreener` fail against current contracts. [Migrating from 0.6.0-beta.1](/sdk/migrating/) lists every difference. +::: ## 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. +| Role | Methods | +| --- | --- | +| Depositor | `deposit`, `setDepositRefundTo`, `reclaimDeposit`, `refreshScreening` | +| Member | `join`, `spend` for a private payment or a withdrawal | +| Reserve admin and permission holders | `grantPermission`, `revokePermission`, `transferAdmin`, `acceptAdmin`, `setAssetMinDeposit`, `removeUser`, `revokeRegistration`, `updateAuditorKey`, `setReserveScreener` | +| Key holder | The Reserve's half of `join`, and `openPayload` to read a member's spend | +| Screener | `queuedDeposits`, `approveDeposits`, `rejectDeposits` | +| Chamber owner | `registerReserve` | + +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. The proofs are Groth16 and the registration signature is ECDSA or ERC-1271, so neither is post-quantum. + +## Pages + + + +## Limits to know first + +- `secretOf` derives a MIST secret from a private key and is for development only. A browser wallet never exposes its key, so an application derives 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 client keeps notes and key exchanges in memory. The host persists them, and calls `restoreKeyIndices()` at startup when it passes a `store`. [Notes and keys](/sdk/notes-and-keys/) has the detail. -The repository's [README](https://github.com/mistcash/sdk) has the full setup, including bundler configuration for Vite and webpack. +The [README](https://github.com/mistcash/sdk) in the SDK repository covers bundler configuration for Vite and webpack. From 59a5a68ab0536f6b3c73a123dc53d9e43357ff19 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:17:42 +0530 Subject: [PATCH 13/14] docs(sdk): a reverted receipt fails the call Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/client.mdx | 6 +++--- src/content/docs/sdk/joining-a-reserve.mdx | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/content/docs/sdk/client.mdx b/src/content/docs/sdk/client.mdx index a7c0e8e..8988573 100644 --- a/src/content/docs/sdk/client.mdx +++ b/src/content/docs/sdk/client.mdx @@ -63,12 +63,12 @@ interface ChainAdapter { | Member | Must return | | --- | --- | | `readContract` | The decoded result of a view call. Every function name the client reads is in `CORE_ABI` | -| `sendTransaction` | `{ hash?, result?, receipt }` once the transaction is confirmed. `receipt` carries `transactionHash` and `logs`, and optionally `gasUsed` and `status` | +| `sendTransaction` | `{ hash?, result?, receipt }` once the transaction is confirmed. `receipt` carries `transactionHash` and `logs`, and optionally `gasUsed` and `status`, which is `success` or `reverted` | | `getEvents` | Decoded events with `args`. Optional, but `queuedDeposits`, `registeredUserLeaves` and every `spend` at a Reserve with members need it | ### sendTransaction -The host owns signing, simulation, gas and waiting. The client calls `sendTransaction` for every write and never reads `receipt.status`, so an adapter throws when a transaction reverts. Otherwise the client records a membership or a spend that never happened. +The host owns signing, simulation, gas and waiting. The client calls `sendTransaction` for every write. A receipt with `status` of `reverted` fails the call with `MistClient: reverted ()`, before `onTx` fires and before the client changes any local state. An adapter that leaves `status` out must throw on a revert itself. Otherwise the client records a membership or a spend that never happened. `receipt.logs` is required. @@ -92,7 +92,7 @@ The adapter also decides who submits. [Private transfers and withdrawals](/sdk/t | --- | --- | --- | | `onProgress(stage)` | At each stage: `Approving`, `Depositing`, `Exchanging keys`, `Registering`, `Proving in your browser`, `Relayer submitting` or `Submitting` | Progress display. The strings are for people, not for matching | | `onBeforeSend({ to, data, functionName })` | Before each `sendTransaction` | Return `false` to veto. The call throws `MistClient: send of vetoed by onBeforeSend` | -| `onTx({ functionName, receipt })` | After each confirmed write | Logging and fan-out | +| `onTx({ functionName, receipt })` | After each confirmed write, never after a reverted one | Logging and fan-out | | `onProof({ kind: "spend", secs })` | After proving | Timing | ## Storage adapter diff --git a/src/content/docs/sdk/joining-a-reserve.mdx b/src/content/docs/sdk/joining-a-reserve.mdx index cbf31a2..768be67 100644 --- a/src/content/docs/sdk/joining-a-reserve.mdx +++ b/src/content/docs/sdk/joining-a-reserve.mdx @@ -98,6 +98,6 @@ Three of those values move on their own, which is why the digest is read just be Two more reverts come from the Reserve. `Reserve: missing permission` means the registrar does not hold `USERS`. `Reserve: user already registered` means the leaf is already in the tree. -When the transaction reverts and the adapter throws, `join` records no membership. A contract signer's ERC-1271 check runs after the ECDSA check. `USERS` should go only to contracts whose ERC-1271 cannot approve arbitrary digests. +When the transaction reverts, `join` records no membership: a `reverted` receipt throws `MistClient: registerUser reverted ()`, and so does an adapter that throws itself. A contract signer's ERC-1271 check runs after the ECDSA check. `USERS` should go only to contracts whose ERC-1271 cannot approve arbitrary digests. Leaving is the Reserve's act. `removeUser` zeroes a member's leaf. See [Reserve administration](/sdk/reserve-administration/). From c4ee1639d0d08d2b14cf05871c5dcf90b9f28960 Mon Sep 17 00:00:00 2001 From: Shramee Srivastav <11048263+shramee@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:17:42 +0530 Subject: [PATCH 14/14] docs(sdk): spend needs a recipient for an amount, and the 256-spend key-index limit Co-Authored-By: Claude Sonnet 5.5 --- src/content/docs/sdk/errors.mdx | 4 ++++ src/content/docs/sdk/migrating.mdx | 2 ++ src/content/docs/sdk/notes-and-keys.mdx | 4 ++-- src/content/docs/sdk/transfers.mdx | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/content/docs/sdk/errors.mdx b/src/content/docs/sdk/errors.mdx index 3a77775..fab4d4c 100644 --- a/src/content/docs/sdk/errors.mdx +++ b/src/content/docs/sdk/errors.mdx @@ -39,6 +39,8 @@ The guardian pauses two things separately. `inflowsPaused` stops `deposit` and ` ## Spends +- `to is required to send an amount: a note with no owner can never be spent` + Amount without a recipient. Pass `to`, or use `amount: 0n` for a withdrawal. - `withdrawTo is required for withdrawals` Withdrawal without recipient. Pass `withdrawTo`. - ``No reserve: pass `reserve` explicitly or deposit first.`` @@ -70,6 +72,8 @@ The guardian pauses two things separately. `inflowsPaused` stops `deposit` and ` No secret lookup. Pass `secretOf`. - `MistClient: addressOf not configured` No address lookup. Pass `addressOf`. +- `MistClient: reverted ()` + The transaction was mined and reverted. Read the contract revert below. No local state changed. - `MistClient: send of vetoed by onBeforeSend` Send vetoed. The hook returned `false`. - `Prover predates decrypt: rebuild mist.wasm.` diff --git a/src/content/docs/sdk/migrating.mdx b/src/content/docs/sdk/migrating.mdx index bdfb87e..337d2a9 100644 --- a/src/content/docs/sdk/migrating.mdx +++ b/src/content/docs/sdk/migrating.mdx @@ -22,6 +22,8 @@ The release that follows `0.6.0-beta.1` targets core `fa7b92d`. The prover's req | 9 | The contents of `CORE_ABI` and `SCREENING_ABI` changed. `SCREENING_ABI` gains `setDepositRefundTo` and `DepositRefundToSet`, and `DepositQueued` carries `refundTo` | Rebuild any `parseAbi(CORE_ABI)` and event decoding from the new exports | | 10 | Reclaiming a pending deposit is the depositor's alone and refunds the depositor. `refundTo` is paid only after a rejection | Update any flow that reclaimed a pending deposit as `refundTo` | | 11 | `revokeRegistration(reserve, leaf)` takes no deadline and voids every signature for the leaf | Drop the deadline argument | +| 12 | `TxReceipt.status` is narrowed to `success` or `reverted`. A `reverted` receipt makes the call throw `MistClient: reverted ()` before `onTx` and before any local state changes | Return viem's status as it is, or leave `status` out and throw on a revert in the adapter | +| 13 | `spend` refuses a positive `amount` without `to` before proving | Pass `to`, or `amount: 0n` with `withdraw` for a withdrawal | New in this release: `grantPermission`, `revokePermission`, `transferAdmin`, `acceptAdmin`, `hasPermission`, `setAssetMinDeposit`, `removeUser`, `revokeRegistration`, `setDepositRefundTo`, `txTreeLeaves`, `registeredUserLeaves`, `RESERVE_ROLES` and `ManagerApproval`. `Note` gains `txIndex`, `DepositOpts` gains `refundTo`, `pick` takes a third argument `txTreeCapacity`, and `plan` takes `txTreeCapacity` and returns `txTree`. diff --git a/src/content/docs/sdk/notes-and-keys.mdx b/src/content/docs/sdk/notes-and-keys.mdx index edc35ba..8304b6e 100644 --- a/src/content/docs/sdk/notes-and-keys.mdx +++ b/src/content/docs/sdk/notes-and-keys.mdx @@ -65,8 +65,8 @@ A key holder's client reads the same map. `openPayload` tries each `ukx` entry o Each member spend carries a key index from 0 to 255, and the Chamber files the spend under a private transaction key derived from the key exchange and that index. The Chamber rejects a key it has seen, so an index is used once per key exchange. - `spend` draws an index at random from those not yet used for the key exchange. The indices live in `client.usedKeyIndices`. -- A key exchange allows 256 member spends. After that the draw throws `All 256 key indices used for this ukx`, and the member joins again to get a fresh key exchange. -- A spend by a non-member at a Reserve without members uses no recorded index. +- A key exchange covers 256 spends that publish commitments, which is every spend at a Reserve with members. After that the draw throws `All 256 key indices used for this ukx`. The member joins the Reserve again for a fresh key exchange, which means a new leaf and a new Reserve signature. +- A spend at a Reserve without members uses no recorded index. - Used indices persist through the `store`, under `mist:keyIndices`. The client merges into the stored map and never overwrites it, so two clients sharing one store do not erase each other's indices. Call `restoreKeyIndices()` once at startup when a `store` is passed. `spend` also re-reads the store before it draws. Without the startup call, a reload begins with an empty set and can draw an index already spent, and the Chamber reverts the spend. diff --git a/src/content/docs/sdk/transfers.mdx b/src/content/docs/sdk/transfers.mdx index fd8044a..caf0970 100644 --- a/src/content/docs/sdk/transfers.mdx +++ b/src/content/docs/sdk/transfers.mdx @@ -28,7 +28,7 @@ await client.spend({ id: "alice (MIST)", amount: 0n, withdraw: amount, withdrawT | Option | Meaning | | --- | --- | | `id` | The spending identity | -| `amount` | The value sent to `to`. Pass `0n` for a withdrawal, since a non-zero `amount` is a payment and needs `to` | +| `amount` | The value sent to `to`. Pass `0n` for a withdrawal. A non-zero `amount` without `to` is refused before proving, since that output would have no owner and could never be spent | | `to` | The recipient identity. Unset for a withdrawal | | `withdraw`, `withdrawTo` | A public payout and the account name that receives it. `withdrawTo` is required when `withdraw` is above zero | | `reserve` | The Reserve to spend at. Defaults to the Reserve of the first unspent note |