Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions src/content/docs/sdk/client.mdx
Original file line number Diff line number Diff line change
@@ -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/<chainId>.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<unknown>;
sendTransaction(tx: { to: Hex; data: Hex; value?: bigint }): Promise<SentTx>;
getEvents?(address: Hex, eventName: string, fromBlock?: bigint): Promise<Array<{ args: Record<string, unknown> }>>;
}
```

| 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`, 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. A receipt with `status` of `reverted` fails the call with `MistClient: <function> reverted (<hash>)`, 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.

- `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 <functionName> vetoed by onBeforeSend` |
| `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

```ts
interface StorageAdapter {
get(key: string): string | null | Promise<string | null>;
set(key: string, value: string): void | Promise<void>;
}
```

`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.
114 changes: 114 additions & 0 deletions src/content/docs/sdk/deposits.mdx
Original file line number Diff line number Diff line change
@@ -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);
```
112 changes: 112 additions & 0 deletions src/content/docs/sdk/errors.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
---
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

- `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.``
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: <function> reverted (<hash>)`
The transaction was mined and reverted. Read the contract revert below. No local state changed.
- `MistClient: send of <function> 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 <address>`
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 |
Loading
Loading