-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathindex.ts
executable file
·2062 lines (1860 loc) · 81.5 KB
/
index.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
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bun
import "./side-effects"; // doesn't quite work for silencing the bigint error message. why?
import evm from "@wormhole-foundation/sdk/platforms/evm";
import solana from "@wormhole-foundation/sdk/platforms/solana";
import { encoding } from '@wormhole-foundation/sdk-connect';
import { execSync } from "child_process";
import evmDeployFile from "../../evm/script/DeployWormholeNtt.s.sol" with { type: "file" };
import evmDeployFileHelper from "../../evm/script/helpers/DeployWormholeNttBase.sol" with { type: "file" };
import chalk from "chalk";
import yargs from "yargs";
import { $ } from "bun";
import { hideBin } from "yargs/helpers";
import { Connection, Keypair, PublicKey } from "@solana/web3.js";
import * as spl from "@solana/spl-token";
import fs from "fs";
import readline from "readline";
import { ChainContext, UniversalAddress, Wormhole, assertChain, canonicalAddress, chainToPlatform, chains, isNetwork, networks, platforms, signSendWait, toUniversal, type AccountAddress, type Chain, type ChainAddress, type ConfigOverrides, type Network, type Platform } from "@wormhole-foundation/sdk";
import "@wormhole-foundation/sdk-evm-ntt";
import "@wormhole-foundation/sdk-solana-ntt";
import "@wormhole-foundation/sdk-definitions-ntt";
import type { Ntt, NttTransceiver } from "@wormhole-foundation/sdk-definitions-ntt";
import { type SolanaChains, SolanaAddress } from "@wormhole-foundation/sdk-solana";
import { colorizeDiff, diffObjects } from "./diff";
import { forgeSignerArgs, getSigner, type SignerType } from "./getSigner";
import { NTT, SolanaNtt } from "@wormhole-foundation/sdk-solana-ntt";
import type { EvmNtt, EvmNttWormholeTranceiver } from "@wormhole-foundation/sdk-evm-ntt";
import type { EvmChains } from "@wormhole-foundation/sdk-evm";
import { getAvailableVersions, getGitTagName } from "./tag";
import * as configuration from "./configuration";
import { ethers } from "ethers";
// TODO: contract upgrades on solana
// TODO: set special relaying?
// TODO: currently, we just default all evm chains to standard relaying. should we not do that? what's a good way to configure this?
// TODO: check if manager can mint the token in burning mode (on solana it's
// simple. on evm we need to simulate with prank)
const overrides: ConfigOverrides<Network> = (function () {
// read overrides.json file if exists
if (fs.existsSync("overrides.json")) {
console.error(chalk.yellow("Using overrides.json"));
return JSON.parse(fs.readFileSync("overrides.json").toString());
} else {
return {};
}
})();
export type Deployment<C extends Chain> = {
ctx: ChainContext<Network, C>,
ntt: Ntt<Network, C>,
whTransceiver: NttTransceiver<Network, C, Ntt.Attestation>,
decimals: number,
manager: ChainAddress<C>,
config: {
remote?: ChainConfig,
local?: ChainConfig,
},
}
// TODO: rename
export type ChainConfig = {
version: string,
mode: Ntt.Mode,
paused: boolean,
owner: string,
pauser?: string,
manager: string,
token: string,
transceivers: {
threshold: number,
wormhole: { address: string, pauser?: string },
},
limits: {
outbound: string,
inbound: Partial<{ [C in Chain]: string }>,
}
}
export type Config = {
network: Network,
chains: Partial<{
[C in Chain]: ChainConfig
}>,
defaultLimits?: {
outbound: string,
}
}
const options = {
network: {
alias: "n",
describe: "Network",
choices: networks,
demandOption: true,
},
deploymentPath: {
alias: "p",
describe: "Path to the deployment file",
default: "deployment.json",
type: "string",
},
yes: {
alias: "y",
describe: "Skip confirmation",
type: "boolean",
default: false,
},
signerType: {
alias: "s",
describe: "Signer type",
type: "string",
choices: ["privateKey", "ledger"],
default: "privateKey",
},
verbose: {
alias: "v",
describe: "Verbose output",
type: "boolean",
default: false,
},
chain: {
describe: "Chain",
type: "string",
choices: chains,
demandOption: true,
},
address: {
describe: "Address",
type: "string",
demandOption: true,
},
local: {
describe: "Use the current local version for deployment (advanced).",
type: "boolean",
default: false,
},
version: {
describe: "Version of NTT to deploy",
type: "string",
demandOption: false,
},
latest: {
describe: "Use the latest version",
type: "boolean",
default: false,
},
platform: {
describe: "Platform",
type: "string",
choices: platforms,
demandOption: true,
},
skipVerify:
{
describe: "Skip contract verification",
type: "boolean",
default: false,
},
payer: {
describe: "Path to the payer json file (Solana)",
type: "string",
},
} as const;
// TODO: this is a temporary hack to allow deploying from main (as we only need
// the changes to the evm script)
async function withCustomEvmDeployerScript<A>(pwd: string, then: () => Promise<A>): Promise<A> {
ensureNttRoot(pwd);
const overrides = [
{ path: `${pwd}/evm/script/DeployWormholeNtt.s.sol`, with: evmDeployFile },
{ path: `${pwd}/evm/script/helpers/DeployWormholeNttBase.sol`, with: evmDeployFileHelper },
]
for (const { path, with: withFile } of overrides) {
const old = `${path}.old`;
if (fs.existsSync(path)) {
fs.copyFileSync(path, old);
}
fs.copyFileSync(withFile, path);
}
try {
return await then()
} finally {
// restore old files
for (const { path } of overrides) {
const old = `${path}.old`;
if (fs.existsSync(old)) {
fs.copyFileSync(old, path);
fs.unlinkSync(old);
}
}
}
}
yargs(hideBin(process.argv))
.wrap(Math.min(process.stdout.columns || 120, 160)) // Use terminal width, but no more than 160 characters
.scriptName("ntt")
.version((() => {
const ver = nttVersion();
if (!ver) {
return "unknown";
}
const { version, commit, path, remote } = ver;
const defaultPath = `${process.env.HOME}/.ntt-cli/.checkout`;
const remoteString = remote.includes("wormhole-foundation") ? "" : `${remote}@`;
if (path === defaultPath) {
return `ntt v${version} (${remoteString}${commit})`;
} else {
return `ntt v${version} (${remoteString}${commit}) from ${path}`;
}
})())
// config group of commands
.command("config",
"configuration commands",
configuration.command
)
.command("update",
"update the NTT CLI",
(yargs) => yargs
.option("path", {
describe: "Path to a local NTT repo to install from. If not specified, the latest version will be installed.",
type: "string",
})
.option("branch", {
describe: "Git branch to install from",
type: "string",
})
.option("repo", {
describe: "Git repository to install from",
type: "string",
})
.example("$0 update", "Update the NTT CLI to the latest version")
.example("$0 update --path /path/to/ntt", "Update the NTT CLI from a local repo")
.example("$0 update --branch cli", "Update the NTT CLI to the cli branch"),
async (argv) => {
const localPath = argv["path"];
if (localPath) {
if (argv["ref"]) {
console.error("Cannot specify both --path and --ref");
process.exit(1);
}
if (argv["repo"]) {
console.error("Cannot specify both --path and --repo");
process.exit(1);
}
await $`${localPath}/cli/install.sh`;
} else {
let branchArg = "";
let repoArg = "";
if (argv["branch"]) {
branchArg = `--branch ${argv["branch"]}`;
}
if (argv["repo"]) {
repoArg = `--repo ${argv["repo"]}`;
}
const installScript = "https://raw.githubusercontent.com/wormhole-foundation/native-token-transfers/main/cli/install.sh";
// save it to "$HOME/.ntt-cli/install.sh"
const nttDir = `${process.env.HOME}/.ntt-cli`;
const installer = `${nttDir}/install.sh`;
execSync(`mkdir -p ${nttDir}`);
execSync(`curl -s ${installScript} > ${installer}`);
execSync(`chmod +x ${installer}`);
execSync(`${installer} ${branchArg} ${repoArg}`, { stdio: "inherit" });
}
})
.command("new <path>",
"create a new NTT project",
(yargs) => yargs
.positional("path", {
describe: "Path to the project",
type: "string",
demandOption: true,
})
.example("$0 new my-ntt-project", "Create a new NTT project in the 'my-ntt-project' directory"),
async (argv) => {
const git = execSync("git rev-parse --is-inside-work-tree || echo false", {
stdio: ["inherit", null, null]
});
if (git.toString().trim() === "true") {
console.error("Already in a git repository");
process.exit(1);
}
const path = argv["path"];
await $`git clone -b main https://github.com/wormhole-foundation/native-token-transfers.git ${path}`;
})
.command("add-chain <chain>",
"add a chain to the deployment file",
(yargs) => yargs
.positional("chain", options.chain)
// TODO: add ability to specify manager address (then just pull the config)
// .option("manager", {
// describe: "Manager address",
// type: "string",
// })
.option("program-key", {
describe: "Path to program key json (Solana)",
type: "string",
})
.option("payer", {
describe: "Path to payer key json (Solana)",
type: "string",
})
.option("binary", {
describe: "Path to program binary (.so file -- Solana)",
type: "string",
})
.option("token", {
describe: "Token address",
type: "string",
})
.option("mode", {
alias: "m",
describe: "Mode",
type: "string",
choices: ["locking", "burning"],
})
.option("solana-priority-fee", {
describe: "Priority fee for Solana deployment (in microlamports)",
type: "number",
default: 50000,
})
.option("signer-type", options.signerType)
.option("skip-verify", options.skipVerify)
.option("ver", options.version)
.option("latest", options.latest)
.option("local", options.local)
.option("path", options.deploymentPath)
.option("yes", options.yes)
.example("$0 add-chain Ethereum --token 0x1234... --mode burning --latest", "Add Ethereum chain with the latest contract version in burning mode")
.example("$0 add-chain Solana --token Sol1234... --mode locking --ver 1.0.0", "Add Solana chain with a specific contract version in locking mode")
.example("$0 add-chain Avalanche --token 0xabcd... --mode burning --local", "Add Avalanche chain using the local contract version"),
async (argv) => {
const path = argv["path"];
const deployments: Config = loadConfig(path);
const chain: Chain = argv["chain"];
const version = resolveVersion(argv["latest"], argv["ver"], argv["local"], chainToPlatform(chain));
let mode = argv["mode"] as Ntt.Mode | undefined;
const signerType = argv["signer-type"] as SignerType;
const token = argv["token"];
const network = deployments.network as Network;
if (chain in deployments.chains) {
console.error(`Chain ${chain} already exists in ${path}`);
process.exit(1);
}
validateChain(network, chain);
const existsLocking = Object.values(deployments.chains).some((c) => c.mode === "locking");
if (existsLocking) {
if (mode && mode === "locking") {
console.error("Only one locking chain is allowed");
process.exit(1);
}
mode = "burning";
}
if (!mode) {
console.error("Mode is required (use --mode)");
process.exit(1);
}
if (!token) {
console.error("Token is required (use --token)");
process.exit(1);
}
// let's deploy
// TODO: factor out to function to get chain context
const wh = new Wormhole(network, [solana.Platform, evm.Platform], overrides);
const ch = wh.getChain(chain);
// TODO: make manager configurable
const deployedManager = await deploy(version, mode, ch, token, signerType, !argv["skip-verify"], argv["yes"], argv["payer"], argv["program-key"], argv["binary"], argv["solana-priority-fee"]);
const [config, _ctx, _ntt, decimals] =
await pullChainConfig(network, deployedManager, overrides);
console.log("token decimals:", chalk.yellow(decimals));
deployments.chains[chain] = config;
fs.writeFileSync(path, JSON.stringify(deployments, null, 2));
console.log(`Added ${chain} to ${path}`);
})
.command("upgrade <chain>",
"upgrade the contract on a specific chain",
(yargs) => yargs
.positional("chain", options.chain)
.option("ver", options.version)
.option("latest", {
describe: "Use the latest version",
type: "boolean",
default: false,
})
.option("local", options.local)
.option("signer-type", options.signerType)
.option("skip-verify", options.skipVerify)
.option("path", options.deploymentPath)
.option("yes", options.yes)
.option("payer", {
describe: "Path to payer key json (Solana)",
type: "string",
})
.option("program-key", {
describe: "Path to program key json (Solana)",
type: "string",
})
.option("binary", {
describe: "Path to program binary (.so file -- Solana)",
type: "string",
})
.example("$0 upgrade Ethereum --latest", "Upgrade the Ethereum contract to the latest version")
.example("$0 upgrade Solana --ver 1.1.0", "Upgrade the Solana contract to version 1.1.0")
.example("$0 upgrade Polygon --local --skip-verify", "Upgrade the Polygon contract using the local version, skipping explorer bytecode verification"),
async (argv) => {
const path = argv["path"];
const deployments: Config = loadConfig(path);
const chain: Chain = argv["chain"];
const signerType = argv["signer-type"] as SignerType;
const network = deployments.network as Network;
if (!(chain in deployments.chains)) {
console.error(`Chain ${chain} not found in ${path}`);
process.exit(1);
}
const chainConfig = deployments.chains[chain]!;
const currentVersion = chainConfig.version;
const platform = chainToPlatform(chain);
const toVersion = resolveVersion(argv["latest"], argv["ver"], argv["local"], platform);
if (argv["local"]) {
await warnLocalDeployment(argv["yes"]);
}
if (toVersion === currentVersion && !argv["local"]) {
console.log(`Chain ${chain} is already at version ${currentVersion}`);
process.exit(0);
}
console.log(`Upgrading ${chain} from version ${currentVersion} to ${toVersion || 'local version'}`);
if (!argv["yes"]) {
await askForConfirmation();
}
const wh = new Wormhole(network, [solana.Platform, evm.Platform], overrides);
const ch = wh.getChain(chain);
const [_, ctx, ntt] = await pullChainConfig(
network,
{ chain, address: toUniversal(chain, chainConfig.manager) },
overrides
);
await upgrade(
currentVersion,
toVersion,
ntt,
ctx,
signerType,
!argv["skip-verify"],
argv["payer"],
argv["program-key"],
argv["binary"]
);
// reinit the ntt object to get the new version
// TODO: is there an easier way to do this?
const { ntt: upgraded } = await nttFromManager(ch, chainConfig.manager);
chainConfig.version = getVersion(chain, upgraded)
fs.writeFileSync(path, JSON.stringify(deployments, null, 2));
console.log(`Successfully upgraded ${chain} to version ${toVersion || 'local version'}`);
}
)
.command("clone <network> <chain> <address>",
"initialize a deployment file from an existing contract",
(yargs) => yargs
.positional("network", options.network)
.positional("chain", options.chain)
.positional("address", options.address)
.option("path", options.deploymentPath)
.option("verbose", options.verbose)
.example("$0 clone Testnet Ethereum 0x5678...", "Clone an existing Ethereum deployment on Testnet")
.example("$0 clone Mainnet Solana Sol5678... --path custom-clone.json", "Clone an existing Solana deployment on Mainnet to a custom file"),
async (argv) => {
if (!isNetwork(argv["network"])) {
console.error("Invalid network");
process.exit(1);
}
const path = argv["path"];
const verbose = argv["verbose"];
// check if the file exists
if (fs.existsSync(path)) {
console.error(`Deployment file already exists at ${path}`);
process.exit(1);
}
// step 1. grab the config
// step 2. discover registrations
// step 3. grab registered peer configs
//
// NOTE: we don't recursively grab peer configs. This means the
// discovered peers will be the ones that are directly registered with
// the starting manager (the one we're cloning).
// For example, if we're cloning manager A, and it's registered with
// B, and B is registered with C, but C is not registered with A, then
// C will not be included in the cloned deployment.
// We could do peer discovery recursively but that would be a lot
// slower, since peer discovery is already O(n) in the number of
// supported chains (50+), because there is no way to enumerate the peers, so we
// need to query all possible chains to see if they're registered.
const chain = argv["chain"];
assertChain(chain)
const manager = argv["address"];
const network = argv["network"];
const universalManager = toUniversal(chain, manager);
const ntts: Partial<{ [C in Chain]: Ntt<Network, C> }> = {};
const [config, _ctx, ntt, _decimals] =
await pullChainConfig(network, { chain, address: universalManager }, overrides);
ntts[chain] = ntt as any;
const configs: Partial<{ [C in Chain]: ChainConfig }> = {
[chain]: config,
}
// discover peers
let count = 0;
for (const c of chains) {
process.stdout.write(`[${count}/${chains.length - 1}] Fetching peer config for ${c}`);
await new Promise((resolve) => setTimeout(resolve, 100));
count++;
const peer = await retryWithExponentialBackoff(() => ntt.getPeer(c), 5, 5000);
process.stdout.write(`\n`);
if (peer === null) {
continue;
}
const address: UniversalAddress = peer.address.address.toUniversalAddress()
const [peerConfig, _ctx, peerNtt] = await pullChainConfig(network, { chain: c, address }, overrides);
ntts[c] = peerNtt as any;
configs[c] = peerConfig;
}
// sort chains by name
const sorted = Object.fromEntries(Object.entries(configs).sort(([a], [b]) => a.localeCompare(b)));
// sleep for a bit to avoid rate limiting when making the getDecimals call
// this can happen when the last we hit the rate limit just in the last iteration of the loop above.
// (happens more often than you'd think, because the rate limiter
// gets more aggressive after each hit)
await new Promise((resolve) => setTimeout(resolve, 2000));
// now loop through the chains, and query their peer information to get the inbound limits
await pullInboundLimits(ntts, sorted, verbose)
const deployment: Config = {
network: argv["network"],
chains: sorted,
};
fs.writeFileSync(path, JSON.stringify(deployment, null, 2));
})
.command("init <network>",
"initialize a deployment file",
(yargs) => yargs
.positional("network", options.network)
.option("path", options.deploymentPath)
.example("$0 init Testnet", "Initialize a new deployment file for the Testnet network")
.example("$0 init Mainnet --path custom.json", "Initialize a new deployment file for Mainnet with a custom file name"),
async (argv) => {
if (!isNetwork(argv["network"])) {
console.error("Invalid network");
process.exit(1);
}
const deployment = {
network: argv["network"],
chains: {},
};
const path = argv["path"];
// check if the file exists
if (fs.existsSync(path)) {
console.error(`Deployment file already exists at ${path}. Specify a different path with --path`);
process.exit(1);
}
fs.writeFileSync(path, JSON.stringify(deployment, null, 2));
})
.command("pull",
"pull the remote configuration",
(yargs) => yargs
.option("path", options.deploymentPath)
.option("yes", options.yes)
.option("verbose", options.verbose)
.example("$0 pull", "Pull the latest configuration from the blockchain for all chains")
.example("$0 pull --yes", "Pull the latest configuration and apply changes without confirmation"),
async (argv) => {
const deployments: Config = loadConfig(argv["path"]);
const verbose = argv["verbose"];
const network = deployments.network as Network;
const path = argv["path"];
const deps: Partial<{ [C in Chain]: Deployment<Chain> }> = await pullDeployments(deployments, network, verbose);
let changed = false;
for (const [chain, deployment] of Object.entries(deps)) {
assertChain(chain);
const diff = diffObjects(deployments.chains[chain]!, deployment.config.remote!);
if (Object.keys(diff).length !== 0) {
console.error(chalk.reset(colorizeDiff({ [chain]: diff })));
changed = true;
deployments.chains[chain] = deployment.config.remote!
}
}
if (!changed) {
console.log(`${path} is already up to date`);
process.exit(0);
}
if (!argv["yes"]) {
await askForConfirmation();
}
fs.writeFileSync(path, JSON.stringify(deployments, null, 2));
console.log(`Updated ${path}`);
})
.command("push",
"push the local configuration",
(yargs) => yargs
.option("path", options.deploymentPath)
.option("yes", options.yes)
.option("signer-type", options.signerType)
.option("verbose", options.verbose)
.option("skip-verify", options.skipVerify)
.option("payer", options.payer)
.example("$0 push", "Push local configuration changes to the blockchain")
.example("$0 push --signer-type ledger", "Push changes using a Ledger hardware wallet for signing")
.example("$0 push --skip-verify", "Push changes without verifying contracts on EVM chains")
.example("$0 push --payer <SOLANA_KEYPAIR_PATH>", "Path to the payer json file (Solana), instead of setting SOLANA_PRIVATE_KEY env variable"),
async (argv) => {
const deployments: Config = loadConfig(argv["path"]);
const verbose = argv["verbose"];
const network = deployments.network as Network;
const deps: Partial<{ [C in Chain]: Deployment<Chain> }> = await pullDeployments(deployments, network, verbose);
const signerType = argv["signer-type"] as SignerType;
const payerPath = argv["payer"];
const missing = await missingConfigs(deps, verbose);
if (checkConfigErrors(deps)) {
console.error("There are errors in the config file. Please fix these before continuing.");
process.exit(1);
}
for (const [chain, missingConfig] of Object.entries(missing)) {
assertChain(chain);
const ntt = deps[chain]!.ntt;
const ctx = deps[chain]!.ctx;
const signer = await getSigner(ctx, signerType, undefined, payerPath);
for (const manager of missingConfig.managerPeers) {
const tx = ntt.setPeer(manager.address, manager.tokenDecimals, manager.inboundLimit, signer.address.address)
await signSendWait(ctx, tx, signer.signer)
}
for (const transceiver of missingConfig.transceiverPeers) {
const tx = ntt.setWormholeTransceiverPeer(transceiver, signer.address.address)
await signSendWait(ctx, tx, signer.signer)
}
for (const evmChain of missingConfig.evmChains) {
const tx = (await ntt.getTransceiver(0) as EvmNttWormholeTranceiver<Network, EvmChains>).setIsEvmChain(evmChain, true)
await signSendWait(ctx, tx, signer.signer)
}
for (const relayingTarget of missingConfig.standardRelaying) {
const tx = (await ntt.getTransceiver(0) as EvmNttWormholeTranceiver<Network, EvmChains>).setIsWormholeRelayingEnabled(relayingTarget, true)
await signSendWait(ctx, tx, signer.signer)
}
for (const relayingTarget of missingConfig.specialRelaying) {
const tx = (await ntt.getTransceiver(0) as EvmNttWormholeTranceiver<Network, EvmChains>).setIsSpecialRelayingEnabled(relayingTarget, true)
await signSendWait(ctx, tx, signer.signer)
}
if (missingConfig.solanaWormholeTransceiver) {
if (chainToPlatform(chain) !== "Solana") {
console.error("Solana wormhole transceiver can only be set on Solana chains");
continue;
}
const solanaNtt = ntt as SolanaNtt<Network, SolanaChains>;
const tx = solanaNtt.registerTransceiver({
payer: signer.address.address as AccountAddress<SolanaChains>,
owner: signer.address.address as AccountAddress<SolanaChains>,
transceiver: solanaNtt.program.programId
})
try {
await signSendWait(ctx, tx, signer.signer)
} catch (e: any) {
console.error(e.logs);
}
}
if (missingConfig.solanaUpdateLUT) {
if (chainToPlatform(chain) !== "Solana") {
console.error("Solana update LUT can only be set on Solana chains");
continue;
}
const solanaNtt = ntt as SolanaNtt<Network, SolanaChains>;
const tx = solanaNtt.initializeOrUpdateLUT({ payer: new SolanaAddress(signer.address.address).unwrap() })
try {
await signSendWait(ctx, tx, signer.signer)
} catch (e: any) {
console.error(e.logs);
}
}
}
// pull deps again
const depsAfterRegistrations: Partial<{ [C in Chain]: Deployment<Chain> }> = await pullDeployments(deployments, network, verbose);
for (const [chain, deployment] of Object.entries(depsAfterRegistrations)) {
assertChain(chain);
await pushDeployment(deployment as any, signerType, !argv["skip-verify"], argv["yes"], payerPath);
}
})
.command("status",
"check the status of the deployment",
(yargs) => yargs
.option("path", options.deploymentPath)
.option("verbose", options.verbose)
.example("$0 status", "Check the status of the deployment across all chains")
.example("$0 status --verbose", "Check the status with detailed output"),
async (argv) => {
const path = argv["path"];
const verbose = argv["verbose"];
// TODO: I don't like the variable names here
const deployments: Config = loadConfig(path);
const network = deployments.network as Network;
let deps: Partial<{ [C in Chain]: Deployment<Chain> }> = await pullDeployments(deployments, network, verbose);
let fixable = 0;
const extraInfo: any = {};
if (checkConfigErrors(deps)) {
console.error("There are errors in the config file. Please fix these before continuing.");
process.exit(1);
}
// diff remote and local configs
for (const [chain, deployment] of Object.entries(deps)) {
assertChain(chain);
const local = deployment.config.local;
const remote = deployment.config.remote;
const a = { [chain]: local! };
const b = { [chain]: remote! };
const diff = diffObjects(a, b);
if (Object.keys(diff).length !== 0) {
console.error(chalk.reset(colorizeDiff(diff)));
fixable++;
}
if (verbose) {
const immutables = await getImmutables(chain, deployment.ntt);
if (immutables) {
extraInfo[chain] = immutables;
}
const pdas = await getPdas(chain, deployment.ntt);
if (pdas) {
extraInfo[chain] = pdas;
}
}
}
if (Object.keys(extraInfo).length > 0) {
console.log(chalk.yellow(JSON.stringify(extraInfo, null, 2)));
}
// verify peers
const missing = await missingConfigs(deps, verbose);
if (Object.keys(missing).length > 0) {
fixable++;
}
for (const [chain, missingConfig] of Object.entries(missing)) {
console.error(`${chain} status:`);
for (const manager of missingConfig.managerPeers) {
console.error(` Missing manager peer: ${manager.address.chain}`);
}
for (const transceiver of missingConfig.transceiverPeers) {
console.error(` Missing transceiver peer: ${transceiver.chain}`);
}
for (const evmChain of missingConfig.evmChains) {
console.error(` ${evmChain} needs to be configured as an EVM chain`);
}
for (const relayingTarget of missingConfig.standardRelaying) {
console.warn(` No standard relaying to ${relayingTarget}`);
}
for (const relayingTarget of missingConfig.specialRelaying) {
console.warn(` No special relaying to ${relayingTarget}`);
}
if (missingConfig.solanaWormholeTransceiver) {
console.error(" Missing Solana wormhole transceiver");
}
if (missingConfig.solanaUpdateLUT) {
console.error(" Missing or outdated LUT");
}
}
if (fixable > 0) {
console.error("Run `ntt pull` to pull the remote configuration (overwriting the local one)");
console.error("Run `ntt push` to push the local configuration (overwriting the remote one) by executing the necessary transactions");
process.exit(1);
} else {
console.log(`${path} is up to date with the on-chain configuration.`);
process.exit(0);
}
})
.command("solana",
"Solana commands",
(yargs) => {
yargs
.command("key-base58 <keypair>",
"print private key in base58",
(yargs) => yargs
.positional("keypair", {
describe: "Path to keypair.json",
type: "string",
demandOption: true,
}),
(argv) => {
const keypair = Keypair.fromSecretKey(new Uint8Array(JSON.parse(fs.readFileSync(argv["keypair"]).toString())));
console.log(encoding.b58.encode(keypair.secretKey));
})
.command("token-authority <programId>",
"print the token authority address for a given program ID",
(yargs) => yargs
.positional("programId", {
describe: "Program ID",
type: "string",
demandOption: true,
}),
(argv) => {
const programId = new PublicKey(argv["programId"]);
const tokenAuthority = NTT.pdas(programId).tokenAuthority();
console.log(tokenAuthority.toBase58());
})
.command("ata <mint> <owner> <tokenProgram>",
"print the token authority address for a given program ID",
(yargs) => yargs
.positional("mint", {
describe: "Mint address",
type: "string",
demandOption: true,
})
.positional("owner", {
describe: "Owner address",
type: "string",
demandOption: true,
})
.positional("tokenProgram", {
describe: "Token program ID",
type: "string",
choices: ["legacy", "token22"],
demandOption: true,
}),
(argv) => {
const mint = new PublicKey(argv["mint"]);
const owner = new PublicKey(argv["owner"]);
const tokenProgram = argv["tokenProgram"] === "legacy"
? spl.TOKEN_PROGRAM_ID
: spl.TOKEN_2022_PROGRAM_ID
const ata = spl.getAssociatedTokenAddressSync(mint, owner, true, tokenProgram);
console.log(ata.toBase58());
})
.demandCommand()
}
)
.help()
.strict()
.demandCommand()
.parse();
// Implicit configuration that's missing from a contract deployment. These are
// implicit in the sense that they don't need to be explicitly set in the
// deployment file.
// For example, all managers and transceivers need to be registered with each other.
// Additionally, the EVM chains need to be registered as such, and the standard relaying
// needs to be enabled for all chains where this is supported.
type MissingImplicitConfig = {
managerPeers: Ntt.Peer<Chain>[];
transceiverPeers: ChainAddress<Chain>[];
evmChains: Chain[];
standardRelaying: Chain[];
specialRelaying: Chain[];
solanaWormholeTransceiver: boolean;
solanaUpdateLUT: boolean;
}
function checkConfigErrors(deps: Partial<{ [C in Chain]: Deployment<Chain> }>): number {
let fatal = 0;
for (const [chain, deployment] of Object.entries(deps)) {
assertChain(chain);
const config = deployment.config.local!;
if (!checkNumberFormatting(config.limits.outbound, deployment.decimals)) {
console.error(`ERROR: ${chain} has an outbound limit (${config.limits.outbound}) with the wrong number of decimals. The number should have ${deployment.decimals} decimals.`);
fatal++;
}
if (config.limits.outbound === formatNumber(0n, deployment.decimals)) {
console.warn(chalk.yellow(`${chain} has an outbound limit of 0`));
}
for (const [c, limit] of Object.entries(config.limits.inbound)) {
if (!checkNumberFormatting(limit, deployment.decimals)) {
console.error(`ERROR: ${chain} has an inbound limit with the wrong number of decimals for ${c} (${limit}). The number should have ${deployment.decimals} decimals.`);
fatal++;
}
if (limit === formatNumber(0n, deployment.decimals)) {
console.warn(chalk.yellow(`${chain} has an inbound limit of 0 from ${c}`));
}
}
}
return fatal;
}
function createWorkTree(platform: Platform, version: string): string {
const tag = getGitTagName(platform, version);
if (!tag) {
console.error(`No tag found matching ${version} for ${platform}`);
process.exit(1);
}
const worktreeName = `.deployments/${platform}-${version}`;
if (fs.existsSync(worktreeName)) {
console.log(chalk.yellow(`Worktree already exists at ${worktreeName}. Resetting to ${tag}`));
execSync(`git -C ${worktreeName} reset --hard ${tag}`, {
stdio: "inherit"
});
} else {
// create worktree
execSync(`git worktree add ${worktreeName} ${tag}`, {
stdio: "inherit"
});
}
// NOTE: we create this symlink whether or not the file exists.
// this way, if it's created later, the symlink will be correct
execSync(`ln -fs $(pwd)/overrides.json $(pwd)/${worktreeName}/overrides.json`, {
stdio: "inherit"
});
console.log(chalk.green(`Created worktree at ${worktreeName} from tag ${tag}`));
return worktreeName;
}
async function upgrade<N extends Network, C extends Chain>(
_fromVersion: string,
toVersion: string | null,
ntt: Ntt<N, C>,
ctx: ChainContext<N, C>,
signerType: SignerType,
evmVerify: boolean,
solanaPayer?: string,
solanaProgramKeyPath?: string,
solanaBinaryPath?: string
): Promise<void> {
// TODO: check that fromVersion is safe to upgrade to toVersion from
const platform = chainToPlatform(ctx.chain);
const worktree = toVersion ? createWorkTree(platform, toVersion) : ".";
switch (platform) {
case "Evm":
const evmNtt = ntt as EvmNtt<N, EvmChains>;
const evmCtx = ctx as ChainContext<N, EvmChains>;
return upgradeEvm(worktree, evmNtt, evmCtx, signerType, evmVerify);
case "Solana":
if (solanaPayer === undefined || !fs.existsSync(solanaPayer)) {
console.error("Payer not found. Specify with --payer");
process.exit(1);
}
const solanaNtt = ntt as SolanaNtt<N, SolanaChains>;
const solanaCtx = ctx as ChainContext<N, SolanaChains>;
return upgradeSolana(worktree, toVersion, solanaNtt, solanaCtx, solanaPayer, solanaProgramKeyPath, solanaBinaryPath);
default:
throw new Error("Unsupported platform");
}
}
async function upgradeEvm<N extends Network, C extends EvmChains>(
pwd: string,