@zerc20/cli 0.0.0-stage → 0.1.1

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/account.ts ADDED
@@ -0,0 +1,181 @@
1
+ // The account a command works on: its key, taken from anywhere but the arguments and never written down, and its
2
+ // wallet over a state file that only the key opens.
3
+
4
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { text } from 'node:stream/consumers';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { mnemonicToEntropy, validateMnemonic } from '@scure/bip39';
9
+ import { wordlist } from '@scure/bip39/wordlists/english.js';
10
+ import { CanisterClient } from '@zerc20/storage-sdk';
11
+ import { type Network, Wallet, accountId, accountKey, networkFromJson, viewKeyAccount } from '@zerc20/wallet-sdk';
12
+ import { type Address, hexToBytes } from 'viem';
13
+ import { privateKeyToAccount } from 'viem/accounts';
14
+ import { Failure, Usage } from './errors.js';
15
+ import { home, localCircuit } from './files.js';
16
+
17
+ /** What opens an account: a view key to watch it, or the seed its recovery phrase spells, to pay from it. */
18
+ export type Key =
19
+ { kind: 'view'; viewKey: string; address: Address } | { kind: 'seed'; seed: Uint8Array; address: Address };
20
+
21
+ export const seedKey = (seed: Uint8Array): Extract<Key, { kind: 'seed' }> => ({
22
+ kind: 'seed',
23
+ seed,
24
+ address: privateKeyToAccount(accountKey(seed)).address,
25
+ });
26
+
27
+ /** The key `input` is: the two look nothing alike, so a command takes either without being told which. */
28
+ export function parseKey(input: string): Key {
29
+ const t = input.trim();
30
+ const watched = viewKeyAccount(t);
31
+ if (watched) return { kind: 'view', viewKey: t, address: watched };
32
+ const phrase = t.toLowerCase().split(/\s+/).join(' ');
33
+ if (phrase.split(' ').length === 24 && validateMnemonic(phrase, wordlist))
34
+ return seedKey(mnemonicToEntropy(phrase, wordlist));
35
+ throw new Failure(
36
+ t
37
+ ? 'not a view key (zerc20view1…) or a 24-word recovery phrase'
38
+ : 'no key: give a view key or a recovery phrase in --key-file, ZERC20_KEY or standard input',
39
+ );
40
+ }
41
+
42
+ /** Thrown where Ctrl-C answers a question. */
43
+ export class Interrupted extends Error {}
44
+
45
+ /** What is typed after `question`, with nothing of it shown. */
46
+ function hidden(question: string): Promise<string> {
47
+ return new Promise((resolve, reject) => {
48
+ const { stdin } = process;
49
+ let typed = '';
50
+ const end = (settle: () => void) => {
51
+ stdin.off('data', read);
52
+ stdin.setRawMode(false);
53
+ stdin.pause();
54
+ process.stderr.write('\n');
55
+ settle();
56
+ };
57
+ const read = (chunk: string) => {
58
+ for (const ch of chunk) {
59
+ if (ch === '\r' || ch === '\n') return end(() => resolve(typed));
60
+ if (ch === '\u0003') return end(() => reject(new Interrupted()));
61
+ typed = ch === '\u007f' || ch === '\b' ? typed.slice(0, -1) : typed + ch;
62
+ }
63
+ };
64
+ process.stderr.write(question);
65
+ stdin.setRawMode(true);
66
+ stdin.setEncoding('utf8');
67
+ stdin.on('data', read);
68
+ stdin.resume();
69
+ });
70
+ }
71
+
72
+ /** The key `file` holds. */
73
+ export const keyIn = (file: string) => parseKey(readFileSync(file, 'utf8'));
74
+
75
+ /** The key a command opens its account with, from anywhere but the arguments, which a shell's history and the process
76
+ * list would keep: a file, the environment, what is piped in, or what is asked for at the terminal. */
77
+ export async function readKey(file: string | undefined): Promise<Key> {
78
+ if (file) return keyIn(file);
79
+ const given = process.env.ZERC20_KEY;
80
+ if (given) return parseKey(given);
81
+ return parseKey(process.stdin.isTTY ? await hidden('View key or recovery phrase: ') : await text(process.stdin));
82
+ }
83
+
84
+ /** `name`'s network: one that ships with this program, pinned as the release that carries it found it, or a
85
+ * network.json of the user's own. */
86
+ export function loadNetwork(name: string): Network {
87
+ const file = ['mainnet', 'testnet'].includes(name)
88
+ ? fileURLToPath(new URL(`../networks/${name}.json`, import.meta.url))
89
+ : name;
90
+ if (!existsSync(file)) throw new Usage(`--network ${name}: mainnet, testnet, or the path of a network.json`);
91
+ return networkFromJson(readFileSync(file, 'utf8'));
92
+ }
93
+
94
+ const alive = (pid: number) => {
95
+ try {
96
+ process.kill(pid, 0);
97
+ return true;
98
+ } catch (e) {
99
+ return (e as NodeJS.ErrnoException).code === 'EPERM';
100
+ }
101
+ };
102
+
103
+ /** Keeps `path` to this process until it exits. The SDK keeps two wallets of one page apart, not two processes: a
104
+ * second command saving over the first one's state would undo what it spent. A lock whose process is gone is taken
105
+ * over: one that names no process, as a full disk leaves it, or this process itself, as a container gives each run
106
+ * the pid of the last. */
107
+ export function lock(path: string): void {
108
+ const file = `${path}.lock`;
109
+ const read = (f: string) => {
110
+ try {
111
+ return readFileSync(f, 'utf8');
112
+ } catch {
113
+ return null;
114
+ }
115
+ };
116
+ for (;;) {
117
+ try {
118
+ writeFileSync(file, String(process.pid), { flag: 'wx' });
119
+ break;
120
+ } catch (e) {
121
+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
122
+ }
123
+ const left = read(file);
124
+ const pid = Number(left);
125
+ if (pid > 0 && pid !== process.pid && alive(pid))
126
+ throw new Failure(`another zerc20 command (process ${pid}) has this account open: let it end first`);
127
+ // Moved aside under a name of this process's own before it is removed: of two commands taking it over, one finds
128
+ // it gone, and one that moved the other's new lock instead puts it back.
129
+ const aside = `${file}.${process.pid}`;
130
+ try {
131
+ renameSync(file, aside);
132
+ } catch {
133
+ continue;
134
+ }
135
+ if (read(aside) === left) rmSync(aside, { force: true });
136
+ else renameSync(aside, file);
137
+ }
138
+ process.on('exit', () => rmSync(file, { force: true }));
139
+ }
140
+
141
+ /** Where `key`'s account on `network` keeps its state, whose name other files of the account's start with. */
142
+ export function stateFile(network: Network, key: Key): string {
143
+ const dir = join(home(), network.name);
144
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
145
+ return join(dir, `${key.address.toLowerCase()}.${key.kind === 'view' ? 'view' : 'full'}.bin`);
146
+ }
147
+
148
+ /** Opens `key`'s account on `network`. Its state, sealed by the SDK under a key of `key`'s, is all that stays on this
149
+ * machine: without the key it tells nothing, and with it the next run reads only what is new.
150
+ *
151
+ * A recovery phrase whose account was never used is refused unless `create`: the SDK registers an account the first
152
+ * time it opens, so a mistyped phrase would quietly make an empty one. `prove` fetches what a payment proves with. */
153
+ export async function openAccount(network: Network, key: Key, { create = false, prove = false } = {}): Promise<Wallet> {
154
+ const path = stateFile(network, key);
155
+ lock(path);
156
+ const persist = {
157
+ load: () => Promise.resolve(existsSync(path) ? readFileSync(path) : null),
158
+ // whole or not at all: a crash while writing leaves the state before it
159
+ save: (bytes: Uint8Array) => {
160
+ writeFileSync(`${path}.tmp`, bytes, { mode: 0o600 });
161
+ renameSync(`${path}.tmp`, path);
162
+ return Promise.resolve();
163
+ },
164
+ };
165
+ if (key.kind === 'view') return Wallet.watch({ network, viewKey: key.viewKey, persist });
166
+ if (!create && !existsSync(path)) {
167
+ const storage = await CanisterClient.connect(network.storage.host, network.storage.canisterId);
168
+ if (!(await storage.registration(hexToBytes(key.address))))
169
+ throw new Failure(
170
+ `this recovery phrase has no account on ${network.name} (it would be ${accountId(key.address)}): ` +
171
+ 'check the phrase, or make the account with `zerc20 new`',
172
+ );
173
+ }
174
+ const circuits = { ...network.circuits, joinsplit: await localCircuit(network.circuits.joinsplit, prove) };
175
+ return Wallet.open({
176
+ network: { ...network, circuits },
177
+ account: privateKeyToAccount(accountKey(key.seed)),
178
+ seed: key.seed,
179
+ persist,
180
+ });
181
+ }