@zerc20/cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,520 @@
1
+ // The commands. What a command answers goes to standard output, alone, so that it pipes; what it is doing, asks or
2
+ // warns of goes to standard error.
3
+
4
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { createInterface } from 'node:readline/promises';
6
+ import { entropyToMnemonic } from '@scure/bip39';
7
+ import { wordlist } from '@scure/bip39/wordlists/english.js';
8
+ import {
9
+ type Activity,
10
+ type FeeQuote,
11
+ type Network,
12
+ type Operation,
13
+ type Token,
14
+ type Wallet,
15
+ WalletError,
16
+ accountId,
17
+ } from '@zerc20/wallet-sdk';
18
+ import { type Address, isAddress } from 'viem';
19
+ import { type Key, keyIn, loadNetwork, openAccount, readKey, seedKey, stateFile } from './account.js';
20
+ import { Failure, Usage } from './errors.js';
21
+ import {
22
+ amount,
23
+ chainName,
24
+ chainNamed,
25
+ csv,
26
+ minute,
27
+ parseAmount,
28
+ short,
29
+ table,
30
+ tokensNamed,
31
+ underlyingSymbol,
32
+ until,
33
+ } from './format.js';
34
+
35
+ export interface Flags {
36
+ network: string;
37
+ chain?: string;
38
+ 'key-file'?: string;
39
+ 'max-fee'?: string;
40
+ prover?: string;
41
+ json: boolean;
42
+ yes: boolean;
43
+ wrapped: boolean;
44
+ csv: boolean;
45
+ tx: boolean;
46
+ }
47
+
48
+ /** Where a merge prover on this machine listens, unless told otherwise. */
49
+ export const LOCAL_PROVER = 'http://127.0.0.1:3006';
50
+
51
+ const say = (line: string) => process.stderr.write(`${line}\n`);
52
+
53
+ /** A command's answer: `data` as JSON where a program reads it, `human` otherwise. */
54
+ const answer = (flags: Flags, human: string, data: unknown) =>
55
+ process.stdout.write(`${flags.json ? JSON.stringify(data, null, 2) : human}\n`);
56
+
57
+ const quit = () => process.exit(130);
58
+ /** What Ctrl-C, or a terminal that closes, does now. */
59
+ let interrupt: () => void = quit;
60
+ export const onSignal = () => interrupt();
61
+ export const whenInterrupted = (f: () => void) => void (interrupt = f);
62
+
63
+ /** The wallet a command opened, for `close`. */
64
+ let opened: Wallet | undefined;
65
+
66
+ /** Lets the wallet go once a command is done: a burn address being recorded ahead stops, rather than being cut off by
67
+ * the exit. It is not waited on for long, as nothing of the command's is left in it. */
68
+ export const close = () =>
69
+ Promise.race([opened?.close().catch(() => {}), new Promise((r) => setTimeout(r, 3000).unref())]);
70
+
71
+ /** `network` with its merges proved on this machine, by the prover at `url`. */
72
+ const provedHere = (network: Network, url: string): Network => ({
73
+ ...network,
74
+ mergeProver: { url, trust: { local: true } },
75
+ });
76
+
77
+ /** The network a command works on, with `--prover` its merges proved on this machine. */
78
+ function networkOf(flags: Flags): Network {
79
+ const network = loadNetwork(flags.network);
80
+ return flags.prover ? provedHere(network, flags.prover === 'local' ? LOCAL_PROVER : flags.prover) : network;
81
+ }
82
+
83
+ /** Where an account notes the prover of this machine that its merge under way is proved by. Every command's sync
84
+ * moves that merge on, and one that names no prover would hand the rest of it to the network's, which the merge's
85
+ * owner chose not to show it to. */
86
+ const proverNote = (network: Network, key: Key) => `${stateFile(network, key)}.prover`;
87
+
88
+ interface Session {
89
+ flags: Flags;
90
+ network: Network;
91
+ key: Key;
92
+ wallet: Wallet;
93
+ }
94
+
95
+ const KIND = { send: 'payment', withdraw: 'withdrawal', consolidate: 'merge', deposit: 'deposit' } as const;
96
+
97
+ /** Opens the account of the key given. `seed` is for what a view key cannot do. An operation an earlier run left under
98
+ * way is named, as this run's syncs move it on: nothing is paid without a line saying so. */
99
+ async function open(flags: Flags, need: 'any' | 'seed', prove = false): Promise<Session> {
100
+ let network = networkOf(flags);
101
+ const key = await readKey(flags['key-file']);
102
+ if (need === 'seed' && key.kind === 'view')
103
+ throw new Failure('a view key only watches its account: this takes the recovery phrase');
104
+ const note = proverNote(network, key);
105
+ if (!flags.prover && existsSync(note)) network = provedHere(network, readFileSync(note, 'utf8'));
106
+ const wallet = (opened = await openAccount(network, key, { prove }));
107
+ if (!wallet.operations().some((op) => op.kind === 'consolidate' && op.status === 'pending'))
108
+ rmSync(note, { force: true });
109
+ for (const op of wallet.operations()) {
110
+ if (op.status !== 'pending') continue;
111
+ const [what, chain] = [KIND[op.kind], chainName(op.chainId)];
112
+ // in a block, an operation is only watched until it is final
113
+ if (op.txHashes.length > 0 && op.kind !== 'consolidate')
114
+ say(`An earlier ${what} on ${chain} is in a block, not final yet.`);
115
+ else say(`Going on with a ${what} on ${chain} started earlier.`);
116
+ }
117
+ return { flags, network, key, wallet };
118
+ }
119
+
120
+ /** Catches up with the chains. One that cannot be read holds back only its own: the rest is still shown, with a
121
+ * warning, and with `whole` a status that says the answer is not all of it. What keeps an earlier operation from
122
+ * going on is said too, as nothing else of this command would show it. */
123
+ async function sync(s: Session, whole: boolean): Promise<void> {
124
+ try {
125
+ await s.wallet.sync();
126
+ } catch (e) {
127
+ say(`Not all of it could be read: ${(e as Error).message}`);
128
+ if (whole) process.exitCode = 1;
129
+ }
130
+ for (const op of s.wallet.operations()) {
131
+ if (op.status === 'pending' && op.retrying)
132
+ say(`The ${KIND[op.kind]} on ${chainName(op.chainId)} is held up: ${op.retrying.message}`);
133
+ }
134
+ }
135
+
136
+ const spendable = (s: Session, token: Token) => s.wallet.balances().find((b) => b.token === token)?.spendable ?? 0n;
137
+
138
+ /** The token `symbol` names. On several chains with no `--chain`, the one that holds `need` of it spendable, if only
139
+ * one does: a payment names its chain by where the funds are. */
140
+ function tokenOf(s: Session, symbol: string | undefined, need?: (t: Token) => bigint): Token {
141
+ if (!symbol) throw new Usage('name a token');
142
+ const chain = s.flags.chain ? chainNamed(s.network, s.flags.chain) : undefined;
143
+ const named = tokensNamed(s.network, s.wallet.tokens(), symbol, chain);
144
+ if (named.length === 0) {
145
+ const known = [...new Set(s.wallet.tokens().map((t) => t.symbol))].join(', ');
146
+ throw new Failure(`no token ${symbol}${chain ? ` on ${chainName(chain.chainId)}` : ''}: there is ${known}`);
147
+ }
148
+ if (named.length === 1) return named[0];
149
+ const holding = need ? named.filter((t) => spendable(s, t) >= need(t)) : [];
150
+ if (holding.length === 1) return holding[0];
151
+ const rows = named.map((t) => [` ${chainName(t.chainId)}`, `${amount(spendable(s, t), t)} spendable`]);
152
+ throw new Usage(`${symbol} is on several chains: name one with --chain\n${table(['', ''], rows).trimStart()}`);
153
+ }
154
+
155
+ /** Asks before anything is paid. Where no one can answer, only `--yes` pays: a script never pays by accident. The
156
+ * question is still shown there, as it tells a program what it would pay, fee included, before it passes `--yes`. */
157
+ async function confirm(flags: Flags, question: string): Promise<void> {
158
+ if (flags.yes) return;
159
+ if (!process.stdin.isTTY) {
160
+ say(question);
161
+ throw new Usage('no terminal to confirm on: pass --yes to pay without being asked');
162
+ }
163
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
164
+ // a terminal's Ctrl-C reaches the question, not the process
165
+ rl.on('SIGINT', onSignal);
166
+ const reply = await rl.question(`${question} [y/N] `);
167
+ rl.close();
168
+ if (!/^y(es)?$/i.test(reply.trim())) throw new Failure('Nothing was paid.');
169
+ }
170
+
171
+ /** The most the fees may come to: the quote just shown, or `--max-fee`, which a higher quote fails. */
172
+ function feeCap(flags: Flags, token: Token, quote: FeeQuote): bigint {
173
+ if (!flags['max-fee']) return quote.fee;
174
+ const cap = parseAmount(flags['max-fee'], token.decimals);
175
+ if (quote.fee > cap) throw new Failure(`the fee is ${amount(quote.fee, token)} ${token.symbol}, above --max-fee`);
176
+ return cap;
177
+ }
178
+
179
+ /** What an operation is waiting on, from the stage it reached last. */
180
+ function doing(op: Operation): string {
181
+ if (op.kind === 'consolidate') {
182
+ const merge = {
183
+ planned: 'Writing its note…',
184
+ noted: 'Asking the attester…',
185
+ attested: 'Sending it to the merge prover…',
186
+ proving: 'The merge prover is proving it: minutes…',
187
+ proved: 'Relaying…',
188
+ relayed: 'Waiting for its block…',
189
+ };
190
+ return op.stage ? merge[op.stage] : 'Waiting for a proved root over the last merge…';
191
+ }
192
+ const payment = {
193
+ planned: 'Writing its notes…',
194
+ noted: 'Proving…',
195
+ proved: 'Asking the attester…',
196
+ attested: 'Relaying…',
197
+ proving: '',
198
+ relayed: 'Waiting for its block…',
199
+ };
200
+ return op.stage ? payment[op.stage] : '';
201
+ }
202
+
203
+ /** Waits until `op` is in a block, saying what it waits on. Ctrl-C cancels it while it has paid nothing and asked the
204
+ * relayer nothing; past that it can only finish, now or the next time the account is opened. */
205
+ async function follow(flags: Flags, op: Operation): Promise<void> {
206
+ let told = '';
207
+ const tell = () => {
208
+ const now = op.retrying ? `Trying again: ${op.retrying.message}` : doing(op);
209
+ if (now && now !== told) say((told = now));
210
+ };
211
+ const timer = setInterval(tell, 300);
212
+ interrupt = () => {
213
+ interrupt = quit;
214
+ const left = `The ${KIND[op.kind]} is under way: it goes on whenever this account is opened.`;
215
+ if (!op.cancellable) {
216
+ say(left);
217
+ return quit();
218
+ }
219
+ op.cancel()
220
+ .then(
221
+ () => say('Cancelled: nothing was paid.'),
222
+ () => say(left),
223
+ )
224
+ .finally(quit);
225
+ };
226
+ try {
227
+ await op.wait();
228
+ } finally {
229
+ clearInterval(timer);
230
+ interrupt = quit;
231
+ }
232
+ say('In a block. What it left the account is spendable again in some minutes, under a proved root.');
233
+ answer(flags, op.txHashes.join('\n'), { kind: KIND[op.kind], chainId: String(op.chainId), txHashes: op.txHashes });
234
+ }
235
+
236
+ const NOT_YET = {
237
+ incoming: 'arriving',
238
+ 'awaiting-root': 'settling',
239
+ 'roots-halted': 'halted',
240
+ screening: 'screening',
241
+ } as const;
242
+
243
+ export async function balance(flags: Flags): Promise<void> {
244
+ const s = await open(flags, 'any');
245
+ await sync(s, true);
246
+ const held = s.wallet.balances().filter((b) => b.spendable > 0n || b.pending.length > 0 || b.blocked > 0n);
247
+ const id = accountId(s.wallet.address);
248
+ const rows = held.map((b) => {
249
+ const waiting = new Map<string, bigint>();
250
+ for (const p of b.pending) waiting.set(NOT_YET[p.reason], (waiting.get(NOT_YET[p.reason]) ?? 0n) + p.amount);
251
+ if (b.blocked > 0n) waiting.set('blocked', b.blocked);
252
+ const notYet = [...waiting].map(([why, v]) => `${amount(v, b.token)} ${why}`).join(', ');
253
+ return [b.token.symbol, chainName(b.token.chainId), amount(b.spendable, b.token), notYet];
254
+ });
255
+ const nothing =
256
+ s.key.kind === 'seed' ? 'Nothing yet: `zerc20 deposit <token>` gives an address to pay in.' : 'Nothing yet.';
257
+ answer(
258
+ flags,
259
+ `${id} ${s.network.name}\n\n${rows.length ? table(['TOKEN', 'CHAIN', 'SPENDABLE', 'NOT YET'], rows, [2]) : nothing}`,
260
+ {
261
+ id,
262
+ address: s.wallet.address,
263
+ network: s.network.name,
264
+ balances: held.map((b) => ({
265
+ token: b.token.symbol,
266
+ chain: chainName(b.token.chainId),
267
+ chainId: String(b.token.chainId),
268
+ spendable: amount(b.spendable, b.token),
269
+ pending: b.pending.map((p) => ({ amount: amount(p.amount, b.token), reason: p.reason })),
270
+ blocked: amount(b.blocked, b.token),
271
+ })),
272
+ },
273
+ );
274
+ }
275
+
276
+ /** `f` over `items`, a few at a time. */
277
+ async function each<T, R>(items: T[], f: (item: T) => Promise<R>): Promise<R[]> {
278
+ const out = new Array<R>(items.length);
279
+ let next = 0;
280
+ const worker = async () => {
281
+ while (next < items.length) {
282
+ const i = next++;
283
+ out[i] = await f(items[i]);
284
+ }
285
+ };
286
+ await Promise.all(Array.from({ length: 4 }, worker));
287
+ return out;
288
+ }
289
+
290
+ /** Whom an activity was with, as its owner would name them: an account by its zERC20 ID, anyone else by address. */
291
+ function counterparty(a: Activity): string {
292
+ if (a.via && 'code' in a.via) return a.via.code;
293
+ if (!a.counterparty) return '';
294
+ return a.kind === 'sent' || (a.kind === 'received' && !a.burnAddress) ? accountId(a.counterparty) : a.counterparty;
295
+ }
296
+
297
+ /** What `history` tells of each activity, as a CSV's columns. */
298
+ const FIELDS = [
299
+ 'time',
300
+ 'kind',
301
+ 'status',
302
+ 'amount',
303
+ 'token',
304
+ 'chain',
305
+ 'chainId',
306
+ 'fee',
307
+ 'counterparty',
308
+ 'depositAddress',
309
+ 'coin',
310
+ 'tx',
311
+ ] as const;
312
+
313
+ export async function history(flags: Flags): Promise<void> {
314
+ const s = await open(flags, 'any');
315
+ await sync(s, true);
316
+ if (s.key.kind === 'view') say('A view key does not show payments to the account’s receive codes.');
317
+ const activity = s.wallet.activity();
318
+ // a sync reads no transaction: each is looked up, a few reads of its chain
319
+ const txs = flags.tx ? await each(activity, (a) => s.wallet.transaction(a).catch(() => null)) : [];
320
+ const entries: Record<(typeof FIELDS)[number], string>[] = activity.map((a, i) => ({
321
+ time: (txs[i]?.at ?? a.at)?.toISOString() ?? '',
322
+ kind: a.kind,
323
+ status: a.status,
324
+ amount: amount(a.amount, a.token),
325
+ token: a.token.symbol,
326
+ chain: chainName(a.token.chainId),
327
+ chainId: String(a.token.chainId),
328
+ fee: a.fee === null ? '' : amount(a.fee, a.token),
329
+ counterparty: counterparty(a),
330
+ depositAddress: a.via && 'depositAddress' in a.via ? a.via.depositAddress : '',
331
+ coin: a.coin ?? '',
332
+ tx: txs[i]?.hash ?? a.txHash ?? '',
333
+ }));
334
+ if (flags.json) return void answer(flags, '', entries);
335
+ if (flags.csv) {
336
+ return void process.stdout.write(`${csv([[...FIELDS], ...entries.map((e) => FIELDS.map((f) => e[f]))])}\n`);
337
+ }
338
+ const rows = entries.map((e) => [
339
+ minute(e.time ? new Date(e.time) : null),
340
+ e.status === 'failed' ? `${e.kind} (failed)` : e.kind,
341
+ e.amount,
342
+ e.token,
343
+ e.chain,
344
+ short(e.counterparty),
345
+ e.fee,
346
+ ...(flags.tx ? [e.tx] : []),
347
+ ]);
348
+ const head = ['TIME (UTC)', 'KIND', 'AMOUNT', 'TOKEN', 'CHAIN', 'WITH', 'FEE', ...(flags.tx ? ['TRANSACTION'] : [])];
349
+ answer(flags, rows.length ? table(head, rows, [2, 6]) : 'Nothing yet.', entries);
350
+ }
351
+
352
+ export async function coins(flags: Flags): Promise<void> {
353
+ const s = await open(flags, 'any');
354
+ await sync(s, true);
355
+ const all = s.wallet.coins();
356
+ const state = (c: (typeof all)[number]) =>
357
+ c.state === 'spendable' || c.state === 'spending' || c.state === 'blocked' ? c.state : NOT_YET[c.state];
358
+ const rows = all.map((c) => [
359
+ c.id,
360
+ c.kind,
361
+ c.token.symbol,
362
+ chainName(c.token.chainId),
363
+ amount(c.amount, c.token),
364
+ c.readyBy ? `${state(c)} ${until(c.readyBy)}` : state(c),
365
+ ]);
366
+ answer(
367
+ flags,
368
+ rows.length ? table(['COIN', 'KIND', 'TOKEN', 'CHAIN', 'AMOUNT', 'STATE'], rows, [4]) : 'Nothing yet.',
369
+ all.map((c) => ({
370
+ id: c.id,
371
+ kind: c.kind,
372
+ token: c.token.symbol,
373
+ chain: chainName(c.token.chainId),
374
+ chainId: String(c.token.chainId),
375
+ amount: amount(c.amount, c.token),
376
+ state: c.state,
377
+ readyBy: c.readyBy?.toISOString() ?? null,
378
+ })),
379
+ );
380
+ }
381
+
382
+ export async function receive(flags: Flags, [symbol]: string[]): Promise<void> {
383
+ if (!symbol) {
384
+ // the account's address under another spelling: the key alone gives it
385
+ const key = await readKey(flags['key-file']);
386
+ return void answer(flags, accountId(key.address), { id: accountId(key.address), address: key.address });
387
+ }
388
+ const s = await open(flags, 'seed');
389
+ const token = tokenOf(s, symbol);
390
+ const code = await s.wallet.receiveCode(token);
391
+ say(
392
+ `Whoever has this code pays ${token.symbol} on ${chainName(token.chainId)} into the account, and no view key shows it.`,
393
+ );
394
+ answer(flags, code, { code, token: token.symbol, chain: chainName(token.chainId), chainId: String(token.chainId) });
395
+ }
396
+
397
+ export async function deposit(flags: Flags, [symbol]: string[]): Promise<void> {
398
+ const s = await open(flags, 'seed');
399
+ const token = tokenOf(s, symbol);
400
+ const { address, fee } = await s.wallet.depositAddress(token);
401
+ const [asset, chain] = [underlyingSymbol(s.network, token), chainName(token.chainId)];
402
+ const watchedUntil = new Date(Date.now() + 7 * 24 * 3600 * 1000);
403
+ say(`Send ${asset} on ${chain} to this address, from anywhere. On ${chain} only: sent on another chain, it is lost.`);
404
+ say(
405
+ `Each payment pays ${amount(fee, token)} ${asset} to the deposit relayer, and has to be more than that. ` +
406
+ `Watched until ${watchedUntil.toISOString().slice(0, 10)}.`,
407
+ );
408
+ answer(flags, address, {
409
+ address,
410
+ asset,
411
+ chain,
412
+ chainId: String(token.chainId),
413
+ fee: amount(fee, token),
414
+ watchedUntil: watchedUntil.toISOString(),
415
+ });
416
+ }
417
+
418
+ /** Why `token` cannot pay what was asked, in its own units, where `e` is the wallet saying so in base units. */
419
+ function shortfall(s: Session, token: Token, e: unknown): unknown {
420
+ if (!(e instanceof WalletError) || (e.code !== 'funds-settling' && e.code !== 'insufficient-funds')) return e;
421
+ const has = `${amount(spendable(s, token), token)} ${token.symbol} on ${chainName(token.chainId)} is spendable`;
422
+ if (e.code === 'insufficient-funds') return new Failure(`not enough to pay that and its fee: ${has}`);
423
+ const when = e.waitsOn?.readyBy ? `, which should do in ${until(e.waitsOn.readyBy)}` : '';
424
+ return new Failure(`not enough is spendable yet: ${has}, and the rest is settling${when}`);
425
+ }
426
+
427
+ /** A send or a withdrawal: both pay `amount` out of what is spendable, with the fees on top. */
428
+ async function pay(flags: Flags, kind: 'send' | 'withdraw', [typed, symbol, to]: string[]): Promise<void> {
429
+ if (!typed || !symbol || !to) throw new Usage(`zerc20 ${kind} <amount|max> <token> <to>`);
430
+ if (kind === 'withdraw' && !isAddress(to)) throw new Usage(`${to} is not an address`);
431
+ const s = await open(flags, 'seed', true);
432
+ await sync(s, false);
433
+ const max = typed === 'max';
434
+ // With --yes no one reads which chain was found to pay, and what is paid to an address on a chain its owner does
435
+ // not watch there may be lost: a withdrawal no one confirms names its chain.
436
+ const found =
437
+ kind === 'withdraw' && flags.yes ? undefined : (t: Token) => (max ? 1n : parseAmount(typed, t.decimals));
438
+ const token = tokenOf(s, symbol, found);
439
+ const chain = chainName(token.chainId);
440
+ let value: bigint;
441
+ if (max) {
442
+ const most = await s.wallet.maxAmount({ kind, token });
443
+ if (most.merges > 0)
444
+ throw new Failure(`its coins are too scattered to pay it all at once: \`zerc20 merge ${token.symbol}\` first`);
445
+ if (most.amount === 0n) throw new Failure(`no ${token.symbol} on ${chain} is left to pay once the fee is taken`);
446
+ value = most.amount;
447
+ } else value = parseAmount(typed, token.decimals);
448
+ const quote = await s.wallet.fees({ kind, token, amount: value }).catch((e: unknown) => {
449
+ throw shortfall(s, token, e);
450
+ });
451
+ const maxFee = feeCap(flags, token, quote);
452
+ const fee = `fee ${amount(quote.fee, token)} ${token.symbol}`;
453
+ if (kind === 'send') {
454
+ await confirm(flags, `Send ${amount(value, token)} ${token.symbol} on ${chain} to ${short(to)}, ${fee}?`);
455
+ return follow(flags, await s.wallet.send({ to, token, amount: value, maxFee }));
456
+ }
457
+ // a public address most often expects the asset itself: the zERC20 token is paid out only when asked for
458
+ const paid = flags.wrapped ? `${token.symbol} (the zERC20 token itself)` : underlyingSymbol(s.network, token);
459
+ await confirm(flags, `Withdraw ${amount(value, token)} ${paid} on ${chain} to ${to}, in public, ${fee}?`);
460
+ const address = to as Address; // checked before the wallet opened
461
+ return follow(flags, await s.wallet.withdraw({ to: address, token, amount: value, maxFee, unwrap: !flags.wrapped }));
462
+ }
463
+
464
+ export const send = (flags: Flags, args: string[]) => pay(flags, 'send', args);
465
+ export const withdraw = (flags: Flags, args: string[]) => pay(flags, 'withdraw', args);
466
+
467
+ export async function merge(flags: Flags, [symbol]: string[]): Promise<void> {
468
+ const s = await open(flags, 'seed');
469
+ await sync(s, false);
470
+ const token = tokenOf(s, symbol, () => 1n);
471
+ const chain = chainName(token.chainId);
472
+ const first = await s.wallet.nextMerge(token);
473
+ if (!first) {
474
+ say(`Nothing to merge: ${token.symbol} on ${chain} is in one note, or none of it is spendable.`);
475
+ if (flags.json) answer(flags, '', { kind: KIND.consolidate, chainId: String(token.chainId), txHashes: [] });
476
+ return;
477
+ }
478
+ const quote = await s.wallet.fees({ kind: 'consolidate', token });
479
+ const maxFee = feeCap(flags, token, quote);
480
+ const prover = s.network.mergeProver;
481
+ const here = prover && 'local' in prover.trust;
482
+ if (here) {
483
+ const ready = await fetch(`${prover.url}/status`)
484
+ .then((r) => r.json() as Promise<{ mergeKey?: boolean }>)
485
+ .catch(() => null);
486
+ if (!ready?.mergeKey)
487
+ throw new Failure(`no merge prover is ready at ${prover.url}: run \`zerc20 prover start\` and wait for it`);
488
+ }
489
+ const by = here ? `the prover on this machine` : `the network's merge prover`;
490
+ const merges = quote.steps === 1 ? 'one merge' : `${quote.steps} merges`;
491
+ await confirm(
492
+ flags,
493
+ `Merge ${token.symbol} on ${chain} into one note, in ${merges} that ${by} proves, ` +
494
+ `fee ${amount(quote.fee, token)} ${token.symbol}?`,
495
+ );
496
+ if (here) writeFileSync(proverNote(s.network, s.key), prover.url);
497
+ return follow(flags, await s.wallet.consolidate({ token, maxFee }));
498
+ }
499
+
500
+ export async function viewKey(flags: Flags): Promise<void> {
501
+ const s = await open(flags, 'seed');
502
+ say(`Whoever has this key sees what the account holds and did on ${s.network.name}, and can spend none of it.`);
503
+ answer(flags, s.wallet.viewKey(), { viewKey: s.wallet.viewKey(), network: s.network.name });
504
+ }
505
+
506
+ /** Makes an account: of a fresh recovery phrase, or of the one in `--key-file`, which registers an account whose
507
+ * phrase was made elsewhere. `ZERC20_KEY` is not looked at: a shell that still exports another account's key would
508
+ * be answered with that account, in place of a new one. The phrase is printed once the account exists, and nowhere
509
+ * kept. */
510
+ export async function create(flags: Flags): Promise<void> {
511
+ const network = networkOf(flags);
512
+ const given = flags['key-file'] ? keyIn(flags['key-file']) : null;
513
+ if (given?.kind === 'view') throw new Failure('a view key watches an account: it makes none');
514
+ const key = given ?? seedKey(crypto.getRandomValues(new Uint8Array(32)));
515
+ opened = await openAccount(network, key, { create: true });
516
+ const [id, phrase] = [accountId(key.address), entropyToMnemonic(key.seed, wordlist)];
517
+ say(`${id} is on ${network.name}.`);
518
+ if (!given) say('These 24 words are its only key, and are shown this once: keep them where nothing else reads them.');
519
+ answer(flags, given ? id : phrase, { id, address: key.address, network: network.name, ...(given ? {} : { phrase }) });
520
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,7 @@
1
+ // How a command ends when it cannot go on: what it prints, and the status it exits with.
2
+
3
+ /** The command line itself is wrong: exits 2. */
4
+ export class Usage extends Error {}
5
+
6
+ /** The command could not do what was asked: exits 1. */
7
+ export class Failure extends Error {}
package/src/files.ts ADDED
@@ -0,0 +1,86 @@
1
+ // Files this machine keeps between runs, under one directory: each account's state as the SDK seals it, and the
2
+ // public files proving needs, fetched once and checked against a pinned SHA-256.
3
+
4
+ import { createHash } from 'node:crypto';
5
+ import { createReadStream, createWriteStream, existsSync, mkdirSync, renameSync, rmSync, statSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { dirname, join } from 'node:path';
8
+ import { Readable } from 'node:stream';
9
+ import { pipeline } from 'node:stream/promises';
10
+ import { pathToFileURL } from 'node:url';
11
+ import type { Circuit } from '@zerc20/wallet-sdk';
12
+ import { Failure } from './errors.js';
13
+
14
+ /** Where everything is kept. */
15
+ export const home = () => process.env.ZERC20_HOME ?? join(homedir(), '.zerc20');
16
+
17
+ async function sha256Of(path: string): Promise<string> {
18
+ const hash = createHash('sha256');
19
+ await pipeline(createReadStream(path), hash);
20
+ return hash.digest('hex');
21
+ }
22
+
23
+ /** Fetches `url` to `path`, unless it is there already. A download that stopped goes on from where it did, as a file
24
+ * of gigabytes is not started over; it gets its name only once its SHA-256 is `sha256`, so what is at `path` is
25
+ * whole and the file expected. `progress` hears the bytes so far and their total. */
26
+ export async function download(
27
+ url: string,
28
+ path: string,
29
+ sha256: string,
30
+ progress: (done: number, total: number) => void = () => {},
31
+ ): Promise<void> {
32
+ if (existsSync(path)) return;
33
+ mkdirSync(dirname(path), { recursive: true });
34
+ const part = `${path}.part`;
35
+ const have = existsSync(part) ? statSync(part).size : 0;
36
+ // as it is stored: a range and a length count the bytes of the file only where the server sends it unpacked
37
+ const r = await fetch(url, {
38
+ headers: { 'accept-encoding': 'identity', ...(have ? { range: `bytes=${have}-` } : {}) },
39
+ });
40
+ // 416: nothing past what is here, so it is whole and only its check is left
41
+ if (r.status !== 416) {
42
+ if (!r.ok || !r.body) throw new Failure(`${url}: HTTP ${r.status}`);
43
+ // a server that ignores the range sends it all again
44
+ const resumed = r.status === 206;
45
+ let done = resumed ? have : 0;
46
+ const total = done + Number(r.headers.get('content-length') ?? 0);
47
+ const body = Readable.fromWeb(r.body);
48
+ body.on('data', (chunk: Buffer) => progress((done += chunk.length), total));
49
+ await pipeline(body, createWriteStream(part, { flags: resumed ? 'a' : 'w' }));
50
+ }
51
+ const got = await sha256Of(part);
52
+ if (got !== sha256.toLowerCase()) {
53
+ rmSync(part);
54
+ throw new Failure(`${url} is not the file expected (its SHA-256 is ${got}): try again`);
55
+ }
56
+ renameSync(part, path);
57
+ }
58
+
59
+ /** A line on the terminal that follows a download, and nothing where no one watches. */
60
+ export function showProgress(label: string): (done: number, total: number) => void {
61
+ if (!process.stderr.isTTY) return () => {};
62
+ const mb = (n: number) => (n / 1e6).toFixed(n < 1e9 ? 1 : 0);
63
+ let shown = 0;
64
+ return (done, total) => {
65
+ if (done < total && Date.now() - shown < 200) return;
66
+ shown = Date.now();
67
+ process.stderr.write(`\r${label} ${mb(done)} / ${mb(total)} MB${done >= total ? '\n' : ''}`);
68
+ };
69
+ }
70
+
71
+ /** `circuit` read from this machine where its files are kept, and with `fetchMissing`, fetched first. The SDK keeps a
72
+ * circuit only in memory, and a command is a process of its own: without this each payment downloads its 25 MB again.
73
+ * The SDK checks the files against the same hashes whenever it reads them. */
74
+ export async function localCircuit(circuit: Circuit, fetchMissing: boolean): Promise<Circuit> {
75
+ const local = async (url: string, sha256: string, ext: string) => {
76
+ const path = join(home(), 'circuits', `${sha256}.${ext}`);
77
+ if (fetchMissing && !url.startsWith('file:'))
78
+ await download(url, path, sha256, showProgress(`Fetching the proving ${ext}`));
79
+ return existsSync(path) ? pathToFileURL(path).href : url;
80
+ };
81
+ return {
82
+ ...circuit,
83
+ wasm: await local(circuit.wasm, circuit.wasmSha256, 'wasm'),
84
+ zkey: await local(circuit.zkey, circuit.zkeySha256, 'zkey'),
85
+ };
86
+ }