-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathntt.ts
904 lines (792 loc) · 30.3 KB
/
ntt.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
import { type ChainName, toChainId, coalesceChainId, type ChainId, type SignedVaa } from '@certusone/wormhole-sdk'
import { serializeLayout, toChainId as SDKv2toChainId } from '@wormhole-foundation/sdk-base'
import {
deserialize,
} from '@wormhole-foundation/sdk-definitions'
import {
type NttManagerMessage,
nttManagerMessageLayout,
nativeTokenTransferLayout
} from './nttLayout'
import { derivePostedVaaKey, getWormholeDerivedAccounts } from '@certusone/wormhole-sdk/lib/cjs/solana/wormhole'
import { BN, translateError, type IdlAccounts, Program, AnchorProvider, Wallet, } from '@coral-xyz/anchor'
import { associatedAddress } from '@coral-xyz/anchor/dist/cjs/utils/token'
import { getAssociatedTokenAddressSync } from '@solana/spl-token'
import {
PublicKey, Keypair,
type TransactionInstruction,
Transaction,
sendAndConfirmTransaction,
type TransactionSignature,
type Connection,
TransactionMessage,
VersionedTransaction
} from '@solana/web3.js'
import { Keccak } from 'sha3'
import { type ExampleNativeTokenTransfers as RawExampleNativeTokenTransfers } from '../../idl/ts/example_native_token_transfers'
import { BPF_LOADER_UPGRADEABLE_PROGRAM_ID, programDataAddress, chainIdToBeBytes, derivePda } from './utils'
import * as splToken from '@solana/spl-token';
import IDL from '../../idl/json/example_native_token_transfers.json';
export * from './utils/wormhole'
export const nttMessageLayout = nttManagerMessageLayout(nativeTokenTransferLayout);
export type NttMessage = NttManagerMessage<typeof nativeTokenTransferLayout>;
// This is a workaround for the fact that the anchor idl doesn't support generics
// yet. This type is used to remove the generics from the idl types.
type OmitGenerics<T> = {
[P in keyof T]: T[P] extends Record<"generics", any>
? never
: T[P] extends object
? OmitGenerics<T[P]>
: T[P];
};
export type ExampleNativeTokenTransfers = OmitGenerics<RawExampleNativeTokenTransfers>
export type Config = IdlAccounts<ExampleNativeTokenTransfers>['config']
export type InboxItem = IdlAccounts<ExampleNativeTokenTransfers>['inboxItem']
export interface TransferArgs {
amount: BN
recipientChain: { id: ChainId }
recipientAddress: number[]
shouldQueue: boolean
}
export const NTT_PROGRAM_IDS = [
"nttiK1SepaQt6sZ4WGW5whvc9tEnGXGxuKeptcQPCcS",
"NTTManager111111111111111111111111111111111",
"NTTManager222222222222222222222222222222222",
] as const;
export const WORMHOLE_PROGRAM_IDS = [
"worm2ZoG2kUd4vFXhvjh93UUH596ayRfgQ2MgjNMTth", // mainnet
"3u8hJUVTA4jH1wYAyUur7FFZVQ8H635K3tSHHF4ssjQ5", // testnet
"Bridge1p5gheXUvJ6jGWGeCsgPKgnE3YgdGKRVCMY9o", // tilt
] as const;
export type NttProgramId = (typeof NTT_PROGRAM_IDS)[number];
export type WormholeProgramId = (typeof WORMHOLE_PROGRAM_IDS)[number];
export class NTT {
readonly program: Program<ExampleNativeTokenTransfers>
readonly wormholeId: PublicKey
// mapping from error code to error message. Used for prettifying error messages
private readonly errors: Map<number, string>
constructor(connection: Connection, args: { nttId: NttProgramId, wormholeId: WormholeProgramId }) {
// TODO: initialise a new Program here with a passed in Connection
this.program = new Program(IDL as any, new PublicKey(args.nttId), { connection });
this.wormholeId = new PublicKey(args.wormholeId)
this.errors = this.processErrors()
}
// The `translateError` function expects this format, but the idl gives us a
// different one, so we preprocess the idl and store the expected format.
// NOTE: I'm sure there's a function within anchor that does this, but I
// couldn't find it.
private processErrors(): Map<number, string> {
const errors = this.program.idl.errors
const result: Map<number, string> = new Map<number, string>()
errors.forEach(entry => result.set(entry.code, entry.msg))
return result
}
// Account addresses
private derivePda(seeds: Parameters<typeof derivePda>[0]): PublicKey {
return derivePda(seeds, this.program.programId)
}
configAccountAddress(): PublicKey {
return this.derivePda('config')
}
outboxRateLimitAccountAddress(): PublicKey {
return this.derivePda('outbox_rate_limit')
}
inboxRateLimitAccountAddress(chain: ChainName | ChainId): PublicKey {
const chainId = coalesceChainId(chain)
return this.derivePda(['inbox_rate_limit', chainIdToBeBytes(chainId)])
}
inboxItemAccountAddress(chain: ChainName | ChainId, nttMessage: NttMessage): PublicKey {
const chainId = coalesceChainId(chain)
const serialized = Buffer.from(
serializeLayout(nttManagerMessageLayout(nativeTokenTransferLayout), nttMessage)
)
const hasher = new Keccak(256) //TODO replace with keccak256 from SDKv2
hasher.update(Buffer.from(chainIdToBeBytes(chainId)))
hasher.update(serialized)
return this.derivePda(['inbox_item', hasher.digest()])
}
sessionAuthorityAddress(sender: PublicKey, args: TransferArgs): PublicKey {
const { amount, recipientChain, recipientAddress, shouldQueue } = args
const serialized = Buffer.concat([
amount.toArrayLike(Buffer, 'be', 8),
Buffer.from(new BN(recipientChain.id).toArrayLike(Buffer, 'be', 2)),
Buffer.from(new Uint8Array(recipientAddress)),
Buffer.from([shouldQueue ? 1 : 0])
])
const hasher = new Keccak(256)
hasher.update(serialized)
return this.derivePda(['session_authority', sender.toBytes(), hasher.digest()])
}
tokenAuthorityAddress(): PublicKey {
return this.derivePda('token_authority')
}
emitterAccountAddress(): PublicKey {
return this.derivePda('emitter')
}
wormholeMessageAccountAddress(outboxItem: PublicKey): PublicKey {
return this.derivePda(['message', outboxItem.toBytes()])
}
peerAccountAddress(chain: ChainName | ChainId): PublicKey {
const chainId = coalesceChainId(chain)
return this.derivePda(['peer', chainIdToBeBytes(chainId)])
}
transceiverPeerAccountAddress(chain: ChainName | ChainId): PublicKey {
const chainId = coalesceChainId(chain)
return this.derivePda(['transceiver_peer', chainIdToBeBytes(chainId)])
}
transceiverMessageAccountAddress(chain: ChainName | ChainId, id: Uint8Array): PublicKey {
const chainId = coalesceChainId(chain)
if (id.length != 32) {
throw new Error('id must be 32 bytes')
}
return this.derivePda(['transceiver_message', chainIdToBeBytes(chainId), id])
}
registeredTransceiverAddress(transceiver: PublicKey): PublicKey {
return this.derivePda(['registered_transceiver', transceiver.toBytes()])
}
// View functions
async version(pubkey: PublicKey): Promise<string> {
// the anchor library has a built-in method to read view functions. However,
// it requires a signer, which would trigger a wallet prompt on the frontend.
// Instead, we manually construct a versioned transaction and call the
// simulate function with sigVerify: false below.
//
// This way, the simulation won't require a signer, but it still requires
// the pubkey of an account that has some lamports in it (since the
// simulation checks if the account has enough money to pay for the transaction).
//
// It's a little unfortunate but it's the best we can do.
const ix = await this.program.methods.version()
.accountsStrict({}).instruction()
const latestBlockHash = await this.program.provider.connection.getLatestBlockhash()
const msg = new TransactionMessage({
payerKey: pubkey,
recentBlockhash: latestBlockHash.blockhash,
instructions: [ix],
}).compileToV0Message();
const tx = new VersionedTransaction(msg);
const txSimulation =
await this.program.provider.connection
.simulateTransaction(tx, {
sigVerify: false,
})
// the return buffer is in base64 and it encodes the string with a 32 bit
// little endian length prefix.
const buffer = Buffer.from(txSimulation.value.returnData?.data[0], 'base64')
const len = buffer.readUInt32LE(0)
return buffer.slice(4, len + 4).toString()
}
// Instructions
async initialize(args: {
payer: Keypair
owner: Keypair
chain: ChainName
mint: PublicKey
outboundLimit: BN
mode: 'burning' | 'locking'
}) {
const mode: any =
args.mode === 'burning'
? { burning: {} }
: { locking: {} }
const chainId = toChainId(args.chain)
const mintInfo = await this.program.provider.connection.getAccountInfo(args.mint)
if (mintInfo === null) {
throw new Error("Couldn't determine token program. Mint account is null.")
}
const tokenProgram = mintInfo.owner
const ix = await this.program.methods
.initialize({ chainId, limit: args.outboundLimit, mode })
.accounts({
payer: args.payer.publicKey,
deployer: args.owner.publicKey,
programData: programDataAddress(this.program.programId),
config: this.configAccountAddress(),
mint: args.mint,
rateLimit: this.outboxRateLimitAccountAddress(),
tokenProgram,
tokenAuthority: this.tokenAuthorityAddress(),
custody: await this.custodyAccountAddress(args.mint),
bpfLoaderUpgradeableProgram: BPF_LOADER_UPGRADEABLE_PROGRAM_ID,
}).instruction();
return sendAndConfirmTransaction(this.program.provider.connection, new Transaction().add(ix), [args.payer, args.owner]);
}
async transfer(args: {
payer: Keypair
from: PublicKey
fromAuthority: Keypair
amount: BN
recipientChain: ChainName
recipientAddress: ArrayLike<number>
shouldQueue: boolean
outboxItem?: Keypair
config?: Config
}): Promise<PublicKey> {
const config: Config = await this.getConfig(args.config)
const outboxItem = args.outboxItem ?? Keypair.generate()
const txArgs = {
...args,
payer: args.payer.publicKey,
fromAuthority: args.fromAuthority.publicKey,
outboxItem: outboxItem.publicKey,
config
}
let transferIx: TransactionInstruction
if (config.mode.locking != null) {
transferIx = await this.createTransferLockInstruction(txArgs)
} else if (config.mode.burning != null) {
transferIx = await this.createTransferBurnInstruction(txArgs)
} else {
// @ts-ignore
transferIx = exhaustive(config.mode)
}
const releaseIx: TransactionInstruction = await this.createReleaseOutboundInstruction({
payer: args.payer.publicKey,
outboxItem: outboxItem.publicKey,
revertOnDelay: !args.shouldQueue
})
const signers = [args.payer, args.fromAuthority, outboxItem]
const transferArgs: TransferArgs = {
amount: args.amount,
recipientChain: { id: toChainId(args.recipientChain) },
recipientAddress: Array.from(args.recipientAddress),
shouldQueue: args.shouldQueue
}
const approveIx = splToken.createApproveInstruction(
args.from,
this.sessionAuthorityAddress(args.fromAuthority.publicKey, transferArgs),
args.fromAuthority.publicKey,
BigInt(args.amount.toString())
);
const tx = new Transaction()
tx.add(approveIx, transferIx, releaseIx)
await this.sendAndConfirmTransaction(tx, signers)
return outboxItem.publicKey
}
/**
* Like `sendAndConfirmTransaction` but parses the anchor error code.
*/
private async sendAndConfirmTransaction(tx: Transaction, signers: Keypair[]): Promise<TransactionSignature> {
try {
return await sendAndConfirmTransaction(this.program.provider.connection, tx, signers)
} catch (err) {
throw translateError(err, this.errors)
}
}
/**
* Creates a transfer_burn instruction. The `payer` and `fromAuthority`
* arguments must sign the transaction
*/
async createTransferBurnInstruction(args: {
payer: PublicKey
from: PublicKey
fromAuthority: PublicKey
amount: BN
recipientChain: ChainName
recipientAddress: ArrayLike<number>
outboxItem: PublicKey
shouldQueue: boolean
config?: Config
}): Promise<TransactionInstruction> {
const config = await this.getConfig(args.config)
if (await this.isPaused(config)) {
throw new Error('Contract is paused')
}
const chainId = toChainId(args.recipientChain)
const mint = await this.mintAccountAddress(config)
const transferArgs: TransferArgs = {
amount: args.amount,
recipientChain: { id: chainId },
recipientAddress: Array.from(args.recipientAddress),
shouldQueue: args.shouldQueue
}
return await this.program.methods
.transferBurn(transferArgs)
.accounts({
common: {
payer: args.payer,
config: { config: this.configAccountAddress() },
mint,
from: args.from,
outboxItem: args.outboxItem,
outboxRateLimit: this.outboxRateLimitAccountAddress()
},
peer: this.peerAccountAddress(args.recipientChain),
inboxRateLimit: this.inboxRateLimitAccountAddress(args.recipientChain),
sessionAuthority: this.sessionAuthorityAddress(args.fromAuthority, transferArgs)
})
.instruction()
}
/**
* Creates a transfer_lock instruction. The `payer`, `fromAuthority`, and `outboxItem`
* arguments must sign the transaction
*/
async createTransferLockInstruction(args: {
payer: PublicKey
from: PublicKey
fromAuthority: PublicKey
amount: BN
recipientChain: ChainName
recipientAddress: ArrayLike<number>
shouldQueue: boolean
outboxItem: PublicKey
config?: Config
}): Promise<TransactionInstruction> {
const config = await this.getConfig(args.config)
if (await this.isPaused(config)) {
throw new Error('Contract is paused')
}
const chainId = toChainId(args.recipientChain)
const mint = await this.mintAccountAddress(config)
const transferArgs: TransferArgs = {
amount: args.amount,
recipientChain: { id: chainId },
recipientAddress: Array.from(args.recipientAddress),
shouldQueue: args.shouldQueue
}
return await this.program.methods
.transferLock(transferArgs)
.accounts({
common: {
payer: args.payer,
config: { config: this.configAccountAddress() },
mint,
from: args.from,
tokenProgram: await this.tokenProgram(config),
outboxItem: args.outboxItem,
outboxRateLimit: this.outboxRateLimitAccountAddress()
},
peer: this.peerAccountAddress(args.recipientChain),
inboxRateLimit: this.inboxRateLimitAccountAddress(args.recipientChain),
custody: await this.custodyAccountAddress(config),
sessionAuthority: this.sessionAuthorityAddress(args.fromAuthority, transferArgs)
})
.instruction()
}
/**
* Creates a release_outbound instruction. The `payer` needs to sign the transaction.
*/
async createReleaseOutboundInstruction(args: {
payer: PublicKey
outboxItem: PublicKey
revertOnDelay: boolean
}): Promise<TransactionInstruction> {
const whAccs = getWormholeDerivedAccounts(this.program.programId, this.wormholeId)
return await this.program.methods
.releaseWormholeOutbound({
revertOnDelay: args.revertOnDelay
})
.accounts({
payer: args.payer,
config: { config: this.configAccountAddress() },
outboxItem: args.outboxItem,
wormholeMessage: this.wormholeMessageAccountAddress(args.outboxItem),
emitter: whAccs.wormholeEmitter,
transceiver: this.registeredTransceiverAddress(this.program.programId),
wormhole: {
bridge: whAccs.wormholeBridge,
feeCollector: whAccs.wormholeFeeCollector,
sequence: whAccs.wormholeSequence,
program: this.wormholeId
}
})
.instruction()
}
async releaseOutbound(args: {
payer: Keypair
outboxItem: PublicKey
revertOnDelay: boolean
config?: Config
}) {
if (await this.isPaused()) {
throw new Error('Contract is paused')
}
const txArgs = {
...args,
payer: args.payer.publicKey
}
const tx = new Transaction()
tx.add(await this.createReleaseOutboundInstruction(txArgs))
const signers = [args.payer]
return await sendAndConfirmTransaction(this.program.provider.connection, tx, signers)
}
// TODO: document that if recipient is provided, then the instruction can be
// created before the inbox item is created (i.e. they can be put in the same tx)
async createReleaseInboundMintInstruction(args: {
payer: PublicKey
chain: ChainName | ChainId
nttMessage: NttMessage
revertWhenNotReady: boolean
recipient?: PublicKey
config?: Config
}): Promise<TransactionInstruction> {
const config = await this.getConfig(args.config)
if (await this.isPaused(config)) {
throw new Error('Contract is paused')
}
const recipientAddress =
args.recipient ?? (await this.getInboxItem(args.chain, args.nttMessage)).recipientAddress
const mint = await this.mintAccountAddress(config)
return await this.program.methods
.releaseInboundMint({
revertWhenNotReady: args.revertWhenNotReady
})
.accounts({
common: {
payer: args.payer,
config: { config: this.configAccountAddress() },
inboxItem: this.inboxItemAccountAddress(args.chain, args.nttMessage),
recipient: getAssociatedTokenAddressSync(mint, recipientAddress),
mint,
tokenAuthority: this.tokenAuthorityAddress()
}
})
.instruction()
}
async releaseInboundMint(args: {
payer: Keypair
chain: ChainName | ChainId
nttMessage: NttMessage
revertWhenNotReady: boolean
config?: Config
}): Promise<void> {
if (await this.isPaused()) {
throw new Error('Contract is paused')
}
const txArgs = {
...args,
payer: args.payer.publicKey
}
const tx = new Transaction()
tx.add(await this.createReleaseInboundMintInstruction(txArgs))
const signers = [args.payer]
await this.sendAndConfirmTransaction(tx, signers)
}
async createReleaseInboundUnlockInstruction(args: {
payer: PublicKey
chain: ChainName | ChainId
nttMessage: NttMessage
revertWhenNotReady: boolean
recipient?: PublicKey
config?: Config
}): Promise<TransactionInstruction> {
const config = await this.getConfig(args.config)
if (await this.isPaused(config)) {
throw new Error('Contract is paused')
}
const recipientAddress =
args.recipient ?? (await this.getInboxItem(args.chain, args.nttMessage)).recipientAddress
const mint = await this.mintAccountAddress(config)
return await this.program.methods
.releaseInboundUnlock({
revertWhenNotReady: args.revertWhenNotReady
})
.accounts({
common: {
payer: args.payer,
config: { config: this.configAccountAddress() },
inboxItem: this.inboxItemAccountAddress(args.chain, args.nttMessage),
recipient: getAssociatedTokenAddressSync(mint, recipientAddress),
mint,
tokenAuthority: this.tokenAuthorityAddress()
},
custody: await this.custodyAccountAddress(config)
})
.instruction()
}
async releaseInboundUnlock(args: {
payer: Keypair
chain: ChainName | ChainId
nttMessage: NttMessage
revertWhenNotReady: boolean
config?: Config
}): Promise<void> {
if (await this.isPaused()) {
throw new Error('Contract is paused')
}
const txArgs = {
...args,
payer: args.payer.publicKey
}
const tx = new Transaction()
tx.add(await this.createReleaseInboundUnlockInstruction(txArgs))
const signers = [args.payer]
await this.sendAndConfirmTransaction(tx, signers)
}
async setPeer(args: {
payer: Keypair
owner: Keypair
chain: ChainName
address: ArrayLike<number>
limit: BN
tokenDecimals: number
config?: Config
}) {
const ix = await this.program.methods.setPeer({
chainId: { id: toChainId(args.chain) },
address: Array.from(args.address),
limit: args.limit,
tokenDecimals: args.tokenDecimals
})
.accounts({
payer: args.payer.publicKey,
owner: args.owner.publicKey,
config: this.configAccountAddress(),
peer: this.peerAccountAddress(args.chain),
inboxRateLimit: this.inboxRateLimitAccountAddress(args.chain)
}).instruction()
return await sendAndConfirmTransaction(this.program.provider.connection, new Transaction().add(ix), [args.payer, args.owner])
}
async setWormholeTransceiverPeer(args: {
payer: Keypair
owner: Keypair
chain: ChainName
address: ArrayLike<number>
config?: Config
}) {
const ix = await this.program.methods.setWormholePeer({
chainId: { id: toChainId(args.chain) },
address: Array.from(args.address)
})
.accounts({
payer: args.payer.publicKey,
owner: args.owner.publicKey,
config: this.configAccountAddress(),
peer: this.transceiverPeerAccountAddress(args.chain)
}).instruction()
const wormholeMessage = Keypair.generate()
const whAccs = getWormholeDerivedAccounts(this.program.programId, this.wormholeId)
const broadcastIx = await this.program.methods.broadcastWormholePeer({ chainId: toChainId(args.chain) })
.accounts({
payer: args.payer.publicKey,
config: this.configAccountAddress(),
peer: this.transceiverPeerAccountAddress(args.chain),
wormholeMessage: wormholeMessage.publicKey,
emitter: this.emitterAccountAddress(),
wormhole: {
bridge: whAccs.wormholeBridge,
feeCollector: whAccs.wormholeFeeCollector,
sequence: whAccs.wormholeSequence,
program: this.wormholeId
}
}).instruction()
return await sendAndConfirmTransaction(this.program.provider.connection, new Transaction().add(ix, broadcastIx), [args.payer, args.owner, wormholeMessage])
}
async registerTransceiver(args: {
payer: Keypair
owner: Keypair
transceiver: PublicKey
}) {
const ix = await this.program.methods.registerTransceiver()
.accounts({
payer: args.payer.publicKey,
owner: args.owner.publicKey,
config: this.configAccountAddress(),
transceiver: args.transceiver,
registeredTransceiver: this.registeredTransceiverAddress(args.transceiver)
}).instruction()
const wormholeMessage = Keypair.generate()
const whAccs = getWormholeDerivedAccounts(this.program.programId, this.wormholeId)
const broadcastIx = await this.program.methods.broadcastWormholeId()
.accounts({
payer: args.payer.publicKey,
config: this.configAccountAddress(),
mint: await this.mintAccountAddress(),
wormholeMessage: wormholeMessage.publicKey,
emitter: this.emitterAccountAddress(),
wormhole: {
bridge: whAccs.wormholeBridge,
feeCollector: whAccs.wormholeFeeCollector,
sequence: whAccs.wormholeSequence,
program: this.wormholeId
}
}).instruction()
return await sendAndConfirmTransaction(
this.program.provider.connection, new Transaction().add(ix, broadcastIx), [args.payer, args.owner, wormholeMessage])
}
async setOutboundLimit(args: {
owner: Keypair
chain: ChainName
limit: BN
}) {
const ix = await this.program.methods.setOutboundLimit({
limit: args.limit
})
.accounts({
owner: args.owner.publicKey,
config: this.configAccountAddress(),
rateLimit: this.outboxRateLimitAccountAddress(),
}).instruction();
return sendAndConfirmTransaction(this.program.provider.connection, new Transaction().add(ix), [args.owner]);
}
async setInboundLimit(args: {
owner: Keypair
chain: ChainName
limit: BN
}) {
const ix = await this.program.methods.setInboundLimit({
chainId: { id: toChainId(args.chain) },
limit: args.limit
})
.accounts({
owner: args.owner.publicKey,
config: this.configAccountAddress(),
rateLimit: this.inboxRateLimitAccountAddress(args.chain),
}).instruction();
return sendAndConfirmTransaction(this.program.provider.connection, new Transaction().add(ix), [args.owner]);
}
async createReceiveWormholeMessageInstruction(args: {
payer: PublicKey
vaa: SignedVaa
config?: Config
}): Promise<TransactionInstruction> {
const config = await this.getConfig(args.config)
if (await this.isPaused(config)) {
throw new Error('Contract is paused')
}
const wormholeNTT = deserialize('Ntt:WormholeTransfer', args.vaa)
const nttMessage = wormholeNTT.payload.nttManagerPayload
// NOTE: we do an 'as ChainId' cast here, which is generally unsafe.
// TODO: explain why this is fine here
const chainId = SDKv2toChainId(wormholeNTT.emitterChain) as ChainId
const transceiverPeer = this.transceiverPeerAccountAddress(chainId)
return await this.program.methods.receiveWormholeMessage().accounts({
payer: args.payer,
config: { config: this.configAccountAddress() },
peer: transceiverPeer,
vaa: derivePostedVaaKey(this.wormholeId, Buffer.from(wormholeNTT.hash)),
transceiverMessage: this.transceiverMessageAccountAddress(
chainId,
nttMessage.id
)
}).instruction()
}
async createRedeemInstruction(args: {
payer: PublicKey
vaa: SignedVaa
config?: Config
}): Promise<TransactionInstruction> {
const config = await this.getConfig(args.config)
if (await this.isPaused(config)) {
throw new Error('Contract is paused')
}
const wormholeNTT = deserialize('Ntt:WormholeTransfer', args.vaa)
const nttMessage = wormholeNTT.payload.nttManagerPayload
// NOTE: we do an 'as ChainId' cast here, which is generally unsafe.
// TODO: explain why this is fine here
const chainId = SDKv2toChainId(wormholeNTT.emitterChain) as ChainId
const nttManagerPeer = this.peerAccountAddress(chainId)
const inboxRateLimit = this.inboxRateLimitAccountAddress(chainId)
return await this.program.methods
.redeem({})
.accounts({
payer: args.payer,
config: this.configAccountAddress(),
peer: nttManagerPeer,
transceiverMessage: this.transceiverMessageAccountAddress(chainId, nttMessage.id),
transceiver: this.registeredTransceiverAddress(this.program.programId),
mint: await this.mintAccountAddress(config),
inboxItem: this.inboxItemAccountAddress(chainId, nttMessage),
inboxRateLimit,
outboxRateLimit: this.outboxRateLimitAccountAddress()
})
.instruction()
}
/**
* Redeems a VAA.
*
* @returns Whether the transfer was released. If the transfer was delayed,
* this will be false. In that case, a subsequent call to
* `releaseInboundMint` or `releaseInboundUnlock` will release the
* transfer after the delay (24h).
*/
async redeem(args: {
payer: Keypair
vaa: SignedVaa
config?: Config
}): Promise<boolean> {
const config = await this.getConfig(args.config)
const redeemArgs = {
...args,
payer: args.payer.publicKey
}
const wormholeNTT = deserialize('Ntt:WormholeTransfer', args.vaa)
const nttMessage = wormholeNTT.payload.nttManagerPayload
// TODO: explain why this is fine here
const chainId = SDKv2toChainId(wormholeNTT.emitterChain) as ChainId
// Here we create a transaction with three instructions:
// 1. receive wormhole messsage (vaa)
// 1. redeem
// 2. releaseInboundMint or releaseInboundUnlock (depending on mode)
//
// The first instruction verifies the VAA.
// The second instruction places the transfer in the inbox, then the third instruction
// releases it.
//
// In case the redeemed amount exceeds the remaining inbound rate limit capacity,
// the transaction gets delayed. If this happens, the second instruction will not actually
// be able to release the transfer yet.
// To make sure the transaction still succeeds, we set revertWhenNotReady to false, which will
// just make the second instruction a no-op in case the transfer is delayed.
const tx = new Transaction()
tx.add(await this.createReceiveWormholeMessageInstruction(redeemArgs))
tx.add(await this.createRedeemInstruction(redeemArgs))
const releaseArgs = {
...args,
payer: args.payer.publicKey,
nttMessage,
recipient: new PublicKey(nttMessage.payload.recipientAddress.toUint8Array()),
chain: chainId,
revertWhenNotReady: false
}
if (config.mode.locking != null) {
tx.add(await this.createReleaseInboundUnlockInstruction(releaseArgs))
} else {
tx.add(await this.createReleaseInboundMintInstruction(releaseArgs))
}
const signers = [args.payer]
await this.sendAndConfirmTransaction(tx, signers)
// Let's check if the transfer was released
const inboxItem = await this.getInboxItem(chainId, nttMessage)
return inboxItem.releaseStatus.released !== undefined
}
// Account access
/**
* Fetches the Config account from the contract.
*
* @param config If provided, the config is just returned without making a
* network request. This is handy in case multiple config
* accessor functions are used, the config can just be queried
* once and passed around.
*/
async getConfig(config?: Config): Promise<Config> {
return config ?? await this.program.account.config.fetch(this.configAccountAddress())
}
async isPaused(config?: Config): Promise<boolean> {
return (await this.getConfig(config)).paused
}
async mintAccountAddress(config?: Config): Promise<PublicKey> {
return (await this.getConfig(config)).mint
}
async tokenProgram(config?: Config): Promise<PublicKey> {
return (await this.getConfig(config)).tokenProgram
}
async getInboxItem(chain: ChainName | ChainId, nttMessage: NttMessage): Promise<InboxItem> {
return await this.program.account.inboxItem.fetch(this.inboxItemAccountAddress(chain, nttMessage))
}
/**
* Returns the address of the custody account. If the config is available
* (i.e. the program is initialised), the mint is derived from the config.
* Otherwise, the mint must be provided.
*/
async custodyAccountAddress(configOrMint: Config | PublicKey): Promise<PublicKey> {
if (configOrMint instanceof PublicKey) {
return associatedAddress({ mint: configOrMint, owner: this.tokenAuthorityAddress() })
} else {
return associatedAddress({ mint: await this.mintAccountAddress(configOrMint), owner: this.tokenAuthorityAddress() })
}
}
}
function exhaustive<A>(_: never): A {
throw new Error('Impossible')
}