@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/LICENSE +661 -0
- package/README.md +20 -2
- package/dist/account.js +177 -0
- package/dist/account.js.map +1 -0
- package/dist/commands.js +454 -0
- package/dist/commands.js.map +1 -0
- package/dist/errors.js +27 -0
- package/dist/errors.js.map +1 -0
- package/dist/files.js +79 -0
- package/dist/files.js.map +1 -0
- package/dist/format.js +73 -0
- package/dist/format.js.map +1 -0
- package/dist/main.js +176 -0
- package/dist/main.js.map +1 -0
- package/dist/mergeKeys.js +19 -0
- package/dist/mergeKeys.js.map +1 -0
- package/dist/prover.js +71 -0
- package/dist/prover.js.map +1 -0
- package/dist/skill.js +34 -0
- package/dist/skill.js.map +1 -0
- package/dist/update.js +89 -0
- package/dist/update.js.map +1 -0
- package/networks/mainnet.json +153 -0
- package/networks/testnet.json +158 -0
- package/package.json +51 -4
- package/skill/SKILL.md +170 -0
- package/src/account.ts +181 -0
- package/src/commands.ts +520 -0
- package/src/errors.ts +26 -0
- package/src/files.ts +86 -0
- package/src/format.ts +87 -0
- package/src/main.ts +170 -0
- package/src/mergeKeys.ts +20 -0
- package/src/prover.ts +71 -0
- package/src/skill.ts +44 -0
- package/src/update.ts +103 -0
package/README.md
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zerc20/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A zERC20 account in a terminal: `zerc20` watches an account by its view key, pays from one by its recovery phrase, and
|
|
4
|
+
runs a merge prover on your own machine.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
npm install -g @zerc20/cli
|
|
8
|
+
|
|
9
|
+
export ZERC20_KEY='zerc20view1…' # a view key to look, or the 24-word recovery phrase to pay
|
|
10
|
+
zerc20 balance
|
|
11
|
+
zerc20 history --csv
|
|
12
|
+
zerc20 send 10 USDC zerc20id1…
|
|
13
|
+
zerc20 prover start # then: zerc20 merge USDC --prover local
|
|
14
|
+
zerc20 install-skill # teaches the coding agents on this machine to use it
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`zerc20 --help` lists every command; [docs.zerc20.io](https://docs.zerc20.io/developers/cli) says more.
|
|
18
|
+
|
|
19
|
+
## License
|
|
20
|
+
|
|
21
|
+
[AGPL-3.0](LICENSE). The merge prover's packages are under the nodes' Business Source License.
|
package/dist/account.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
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
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { text } from 'node:stream/consumers';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { mnemonicToEntropy, validateMnemonic } from '@scure/bip39';
|
|
8
|
+
import { wordlist } from '@scure/bip39/wordlists/english.js';
|
|
9
|
+
import { CanisterClient } from '@zerc20/storage-sdk';
|
|
10
|
+
import { Wallet, accountId, accountKey, networkFromJson, viewKeyAccount } from '@zerc20/wallet-sdk';
|
|
11
|
+
import { hexToBytes } from 'viem';
|
|
12
|
+
import { privateKeyToAccount } from 'viem/accounts';
|
|
13
|
+
import { Failure, Usage } from './errors.js';
|
|
14
|
+
import { home, localCircuit } from './files.js';
|
|
15
|
+
export const seedKey = (seed) => ({
|
|
16
|
+
kind: 'seed',
|
|
17
|
+
seed,
|
|
18
|
+
address: privateKeyToAccount(accountKey(seed)).address,
|
|
19
|
+
});
|
|
20
|
+
/** The key `input` is: the two look nothing alike, so a command takes either without being told which. */
|
|
21
|
+
export function parseKey(input) {
|
|
22
|
+
const t = input.trim();
|
|
23
|
+
const watched = viewKeyAccount(t);
|
|
24
|
+
if (watched)
|
|
25
|
+
return { kind: 'view', viewKey: t, address: watched };
|
|
26
|
+
const phrase = t.toLowerCase().split(/\s+/).join(' ');
|
|
27
|
+
if (phrase.split(' ').length === 24 && validateMnemonic(phrase, wordlist))
|
|
28
|
+
return seedKey(mnemonicToEntropy(phrase, wordlist));
|
|
29
|
+
throw new Failure(t
|
|
30
|
+
? 'not a view key (zerc20view1…) or a 24-word recovery phrase'
|
|
31
|
+
: 'no key: give a view key or a recovery phrase in --key-file, ZERC20_KEY or standard input');
|
|
32
|
+
}
|
|
33
|
+
/** Thrown where Ctrl-C answers a question. */
|
|
34
|
+
export class Interrupted extends Error {
|
|
35
|
+
}
|
|
36
|
+
/** What is typed after `question`, with nothing of it shown. */
|
|
37
|
+
function hidden(question) {
|
|
38
|
+
return new Promise((resolve, reject) => {
|
|
39
|
+
const { stdin } = process;
|
|
40
|
+
let typed = '';
|
|
41
|
+
const end = (settle) => {
|
|
42
|
+
stdin.off('data', read);
|
|
43
|
+
stdin.setRawMode(false);
|
|
44
|
+
stdin.pause();
|
|
45
|
+
process.stderr.write('\n');
|
|
46
|
+
settle();
|
|
47
|
+
};
|
|
48
|
+
const read = (chunk) => {
|
|
49
|
+
for (const ch of chunk) {
|
|
50
|
+
if (ch === '\r' || ch === '\n')
|
|
51
|
+
return end(() => resolve(typed));
|
|
52
|
+
if (ch === '\u0003')
|
|
53
|
+
return end(() => reject(new Interrupted()));
|
|
54
|
+
typed = ch === '\u007f' || ch === '\b' ? typed.slice(0, -1) : typed + ch;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
process.stderr.write(question);
|
|
58
|
+
stdin.setRawMode(true);
|
|
59
|
+
stdin.setEncoding('utf8');
|
|
60
|
+
stdin.on('data', read);
|
|
61
|
+
stdin.resume();
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/** The key `file` holds. */
|
|
65
|
+
export const keyIn = (file) => parseKey(readFileSync(file, 'utf8'));
|
|
66
|
+
/** The key a command opens its account with, from anywhere but the arguments, which a shell's history and the process
|
|
67
|
+
* list would keep: a file, the environment, what is piped in, or what is asked for at the terminal. */
|
|
68
|
+
export async function readKey(file) {
|
|
69
|
+
if (file)
|
|
70
|
+
return keyIn(file);
|
|
71
|
+
const given = process.env.ZERC20_KEY;
|
|
72
|
+
if (given)
|
|
73
|
+
return parseKey(given);
|
|
74
|
+
return parseKey(process.stdin.isTTY ? await hidden('View key or recovery phrase: ') : await text(process.stdin));
|
|
75
|
+
}
|
|
76
|
+
/** `name`'s network: one that ships with this program, pinned as the release that carries it found it, or a
|
|
77
|
+
* network.json of the user's own. */
|
|
78
|
+
export function loadNetwork(name) {
|
|
79
|
+
const file = ['mainnet', 'testnet'].includes(name)
|
|
80
|
+
? fileURLToPath(new URL(`../networks/${name}.json`, import.meta.url))
|
|
81
|
+
: name;
|
|
82
|
+
if (!existsSync(file))
|
|
83
|
+
throw new Usage(`--network ${name}: mainnet, testnet, or the path of a network.json`);
|
|
84
|
+
return networkFromJson(readFileSync(file, 'utf8'));
|
|
85
|
+
}
|
|
86
|
+
const alive = (pid) => {
|
|
87
|
+
try {
|
|
88
|
+
process.kill(pid, 0);
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
catch (e) {
|
|
92
|
+
return e.code === 'EPERM';
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
/** Keeps `path` to this process until it exits. The SDK keeps two wallets of one page apart, not two processes: a
|
|
96
|
+
* second command saving over the first one's state would undo what it spent. A lock whose process is gone is taken
|
|
97
|
+
* over: one that names no process, as a full disk leaves it, or this process itself, as a container gives each run
|
|
98
|
+
* the pid of the last. */
|
|
99
|
+
export function lock(path) {
|
|
100
|
+
const file = `${path}.lock`;
|
|
101
|
+
const read = (f) => {
|
|
102
|
+
try {
|
|
103
|
+
return readFileSync(f, 'utf8');
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
for (;;) {
|
|
110
|
+
try {
|
|
111
|
+
writeFileSync(file, String(process.pid), { flag: 'wx' });
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
catch (e) {
|
|
115
|
+
if (e.code !== 'EEXIST')
|
|
116
|
+
throw e;
|
|
117
|
+
}
|
|
118
|
+
const left = read(file);
|
|
119
|
+
const pid = Number(left);
|
|
120
|
+
if (pid > 0 && pid !== process.pid && alive(pid))
|
|
121
|
+
throw new Failure(`another zerc20 command (process ${pid}) has this account open: let it end first`);
|
|
122
|
+
// Moved aside under a name of this process's own before it is removed: of two commands taking it over, one finds
|
|
123
|
+
// it gone, and one that moved the other's new lock instead puts it back.
|
|
124
|
+
const aside = `${file}.${process.pid}`;
|
|
125
|
+
try {
|
|
126
|
+
renameSync(file, aside);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (read(aside) === left)
|
|
132
|
+
rmSync(aside, { force: true });
|
|
133
|
+
else
|
|
134
|
+
renameSync(aside, file);
|
|
135
|
+
}
|
|
136
|
+
process.on('exit', () => rmSync(file, { force: true }));
|
|
137
|
+
}
|
|
138
|
+
/** Where `key`'s account on `network` keeps its state, whose name other files of the account's start with. */
|
|
139
|
+
export function stateFile(network, key) {
|
|
140
|
+
const dir = join(home(), network.name);
|
|
141
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
142
|
+
return join(dir, `${key.address.toLowerCase()}.${key.kind === 'view' ? 'view' : 'full'}.bin`);
|
|
143
|
+
}
|
|
144
|
+
/** Opens `key`'s account on `network`. Its state, sealed by the SDK under a key of `key`'s, is all that stays on this
|
|
145
|
+
* machine: without the key it tells nothing, and with it the next run reads only what is new.
|
|
146
|
+
*
|
|
147
|
+
* A recovery phrase whose account was never used is refused unless `create`: the SDK registers an account the first
|
|
148
|
+
* time it opens, so a mistyped phrase would quietly make an empty one. `prove` fetches what a payment proves with. */
|
|
149
|
+
export async function openAccount(network, key, { create = false, prove = false } = {}) {
|
|
150
|
+
const path = stateFile(network, key);
|
|
151
|
+
lock(path);
|
|
152
|
+
const persist = {
|
|
153
|
+
load: () => Promise.resolve(existsSync(path) ? readFileSync(path) : null),
|
|
154
|
+
// whole or not at all: a crash while writing leaves the state before it
|
|
155
|
+
save: (bytes) => {
|
|
156
|
+
writeFileSync(`${path}.tmp`, bytes, { mode: 0o600 });
|
|
157
|
+
renameSync(`${path}.tmp`, path);
|
|
158
|
+
return Promise.resolve();
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
if (key.kind === 'view')
|
|
162
|
+
return Wallet.watch({ network, viewKey: key.viewKey, persist });
|
|
163
|
+
if (!create && !existsSync(path)) {
|
|
164
|
+
const storage = await CanisterClient.connect(network.storage.host, network.storage.canisterId);
|
|
165
|
+
if (!(await storage.registration(hexToBytes(key.address))))
|
|
166
|
+
throw new Failure(`this recovery phrase has no account on ${network.name} (it would be ${accountId(key.address)}): ` +
|
|
167
|
+
'check the phrase, or make the account with `zerc20 new`');
|
|
168
|
+
}
|
|
169
|
+
const circuits = { ...network.circuits, joinsplit: await localCircuit(network.circuits.joinsplit, prove) };
|
|
170
|
+
return Wallet.open({
|
|
171
|
+
network: { ...network, circuits },
|
|
172
|
+
account: privateKeyToAccount(accountKey(key.seed)),
|
|
173
|
+
seed: key.seed,
|
|
174
|
+
persist,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
//# sourceMappingURL=account.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"account.js","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":"AAAA,iHAAiH;AACjH,oDAAoD;AAEpD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACjG,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,iBAA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,CAAC;IAC3G,OAAO,MAAM,CAAC,IAAI,CAAC;QACjB,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,QAAQ,EAAE;QACjC,OAAO,EAAE,mBAAmB,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAClD,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,OAAO;KACR,CAAC,CAAC;AACL,CAAC"}
|
package/dist/commands.js
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
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
|
+
import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { createInterface } from 'node:readline/promises';
|
|
5
|
+
import { entropyToMnemonic } from '@scure/bip39';
|
|
6
|
+
import { wordlist } from '@scure/bip39/wordlists/english.js';
|
|
7
|
+
import { WalletError, accountId, } from '@zerc20/wallet-sdk';
|
|
8
|
+
import { isAddress } from 'viem';
|
|
9
|
+
import { keyIn, loadNetwork, openAccount, readKey, seedKey, stateFile } from './account.js';
|
|
10
|
+
import { Failure, Usage, told } from './errors.js';
|
|
11
|
+
import { amount, chainName, chainNamed, csv, minute, parseAmount, short, table, tokensNamed, underlyingSymbol, until, } from './format.js';
|
|
12
|
+
/** Where a merge prover on this machine listens, unless told otherwise. */
|
|
13
|
+
export const LOCAL_PROVER = 'http://127.0.0.1:3006';
|
|
14
|
+
const say = (line) => process.stderr.write(`${line}\n`);
|
|
15
|
+
/** A command's answer: `data` as JSON where a program reads it, `human` otherwise. */
|
|
16
|
+
const answer = (flags, human, data) => process.stdout.write(`${flags.json ? JSON.stringify(data, null, 2) : human}\n`);
|
|
17
|
+
const quit = () => process.exit(130);
|
|
18
|
+
/** What Ctrl-C, or a terminal that closes, does now. */
|
|
19
|
+
let interrupt = quit;
|
|
20
|
+
export const onSignal = () => interrupt();
|
|
21
|
+
export const whenInterrupted = (f) => void (interrupt = f);
|
|
22
|
+
/** The wallet a command opened, for `close`. */
|
|
23
|
+
let opened;
|
|
24
|
+
/** Lets the wallet go once a command is done: a burn address being recorded ahead stops, rather than being cut off by
|
|
25
|
+
* the exit. It is not waited on for long, as nothing of the command's is left in it. */
|
|
26
|
+
export const close = () => Promise.race([opened?.close().catch(() => { }), new Promise((r) => setTimeout(r, 3000).unref())]);
|
|
27
|
+
/** `network` with its merges proved on this machine, by the prover at `url`. */
|
|
28
|
+
const provedHere = (network, url) => ({
|
|
29
|
+
...network,
|
|
30
|
+
mergeProver: { url, trust: { local: true } },
|
|
31
|
+
});
|
|
32
|
+
/** The network a command works on, with `--prover` its merges proved on this machine. */
|
|
33
|
+
function networkOf(flags) {
|
|
34
|
+
const network = loadNetwork(flags.network);
|
|
35
|
+
return flags.prover ? provedHere(network, flags.prover === 'local' ? LOCAL_PROVER : flags.prover) : network;
|
|
36
|
+
}
|
|
37
|
+
/** Where an account notes the prover of this machine that its merge under way is proved by. Every command's sync
|
|
38
|
+
* moves that merge on, and one that names no prover would hand the rest of it to the network's, which the merge's
|
|
39
|
+
* owner chose not to show it to. */
|
|
40
|
+
const proverNote = (network, key) => `${stateFile(network, key)}.prover`;
|
|
41
|
+
const KIND = { send: 'payment', withdraw: 'withdrawal', consolidate: 'merge', deposit: 'deposit' };
|
|
42
|
+
/** Opens the account of the key given. `seed` is for what a view key cannot do. An operation an earlier run left under
|
|
43
|
+
* way is named, as this run's syncs move it on: nothing is paid without a line saying so. */
|
|
44
|
+
async function open(flags, need, prove = false) {
|
|
45
|
+
let network = networkOf(flags);
|
|
46
|
+
const key = await readKey(flags['key-file']);
|
|
47
|
+
if (need === 'seed' && key.kind === 'view')
|
|
48
|
+
throw new Failure('a view key only watches its account: this takes the recovery phrase');
|
|
49
|
+
const note = proverNote(network, key);
|
|
50
|
+
if (!flags.prover && existsSync(note))
|
|
51
|
+
network = provedHere(network, readFileSync(note, 'utf8'));
|
|
52
|
+
const wallet = (opened = await openAccount(network, key, { prove }));
|
|
53
|
+
if (!wallet.operations().some((op) => op.kind === 'consolidate' && op.status === 'pending'))
|
|
54
|
+
rmSync(note, { force: true });
|
|
55
|
+
for (const op of wallet.operations()) {
|
|
56
|
+
if (op.status !== 'pending')
|
|
57
|
+
continue;
|
|
58
|
+
const [what, chain] = [KIND[op.kind], chainName(op.chainId)];
|
|
59
|
+
// in a block, an operation is only watched until it is final
|
|
60
|
+
if (op.txHashes.length > 0 && op.kind !== 'consolidate')
|
|
61
|
+
say(`An earlier ${what} on ${chain} is in a block, not final yet.`);
|
|
62
|
+
else
|
|
63
|
+
say(`Going on with a ${what} on ${chain} started earlier.`);
|
|
64
|
+
}
|
|
65
|
+
return { flags, network, key, wallet };
|
|
66
|
+
}
|
|
67
|
+
/** Catches up with the chains. One that cannot be read holds back only its own: the rest is still shown, with a
|
|
68
|
+
* warning, and with `whole` a status that says the answer is not all of it. What keeps an earlier operation from
|
|
69
|
+
* going on is said too, as nothing else of this command would show it. */
|
|
70
|
+
async function sync(s, whole) {
|
|
71
|
+
try {
|
|
72
|
+
await s.wallet.sync();
|
|
73
|
+
}
|
|
74
|
+
catch (e) {
|
|
75
|
+
say(`Not all of it could be read: ${e instanceof Error ? told(e) : String(e)}`);
|
|
76
|
+
if (whole)
|
|
77
|
+
process.exitCode = 1;
|
|
78
|
+
}
|
|
79
|
+
for (const op of s.wallet.operations()) {
|
|
80
|
+
if (op.status === 'pending' && op.retrying)
|
|
81
|
+
say(`The ${KIND[op.kind]} on ${chainName(op.chainId)} is held up: ${op.retrying.message}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const spendable = (s, token) => s.wallet.balances().find((b) => b.token === token)?.spendable ?? 0n;
|
|
85
|
+
/** The token `symbol` names. On several chains with no `--chain`, the one that holds `need` of it spendable, if only
|
|
86
|
+
* one does: a payment names its chain by where the funds are. */
|
|
87
|
+
function tokenOf(s, symbol, need) {
|
|
88
|
+
if (!symbol)
|
|
89
|
+
throw new Usage('name a token');
|
|
90
|
+
const chain = s.flags.chain ? chainNamed(s.network, s.flags.chain) : undefined;
|
|
91
|
+
const named = tokensNamed(s.network, s.wallet.tokens(), symbol, chain);
|
|
92
|
+
if (named.length === 0) {
|
|
93
|
+
const known = [...new Set(s.wallet.tokens().map((t) => t.symbol))].join(', ');
|
|
94
|
+
throw new Failure(`no token ${symbol}${chain ? ` on ${chainName(chain.chainId)}` : ''}: there is ${known}`);
|
|
95
|
+
}
|
|
96
|
+
if (named.length === 1)
|
|
97
|
+
return named[0];
|
|
98
|
+
const holding = need ? named.filter((t) => spendable(s, t) >= need(t)) : [];
|
|
99
|
+
if (holding.length === 1)
|
|
100
|
+
return holding[0];
|
|
101
|
+
const rows = named.map((t) => [` ${chainName(t.chainId)}`, `${amount(spendable(s, t), t)} spendable`]);
|
|
102
|
+
throw new Usage(`${symbol} is on several chains: name one with --chain\n${table(['', ''], rows).trimStart()}`);
|
|
103
|
+
}
|
|
104
|
+
/** Asks before anything is paid. Where no one can answer, only `--yes` pays: a script never pays by accident. The
|
|
105
|
+
* question is still shown there, as it tells a program what it would pay, fee included, before it passes `--yes`. */
|
|
106
|
+
async function confirm(flags, question) {
|
|
107
|
+
if (flags.yes)
|
|
108
|
+
return;
|
|
109
|
+
if (!process.stdin.isTTY) {
|
|
110
|
+
say(question);
|
|
111
|
+
throw new Usage('no terminal to confirm on: pass --yes to pay without being asked');
|
|
112
|
+
}
|
|
113
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
114
|
+
// a terminal's Ctrl-C reaches the question, not the process
|
|
115
|
+
rl.on('SIGINT', onSignal);
|
|
116
|
+
const reply = await rl.question(`${question} [y/N] `);
|
|
117
|
+
rl.close();
|
|
118
|
+
if (!/^y(es)?$/i.test(reply.trim()))
|
|
119
|
+
throw new Failure('Nothing was paid.');
|
|
120
|
+
}
|
|
121
|
+
/** The most the fees may come to: the quote just shown, or `--max-fee`, which a higher quote fails. */
|
|
122
|
+
function feeCap(flags, token, quote) {
|
|
123
|
+
if (!flags['max-fee'])
|
|
124
|
+
return quote.fee;
|
|
125
|
+
const cap = parseAmount(flags['max-fee'], token.decimals);
|
|
126
|
+
if (quote.fee > cap)
|
|
127
|
+
throw new Failure(`the fee is ${amount(quote.fee, token)} ${token.symbol}, above --max-fee`);
|
|
128
|
+
return cap;
|
|
129
|
+
}
|
|
130
|
+
/** What an operation is waiting on, from the stage it reached last. */
|
|
131
|
+
function doing(op) {
|
|
132
|
+
if (op.kind === 'consolidate') {
|
|
133
|
+
const merge = {
|
|
134
|
+
planned: 'Writing its note…',
|
|
135
|
+
noted: 'Asking the attester…',
|
|
136
|
+
attested: 'Sending it to the merge prover…',
|
|
137
|
+
proving: 'The merge prover is proving it: minutes…',
|
|
138
|
+
proved: 'Relaying…',
|
|
139
|
+
relayed: 'Waiting for its block…',
|
|
140
|
+
};
|
|
141
|
+
return op.stage ? merge[op.stage] : 'Waiting for a proved root over the last merge…';
|
|
142
|
+
}
|
|
143
|
+
const payment = {
|
|
144
|
+
planned: 'Writing its notes…',
|
|
145
|
+
noted: 'Proving…',
|
|
146
|
+
proved: 'Asking the attester…',
|
|
147
|
+
attested: 'Relaying…',
|
|
148
|
+
proving: '',
|
|
149
|
+
relayed: 'Waiting for its block…',
|
|
150
|
+
};
|
|
151
|
+
return op.stage ? payment[op.stage] : '';
|
|
152
|
+
}
|
|
153
|
+
/** Waits until `op` is in a block, saying what it waits on. Ctrl-C cancels it while it has paid nothing and asked the
|
|
154
|
+
* relayer nothing; past that it can only finish, now or the next time the account is opened. */
|
|
155
|
+
async function follow(flags, op) {
|
|
156
|
+
let told = '';
|
|
157
|
+
const tell = () => {
|
|
158
|
+
const now = op.retrying ? `Trying again: ${op.retrying.message}` : doing(op);
|
|
159
|
+
if (now && now !== told)
|
|
160
|
+
say((told = now));
|
|
161
|
+
};
|
|
162
|
+
const timer = setInterval(tell, 300);
|
|
163
|
+
interrupt = () => {
|
|
164
|
+
interrupt = quit;
|
|
165
|
+
const left = `The ${KIND[op.kind]} is under way: it goes on whenever this account is opened.`;
|
|
166
|
+
if (!op.cancellable) {
|
|
167
|
+
say(left);
|
|
168
|
+
return quit();
|
|
169
|
+
}
|
|
170
|
+
op.cancel()
|
|
171
|
+
.then(() => say('Cancelled: nothing was paid.'), () => say(left))
|
|
172
|
+
.finally(quit);
|
|
173
|
+
};
|
|
174
|
+
try {
|
|
175
|
+
await op.wait();
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
clearInterval(timer);
|
|
179
|
+
interrupt = quit;
|
|
180
|
+
}
|
|
181
|
+
say('In a block. What it left the account is spendable again in some minutes, under a proved root.');
|
|
182
|
+
answer(flags, op.txHashes.join('\n'), { kind: KIND[op.kind], chainId: String(op.chainId), txHashes: op.txHashes });
|
|
183
|
+
}
|
|
184
|
+
const NOT_YET = {
|
|
185
|
+
incoming: 'arriving',
|
|
186
|
+
'awaiting-root': 'settling',
|
|
187
|
+
'roots-halted': 'halted',
|
|
188
|
+
screening: 'screening',
|
|
189
|
+
};
|
|
190
|
+
export async function balance(flags) {
|
|
191
|
+
const s = await open(flags, 'any');
|
|
192
|
+
await sync(s, true);
|
|
193
|
+
const held = s.wallet.balances().filter((b) => b.spendable > 0n || b.pending.length > 0 || b.blocked > 0n);
|
|
194
|
+
const id = accountId(s.wallet.address);
|
|
195
|
+
const rows = held.map((b) => {
|
|
196
|
+
const waiting = new Map();
|
|
197
|
+
for (const p of b.pending)
|
|
198
|
+
waiting.set(NOT_YET[p.reason], (waiting.get(NOT_YET[p.reason]) ?? 0n) + p.amount);
|
|
199
|
+
if (b.blocked > 0n)
|
|
200
|
+
waiting.set('blocked', b.blocked);
|
|
201
|
+
const notYet = [...waiting].map(([why, v]) => `${amount(v, b.token)} ${why}`).join(', ');
|
|
202
|
+
return [b.token.symbol, chainName(b.token.chainId), amount(b.spendable, b.token), notYet];
|
|
203
|
+
});
|
|
204
|
+
const nothing = s.key.kind === 'seed' ? 'Nothing yet: `zerc20 deposit <token>` gives an address to pay in.' : 'Nothing yet.';
|
|
205
|
+
answer(flags, `${id} ${s.network.name}\n\n${rows.length ? table(['TOKEN', 'CHAIN', 'SPENDABLE', 'NOT YET'], rows, [2]) : nothing}`, {
|
|
206
|
+
id,
|
|
207
|
+
address: s.wallet.address,
|
|
208
|
+
network: s.network.name,
|
|
209
|
+
balances: held.map((b) => ({
|
|
210
|
+
token: b.token.symbol,
|
|
211
|
+
chain: chainName(b.token.chainId),
|
|
212
|
+
chainId: String(b.token.chainId),
|
|
213
|
+
spendable: amount(b.spendable, b.token),
|
|
214
|
+
pending: b.pending.map((p) => ({ amount: amount(p.amount, b.token), reason: p.reason })),
|
|
215
|
+
blocked: amount(b.blocked, b.token),
|
|
216
|
+
})),
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
/** `f` over `items`, a few at a time. */
|
|
220
|
+
async function each(items, f) {
|
|
221
|
+
const out = new Array(items.length);
|
|
222
|
+
let next = 0;
|
|
223
|
+
const worker = async () => {
|
|
224
|
+
while (next < items.length) {
|
|
225
|
+
const i = next++;
|
|
226
|
+
out[i] = await f(items[i]);
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
await Promise.all(Array.from({ length: 4 }, worker));
|
|
230
|
+
return out;
|
|
231
|
+
}
|
|
232
|
+
/** Whom an activity was with, as its owner would name them: an account by its zERC20 ID, anyone else by address. */
|
|
233
|
+
function counterparty(a) {
|
|
234
|
+
if (a.via && 'code' in a.via)
|
|
235
|
+
return a.via.code;
|
|
236
|
+
if (!a.counterparty)
|
|
237
|
+
return '';
|
|
238
|
+
return a.kind === 'sent' || (a.kind === 'received' && !a.burnAddress) ? accountId(a.counterparty) : a.counterparty;
|
|
239
|
+
}
|
|
240
|
+
/** What `history` tells of each activity, as a CSV's columns. */
|
|
241
|
+
const FIELDS = [
|
|
242
|
+
'time',
|
|
243
|
+
'kind',
|
|
244
|
+
'status',
|
|
245
|
+
'amount',
|
|
246
|
+
'token',
|
|
247
|
+
'chain',
|
|
248
|
+
'chainId',
|
|
249
|
+
'fee',
|
|
250
|
+
'counterparty',
|
|
251
|
+
'depositAddress',
|
|
252
|
+
'coin',
|
|
253
|
+
'tx',
|
|
254
|
+
];
|
|
255
|
+
export async function history(flags) {
|
|
256
|
+
const s = await open(flags, 'any');
|
|
257
|
+
await sync(s, true);
|
|
258
|
+
if (s.key.kind === 'view')
|
|
259
|
+
say('A view key does not show payments to the account’s receive codes.');
|
|
260
|
+
const activity = s.wallet.activity();
|
|
261
|
+
// a sync reads no transaction: each is looked up, a few reads of its chain
|
|
262
|
+
const txs = flags.tx ? await each(activity, (a) => s.wallet.transaction(a).catch(() => null)) : [];
|
|
263
|
+
const entries = activity.map((a, i) => ({
|
|
264
|
+
time: (txs[i]?.at ?? a.at)?.toISOString() ?? '',
|
|
265
|
+
kind: a.kind,
|
|
266
|
+
status: a.status,
|
|
267
|
+
amount: amount(a.amount, a.token),
|
|
268
|
+
token: a.token.symbol,
|
|
269
|
+
chain: chainName(a.token.chainId),
|
|
270
|
+
chainId: String(a.token.chainId),
|
|
271
|
+
fee: a.fee === null ? '' : amount(a.fee, a.token),
|
|
272
|
+
counterparty: counterparty(a),
|
|
273
|
+
depositAddress: a.via && 'depositAddress' in a.via ? a.via.depositAddress : '',
|
|
274
|
+
coin: a.coin ?? '',
|
|
275
|
+
tx: txs[i]?.hash ?? a.txHash ?? '',
|
|
276
|
+
}));
|
|
277
|
+
if (flags.json)
|
|
278
|
+
return void answer(flags, '', entries);
|
|
279
|
+
if (flags.csv) {
|
|
280
|
+
return void process.stdout.write(`${csv([[...FIELDS], ...entries.map((e) => FIELDS.map((f) => e[f]))])}\n`);
|
|
281
|
+
}
|
|
282
|
+
const rows = entries.map((e) => [
|
|
283
|
+
minute(e.time ? new Date(e.time) : null),
|
|
284
|
+
e.status === 'failed' ? `${e.kind} (failed)` : e.kind,
|
|
285
|
+
e.amount,
|
|
286
|
+
e.token,
|
|
287
|
+
e.chain,
|
|
288
|
+
short(e.counterparty),
|
|
289
|
+
e.fee,
|
|
290
|
+
...(flags.tx ? [e.tx] : []),
|
|
291
|
+
]);
|
|
292
|
+
const head = ['TIME (UTC)', 'KIND', 'AMOUNT', 'TOKEN', 'CHAIN', 'WITH', 'FEE', ...(flags.tx ? ['TRANSACTION'] : [])];
|
|
293
|
+
answer(flags, rows.length ? table(head, rows, [2, 6]) : 'Nothing yet.', entries);
|
|
294
|
+
}
|
|
295
|
+
export async function coins(flags) {
|
|
296
|
+
const s = await open(flags, 'any');
|
|
297
|
+
await sync(s, true);
|
|
298
|
+
const all = s.wallet.coins();
|
|
299
|
+
const state = (c) => c.state === 'spendable' || c.state === 'spending' || c.state === 'blocked' ? c.state : NOT_YET[c.state];
|
|
300
|
+
const rows = all.map((c) => [
|
|
301
|
+
c.id,
|
|
302
|
+
c.kind,
|
|
303
|
+
c.token.symbol,
|
|
304
|
+
chainName(c.token.chainId),
|
|
305
|
+
amount(c.amount, c.token),
|
|
306
|
+
c.readyBy ? `${state(c)} ${until(c.readyBy)}` : state(c),
|
|
307
|
+
]);
|
|
308
|
+
answer(flags, rows.length ? table(['COIN', 'KIND', 'TOKEN', 'CHAIN', 'AMOUNT', 'STATE'], rows, [4]) : 'Nothing yet.', all.map((c) => ({
|
|
309
|
+
id: c.id,
|
|
310
|
+
kind: c.kind,
|
|
311
|
+
token: c.token.symbol,
|
|
312
|
+
chain: chainName(c.token.chainId),
|
|
313
|
+
chainId: String(c.token.chainId),
|
|
314
|
+
amount: amount(c.amount, c.token),
|
|
315
|
+
state: c.state,
|
|
316
|
+
readyBy: c.readyBy?.toISOString() ?? null,
|
|
317
|
+
})));
|
|
318
|
+
}
|
|
319
|
+
export async function receive(flags, [symbol]) {
|
|
320
|
+
if (!symbol) {
|
|
321
|
+
// the account's address under another spelling: the key alone gives it
|
|
322
|
+
const key = await readKey(flags['key-file']);
|
|
323
|
+
return void answer(flags, accountId(key.address), { id: accountId(key.address), address: key.address });
|
|
324
|
+
}
|
|
325
|
+
const s = await open(flags, 'seed');
|
|
326
|
+
const token = tokenOf(s, symbol);
|
|
327
|
+
const code = await s.wallet.receiveCode(token);
|
|
328
|
+
say(`Whoever has this code pays ${token.symbol} on ${chainName(token.chainId)} into the account, and no view key shows it.`);
|
|
329
|
+
answer(flags, code, { code, token: token.symbol, chain: chainName(token.chainId), chainId: String(token.chainId) });
|
|
330
|
+
}
|
|
331
|
+
export async function deposit(flags, [symbol]) {
|
|
332
|
+
const s = await open(flags, 'seed');
|
|
333
|
+
const token = tokenOf(s, symbol);
|
|
334
|
+
const { address, fee } = await s.wallet.depositAddress(token);
|
|
335
|
+
const [asset, chain] = [underlyingSymbol(s.network, token), chainName(token.chainId)];
|
|
336
|
+
const watchedUntil = new Date(Date.now() + 7 * 24 * 3600 * 1000);
|
|
337
|
+
say(`Send ${asset} on ${chain} to this address, from anywhere. On ${chain} only: sent on another chain, it is lost.`);
|
|
338
|
+
say(`Each payment pays ${amount(fee, token)} ${asset} to the deposit relayer, and has to be more than that. ` +
|
|
339
|
+
`Watched until ${watchedUntil.toISOString().slice(0, 10)}.`);
|
|
340
|
+
answer(flags, address, {
|
|
341
|
+
address,
|
|
342
|
+
asset,
|
|
343
|
+
chain,
|
|
344
|
+
chainId: String(token.chainId),
|
|
345
|
+
fee: amount(fee, token),
|
|
346
|
+
watchedUntil: watchedUntil.toISOString(),
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
/** Why `token` cannot pay what was asked, in its own units, where `e` is the wallet saying so in base units. */
|
|
350
|
+
function shortfall(s, token, e) {
|
|
351
|
+
if (!(e instanceof WalletError) || (e.code !== 'funds-settling' && e.code !== 'insufficient-funds'))
|
|
352
|
+
return e;
|
|
353
|
+
const has = `${amount(spendable(s, token), token)} ${token.symbol} on ${chainName(token.chainId)} is spendable`;
|
|
354
|
+
if (e.code === 'insufficient-funds')
|
|
355
|
+
return new Failure(`not enough to pay that and its fee: ${has}`);
|
|
356
|
+
const when = e.waitsOn?.readyBy ? `, which should do in ${until(e.waitsOn.readyBy)}` : '';
|
|
357
|
+
return new Failure(`not enough is spendable yet: ${has}, and the rest is settling${when}`);
|
|
358
|
+
}
|
|
359
|
+
/** A send or a withdrawal: both pay `amount` out of what is spendable, with the fees on top. */
|
|
360
|
+
async function pay(flags, kind, [typed, symbol, to]) {
|
|
361
|
+
if (!typed || !symbol || !to)
|
|
362
|
+
throw new Usage(`zerc20 ${kind} <amount|max> <token> <to>`);
|
|
363
|
+
if (kind === 'withdraw' && !isAddress(to))
|
|
364
|
+
throw new Usage(`${to} is not an address`);
|
|
365
|
+
const s = await open(flags, 'seed', true);
|
|
366
|
+
await sync(s, false);
|
|
367
|
+
const max = typed === 'max';
|
|
368
|
+
// With --yes no one reads which chain was found to pay, and what is paid to an address on a chain its owner does
|
|
369
|
+
// not watch there may be lost: a withdrawal no one confirms names its chain.
|
|
370
|
+
const found = kind === 'withdraw' && flags.yes ? undefined : (t) => (max ? 1n : parseAmount(typed, t.decimals));
|
|
371
|
+
const token = tokenOf(s, symbol, found);
|
|
372
|
+
const chain = chainName(token.chainId);
|
|
373
|
+
let value;
|
|
374
|
+
if (max) {
|
|
375
|
+
const most = await s.wallet.maxAmount({ kind, token });
|
|
376
|
+
if (most.merges > 0)
|
|
377
|
+
throw new Failure(`its coins are too scattered to pay it all at once: \`zerc20 merge ${token.symbol}\` first`);
|
|
378
|
+
if (most.amount === 0n)
|
|
379
|
+
throw new Failure(`no ${token.symbol} on ${chain} is left to pay once the fee is taken`);
|
|
380
|
+
value = most.amount;
|
|
381
|
+
}
|
|
382
|
+
else
|
|
383
|
+
value = parseAmount(typed, token.decimals);
|
|
384
|
+
const quote = await s.wallet.fees({ kind, token, amount: value }).catch((e) => {
|
|
385
|
+
throw shortfall(s, token, e);
|
|
386
|
+
});
|
|
387
|
+
const maxFee = feeCap(flags, token, quote);
|
|
388
|
+
const fee = `fee ${amount(quote.fee, token)} ${token.symbol}`;
|
|
389
|
+
if (kind === 'send') {
|
|
390
|
+
await confirm(flags, `Send ${amount(value, token)} ${token.symbol} on ${chain} to ${short(to)}, ${fee}?`);
|
|
391
|
+
return follow(flags, await s.wallet.send({ to, token, amount: value, maxFee }));
|
|
392
|
+
}
|
|
393
|
+
// a public address most often expects the asset itself: the zERC20 token is paid out only when asked for
|
|
394
|
+
const paid = flags.wrapped ? `${token.symbol} (the zERC20 token itself)` : underlyingSymbol(s.network, token);
|
|
395
|
+
await confirm(flags, `Withdraw ${amount(value, token)} ${paid} on ${chain} to ${to}, in public, ${fee}?`);
|
|
396
|
+
const address = to; // checked before the wallet opened
|
|
397
|
+
return follow(flags, await s.wallet.withdraw({ to: address, token, amount: value, maxFee, unwrap: !flags.wrapped }));
|
|
398
|
+
}
|
|
399
|
+
export const send = (flags, args) => pay(flags, 'send', args);
|
|
400
|
+
export const withdraw = (flags, args) => pay(flags, 'withdraw', args);
|
|
401
|
+
export async function merge(flags, [symbol]) {
|
|
402
|
+
const s = await open(flags, 'seed');
|
|
403
|
+
await sync(s, false);
|
|
404
|
+
const token = tokenOf(s, symbol, () => 1n);
|
|
405
|
+
const chain = chainName(token.chainId);
|
|
406
|
+
const first = await s.wallet.nextMerge(token);
|
|
407
|
+
if (!first) {
|
|
408
|
+
say(`Nothing to merge: ${token.symbol} on ${chain} is in one note, or none of it is spendable.`);
|
|
409
|
+
if (flags.json)
|
|
410
|
+
answer(flags, '', { kind: KIND.consolidate, chainId: String(token.chainId), txHashes: [] });
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
const quote = await s.wallet.fees({ kind: 'consolidate', token });
|
|
414
|
+
const maxFee = feeCap(flags, token, quote);
|
|
415
|
+
const prover = s.network.mergeProver;
|
|
416
|
+
const here = prover && 'local' in prover.trust;
|
|
417
|
+
if (here) {
|
|
418
|
+
const ready = await fetch(`${prover.url}/status`)
|
|
419
|
+
.then((r) => r.json())
|
|
420
|
+
.catch(() => null);
|
|
421
|
+
if (!ready?.mergeKey)
|
|
422
|
+
throw new Failure(`no merge prover is ready at ${prover.url}: run \`zerc20 prover start\` and wait for it`);
|
|
423
|
+
}
|
|
424
|
+
const by = here ? `the prover on this machine` : `the network's merge prover`;
|
|
425
|
+
const merges = quote.steps === 1 ? 'one merge' : `${quote.steps} merges`;
|
|
426
|
+
await confirm(flags, `Merge ${token.symbol} on ${chain} into one note, in ${merges} that ${by} proves, ` +
|
|
427
|
+
`fee ${amount(quote.fee, token)} ${token.symbol}?`);
|
|
428
|
+
if (here)
|
|
429
|
+
writeFileSync(proverNote(s.network, s.key), prover.url);
|
|
430
|
+
return follow(flags, await s.wallet.consolidate({ token, maxFee }));
|
|
431
|
+
}
|
|
432
|
+
export async function viewKey(flags) {
|
|
433
|
+
const s = await open(flags, 'seed');
|
|
434
|
+
say(`Whoever has this key sees what the account holds and did on ${s.network.name}, and can spend none of it.`);
|
|
435
|
+
answer(flags, s.wallet.viewKey(), { viewKey: s.wallet.viewKey(), network: s.network.name });
|
|
436
|
+
}
|
|
437
|
+
/** Makes an account: of a fresh recovery phrase, or of the one in `--key-file`, which registers an account whose
|
|
438
|
+
* phrase was made elsewhere. `ZERC20_KEY` is not looked at: a shell that still exports another account's key would
|
|
439
|
+
* be answered with that account, in place of a new one. The phrase is printed once the account exists, and nowhere
|
|
440
|
+
* kept. */
|
|
441
|
+
export async function create(flags) {
|
|
442
|
+
const network = networkOf(flags);
|
|
443
|
+
const given = flags['key-file'] ? keyIn(flags['key-file']) : null;
|
|
444
|
+
if (given?.kind === 'view')
|
|
445
|
+
throw new Failure('a view key watches an account: it makes none');
|
|
446
|
+
const key = given ?? seedKey(crypto.getRandomValues(new Uint8Array(32)));
|
|
447
|
+
opened = await openAccount(network, key, { create: true });
|
|
448
|
+
const [id, phrase] = [accountId(key.address), entropyToMnemonic(key.seed, wordlist)];
|
|
449
|
+
say(`${id} is on ${network.name}.`);
|
|
450
|
+
if (!given)
|
|
451
|
+
say('These 24 words are its only key, and are shown this once: keep them where nothing else reads them.');
|
|
452
|
+
answer(flags, given ? id : phrase, { id, address: key.address, network: network.name, ...(given ? {} : { phrase }) });
|
|
453
|
+
}
|
|
454
|
+
//# sourceMappingURL=commands.js.map
|