@zerc20/wallet-sdk 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/burnWorker.ts CHANGED
@@ -1,25 +1,24 @@
1
- // Searches a burn address off the main thread: core.ts starts one per search, a Web Worker in a browser and a worker
2
- // thread in Node.
1
+ // Runs blocks of burn address searches off the main thread, one at a time: core.ts keeps a pool of these, Web Workers
2
+ // in a browser and worker threads in Node.
3
3
 
4
- import { type BurnAnswer, type BurnSearch, initCore, searchHere } from './core.js';
4
+ import { type BurnAnswer, type BurnBlock, initCore, runBlock } from './core.js';
5
5
 
6
- async function answer(s: BurnSearch): Promise<BurnAnswer> {
6
+ async function answer(b: BurnBlock): Promise<BurnAnswer> {
7
7
  try {
8
8
  await initCore();
9
- return { burn: searchHere(s) };
9
+ return { burn: runBlock(b) };
10
10
  } catch (e) {
11
11
  return { error: e instanceof Error ? e.message : String(e) };
12
12
  }
13
13
  }
14
14
 
15
15
  if (typeof self !== 'undefined') {
16
- self.onmessage = async ({ data }: MessageEvent<BurnSearch>) => postMessage(await answer(data));
16
+ self.onmessage = async ({ data }: MessageEvent<BurnBlock>) => postMessage(await answer(data));
17
17
  } else {
18
18
  // a variable, so that bundlers for the browser leave Node's module alone
19
19
  const threads = 'node:worker_threads';
20
- type Port = { postMessage(a: BurnAnswer): void };
21
- void import(/* @vite-ignore */ threads).then(
22
- async ({ parentPort, workerData }: { parentPort: Port; workerData: BurnSearch }) =>
23
- parentPort.postMessage(await answer(workerData)),
20
+ type Port = { on(event: 'message', f: (b: BurnBlock) => void): void; postMessage(a: BurnAnswer): void };
21
+ void import(/* @vite-ignore */ threads).then(({ parentPort }: { parentPort: Port }) =>
22
+ parentPort.on('message', (b) => void answer(b).then((a) => parentPort.postMessage(a))),
24
23
  );
25
24
  }
package/src/context.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  // Everything an open wallet works with, shared by sync and the operations.
2
2
 
3
3
  import type { CanisterClient, ViewKey } from '@zerc20/storage-sdk';
4
- import { type Hex, type WalletClient, publicActions } from 'viem';
4
+ import { type Account, type Hex, type WalletClient, createWalletClient, http, publicActions } from 'viem';
5
5
  import type { Chain } from './chain.js';
6
6
  import { core } from './core.js';
7
+ import { guard } from './errors.js';
7
8
  import type { ChainConfig, Network } from './network.js';
8
9
  import type { Asp, Indexer } from './servers.js';
9
10
  import type { ChainState, WalletState } from './state.js';
@@ -24,11 +25,21 @@ export interface SpendKey {
24
25
  nullifyingKey: Hex;
25
26
  }
26
27
 
28
+ /** What a sync needs of a key: its public key and nullifying key, which find and follow what it owns but spend none of
29
+ * it. */
30
+ export type Owner = Pick<SpendKey, 'publicKey' | 'nullifyingKey'>;
31
+
27
32
  export interface Ctx {
28
33
  network: Network;
29
- seed: Uint8Array;
34
+ /** The root of every key. Opened with a function for it, held only while something needs it; otherwise always. */
35
+ seed: Uint8Array | null;
36
+ /** The owners derived while the seed was held, by key: the wallet's own (`''`) and each receive code's. */
37
+ owners: Map<string, Owner>;
30
38
  address: Hex;
31
- walletClient: WalletClient;
39
+ /** The account that holds the public funds, and signs for them. */
40
+ account: Account;
41
+ /** The user's wallet, when it is what signs and sends rather than an account of the app's own (`walletOn`). */
42
+ walletClient: WalletClient | null;
32
43
  storage: CanisterClient;
33
44
  view: ViewKey;
34
45
  chains: ChainCtx[];
@@ -47,20 +58,36 @@ export interface CodeId {
47
58
  index: number;
48
59
  }
49
60
 
61
+ const idOf = (code?: CodeId) => (code ? `${code.chainId}:${code.tokenId}:${code.index}` : '');
62
+
63
+ /** The seed, which the wallet holds whenever it does what needs it. */
64
+ export function seedOf(ctx: Ctx): Uint8Array {
65
+ if (!ctx.seed) throw new Error('the wallet does not hold its seed now');
66
+ return ctx.seed;
67
+ }
68
+
50
69
  /** The key that owns this seed's notes and deposits on every chain and token, or with `code`, the notes paid to that
51
- * receive code. */
70
+ * receive code. Its owner is kept for when the seed is not held. */
52
71
  export function spendKey(ctx: Ctx, code?: CodeId): SpendKey {
53
- let bySeed = keys.get(ctx.seed);
54
- if (!bySeed) keys.set(ctx.seed, (bySeed = new Map<string, SpendKey>()));
55
- const id = code ? `${code.chainId}:${code.tokenId}:${code.index}` : '';
72
+ const seed = seedOf(ctx);
73
+ let bySeed = keys.get(seed);
74
+ if (!bySeed) keys.set(seed, (bySeed = new Map<string, SpendKey>()));
75
+ const id = idOf(code);
56
76
  let key = bySeed.get(id);
57
77
  if (!key) {
58
- key = (code ? core.codeKey(ctx.seed, code.chainId, code.tokenId, code.index) : core.spendKey(ctx.seed)) as SpendKey;
78
+ key = (code ? core.codeSpendKey(seed, code.chainId, code.tokenId, code.index) : core.spendKey(seed)) as SpendKey;
59
79
  bySeed.set(id, key);
60
80
  }
81
+ if (!ctx.owners.has(id)) ctx.owners.set(id, { publicKey: key.publicKey, nullifyingKey: key.nullifyingKey });
61
82
  return key;
62
83
  }
63
84
 
85
+ /** `spendKey`'s owner: derived before, or now if the seed is held; null if neither. The wallet's own is derived as it
86
+ * opens. */
87
+ export function owner(ctx: Ctx, code?: CodeId): Owner | null {
88
+ return ctx.owners.get(idOf(code)) ?? (ctx.seed ? spendKey(ctx, code) : null);
89
+ }
90
+
64
91
  export function chainCtx(ctx: Ctx, chainId: bigint): ChainCtx {
65
92
  const c = ctx.chains.find((c) => c.config.chainId === chainId);
66
93
  if (!c) throw new Error(`chain ${chainId} is not in this network`);
@@ -73,6 +100,19 @@ export function chainState(ctx: Ctx, chainId: bigint): ChainState {
73
100
  return s;
74
101
  }
75
102
 
103
+ /** `wc` on `chainId`, switched there first: a browser wallet is on one chain at a time. */
104
+ export async function switched(wc: WalletClient, chainId: bigint): Promise<WalletClient> {
105
+ if ((await wc.getChainId()) !== Number(chainId)) await guard(wc.switchChain({ id: Number(chainId) }));
106
+ return wc;
107
+ }
108
+
109
+ /** The client that sends the account's transactions on `chainId`: the user's wallet, switched to the chain, or the
110
+ * app's own account, through the chain's RPC. */
111
+ export async function walletOn(ctx: Ctx, chainId: bigint): Promise<WalletClient> {
112
+ if (ctx.walletClient) return switched(ctx.walletClient, chainId);
113
+ return createWalletClient({ account: ctx.account, transport: http(chainCtx(ctx, chainId).config.rpcUrl) });
114
+ }
115
+
76
116
  /** Waits until the wallet's own node has a transaction mined on ours too: the wallet simulates the next one there, and
77
117
  * where blocks are fast that node lags ours now and then, so the next one would show as reverting. A wallet that does
78
118
  * not answer is not waited on. */
package/src/core.ts CHANGED
@@ -26,27 +26,17 @@ export interface Burn {
26
26
  address: Address;
27
27
  }
28
28
 
29
- /** A seed's `index`-th burn address of a token, with its salt: about 2^16 hashes, up to tens of seconds on a phone.
30
- * Searched off the main thread (a Web Worker in a browser, a worker thread in Node), so that the app stays
31
- * responsive; `signal` stops the search. */
29
+ /** The `index`-th burn address of `publicKey` on a chain and token, and its salt, from `burnKey`: the wallet's own burn
30
+ * key, or a point of sale's (`wallet_keys::derive_burn_address`). About 2^16 hashes, spread over the device's cores
31
+ * (Web Workers in a browser, worker threads in Node) so that the app stays responsive; `signal` stops the search. */
32
32
  export const burnAddress = (
33
- seed: Uint8Array,
33
+ burnKey: Uint8Array,
34
34
  chainId: bigint,
35
35
  tokenId: number,
36
36
  index: number,
37
- signal?: AbortSignal,
38
- ): Promise<Burn> => search({ seed, chainId, tokenId, index }, signal);
39
-
40
- /** The `k`-th burn address a point of sale holding `laneKey` makes for its owner's `publicKey` on a chain and token
41
- * (`keys::pos_burn`), with its salt: about 2^16 hashes too, searched the same way. */
42
- export const posBurnAddress = (
43
- laneKey: Uint8Array,
44
- chainId: bigint,
45
- tokenId: number,
46
- k: number,
47
37
  publicKey: Hex,
48
38
  signal?: AbortSignal,
49
- ): Promise<Burn> => search({ laneKey, chainId, tokenId, k, publicKey }, signal);
39
+ ): Promise<Burn> => search({ burnKey, chainId, tokenId, index, publicKey }, signal);
50
40
 
51
41
  /** A burn address of someone else's `publicKey` (one they published to be paid), with a random salt that has the proof
52
42
  * of work: about 2^16 hashes too, searched the same way. Only who holds the salt finds it: the payer, and the owner once
@@ -55,93 +45,295 @@ export const burnAddressFor = (chainId: bigint, publicKey: Hex, signal?: AbortSi
55
45
  search({ chainId, publicKey }, signal);
56
46
 
57
47
  export type BurnSearch =
58
- | { seed: Uint8Array; chainId: bigint; tokenId: number; index: number }
59
- | { laneKey: Uint8Array; chainId: bigint; tokenId: number; k: number; publicKey: Hex }
48
+ | { burnKey: Uint8Array; chainId: bigint; tokenId: number; index: number; publicKey: Hex }
60
49
  | { chainId: bigint; publicKey: Hex };
61
50
 
62
- /** A search, where it runs: a seed's index, or a point of sale's counter, derives its salts; someone else's key takes
63
- * random ones. */
64
- export function searchHere(s: BurnSearch): Burn {
65
- if ('seed' in s) return core.burnAddress(s.seed, s.chainId, s.tokenId, s.index) as Burn;
66
- if ('laneKey' in s) return core.posBurnAddress(s.laneKey, s.chainId, s.tokenId, s.k, s.publicKey) as Burn;
67
- for (;;) {
68
- const bytes = crypto.getRandomValues(new Uint8Array(32));
69
- bytes[0] = bytes[0] & 0x1f; // below 2^253: a canonical field element
70
- const salt = bytesToHex(bytes);
71
- const address = core.burnAddressOf(s.chainId, s.publicKey, salt) as Address | undefined;
72
- if (address) return { salt, address };
51
+ /** Counters per block: about 20 ms of hashing on a laptop, a few times that on a phone. */
52
+ const BLOCK = 512;
53
+
54
+ /** A block of a search: its salt counters `from..=to`, or as many random salts for someone else's key. */
55
+ export interface BurnBlock {
56
+ search: BurnSearch;
57
+ from: number;
58
+ to: number;
59
+ }
60
+
61
+ export type BurnAnswer = { burn: Burn | null } | { error: string };
62
+
63
+ /** The address a block holds, if any. Its salts count up from a start: one the burn key derives, or for someone else's
64
+ * key a random one below 2^253, so that every salt is a field element. */
65
+ export function runBlock({ search: s, from, to }: BurnBlock): Burn | null {
66
+ let burn: unknown;
67
+ if ('burnKey' in s) burn = core.burnBlock(s.burnKey, s.chainId, s.tokenId, s.index, s.publicKey, from, to);
68
+ else {
69
+ const start = crypto.getRandomValues(new Uint8Array(32));
70
+ start[0] = start[0] & 0x1f;
71
+ burn = core.burnBlockFor(s.chainId, s.publicKey, bytesToHex(start), to - from + 1);
72
+ }
73
+ return (burn as Burn | undefined) ?? null;
74
+ }
75
+
76
+ type Outcome = { burn: Burn } | { error: unknown };
77
+
78
+ /** A search in progress, in blocks `0, 1, …` of `BLOCK` counters. From a burn key, the address is the first block's
79
+ * hit, so that every device derives the same one; for someone else's key, it is the first found. */
80
+ export class Search {
81
+ readonly s: BurnSearch;
82
+ readonly #settle: (r: Outcome) => void;
83
+ /** From a burn key: the address is the first block's hit, not the first found. */
84
+ readonly #derived: boolean;
85
+ #settled = false;
86
+ #next = 0;
87
+ /** Blocks a worker took and died with, handed out again before any other. */
88
+ #dropped: number[] = [];
89
+ /** What the finished blocks from `#checked` on hold: every block below it holds none. */
90
+ #found = new Map<number, Burn | null>();
91
+ #checked = 0;
92
+ /** The lowest block known to hold an address: no block above it is needed. */
93
+ #lowest = Infinity;
94
+
95
+ constructor(s: BurnSearch, settle: (r: Outcome) => void) {
96
+ this.s = s;
97
+ this.#settle = settle;
98
+ this.#derived = 'burnKey' in s;
99
+ }
100
+
101
+ take(): number | undefined {
102
+ if (this.#settled) return undefined;
103
+ if (this.#dropped.length) return this.#dropped.shift();
104
+ return this.#next < this.#lowest ? this.#next++ : undefined;
105
+ }
106
+
107
+ drop(block: number) {
108
+ this.#dropped.unshift(block);
109
+ }
110
+
111
+ finish(block: number, burn: Burn | null) {
112
+ if (this.#settled) return;
113
+ if (!this.#derived) {
114
+ if (burn) this.#end({ burn });
115
+ return;
116
+ }
117
+ this.#found.set(block, burn);
118
+ if (burn) this.#lowest = Math.min(this.#lowest, block);
119
+ for (let found; (found = this.#found.get(this.#checked)) !== undefined; this.#checked++) {
120
+ if (found) return this.#end({ burn: found });
121
+ this.#found.delete(this.#checked);
122
+ }
123
+ }
124
+
125
+ fail(error: unknown) {
126
+ if (!this.#settled) this.#end({ error });
127
+ }
128
+
129
+ #end(r: Outcome) {
130
+ this.#settled = true;
131
+ this.#settle(r);
73
132
  }
74
133
  }
75
134
 
76
- export type BurnAnswer = { burn: Burn } | { error: string };
135
+ /** A worker running one block at a time. */
136
+ interface Thread {
137
+ job: Job | null;
138
+ /** Whether it ever answered: one that dies before it does never ran. */
139
+ answered: boolean;
140
+ send(b: BurnBlock): void;
141
+ stop(): void;
142
+ /** In Node, a thread keeps the process up while it works, and only then. */
143
+ busy(working: boolean): void;
144
+ }
145
+
146
+ type Job = { search: Search; block: number };
77
147
 
78
148
  /** What this module takes from Node's worker threads, typed here so that the package needs no Node types. */
79
- type NodeThread = new (
80
- url: URL,
81
- opts: { workerData: BurnSearch },
82
- ) => {
83
- once(event: 'message', f: (a: BurnAnswer) => void): void;
84
- once(event: 'error', f: () => void): void;
149
+ type NodeWorker = new (url: URL) => {
150
+ on(event: 'message', f: (a: BurnAnswer) => void): void;
151
+ on(event: 'error' | 'exit' | 'messageerror', f: () => void): void;
152
+ postMessage(b: BurnBlock): void;
153
+ ref(): void;
154
+ unref(): void;
85
155
  terminate(): Promise<number>;
86
156
  };
87
157
 
88
- /** Starts `s` in a worker, which hands `done` its answer, or null if it did not run; returns how to stop it, or null
89
- * where no worker starts. */
90
- // ponytail: a worker per search, each compiling the wasm; a pool of availableParallelism() workers if a server makes many
91
- async function spawn(s: BurnSearch, done: (a: BurnAnswer | null) => void): Promise<(() => void) | null> {
92
- if (typeof Worker !== 'undefined') {
93
- const worker = new Worker(new URL('./burnWorker.js', import.meta.url), { type: 'module' });
94
- worker.onmessage = ({ data }: MessageEvent<BurnAnswer>) => done(data);
95
- // a worker that does not start (a bundler that left it out) costs responsiveness only
96
- worker.onerror = (e) => {
97
- e.preventDefault();
98
- done(null);
99
- };
100
- worker.postMessage(s);
101
- return () => worker.terminate();
102
- }
103
- // variables, so that bundlers for the browser leave Node's module and a second copy of the worker alone
104
- const [threads, file] = ['node:worker_threads', './burnWorker.js'];
105
- const { Worker: Thread } = (await import(/* @vite-ignore */ threads).catch(() => ({}))) as { Worker?: NodeThread };
106
- if (!Thread) return null;
107
- const thread = new Thread(new URL(file, import.meta.url), { workerData: s });
108
- thread.once('message', done);
109
- thread.once('error', () => done(null)); // run from source, as tests are, there is no burnWorker.js
110
- return () => void thread.terminate();
111
- }
158
+ /** Searches in progress, oldest first: blocks go to the oldest that has one to hand out. */
159
+ const searches: Search[] = [];
160
+ let threads: Thread[] | null = null;
161
+ let starting = false;
162
+ /** Workers do not run here (a page whose CSP forbids them, a bundler that left burnWorker.js out, tests run from
163
+ * source): blocks run on this thread instead. */
164
+ let here = false;
165
+ let runningHere = false;
166
+ let idle: ReturnType<typeof setTimeout> | undefined;
167
+ /** An idle pool stops after this long, freeing a wasm instance per core. */
168
+ const IDLE_MS = 30_000;
112
169
 
113
170
  async function search(s: BurnSearch, signal?: AbortSignal): Promise<Burn> {
114
- signal?.throwIfAborted();
115
171
  await initCore();
172
+ signal?.throwIfAborted();
116
173
  return new Promise((resolve, reject) => {
117
- let stop: (() => void) | null = null;
118
- let settled = false;
119
- const settle = (f: () => void) => {
120
- if (settled) return;
121
- settled = true;
122
- stop?.();
174
+ const abort = () => one.fail(signal!.reason);
175
+ const one = new Search(s, (r) => {
123
176
  signal?.removeEventListener('abort', abort);
124
- f();
125
- };
126
- const here = () =>
127
- settle(() => {
128
- try {
129
- resolve(searchHere(s));
130
- } catch (err) {
131
- reject(err);
132
- }
133
- });
134
- const abort = () => settle(() => reject(signal!.reason));
177
+ searches.splice(searches.indexOf(one), 1);
178
+ if ('burn' in r) resolve(r.burn);
179
+ else reject(r.error);
180
+ });
135
181
  signal?.addEventListener('abort', abort, { once: true });
136
- spawn(s, (a) =>
137
- a === null ? here() : settle(() => ('burn' in a ? resolve(a.burn) : reject(new Error(a.error)))),
138
- ).then(
139
- (stopIt) => {
140
- if (!stopIt) here();
141
- else if (settled) stopIt();
142
- else stop = stopIt;
143
- },
144
- here, // a page whose CSP forbids workers
145
- );
182
+ searches.push(one);
183
+ dispatch();
184
+ });
185
+ }
186
+
187
+ function nextJob(): Job | null {
188
+ for (const search of searches) {
189
+ const block = search.take();
190
+ if (block !== undefined) return { search, block };
191
+ }
192
+ return null;
193
+ }
194
+
195
+ const blockOf = ({ search, block }: Job): BurnBlock => ({
196
+ search: search.s,
197
+ from: block * BLOCK,
198
+ to: block * BLOCK + BLOCK - 1,
199
+ });
200
+
201
+ function deliver({ search, block }: Job, a: BurnAnswer) {
202
+ if ('error' in a) search.fail(new Error(a.error));
203
+ else search.finish(block, a.burn);
204
+ }
205
+
206
+ /** Hands blocks to idle threads, starting the pool if it is not running. */
207
+ function dispatch() {
208
+ clearTimeout(idle);
209
+ if (here) return void runHere();
210
+ if (!threads) return void start();
211
+ for (const t of threads) {
212
+ if (t.job) continue;
213
+ const job = nextJob();
214
+ if (!job) break;
215
+ t.job = job;
216
+ t.busy(true);
217
+ t.send(blockOf(job));
218
+ }
219
+ if (!searches.length && threads.every((t) => !t.job)) {
220
+ idle = setTimeout(stop, IDLE_MS);
221
+ (idle as { unref?: () => void }).unref?.(); // a process need not stay up for it
222
+ }
223
+ }
224
+
225
+ async function start() {
226
+ if (starting) return;
227
+ starting = true;
228
+ const cores = globalThis.navigator?.hardwareConcurrency ?? 1;
229
+ // Node leaves a core to its event loop: a point of sale's server answers while it searches
230
+ const count = Math.max(1, Math.min(16, typeof Worker !== 'undefined' ? cores : cores - 1));
231
+ threads = await spawn(count).catch(() => []);
232
+ starting = false;
233
+ if (!threads.length) {
234
+ threads = null;
235
+ void runHere();
236
+ }
237
+ dispatch();
238
+ }
239
+
240
+ function stop() {
241
+ const stopped = threads ?? [];
242
+ threads = null;
243
+ for (const t of stopped) t.stop();
244
+ }
245
+
246
+ function answered(t: Thread, a: BurnAnswer) {
247
+ t.answered = true;
248
+ const job = t.job!;
249
+ t.job = null;
250
+ t.busy(false);
251
+ deliver(job, a);
252
+ dispatch();
253
+ }
254
+
255
+ function died(t: Thread) {
256
+ if (!threads?.includes(t)) return; // stopped, or already counted
257
+ threads = threads.filter((other) => other !== t);
258
+ if (t.job) t.job.search.drop(t.job.block);
259
+ if (!t.answered) {
260
+ // it never ran: neither will the others
261
+ for (const other of threads) if (other.job) other.job.search.drop(other.job.block);
262
+ stop();
263
+ void runHere();
264
+ return;
265
+ }
266
+ if (!threads.length) threads = null; // started again on the next dispatch
267
+ dispatch();
268
+ }
269
+
270
+ /** Starts `count` workers; none where there are no workers. */
271
+ async function spawn(count: number): Promise<Thread[]> {
272
+ if (typeof Worker !== 'undefined') {
273
+ return Array.from({ length: count }, () => {
274
+ // this exact form is what bundlers (Vite, webpack) look for to emit the worker
275
+ const worker = new Worker(new URL('./burnWorker.js', import.meta.url), { type: 'module' });
276
+ const t: Thread = {
277
+ job: null,
278
+ answered: false,
279
+ send: (b) => worker.postMessage(b),
280
+ stop: () => worker.terminate(),
281
+ busy: () => {},
282
+ };
283
+ worker.onmessage = ({ data }: MessageEvent<BurnAnswer>) => answered(t, data);
284
+ worker.onerror = (e) => {
285
+ e.preventDefault();
286
+ died(t);
287
+ };
288
+ worker.onmessageerror = () => died(t);
289
+ return t;
290
+ });
291
+ }
292
+ // variables, so that bundlers for the browser leave Node's module and a second copy of the worker alone
293
+ const [threadsModule, file] = ['node:worker_threads', './burnWorker.js'];
294
+ const { Worker: ThreadWorker } = (await import(/* @vite-ignore */ threadsModule).catch(() => ({}))) as {
295
+ Worker?: NodeWorker;
296
+ };
297
+ if (!ThreadWorker) return [];
298
+ return Array.from({ length: count }, () => {
299
+ const worker = new ThreadWorker(new URL(file, import.meta.url));
300
+ worker.unref();
301
+ const t: Thread = {
302
+ job: null,
303
+ answered: false,
304
+ send: (b) => worker.postMessage(b),
305
+ stop: () => void worker.terminate(),
306
+ busy: (working) => (working ? worker.ref() : worker.unref()),
307
+ };
308
+ worker.on('message', (a) => answered(t, a));
309
+ // run from source, as tests are, there is no burnWorker.js: the thread exits before it answers
310
+ for (const event of ['error', 'exit', 'messageerror'] as const) worker.on(event, () => died(t));
311
+ return t;
146
312
  });
147
313
  }
314
+
315
+ /** Runs the blocks on this thread, yielding to the event loop every ~100 ms, and no more often: each yield is a timer,
316
+ * which costs 4 ms in a visible tab and a whole second in a hidden one. */
317
+ async function runHere() {
318
+ if (!here) {
319
+ here = true;
320
+ console.warn('zerc20: burn addresses are searched on the main thread, slower: no worker starts here');
321
+ }
322
+ if (runningHere) return;
323
+ runningHere = true;
324
+ let since = Date.now();
325
+ for (let job; (job = nextJob());) {
326
+ let a: BurnAnswer;
327
+ try {
328
+ a = { burn: runBlock(blockOf(job)) };
329
+ } catch (e) {
330
+ a = { error: e instanceof Error ? e.message : String(e) };
331
+ }
332
+ deliver(job, a);
333
+ if (Date.now() - since >= 100) {
334
+ await new Promise((resolve) => setTimeout(resolve, 0));
335
+ since = Date.now();
336
+ }
337
+ }
338
+ runningHere = false;
339
+ }
package/src/index.ts CHANGED
@@ -23,7 +23,7 @@ export {
23
23
  networkFromJson,
24
24
  } from './network.js';
25
25
  export { type Payment, PointOfSale, type PosToken, type Sale, type SaleStatus } from './pos.js';
26
- export { seedFromSignature } from './seed.js';
26
+ export { accountKey, seedFromSignature } from './seed.js';
27
27
  export {
28
28
  type Activity,
29
29
  type Balance,
package/src/pos.ts CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  zeroAddress,
17
17
  } from 'viem';
18
18
  import { Chain, type Token } from './chain.js';
19
- import { core, initCore, posBurnAddress } from './core.js';
19
+ import { burnAddress, core, initCore } from './core.js';
20
20
  import { fail } from './errors.js';
21
21
  import { type ChainConfig, type Network, checkNetwork } from './network.js';
22
22
  import { scan } from './scan.js';
@@ -346,7 +346,7 @@ export class PointOfSale {
346
346
  const laneKey = hexToBytes(c.laneKey);
347
347
  const burns = await Promise.all(
348
348
  Array.from({ length: BURN_BLOCK }, (_, i) =>
349
- posBurnAddress(laneKey, token.chainId, token.tokenId, k + i, c.publicKey),
349
+ burnAddress(laneKey, token.chainId, token.tokenId, k + i, c.publicKey),
350
350
  ),
351
351
  );
352
352
  const block = {
package/src/rageExit.ts CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { type Address, type Hex, decodeEventLog, numberToHex, parseAbi } from 'viem';
6
6
  import { depositAddressAbi, ledgerAbi, verifierAbi } from './chain.js';
7
- import { type ChainCtx, type Ctx, chainCtx, spendKey, walletSees } from './context.js';
7
+ import { type ChainCtx, type Ctx, chainCtx, spendKey, walletOn, walletSees } from './context.js';
8
8
  import { core } from './core.js';
9
9
  import { fail, guard } from './errors.js';
10
10
  import { prove } from './prove.js';
@@ -85,9 +85,8 @@ export async function rageExit(ctx: Ctx, record: DepositRecord, index: number):
85
85
  const c = chainCtx(ctx, record.chainId);
86
86
  const found = record.found.find((f) => f.index === index) ?? fail('invalid', `no deposit at ${index}`);
87
87
  if (found.spent) fail('invalid', 'the deposit is already spent');
88
- const wc = ctx.walletClient;
89
- const account = wc.account!;
90
- if ((await wc.getChainId()) !== Number(record.chainId)) await guard(wc.switchChain({ id: Number(record.chainId) }));
88
+ const wc = await walletOn(ctx, record.chainId);
89
+ const account = ctx.account;
91
90
  const hashes: Hex[] = [];
92
91
  const send: Sender = async (address, abi, functionName, args) => {
93
92
  const hash = await guard(
package/src/seed.ts CHANGED
@@ -1,12 +1,24 @@
1
1
  // A seed from the wallet's own signature, so the account alone restores it. It holds only for wallets whose
2
2
  // signatures are deterministic (RFC 6979, as MetaMask's and hardware wallets' are): keep the fingerprint, and if a
3
3
  // later derivation gives another one, the wallet signs differently each time and the seed must be backed up itself.
4
- // Anything that gets the user to sign the same message gets the seed.
4
+ // Anything that gets the user to sign the same message gets the seed. Or the other way round, an account from a seed:
5
+ // for an app whose seed comes from elsewhere (a passkey), and that has no wallet of its own.
5
6
 
6
7
  import { secp256k1 } from '@noble/curves/secp256k1.js';
8
+ import { entropyToMnemonic } from '@scure/bip39';
9
+ import { wordlist } from '@scure/bip39/wordlists/english.js';
7
10
  import { type Hex, type WalletClient, bytesToHex, hexToBytes, keccak256 } from 'viem';
11
+ import { mnemonicToAccount } from 'viem/accounts';
8
12
  import { fail, guard } from './errors.js';
9
13
 
14
+ /** The private key of the account a seed's own app holds its public funds in: the first account of the seed's recovery
15
+ * phrase (the seed as 24 BIP-39 words) by the standard derivation, BIP-44's m/44'/60'/0'/0/0. Any wallet given the
16
+ * phrase opens the same account, so its public funds stay reachable without this app. */
17
+ export function accountKey(seed: Uint8Array): Hex {
18
+ const key = mnemonicToAccount(entropyToMnemonic(seed, wordlist)).getHdKey().privateKey;
19
+ return bytesToHex(key ?? fail('invalid', 'the seed derives no account key'));
20
+ }
21
+
10
22
  const message = (address: Hex) =>
11
23
  [
12
24
  'zERC20 wallet seed',
package/src/spend.ts CHANGED
@@ -21,7 +21,7 @@ import {
21
21
  parseAbiParameters,
22
22
  } from 'viem';
23
23
  import { UNWRAP_INTENT } from './chain.js';
24
- import { type Ctx, chainCtx, spendKey } from './context.js';
24
+ import { type Ctx, chainCtx, owner, spendKey } from './context.js';
25
25
  import { core } from './core.js';
26
26
  import { fail } from './errors.js';
27
27
  import { prove } from './prove.js';
@@ -36,7 +36,7 @@ import {
36
36
  relayerFees,
37
37
  requestProof,
38
38
  } from './services.js';
39
- import type { NoteRecord, OperationRecord, Position, SpendOperation } from './state.js';
39
+ import { type NoteRecord, type OperationRecord, type Position, type SpendOperation, unspent } from './state.js';
40
40
  import { commitmentsAt, noteReceipt, storageState, takeRefresh, tokenIds } from './sync.js';
41
41
  import { aspPath, aspPaths, commitmentPath, commitmentPaths } from './tree.js';
42
42
 
@@ -141,7 +141,7 @@ export function coins(ctx: Ctx, chainId: bigint, tokenId: number, rootSize: numb
141
141
  );
142
142
  // final or not: once a proved root the chain accepts covers it, a reorg that moves it takes that root back too, and
143
143
  // a JoinSplit against it then fails on chain, which frees its inputs
144
- const usable = (f: { index: number; spent: boolean }) => !f.spent && f.index < rootSize && !locked.has(f.index);
144
+ const usable = (f: Position) => unspent(f) && f.index < rootSize && !locked.has(f.index);
145
145
  const notes = ctx.state.notes
146
146
  .filter((n) => n.chainId === chainId && n.tokenId === tokenId)
147
147
  .flatMap((n) =>
@@ -168,7 +168,7 @@ export function coins(ctx: Ctx, chainId: bigint, tokenId: number, rootSize: numb
168
168
  /** Whether any of `tokenId`'s notes or deposits is on chain but not spendable yet: not final or confirmed, not
169
169
  * screened, or not under the proved root of size `rootSize`. A note only announced does not count: it may never land. */
170
170
  export function settling(ctx: Ctx, chainId: bigint, tokenId: number, rootSize: number): boolean {
171
- const waiting = (f: { index: number; spent: boolean }) => !f.spent && f.index >= rootSize;
171
+ const waiting = (f: Position) => unspent(f) && f.index >= rootSize;
172
172
  // a zero-value change is never spendable: it is there to carry its payment's receipt
173
173
  const notes = ctx.state.notes.filter((n) => n.chainId === chainId && n.tokenId === tokenId && n.value > 0n);
174
174
  const deposits = ctx.state.deposits.filter((d) => d.chainId === chainId);
@@ -305,7 +305,7 @@ export async function planStep(ctx: Ctx, op: SpendOperation): Promise<Step | Mer
305
305
  const all = coins(ctx, op.chainId, op.tokenId, root?.size ?? 0);
306
306
  const { relayer, publicKey: relayerKey, fees } = await relayerFees(c.config);
307
307
  const fee = fees.get(op.tokenId)?.fee ?? fail('unavailable', `the relayer does not relay token ${op.tokenId}`);
308
- const self = spendKey(ctx).publicKey;
308
+ const self = owner(ctx)!.publicKey;
309
309
  const out = (publicKey: Hex, value: bigint, role: Output['role'], salt: Hex = fresh()): Output => ({
310
310
  publicKey,
311
311
  value,