-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
cli.ts
990 lines (809 loc) · 33.7 KB
/
cli.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
"use strict";
import fs from "fs";
import { basename } from "path";
import { ethers } from "ethers";
import * as scrypt from "scrypt-js";
import { getChoice, getPassword, getProgressBar } from "./prompt";
import { version } from "./_version";
const logger = new ethers.utils.Logger(version);
class UsageError extends Error { }
/////////////////////////////
// Signer
/*
const signerStates = new WeakMap();
class SignerState {
signerFunc: () => Promise<ethers.Signer>;
signer: ethers.Signer;
alwaysAllow: boolean;
static get(wrapper: WrappedSigner): SignerState {
return signerStates.get(wrapper);
}
}
*/
const signerFuncs = new WeakMap();
const signers = new WeakMap();
const alwaysAllow = new WeakMap();
// Gets a signer or lazily request it if needed, possibly asking for a password
// to decrypt a JSON wallet
async function getSigner(wrapper: WrappedSigner): Promise<ethers.Signer> {
if (!signers.has(wrapper)) {
let signerFunc: () => Promise<ethers.Signer> = signerFuncs.get(wrapper);
let signer = await signerFunc();
signers.set(wrapper, signer);
}
return signers.get(wrapper);
}
// Throws an error if the user does not allow the operation. If "y" is
// selected, all future operations of that type are automatically accepted
async function isAllowed(wrapper: WrappedSigner, message: string): Promise<boolean> {
if (wrapper.plugin.yes) {
console.log(message + " (--yes => \"y\")");
return true;
}
let allowed = alwaysAllow.get(wrapper) || { };
if (allowed[message]) {
console.log(message + " (previous (a)ll => \"y\")");
return true;
}
try {
let allow = await getChoice(message, "yna", "n");
if (allow === "a") {
allowed[message] = true;
alwaysAllow.set(wrapper, allowed);
} else if (allow === "n") {
throw new Error("Cancelled.");
}
} catch (error) {
throw new Error("Cancelled.");
}
return true;
}
function repeat(chr: string, length: number): string {
let result = chr;
while (result.length < length) { result += result; }
return result.substring(0, length);
}
// @TODO: Make dump recursable for objects
// Dumps key/value pairs in a nice format
export function dump(header: string, info: any): void {
console.log(header);
let maxLength = Object.keys(info).reduce((maxLength, i) => Math.max(maxLength, i.length), 0);
for (let key in info) {
let value = info[key];
if (Array.isArray(value)) {
console.log(" " + key + ":");
value.forEach((value) => {
console.log(" " + value);
});
} else {
console.log(" " + key + ":" + repeat(" ", maxLength - key.length) + " " + info[key]);
}
}
}
// This wraps our signers to prevent the private keys and mnemonics from being exposed.
// It is also in charge of user-interaction, requesting permission before signing or
// sending.
class WrappedSigner extends ethers.Signer {
readonly addressPromise: Promise<string>;
readonly provider: ethers.providers.Provider;
readonly plugin: Plugin;
constructor(addressPromise: Promise<string>, signerFunc: () => Promise<ethers.Signer>, plugin: Plugin) {
super();
signerFuncs.set(this, signerFunc);
ethers.utils.defineReadOnly(this, "addressPromise", addressPromise);
ethers.utils.defineReadOnly(this, "provider", plugin.provider);
ethers.utils.defineReadOnly(this, "plugin", plugin);
}
connect(provider?: ethers.providers.Provider): ethers.Signer {
throw new Error("unsupported for now...");
//return new WrappedSigner(this.addressPromise, () => getSigner(this).then((s) => s.connect(provider)), provider);
}
async getAddress(): Promise<string> {
return this.addressPromise;
}
async signMessage(message: string | ethers.utils.Bytes): Promise<string> {
let signer = await getSigner(this);
let info: any = { };
if (typeof(message) === "string") {
info["Message"] = JSON.stringify(message);
info["Message (hex)"] = ethers.utils.hexlify(ethers.utils.toUtf8Bytes(message));
} else {
let bytes = ethers.utils.arrayify(message);
for (let i = 0; i < bytes.length; i++) {
let c = bytes[i];
if (c < 32 || c > 126) {
bytes = null;
break;
}
}
if (bytes) {
info["Message"] = ethers.utils.toUtf8String(bytes);
}
info["Message (hex)"] = ethers.utils.hexlify(message);
}
dump("Message:", info);
await isAllowed(this, "Sign Message?");
let result = await signer.signMessage(message)
let signature = ethers.utils.splitSignature(result);
dump("Signature", {
Flat: result,
r: signature.r,
s: signature.s,
vs: signature._vs,
v: signature.v,
recid: signature.recoveryParam,
});
return result;
}
async populateTransaction(transactionRequest: ethers.providers.TransactionRequest): Promise<ethers.providers.TransactionRequest> {
transactionRequest = ethers.utils.shallowCopy(transactionRequest);
if (this.plugin.gasPrice != null) {
transactionRequest.gasPrice = this.plugin.gasPrice;
}
if (this.plugin.gasLimit != null) {
transactionRequest.gasLimit = this.plugin.gasLimit;
}
if (this.plugin.nonce != null) {
transactionRequest.nonce = this.plugin.nonce;
}
let signer = await getSigner(this);
return signer.populateTransaction(transactionRequest);
}
async signTransaction(transactionRequest: ethers.providers.TransactionRequest): Promise<string> {
let signer = await getSigner(this);
let network = await this.provider.getNetwork();
let tx = await ethers.utils.resolveProperties(transactionRequest);
let info: any = { };
if (tx.to != null) { info["To"] = tx.to; }
if (tx.from != null) { info["From"] = tx.from; }
info["Value"] = (ethers.utils.formatEther(tx.value || 0) + " ether");
if (tx.nonce != null) { info["Nonce"] = tx.nonce; }
info["Data"] = tx.data;
info["Gas Limit"] = ethers.BigNumber.from(tx.gasLimit || 0).toString();
info["Gas Price"] = (ethers.utils.formatUnits(tx.gasPrice || 0, "gwei") + " gwei"),
info["Chain ID"] = (tx.chainId || 0);
info["Network"] = network.name;
dump("Transaction:", info);
await isAllowed(this, "Sign Transaction?");
let result = await signer.signTransaction(transactionRequest);
let signature = ethers.utils.splitSignature(result);
dump("Signature:", {
Signature: result,
r: signature.r,
s: signature.s,
vs: signature._vs,
v: signature.v,
recid: signature.recoveryParam,
});
return result;
}
async sendTransaction(transactionRequest: ethers.providers.TransactionRequest): Promise<ethers.providers.TransactionResponse> {
let signer = await getSigner(this);
let network = await this.provider.getNetwork();
let tx: any = await this.populateTransaction(transactionRequest);
tx = await ethers.utils.resolveProperties(tx);
let info: any = { };
if (tx.to != null) { info["To"] = tx.to; }
if (tx.from != null) { info["From"] = tx.from; }
info["Value"] = (ethers.utils.formatEther(tx.value || 0) + " ether");
if (tx.nonce != null) { info["Nonce"] = tx.nonce; }
info["Data"] = tx.data;
info["Gas Limit"] = ethers.BigNumber.from(tx.gasLimit || 0).toString();
info["Gas Price"] = (ethers.utils.formatUnits(tx.gasPrice || 0, "gwei") + " gwei"),
info["Chain ID"] = (tx.chainId || 0);
info["Network"] = network.name;
dump("Transaction:", info);
await isAllowed(this, "Send Transaction?");
let response = await signer.sendTransaction(tx);
dump("Response:", {
"Hash": response.hash
});
if (this.plugin.wait) {
try {
let receipt = await response.wait();
dump("Success:", {
"Block Number": receipt.blockNumber,
"Block Hash": receipt.blockHash,
"Gas Used": ethers.utils.commify(receipt.gasUsed.toString()),
"Fee": (ethers.utils.formatEther(receipt.gasUsed.mul(tx.gasPrice)) + " ether")
});
} catch (error) {
dump("Failed:", {
"Error": error.message
});
}
}
return response;
}
async unlock(): Promise<void> {
await getSigner(this);
}
}
class OfflineProvider extends ethers.providers.BaseProvider {
perform(method: string, params: any): Promise<any> {
if (method === "sendTransaction") {
console.log("Signed Transaction:");
console.log(params.signedTransaction);
return Promise.resolve(ethers.utils.keccak256(params.signedTransaction));
}
return super.perform(method, params);
}
}
/////////////////////////////
// Argument Parser
export class ArgParser {
readonly _args: Array<string>
readonly _consumed: Array<boolean>
constructor(args: Array<string>) {
ethers.utils.defineReadOnly(this, "_args", args);
ethers.utils.defineReadOnly(this, "_consumed", args.map((a) => false));
}
_finalizeArgs(): Array<string> {
let args = [ ];
for (let i = 0; i < this._args.length; i++) {
if (this._consumed[i]) { continue; }
let arg = this._args[i];
// Escaped args, add the rest as args
if (arg === "--") {
for (let j = i + 1; j < this._args.length; j++) {
args.push(this._args[j]);
}
break;
}
if (arg.substring(0, 2) === "--") {
throw new UsageError(`unexpected option ${arg}`);
}
args.push(arg);
}
return args;
}
_checkCommandIndex() {
for (let i = 0; i < this._args.length; i++) {
if (this._consumed[i]) { continue; }
return i;
}
return -1;
}
consumeFlag(name: string): boolean {
let count = 0;
for (let i = 0; i < this._args.length; i++) {
let arg = this._args[i];
if (arg === "--") { break; }
if (arg === ("--" + name)) {
count++;
this._consumed[i] = true;
}
}
if (count > 1) {
throw new UsageError("expected at most one --${name}");
}
return (count === 1);
}
consumeMultiOptions(names: Array<string>): Array<{ name: string, value: string }> {
let result: Array<{ name: string, value: string }> = [ ];
if (typeof(names) === "string") { names = [ names ]; }
for (let i = 0; i < this._args.length; i++) {
let arg = this._args[i];
if (arg === "--") { break; }
if (arg.substring(0, 2) === "--") {
let name = arg.substring(2);
let index = names.indexOf(name);
if (index < 0) { continue; }
if (this._args.length === i) {
throw new UsageError("missing argument for --${name}");
}
this._consumed[i] = true;
result.push({ name: name, value: this._args[++i] });
this._consumed[i] = true;
}
}
return result;
}
consumeOptions(name: string): Array<string> {
return this.consumeMultiOptions([ name ]).map((o) => o.value);
}
consumeOption(name: string): string {
let options = this.consumeOptions(name);
if (options.length > 1) {
throw new UsageError(`expected at most one --${name}`);
}
return (options.length ? options[0]: null);
}
}
// Accepts:
// - "-" which indicates to read from the terminal using prompt (which can then be any of the below)
// - JSON Wallet filename (which will require a password to unlock)
// - raw private key
// - mnemonic
async function loadAccount(arg: string, plugin: Plugin, preventFile?: boolean): Promise<WrappedSigner> {
// Secure entry; use prompt with mask
if (arg === "-") {
const content = await getPassword("Private Key / Mnemonic:");
return loadAccount(content, plugin, true);
}
// Raw private key
if (ethers.utils.isHexString(arg, 32)) {
const signer = new ethers.Wallet(arg, plugin.provider);
return Promise.resolve(new WrappedSigner(signer.getAddress(), () => Promise.resolve(signer), plugin));
}
// Mnemonic
if (ethers.utils.isValidMnemonic(arg)) {
const mnemonic = arg;
let signerPromise: Promise<ethers.Wallet> = null;
if (plugin.mnemonicPassword) {
signerPromise = getPassword("Password (mnemonic): ").then((password) => {
let node = ethers.utils.HDNode.fromMnemonic(mnemonic, password).derivePath(ethers.utils.defaultPath);
return new ethers.Wallet(node.privateKey, plugin.provider);
});
} else if (plugin._xxxMnemonicPasswordHard) {
signerPromise = getPassword("Password (mnemonic; experimental - hard): ").then((password) => {
let passwordBytes = ethers.utils.toUtf8Bytes(password, ethers.utils.UnicodeNormalizationForm.NFKC);
let saltBytes = ethers.utils.arrayify(ethers.utils.HDNode.fromMnemonic(mnemonic).privateKey);
let progressBar = getProgressBar("Decrypting");
return scrypt.scrypt(passwordBytes, saltBytes, (1 << 20), 8, 1, 32, progressBar).then((key) => {
const derivedPassword = ethers.utils.hexlify(key).substring(2);
const node = ethers.utils.HDNode.fromMnemonic(mnemonic, derivedPassword).derivePath(ethers.utils.defaultPath);
return new ethers.Wallet(node.privateKey, plugin.provider);
});
});
} else {
signerPromise = Promise.resolve(ethers.Wallet.fromMnemonic(arg).connect(plugin.provider));
}
return Promise.resolve(new WrappedSigner(
signerPromise.then((wallet) => wallet.getAddress()),
() => signerPromise,
plugin
));
}
// Check for a JSON wallet
try {
let content = fs.readFileSync(arg).toString();
let address = ethers.utils.getJsonWalletAddress(content);
if (address) {
return Promise.resolve(new WrappedSigner(
Promise.resolve(address),
async (): Promise<ethers.Signer> => {
let password = await getPassword(`Password (${arg}): `);
let progressBar = getProgressBar("Decrypting");
return ethers.Wallet.fromEncryptedJson(content, password, progressBar).then((wallet) => {
return wallet.connect(plugin.provider);
});
},
plugin));
} else {
return loadAccount(content.trim(), plugin, true);
}
} catch (error) {
if (error.message === "cancelled") {
throw new Error("Cancelled.");
} else if (error.message === "wrong password") {
throw new Error("Incorrect password.");
}
}
throw new UsageError("unknown account option - [REDACTED]");
return null;
}
/////////////////////////////
// Plugin Class
export interface Help {
name: string;
help: string;
}
export interface PluginType {
new(...args: any[]): Plugin;
getHelp?: () => Help;
getOptionHelp?: () => Array<Help>;
}
export abstract class Plugin {
network: ethers.providers.Network;
provider: ethers.providers.Provider;
accounts: ReadonlyArray<WrappedSigner>;
mnemonicPassword: boolean;
_xxxMnemonicPasswordHard: boolean;
gasLimit: ethers.BigNumber;
gasPrice: ethers.BigNumber;
nonce: number;
yes: boolean;
wait: boolean;
constructor() {
}
static getHelp(): Help {
return null;
}
static getOptionHelp(): Array<Help> {
return [ ];
}
async prepareOptions(argParser: ArgParser, verifyOnly?: boolean): Promise<void> {
let runners: Array<Promise<void>> = [ ];
this.wait = argParser.consumeFlag("wait");
this.yes = argParser.consumeFlag("yes");
/////////////////////
// Provider
let network = (argParser.consumeOption("network") || "homestead");
let providers: Array<ethers.providers.BaseProvider> = [ ];
let rpc: Array<ethers.providers.JsonRpcProvider> = [ ];
argParser.consumeOptions("rpc").forEach((url) => {
let provider = new ethers.providers.JsonRpcProvider(url)
providers.push(provider);
rpc.push(provider);
});
if (argParser.consumeFlag("alchemy")) {
providers.push(new ethers.providers.AlchemyProvider(network));
}
if (argParser.consumeFlag("etherscan")) {
providers.push(new ethers.providers.EtherscanProvider(network));
}
if (argParser.consumeFlag("infura")) {
providers.push(new ethers.providers.InfuraProvider(network));
}
if (argParser.consumeFlag("nodesmith")) {
providers.push(new ethers.providers.NodesmithProvider(network));
}
if (argParser.consumeFlag("offline")) {
providers.push(new OfflineProvider(network));
}
if (providers.length === 1) {
ethers.utils.defineReadOnly(this, "provider", providers[0]);
} else if (providers.length) {
ethers.utils.defineReadOnly(this, "provider", new ethers.providers.FallbackProvider(providers));
} else {
ethers.utils.defineReadOnly(this, "provider", ethers.getDefaultProvider(network));
}
/////////////////////
// Accounts
ethers.utils.defineReadOnly(this, "mnemonicPassword", argParser.consumeFlag("mnemonic-password"));
ethers.utils.defineReadOnly(this, "_xxxMnemonicPasswordHard", argParser.consumeFlag("xxx-mnemonic-password"));
let accounts: Array<WrappedSigner> = [ ];
let accountOptions = argParser.consumeMultiOptions([ "account", "account-rpc", "account-void" ]);
for (let i = 0; i < accountOptions.length; i++) {
let account = accountOptions[i];
switch (account.name) {
case "account":
// Verifying does not need to ask for passwords, etc.
if (verifyOnly) { break; }
let wrappedSigner = await loadAccount(account.value, this);
accounts.push(wrappedSigner);
break;
case "account-rpc":
if (rpc.length !== 1) {
this.throwUsageError("--account-rpc requires exactly one JSON-RPC provider");
}
try {
let signer: ethers.providers.JsonRpcSigner = null;
if (account.value.match(/^[0-9]+$/)) {
signer = rpc[0].getSigner(parseInt(account.value));
} else {
signer = rpc[0].getSigner(ethers.utils.getAddress(account.value));
}
accounts.push(new WrappedSigner(signer.getAddress(), () => Promise.resolve(signer), this));
} catch (error) {
this.throwUsageError("invalid --account-rpc - " + account.value);
}
break;
case "account-void": {
let addressPromise = this.provider.resolveName(account.value);
let signerPromise = addressPromise.then((addr) => {
return new ethers.VoidSigner(addr, this.provider);
});
accounts.push(new WrappedSigner(addressPromise, () => signerPromise, this));
break;
}
}
}
ethers.utils.defineReadOnly(this, "accounts", Object.freeze(accounts));
/////////////////////
// Transaction Options
const gasPrice = argParser.consumeOption("gas-price");
if (gasPrice) {
ethers.utils.defineReadOnly(this, "gasPrice", ethers.utils.parseUnits(gasPrice, "gwei"));
} else {
ethers.utils.defineReadOnly(this, "gasPrice", null);
}
const gasLimit = argParser.consumeOption("gas-limit");
if (gasLimit) {
ethers.utils.defineReadOnly(this, "gasLimit", ethers.BigNumber.from(gasLimit));
} else {
ethers.utils.defineReadOnly(this, "gasLimit", null);
}
const nonce = argParser.consumeOption("nonce");
if (nonce) {
this.nonce = ethers.BigNumber.from(nonce).toNumber();
}
// Now wait for all asynchronous options to load
runners.push(this.provider.getNetwork().then((network) => {
ethers.utils.defineReadOnly(this, "network", Object.freeze(network));
}, (error) => {
ethers.utils.defineReadOnly(this, "network", Object.freeze({
chainId: 0,
name: "no-network"
}));
}));
try {
await Promise.all(runners)
} catch (error) {
this.throwError(error);
}
}
prepareArgs(args: Array<string>): Promise<void> {
return Promise.resolve(null);
}
run(): Promise<void> {
return null;
}
getAddress(addressOrName: string, message?: string, allowZero?: boolean): Promise<string> {
try {
return Promise.resolve(ethers.utils.getAddress(addressOrName));
} catch (error) { }
return this.provider.resolveName(addressOrName).then((address) => {
if (address == null) {
this.throwError("ENS name not configured - " + addressOrName);
}
if (address === ethers.constants.AddressZero && !allowZero) {
this.throwError(message || "cannot use the zero address");
}
return address;
});
}
// Dumps formatted data
dump(header: string, info: any): void {
dump(header, info);
}
// Throwing a UsageError causes the --help to be shown above
// the error.message
throwUsageError(message?: string): never {
throw new UsageError(message);
}
// Shows error.message
throwError(message: string): never {
throw new Error(message);
}
}
class CheckPlugin extends Plugin {
prepareOptions(argParser: ArgParser, verifyOnly?: boolean): Promise<void> {
return super.prepareOptions(argParser, true);
}
}
/////////////////////////////
// Command Line Runner
export type Options = {
account?: boolean;
provider?: boolean;
transaction?: boolean;
version?: string;
};
export class CLI {
readonly defaultCommand: string;
readonly plugins: { [ command: string ]: PluginType };
readonly standAlone: PluginType;
readonly options: Options;
constructor(defaultCommand?: string, options?: Options) {
ethers.utils.defineReadOnly(this, "options", {
account: true,
provider: true,
transaction: true,
version: version.split("/").pop(),
});
if (options) {
["account", "provider", "transaction"].forEach((key) => {
if ((<any>options)[key] == null) { return; }
(<any>(this.options))[key] = !!((<any>options)[key]);
});
["version"].forEach((key) => {
if ((<any>options)[key] == null) { return; }
(<any>(this.options))[key] = (<any>options)[key];
});
}
Object.freeze(this.options);
ethers.utils.defineReadOnly(this, "defaultCommand", defaultCommand || null);
ethers.utils.defineReadOnly(this, "plugins", { });
}
static getAppName(): string {
try {
return basename(process.mainModule.filename).split(".")[0];
} catch (error) { }
return "ethers";
}
// @TODO: Better way to specify default; i.e. may not have args
addPlugin(command: string, plugin: PluginType) {
if (this.standAlone) {
logger.throwError("only setPlugin or addPlugin may be used at once", ethers.errors.UNSUPPORTED_OPERATION, {
operation: "addPlugin"
});
} else if (this.plugins[command]) {
logger.throwError("command already exists", ethers.errors.UNSUPPORTED_OPERATION, {
operation: "addPlugin",
command: command
});
}
ethers.utils.defineReadOnly(this.plugins, command, plugin);
}
setPlugin(plugin: PluginType) {
if (Object.keys(this.plugins).length !== 0) {
logger.throwError("only setPlugin or addPlugin may be used at once", ethers.errors.UNSUPPORTED_OPERATION, {
operation: "setPlugin"
});
}
if (this.standAlone) {
logger.throwError("cannot setPlugin more than once", ethers.errors.UNSUPPORTED_OPERATION, {
operation: "setPlugin"
});
}
ethers.utils.defineReadOnly(this, "standAlone", plugin);
}
showUsage(message?: string, status?: number): never {
// Limit: | |
console.log("Usage:");
if (this.standAlone) {
let help = ethers.utils.getStatic<() => Help>(this.standAlone, "getHelp")();
console.log(` ${ CLI.getAppName() } ${ help.name } [ OPTIONS ]`);
console.log("");
let lines: Array<string> = [];
let optionHelp = ethers.utils.getStatic<() => Array<Help>>(this.standAlone, "getOptionHelp")();
optionHelp.forEach((help) => {
lines.push(" " + help.name + repeat(" ", 28 - help.name.length) + help.help);
});
if (lines.length) {
console.log("OPTIONS");
lines.forEach((line) => {
console.log(line);
});
console.log("");
}
} else {
if (this.defaultCommand) {
console.log(` ${ CLI.getAppName() } [ COMMAND ] [ ARGS ] [ OPTIONS ]`);
console.log("");
} else {
console.log(` ${ CLI.getAppName() } COMMAND [ ARGS ] [ OPTIONS ]`);
console.log("");
}
let lines: Array<string> = [];
for (let cmd in this.plugins) {
let plugin = this.plugins[cmd];
let help = ethers.utils.getStatic<() => Help>(plugin, "getHelp")();
if (help == null) { continue; }
let helpLine = " " + help.name;
if (helpLine.length > 28) {
lines.push(helpLine);
lines.push(repeat(" ", 30) + help.help);
} else {
helpLine += repeat(" ", 30 - helpLine.length);
lines.push(helpLine + help.help);
}
let optionHelp = ethers.utils.getStatic<() => Array<Help>>(plugin, "getOptionHelp")();
optionHelp.forEach((help) => {
lines.push(" " + help.name + repeat(" ", 27 - help.name.length) + help.help);
});
}
if (lines.length) {
if (this.defaultCommand) {
console.log(`COMMANDS (default: ${ this.defaultCommand })`);
} else {
console.log("COMMANDS");
}
lines.forEach((line) => {
console.log(line);
});
console.log("");
}
}
if (this.options.account) {
console.log("ACCOUNT OPTIONS");
console.log(" --account FILENAME Load from a file (JSON, RAW or mnemonic)");
console.log(" --account RAW_KEY Use a private key (insecure *)");
console.log(" --account 'MNEMONIC' Use a mnemonic (insecure *)");
console.log(" --account - Use secure entry for a raw key or mnemonic");
console.log(" --account-void ADDRESS Use an address as a void signer");
console.log(" --account-void ENS_NAME Add the resolved address as a void signer");
console.log(" --account-rpc ADDRESS Add the address from a JSON-RPC provider");
console.log(" --account-rpc INDEX Add the index from a JSON-RPC provider");
console.log(" --mnemonic-password Prompt for a password for mnemonics");
console.log(" --xxx-mnemonic-password Prompt for a (experimental) hard password");
console.log("");
}
if (this.options.provider) {
console.log("PROVIDER OPTIONS (default: all + homestead)");
console.log(" --alchemy Include Alchemy");
console.log(" --etherscan Include Etherscan");
console.log(" --infura Include INFURA");
console.log(" --nodesmith Include nodesmith");
console.log(" --rpc URL Include a custom JSON-RPC");
console.log(" --offline Dump signed transactions (no send)");
console.log(" --network NETWORK Network to connect to (default: homestead)");
console.log("");
}
if (this.options.transaction) {
console.log("TRANSACTION OPTIONS (default: query network)");
console.log(" --gasPrice GWEI Default gas price for transactions(in wei)");
console.log(" --gasLimit GAS Default gas limit for transactions");
console.log(" --nonce NONCE Initial nonce for the first transaction");
console.log(" --yes Always accept Signing and Sending");
console.log("");
}
console.log("OTHER OPTIONS");
if (this.options.transaction) {
console.log(" --wait Wait until transactions are mined");
}
console.log(" --debug Show stack traces for errors");
console.log(" --help Show this usage and exit");
console.log(" --version Show this version and exit");
console.log("");
if (this.options.account) {
console.log("(*) By including mnemonics or private keys on the command line they are");
console.log(" possibly readable by other users on your system and may get stored in");
console.log(" your bash history file. This is NOT recommended.");
console.log("");
}
if (message) {
console.log(message);
console.log("");
}
process.exit(status || 0);
throw new Error("never reached");
}
async run(args: Array<string>): Promise<void> {
args = args.slice();
if (this.defaultCommand && !this.plugins[this.defaultCommand]) {
throw new Error("missing defaultCommand plugin");
}
let command: string = null;
// We run a temporary argument parser to check for a command by processing standard options
{
let argParser = new ArgParser(args);
let plugin = new CheckPlugin();
await plugin.prepareOptions(argParser);
// These are not part of the plugin
[ "debug", "help", "version"].forEach((key) => {
argParser.consumeFlag(key);
});
// Find the first unconsumed argument
if (!this.standAlone) {
let commandIndex = argParser._checkCommandIndex();
if (commandIndex === -1) {
command = this.defaultCommand;
} else {
command = args[commandIndex];
args.splice(commandIndex, 1);
}
}
}
// Reset the argument parser
let argParser = new ArgParser(args);
if (argParser.consumeFlag("version")) {
console.log(CLI.getAppName() + "/" + this.options.version);
return;
}
if (argParser.consumeFlag("help")) {
return this.showUsage();
}
const debug = argParser.consumeFlag("debug");
// Create Plug-in instance
let plugin: Plugin = null;
if (this.standAlone) {
plugin = new this.standAlone;
} else {
try {
plugin = new this.plugins[command]();
} catch (error) {
if (command) { this.showUsage("unknown command - " + command); }
return this.showUsage("no command provided", 1);
}
}
try {
await plugin.prepareOptions(argParser);
await plugin.prepareArgs(argParser._finalizeArgs());
await plugin.run();
} catch (error) {
if (error instanceof UsageError) {
return this.showUsage(error.message, 1);
}
if (debug) {
console.log("----- <DEBUG> ------")
console.log(error);
console.log("----- </DEBUG> -----")
}
console.log("Error: " + error.message);
process.exit(2);
}
}
}