-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.ts
More file actions
executable file
·1381 lines (1250 loc) · 36.3 KB
/
index.ts
File metadata and controls
executable file
·1381 lines (1250 loc) · 36.3 KB
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
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* A CLI tool for testing the Ledger hardware wallet integration.
*/
import { Command, Option } from "commander";
import {
GenesisTokenCanister,
GovernanceCanister,
GovernanceError,
InsufficientAmountError,
Vote,
Topic,
} from "@dfinity/nns";
import {
tryParseAccountIdentifier,
tryParseBigInt,
tryParseBool,
tryParseE8s,
tryParseIcrcAccount,
tryParseInt,
tryParseListBigint,
tryParsePercentage,
tryParsePrincipal,
tryParseSnsNeuronId,
} from "./parsers";
import { Principal } from "@dfinity/principal";
import {
assertLedgerVersion,
hasValidStake,
isCurrentVersionSmallerThan,
getLedgerIdentity,
getAgent,
subaccountToHexString,
nowInBigIntNanoSeconds,
isCurrentVersionSmallerThanFullCandidParser,
jsonStringifyWithBigInt,
} from "./utils";
import { CANDID_PARSER_VERSION, HOTKEY_PERMISSIONS } from "./constants";
import { AnonymousIdentity, Identity } from "@dfinity/agent";
import { SnsGovernanceCanister, SnsNeuronId } from "@dfinity/sns";
import {
TokenAmountV2,
fromNullable,
isNullish,
toNullable,
} from "@dfinity/utils";
import {
decodeIcrcAccount,
encodeIcrcAccount,
IcrcAccount,
IcrcLedgerCanister,
toTransferArg,
} from "@dfinity/ledger-icrc";
import chalk from "chalk";
import {
AccountIdentifier,
LedgerCanister,
InsufficientFundsError,
} from "@dfinity/ledger-icp";
// Add polyfill for `window` for `TransportWebHID` checks to work.
import "node-window-polyfill/register";
// @ts-ignore (no types are available)
import fetch from "node-fetch";
import { Secp256k1PublicKey } from "./ledger/secp256k1";
(global as any).fetch = fetch;
// Add polyfill for `window.fetch` for agent-js to work.
(window as any).fetch = fetch;
const program = new Command();
const log = console.log;
const SECONDS_PER_MINUTE = 60;
const SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE;
const SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR;
const SECONDS_PER_YEAR = 365 * SECONDS_PER_DAY + 6 * SECONDS_PER_HOUR;
// TODO: Export from nns-js and use it here.
const MAINNET_LEDGER_CANISTER_ID = Principal.fromText(
"ryjl3-tyaaa-aaaaa-aaaba-cai"
);
async function getIdentity() {
const principalPath = tryParseInt(program.opts().principal);
return getLedgerIdentity(principalPath);
}
async function getCurrentAgent(identity: Identity) {
const network: string = program.opts().network;
return getAgent(identity, network);
}
/**
* SNS Functionality
*/
type SnsCallParams = {
canisterId: Principal;
};
async function snsListNeurons(canisterId: Principal) {
const identity = await getIdentity();
const snsGovernance = SnsGovernanceCanister.create({
agent: await getCurrentAgent(new AnonymousIdentity()),
canisterId,
});
const neurons = await snsGovernance.listNeurons({
certified: true,
principal: identity.getPrincipal(),
});
if (neurons.length > 0) {
neurons.forEach((n) => {
const neuronId = fromNullable(n.id);
if (neuronId !== undefined) {
log(
`Neuron ID: ${subaccountToHexString(Uint8Array.from(neuronId.id))}`
);
} else {
log("Neuron ID: N/A");
}
});
} else {
ok("No neurons found.");
}
}
async function snsAddHotkey({
neuronId,
principal,
canisterId,
}: { neuronId: SnsNeuronId; principal: Principal } & SnsCallParams) {
const identity = await getIdentity();
const snsGovernance = SnsGovernanceCanister.create({
agent: await getCurrentAgent(identity),
canisterId,
});
await snsGovernance.addNeuronPermissions({
neuronId,
principal: principal,
permissions: HOTKEY_PERMISSIONS,
});
ok();
}
async function snsRemoveHotkey({
neuronId,
principal,
canisterId,
}: { neuronId: SnsNeuronId; principal: Principal } & SnsCallParams) {
const identity = await getIdentity();
const snsGovernance = SnsGovernanceCanister.create({
agent: await getCurrentAgent(identity),
canisterId,
});
await snsGovernance.removeNeuronPermissions({
neuronId,
principal: principal,
permissions: HOTKEY_PERMISSIONS,
});
ok();
}
async function snsStartDissolving({
neuronId,
canisterId,
}: { neuronId: SnsNeuronId } & SnsCallParams) {
const identity = await getIdentity();
const snsGovernance = SnsGovernanceCanister.create({
agent: await getCurrentAgent(identity),
canisterId,
});
await snsGovernance.startDissolving(neuronId);
ok();
}
async function snsStopDissolving({
neuronId,
canisterId,
}: { neuronId: SnsNeuronId } & SnsCallParams) {
const identity = await getIdentity();
const snsGovernance = SnsGovernanceCanister.create({
agent: await getCurrentAgent(identity),
canisterId,
});
await snsGovernance.stopDissolving(neuronId);
ok();
}
async function snsDisburse({
neuronId,
canisterId,
amount,
to,
}: {
neuronId: SnsNeuronId;
amount?: TokenAmountV2;
to?: IcrcAccount;
} & SnsCallParams) {
const identity = await getIdentity();
const snsGovernance = SnsGovernanceCanister.create({
agent: await getCurrentAgent(identity),
canisterId,
});
await snsGovernance.disburse({
neuronId,
amount: amount?.toE8s(),
toAccount: to,
});
ok();
}
async function snsSetDissolveDelay({
neuronId,
canisterId,
years,
days,
minutes,
seconds,
}: {
neuronId: SnsNeuronId;
years: number;
days: number;
minutes: number;
seconds: number;
} & SnsCallParams) {
const identity = await getIdentity();
const snsGovernance = SnsGovernanceCanister.create({
agent: await getCurrentAgent(identity),
canisterId,
});
const dissolveDelaySeconds =
years * SECONDS_PER_YEAR +
days * SECONDS_PER_DAY +
minutes * SECONDS_PER_MINUTE +
seconds;
await snsGovernance.setDissolveTimestamp({
neuronId,
dissolveTimestampSeconds: BigInt(
Math.floor(Date.now() / 1000) + dissolveDelaySeconds
),
});
ok();
}
async function snsStakeMaturity({
neuronId,
canisterId,
percentageToStake,
}: {
neuronId: SnsNeuronId;
percentageToStake: number;
} & SnsCallParams) {
const identity = await getIdentity();
const snsGovernance = SnsGovernanceCanister.create({
agent: await getCurrentAgent(identity),
canisterId,
});
await snsGovernance.stakeMaturity({ neuronId, percentageToStake });
ok();
}
/**
* ICRC Functionality
*/
/**
* Fetches the balance of the main ICP account on the wallet.
*/
async function icrcGetBalance(
canisterId: Principal = MAINNET_LEDGER_CANISTER_ID
) {
const identity = await getIdentity();
const account: IcrcAccount = { owner: identity.getPrincipal() };
const ledger = IcrcLedgerCanister.create({
agent: await getCurrentAgent(new AnonymousIdentity()),
canisterId: canisterId ?? MAINNET_LEDGER_CANISTER_ID,
});
const balance = await ledger.balance(account);
ok(`Account ${encodeIcrcAccount(account)} has balance ${balance} e8s`);
}
async function supportedLedgers() {
const identity = await getIdentity();
const supportedTokens = await identity.getSupportedTokens();
const ledgersTextInfo = supportedTokens.map(
(ledger) =>
`Token Symbol: ${ledger.tokenSymbol}, Canister Id: ${ledger.canisterId}, Decimals: ${ledger.decimals}`
);
ok(`Supported ledgers: ${ledgersTextInfo.join("\n")}`);
}
// TODO: Add support for subaccounts
async function icrcSendTokens({
canisterId = MAINNET_LEDGER_CANISTER_ID,
amount,
to,
}: {
amount: bigint;
to: IcrcAccount;
canisterId: Principal;
}) {
const identity = await getIdentity();
const ledger = IcrcLedgerCanister.create({
agent: await getCurrentAgent(identity),
canisterId,
});
const anonymousLedger = IcrcLedgerCanister.create({
agent: await getCurrentAgent(new AnonymousIdentity()),
canisterId,
});
const fee = await anonymousLedger.transactionFee({});
await ledger.transfer({
to: {
owner: to.owner,
subaccount: toNullable(to.subaccount),
},
amount: amount,
fee,
created_at_time: nowInBigIntNanoSeconds(),
});
ok();
}
/**
* NNS Functionality
*/
/**
* Fetches the balance of the main ICP account on the wallet.
*/
async function getBalance() {
const identity = await getIdentity();
const accountIdentifier = AccountIdentifier.fromPrincipal({
principal: identity.getPrincipal(),
});
const ledger = LedgerCanister.create({
agent: await getCurrentAgent(new AnonymousIdentity()),
});
const balance = await ledger.accountBalance({
accountIdentifier: accountIdentifier,
});
ok(`Account ${accountIdentifier.toHex()} has balance ${balance} e8s`);
}
/**
* Send ICP to another address.
*
* @param to The account identifier in hex.
* @param amount Amount to send in e8s.
*/
async function sendICP(to: AccountIdentifier, amount: TokenAmountV2) {
const identity = await getIdentity();
const ledger = LedgerCanister.create({
agent: await getCurrentAgent(identity),
});
const blockHeight = await ledger.transfer({
to: to,
amount: amount.toE8s(),
memo: BigInt(0),
});
ok(`Transaction completed at block height ${blockHeight}.`);
}
/**
* Shows the principal and account idenifier on the terminal and on the wallet's screen.
*/
async function showInfo(showOnDevice?: boolean) {
const identity = await getIdentity();
const accountIdentifier = AccountIdentifier.fromPrincipal({
principal: identity.getPrincipal(),
});
const publicKey = identity.getPublicKey() as Secp256k1PublicKey;
log(chalk.bold(`Principal: `) + identity.getPrincipal());
log(
chalk.bold(`Address (${identity.derivePath}): `) + accountIdentifier.toHex()
);
log(chalk.bold("Public key: ") + publicKey.toHex());
if (showOnDevice) {
log("Displaying the principal and the address on the device...");
await identity.showAddressAndPubKeyOnDevice();
}
}
/**
* Stakes a new neuron.
*
* @param amount Amount to stake in e8s.
*/
async function stakeNeuron(stake: TokenAmountV2) {
const identity = await getIdentity();
const ledger = LedgerCanister.create({
agent: await getCurrentAgent(identity),
});
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(new AnonymousIdentity()),
hardwareWallet: await isCurrentVersionSmallerThanFullCandidParser(identity),
});
// Flag that an upcoming stake neuron transaction is coming to distinguish
// it from a "send ICP" transaction on the device.
identity.flagUpcomingStakeNeuron();
try {
const stakedNeuronId = await governance.stakeNeuron({
stake: stake.toE8s(),
principal: identity.getPrincipal(),
ledgerCanister: ledger,
});
ok(`Staked neuron with ID: ${stakedNeuronId}`);
} catch (error: unknown) {
if (error instanceof InsufficientAmountError) {
err(`Cannot stake less than ${error.minimumAmount} e8s`);
} else if (error instanceof InsufficientFundsError) {
err(
`Your account has insufficient funds (${(error as InsufficientFundsError).balance
} e8s)`
);
} else {
console.log(error);
}
}
}
async function increaseDissolveDelay(
neuronId: bigint,
years: number,
days: number,
minutes: number,
seconds: number
) {
const identity = await getIdentity();
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
});
const additionalDissolveDelaySeconds =
years * SECONDS_PER_YEAR +
days * SECONDS_PER_DAY +
minutes * SECONDS_PER_MINUTE +
seconds;
await governance.increaseDissolveDelay({
neuronId,
additionalDissolveDelaySeconds: additionalDissolveDelaySeconds,
});
ok();
}
async function setDissolveDelay(
neuronId: bigint,
years: number,
days: number,
minutes: number,
seconds: number
) {
const identity = await getIdentity();
await assertLedgerVersion({ identity, minVersion: CANDID_PARSER_VERSION });
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
});
const dissolveDelaySeconds =
years * SECONDS_PER_YEAR +
days * SECONDS_PER_DAY +
minutes * SECONDS_PER_MINUTE +
seconds;
await governance.setDissolveDelay({
neuronId,
dissolveDelaySeconds: Math.floor(Date.now() / 1000) + dissolveDelaySeconds,
});
ok();
}
async function disburseNeuron(neuronId: bigint, to?: string, amount?: bigint) {
const identity = await getIdentity();
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
hardwareWallet: await isCurrentVersionSmallerThanFullCandidParser(identity),
});
await governance.disburse({
neuronId: BigInt(neuronId),
toAccountId: to,
amount: amount,
});
ok();
}
async function splitNeuron(neuronId: bigint, amount: bigint) {
const identity = await getIdentity();
await assertLedgerVersion({ identity, minVersion: CANDID_PARSER_VERSION });
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
});
await governance.splitNeuron({
neuronId: BigInt(neuronId),
amount,
});
ok();
}
async function spawnNeuron(
neuronId: string,
controller?: Principal,
percentage?: number
) {
const identity = await getIdentity();
// Percentage is only supported with version CANDID_PARSER_VERSION and above
if (percentage !== undefined) {
await assertLedgerVersion({ identity, minVersion: CANDID_PARSER_VERSION });
}
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
// `hardwareWallet: true` uses Protobuf and doesn't support percentage
hardwareWallet:
percentage === undefined &&
(await isCurrentVersionSmallerThan({
identity,
version: CANDID_PARSER_VERSION,
})),
});
const spawnedNeuronId = await governance.spawnNeuron({
neuronId: BigInt(neuronId),
newController: controller,
percentageToSpawn: percentage,
});
ok(`Spawned neuron with ID ${spawnedNeuronId}`);
}
async function stakeMaturity(neuronId: bigint, percentage?: number) {
const identity = await getIdentity();
await assertLedgerVersion({ identity, minVersion: CANDID_PARSER_VERSION });
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
});
await governance.stakeMaturity({
neuronId: BigInt(neuronId),
percentageToStake: percentage,
});
ok();
}
async function enableAutoStake(neuronId: bigint, autoStake: boolean) {
const identity = await getIdentity();
await assertLedgerVersion({ identity, minVersion: CANDID_PARSER_VERSION });
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
});
await governance.autoStakeMaturity({
neuronId: BigInt(neuronId),
autoStake,
});
ok();
}
async function startDissolving(neuronId: bigint) {
const identity = await getIdentity();
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
});
await governance.startDissolving(neuronId);
ok();
}
async function stopDissolving(neuronId: bigint) {
const identity = await getIdentity();
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
});
await governance.stopDissolving(neuronId);
ok();
}
async function joinCommunityFund(neuronId: bigint) {
const identity = await getIdentity();
// Even though joining is supported for earler version
// we don't want a user to be able to join but not leave.
await assertLedgerVersion({ identity, minVersion: CANDID_PARSER_VERSION });
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
hardwareWallet: await isCurrentVersionSmallerThanFullCandidParser(identity),
});
await governance.joinCommunityFund(neuronId);
ok();
}
async function leaveCommunityFund(neuronId: bigint) {
const identity = await getIdentity();
await assertLedgerVersion({ identity, minVersion: CANDID_PARSER_VERSION });
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
hardwareWallet: await isCurrentVersionSmallerThanFullCandidParser(identity),
});
await governance.leaveCommunityFund(neuronId);
ok();
}
async function addHotkey(neuronId: bigint, principal: Principal) {
const identity = await getIdentity();
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
hardwareWallet: await isCurrentVersionSmallerThanFullCandidParser(identity),
});
await governance.addHotkey({
neuronId: BigInt(neuronId),
principal: principal,
});
ok();
}
async function removeHotkey(neuronId: bigint, principal: Principal) {
const identity = await getIdentity();
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
hardwareWallet: await isCurrentVersionSmallerThanFullCandidParser(identity),
});
await governance.removeHotkey({
neuronId: BigInt(neuronId),
principal: principal,
});
ok();
}
async function listNeurons(showZeroStake: boolean = false) {
const identity = await getIdentity();
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
hardwareWallet: await isCurrentVersionSmallerThan({
identity,
version: "2.0.0",
}),
});
// We filter neurons with no ICP, as they'll be garbage collected by the governance canister.
const neurons = await governance.listNeurons({
certified: true,
});
if (neurons.length > 0) {
neurons
.filter((n) => showZeroStake || hasValidStake(n))
.forEach((n) => {
log(`Neuron ID: ${n.neuronId}`);
});
} else {
ok("No neurons found.");
}
}
async function mergeNeurons(sourceNeuronId: bigint, targetNeuronId: bigint) {
const identity = await getIdentity();
await assertLedgerVersion({ identity, minVersion: CANDID_PARSER_VERSION });
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
});
await governance.mergeNeurons({
targetNeuronId,
sourceNeuronId,
});
ok();
}
async function registerVote(neuronId: bigint, proposalId: bigint, vote: Vote) {
if (!Object.values(Vote).includes(vote)) {
throw new Error(
`Invalid vote value. Valid values are: ${Object.values(Vote).join(", ")}`
);
}
const identity = await getIdentity();
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
});
await governance.registerVote({
proposalId,
neuronId,
vote,
});
ok();
}
async function setFollowees(
neuronId: bigint,
topic: Topic,
followees: bigint[]
) {
if (!Object.values(Topic).includes(topic)) {
throw new Error(
`Invalid topic value. Valid values are: ${Object.values(Topic).join(
", "
)}`
);
}
const identity = await getIdentity();
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
});
await governance.setFollowees({
neuronId,
topic,
followees,
});
ok();
}
async function setNodeProviderAccount(account: AccountIdentifier) {
const identity = await getIdentity();
await assertLedgerVersion({ identity, minVersion: CANDID_PARSER_VERSION });
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
});
await governance.setNodeProviderAccount(account.toHex());
ok();
}
/**
* Fetches the balance of the main account on the wallet.
*/
async function claimNeurons() {
const identity = await getIdentity();
const publicKey = identity.getPublicKey() as Secp256k1PublicKey;
const hexPubKey = publicKey.toHex();
const governance = await GenesisTokenCanister.create({
agent: await getCurrentAgent(identity),
});
const claimedNeuronIds = await governance.claimNeurons({
hexPubKey,
});
ok(`Successfully claimed the following neurons: ${claimedNeuronIds}`);
}
async function getNeuron(neuronId: bigint) {
const identity = await getIdentity();
const governance = GovernanceCanister.create({
agent: await getCurrentAgent(identity),
});
const neuron = await governance.getNeuron({
certified: true,
neuronId,
});
ok(`Neuron: ${jsonStringifyWithBigInt(neuron)}`);
}
/**
* Runs a function with a try/catch block.
*/
async function run(f: () => void) {
try {
await f();
} catch (error: any) {
err(error);
}
}
function ok(message?: string) {
if (message) {
log(`${chalk.green(chalk.bold("OK"))}: ${message}`);
} else {
log(`${chalk.green(chalk.bold("OK"))}`);
}
}
function err(error: any) {
const message =
error instanceof GovernanceError
? error.detail.error_message
: error instanceof Error
? error.message
: error;
log(`${chalk.bold(chalk.red("Error:"))} ${message}`);
}
async function main() {
const icrc = new Command("icrc")
.description("Commands for managing ICRC ledger.")
.addCommand(
new Command("balance")
.description("Get the balance of the main account on the ICRC wallet.")
.option(
"--canister-id <canister-id>",
"Canister ID (defaults to ICP Ledger)",
tryParsePrincipal
)
.action((args) => run(() => icrcGetBalance(args.canisterId)))
)
.addCommand(
new Command("supported-tokens")
.description("Get supported tokens of the ledger device.")
.action((args) => run(supportedLedgers))
)
.addCommand(
new Command("transfer")
.description("Send tokens from the ICRC wallet to another account.")
.requiredOption(
"--canister-id <canister-id>",
"ICRC ledger Canister ID",
tryParsePrincipal
)
.requiredOption(
"--to <account>",
"ICRC Account",
tryParseIcrcAccount
)
.requiredOption(
"--amount <amount>",
"Amount to transfer in ledger's base unit",
tryParseBigInt
)
.action(({ to, amount, canisterId }) => {
run(() => icrcSendTokens({ to, amount, canisterId }));
})
);
const snsNeuron = new Command("neuron")
.description("Commands for managing sns neurons.")
.addCommand(
new Command("list")
.requiredOption(
"--canister-id <canister-id>",
"Canister ID",
tryParsePrincipal
)
.action((args) => run(() => snsListNeurons(args.canisterId)))
)
.addCommand(
new Command("add-hotkey")
.requiredOption(
"--canister-id <canister-id>",
"Canister ID",
tryParsePrincipal
)
.requiredOption(
"--principal <principal>",
"Principal",
tryParsePrincipal
)
.requiredOption(
"--neuron-id <neuron-id>",
"Neuron ID",
tryParseSnsNeuronId
)
.action(({ canisterId, principal, neuronId }) =>
run(() =>
snsAddHotkey({
canisterId,
principal,
neuronId,
})
)
)
)
.addCommand(
new Command("remove-hotkey")
.requiredOption(
"--canister-id <canister-id>",
"Canister ID",
tryParsePrincipal
)
.requiredOption(
"--principal <principal>",
"Principal",
tryParsePrincipal
)
.requiredOption(
"--neuron-id <neuron-id>",
"Neuron ID",
tryParseSnsNeuronId
)
.action(({ canisterId, principal, neuronId }) =>
run(() =>
snsRemoveHotkey({
canisterId,
principal,
neuronId,
})
)
)
)
.addCommand(
new Command("start-dissolving")
.requiredOption(
"--canister-id <canister-id>",
"Canister ID",
tryParsePrincipal
)
.requiredOption(
"--neuron-id <neuron-id>",
"Neuron ID",
tryParseSnsNeuronId
)
.action(({ canisterId, neuronId }) =>
run(() =>
snsStartDissolving({
canisterId,
neuronId,
})
)
)
)
.addCommand(
new Command("stop-dissolving")
.requiredOption(
"--canister-id <canister-id>",
"Canister ID",
tryParsePrincipal
)
.requiredOption(
"--neuron-id <neuron-id>",
"Neuron ID",
tryParseSnsNeuronId
)
.action(({ canisterId, neuronId }) =>
run(() =>
snsStopDissolving({
canisterId,
neuronId,
})
)
)
)
.addCommand(
new Command("stake-maturity")
.requiredOption(
"--canister-id <canister-id>",
"Canister ID",
tryParsePrincipal
)
.requiredOption(
"--neuron-id <neuron-id>",
"Neuron ID",
tryParseSnsNeuronId
)
.option(
"--percentage <percentage>",