-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathcontext.ts
1213 lines (1125 loc) · 38 KB
/
context.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
import {
CHAIN_ID_SOLANA,
createNonce,
getForeignAssetSolana,
redeemAndUnwrapOnSolana,
redeemOnSolana,
} from '@certusone/wormhole-sdk';
import {
ACCOUNT_SIZE,
ASSOCIATED_TOKEN_PROGRAM_ID,
createCloseAccountInstruction,
createInitializeAccountInstruction,
getMinimumBalanceForRentExemptAccount,
NATIVE_MINT,
TOKEN_PROGRAM_ID,
getAssociatedTokenAddress,
getAccount,
createAssociatedTokenAccountInstruction,
Account,
getAssociatedTokenAddressSync,
TokenAccountNotFoundError,
} from '@solana/spl-token';
import {
clusterApiUrl,
Commitment,
Connection,
Keypair,
PublicKey,
PublicKeyInitData,
SystemProgram,
Transaction,
TransactionInstruction,
} from '@solana/web3.js';
import { BigNumber, BigNumberish } from 'ethers';
import { arrayify, zeroPad, hexlify } from 'ethers/lib/utils';
import MAINNET_CONFIG, { MAINNET_CHAINS } from '../../config/MAINNET';
import {
parseTokenTransferPayload,
parseTokenTransferVaa,
parseVaa,
} from '../../vaa';
import {
TokenId,
ChainName,
ChainId,
NATIVE,
ParsedMessage,
Context,
ParsedRelayerMessage,
} from '../../types';
import { SolContracts } from './contracts';
import { WormholeContext } from '../../wormhole';
import {
createTransferNativeInstruction,
createTransferWrappedInstruction,
createTransferNativeWithPayloadInstruction,
createApproveAuthoritySignerInstruction,
createTransferWrappedWithPayloadInstruction,
deriveWrappedMintKey,
} from './utils/tokenBridge';
import {
deriveClaimKey,
deriveWormholeEmitterKey,
getClaim,
getPostedMessage,
} from './utils/wormhole';
import { addComputeBudget } from './utils/computeBudget';
import { ForeignAssetCache } from '../../utils';
import { RelayerAbstract } from '../abstracts/relayer';
import {
createCompleteWrappedTransferWithRelayInstruction,
createTransferNativeTokensWithRelayInstruction,
createTransferWrappedTokensWithRelayInstruction,
createCompleteNativeTransferWithRelayInstruction,
} from './utils/tokenBridgeRelayer';
const SOLANA_SEQ_LOG = 'Program log: Sequence: ';
const SOLANA_CHAIN_NAME = MAINNET_CONFIG.chains.solana!.key;
const SOLANA_MAINNET_EMMITER_ID =
'ec7372995d5cc8732397fb0ad35c0121e0eaa90d26f828a534cab54391b3a4f5';
const SOLANA_TESTNET_EMITTER_ID =
'3b26409f8aaded3f5ddca184695aa6a0fa829b0c85caf84856324896d214ca98';
/**
* @category Solana
*/
export class SolanaContext<
T extends WormholeContext,
> extends RelayerAbstract<Transaction> {
readonly type = Context.SOLANA;
readonly contracts: SolContracts<T>;
readonly context: T;
connection: Connection | undefined;
private foreignAssetCache: ForeignAssetCache;
constructor(context: T, foreignAssetCache: ForeignAssetCache) {
super();
this.context = context;
const tag = context.environment === 'MAINNET' ? 'mainnet-beta' : 'devnet';
this.connection = new Connection(
context.conf.rpcs.solana || clusterApiUrl(tag),
);
this.contracts = new SolContracts(context);
this.foreignAssetCache = foreignAssetCache;
}
async getTxGasFee(
txId: string,
chain: ChainName | ChainId,
): Promise<BigNumber | undefined> {
if (!this.connection) throw new Error('no connection');
const transaction = await this.connection.getParsedTransaction(txId);
const parsedInstr = transaction?.meta?.innerInstructions![0].instructions;
const gasFee = parsedInstr
? parsedInstr.reduce((acc, c: any) => {
if (!c.parsed || !c.parsed.info || !c.parsed.info.lamports)
return acc;
return acc + c.parsed.info.lamports;
}, 0)
: 0;
return BigNumber.from(gasFee);
}
/**
* Sets the Connection
*
* @param connection The Solana Connection
*/
async setConnection(connection: Connection) {
this.connection = connection;
}
async fetchTokenDecimals(
tokenAddr: string,
chain?: ChainName | ChainId,
): Promise<number> {
if (!this.connection) throw new Error('no connection');
let mint = await this.connection.getParsedAccountInfo(
new PublicKey(tokenAddr),
);
if (!mint) throw new Error('could not fetch token details');
const { decimals } = (mint as any).value.data.parsed.info;
return decimals;
}
/**
* Gets the owner address of an Associated Token Account
*
* @param accountAddr The associated token account address
* @returns The owner address
*/
async getTokenAccountOwner(tokenAddr: string): Promise<string> {
const token = await getAccount(this.connection!, new PublicKey(tokenAddr));
return token.owner.toString();
}
async getNativeBalance(
walletAddress: string,
chain: ChainName | ChainId,
): Promise<BigNumber> {
if (!this.connection) throw new Error('no connection');
const balance = await this.connection.getBalance(
new PublicKey(walletAddress),
);
return BigNumber.from(balance);
}
async getTokenBalance(
walletAddress: string,
tokenId: TokenId,
chain: ChainName | ChainId,
): Promise<BigNumber | null> {
if (!this.connection) throw new Error('no connection');
const address = await this.getForeignAsset(tokenId, chain);
if (!address) return null;
const splToken = await this.connection.getTokenAccountsByOwner(
new PublicKey(walletAddress),
{ mint: new PublicKey(address) },
);
if (!splToken.value[0]) return null;
const balance = await this.connection.getTokenAccountBalance(
splToken.value[0].pubkey,
);
return BigNumber.from(balance.value.amount);
}
async getTokenBalances(
walletAddress: string,
tokenIds: TokenId[],
chain: ChainName | ChainId,
): Promise<(BigNumber | null)[]> {
if (!this.connection) throw new Error('no connection');
const addresses = await Promise.all(
tokenIds.map((tokenId) => this.getForeignAsset(tokenId, chain)),
);
const splParsedTokenAccounts =
await this.connection.getParsedTokenAccountsByOwner(
new PublicKey(walletAddress),
{
programId: new PublicKey(TOKEN_PROGRAM_ID),
},
);
return addresses.map((address) => {
if (!address) return null;
const amount = splParsedTokenAccounts.value.find(
(v) => v?.account.data.parsed?.info?.mint === address,
)?.account.data.parsed?.info?.tokenAmount?.amount;
if (!amount) return null;
return BigNumber.from(amount);
});
}
/**
* Gets the Associate Token Address
*
* @param token The token id (home chain/address)
* @param account The wallet address
* @returns The associated token address
*/
async getAssociatedTokenAddress(token: TokenId, account: PublicKeyInitData) {
const solAddr = await this.mustGetForeignAsset(token, SOLANA_CHAIN_NAME);
return await getAssociatedTokenAddress(
new PublicKey(solAddr),
new PublicKey(account),
undefined,
TOKEN_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID,
);
}
async getAssociatedTokenAccount(
token: TokenId,
account: PublicKeyInitData,
): Promise<Account | null> {
if (!this.connection) throw new Error('no connection');
const addr = await this.getAssociatedTokenAddress(token, account);
try {
const account = await getAccount(this.connection, addr);
return account;
} catch (_) {
return null;
}
}
/**
* Creates the Associated Token Account for a given wallet address. This must exist before a user can send a token bridge transfer, also it is the recipient address when sending the transfer.
*
* @param token The token id (home chain/address)
* @param account The wallet address
* @param commitment The commitment level
* @returns The transaction for creating the Associated Token Account
*/
async createAssociatedTokenAccount(
token: TokenId,
account: PublicKeyInitData,
commitment?: Commitment,
): Promise<Transaction | void> {
if (!this.connection) throw new Error('no connection');
const tokenAccount = await this.getAssociatedTokenAccount(token, account);
if (tokenAccount) return;
const solAddr = await this.mustGetForeignAsset(token, SOLANA_CHAIN_NAME);
const associatedAddr = await this.getAssociatedTokenAddress(token, account);
const payerPublicKey = new PublicKey(account);
const tokenPublicKey = new PublicKey(solAddr);
const associatedPublicKey = new PublicKey(associatedAddr);
const createAccountInst = createAssociatedTokenAccountInstruction(
payerPublicKey,
associatedPublicKey,
payerPublicKey,
tokenPublicKey,
);
const transaction = new Transaction(
await this.connection?.getLatestBlockhash(commitment),
);
transaction.add(createAccountInst);
transaction.feePayer = payerPublicKey;
await addComputeBudget(this.connection!, transaction, [
tokenPublicKey,
associatedPublicKey,
]);
return transaction;
}
/**
* Prepare the transfer instructions for a native token bridge transfer from Solana
*
* @dev This _must_ be claimed on the destination chain, see {@link WormholeContext#redeem | redeem}
*
* @param senderAddress The address of the sender
* @param amount The token amount to be sent
* @param recipientChain The destination chain name or id
* @param recipientAddress The associated token address where funds will be sent
* @param relayerFee The fee that would be paid to a relayer
* @param payload Arbitrary bytes that can contain any addition information about a given transfer
* @param commitment The commitment level
* @returns The transaction for sending Native SOL from Solana
*/
private async transferNativeSol(
senderAddress: PublicKeyInitData,
amount: bigint,
recipientChain: ChainId | ChainName,
recipientAddress: Uint8Array | Buffer,
relayerFee?: bigint,
payload?: Uint8Array | Buffer,
commitment?: Commitment,
): Promise<Transaction> {
if (!this.connection) throw new Error('no connection');
const contracts = this.contracts.mustGetContracts(SOLANA_CHAIN_NAME);
if (!contracts.core || !contracts.token_bridge) {
throw new Error('contracts not found');
}
const rentBalance = await getMinimumBalanceForRentExemptAccount(
this.connection,
commitment,
);
const payerPublicKey = new PublicKey(senderAddress);
const ancillaryKeypair = Keypair.generate();
//This will create a temporary account where the wSOL will be created.
const createAncillaryAccountIx = SystemProgram.createAccount({
fromPubkey: payerPublicKey,
newAccountPubkey: ancillaryKeypair.publicKey,
lamports: rentBalance, //spl token accounts need rent exemption
space: ACCOUNT_SIZE,
programId: TOKEN_PROGRAM_ID,
});
//Send in the amount of SOL which we want converted to wSOL
const initialBalanceTransferIx = SystemProgram.transfer({
fromPubkey: payerPublicKey,
lamports: amount,
toPubkey: ancillaryKeypair.publicKey,
});
//Initialize the account as a WSOL account, with the original payerAddress as owner
const initAccountIx = createInitializeAccountInstruction(
ancillaryKeypair.publicKey,
NATIVE_MINT,
payerPublicKey,
);
//Normal approve & transfer instructions, except that the wSOL is sent from the ancillary account.
const approvalIx = createApproveAuthoritySignerInstruction(
contracts.token_bridge,
ancillaryKeypair.publicKey,
payerPublicKey,
amount,
);
const message = Keypair.generate();
const nonce = createNonce().readUInt32LE(0);
const tokenBridgeTransferIx = payload
? createTransferNativeWithPayloadInstruction(
this.connection,
contracts.token_bridge,
contracts.core,
senderAddress,
message.publicKey,
ancillaryKeypair.publicKey,
NATIVE_MINT,
nonce,
amount,
Buffer.from(recipientAddress),
this.context.toChainId(recipientChain),
payload,
)
: createTransferNativeInstruction(
this.connection,
contracts.token_bridge,
contracts.core,
senderAddress,
message.publicKey,
ancillaryKeypair.publicKey,
NATIVE_MINT,
nonce,
amount,
relayerFee || BigInt(0),
Buffer.from(recipientAddress),
this.context.toChainId(recipientChain),
);
//Close the ancillary account for cleanup. Payer address receives any remaining funds
const closeAccountIx = createCloseAccountInstruction(
ancillaryKeypair.publicKey, //account to close
payerPublicKey, //Remaining funds destination
payerPublicKey, //authority
);
const transaction = new Transaction(
await this.connection?.getLatestBlockhash(commitment),
);
transaction.add(
createAncillaryAccountIx,
initialBalanceTransferIx,
initAccountIx,
approvalIx,
tokenBridgeTransferIx,
closeAccountIx,
);
transaction.feePayer = payerPublicKey;
await addComputeBudget(this.connection!, transaction, [NATIVE_MINT]);
transaction.partialSign(message, ancillaryKeypair);
return transaction;
}
/**
* Prepare the transfer instructions for a token bridge transfer from Solana
*
* @dev This _must_ be claimed on the destination chain, see {@link WormholeContext#redeem | redeem}
*
* @param senderAddress The address of the sender
* @param amount The token amount to be sent
* @param recipientChain The destination chain name or id
* @param recipientAddress The associated token address where funds will be sent
* @param fromAddress The token account pubkey, owned by fromOwner address
* @param tokenChainId The id of the token's chain
* @param mintAddress The token address on the destination
* @param fromOwnerAddress If not specified, will default to the sender address
* @param relayerFee The fee that would be paid to a relayer
* @param payload Arbitrary bytes that can contain any addition information about a given transfer
* @param commitment The commitment level
* @returns The transaction for sending tokens from Solana
*/
private async transferFromSolana(
senderAddress: PublicKeyInitData,
amount: bigint,
recipientChain: ChainId | ChainName,
recipientAddress: Uint8Array | Buffer,
fromAddress: PublicKeyInitData, // token account pubkey, owned by fromOwner address
tokenChainId: number,
mintAddress: Uint8Array, // token address
fromOwnerAddress?: PublicKeyInitData,
relayerFee?: bigint,
payload?: Uint8Array | Buffer,
commitment?: Commitment,
): Promise<Transaction> {
if (!this.connection) throw new Error('no connection');
const contracts = this.contracts.mustGetContracts(SOLANA_CHAIN_NAME);
if (!contracts.core || !contracts.token_bridge) {
throw new Error('contracts not found');
}
const recipientChainId = this.context.toChainId(recipientChain);
if (fromOwnerAddress === undefined) {
fromOwnerAddress = senderAddress;
}
const nonce = createNonce().readUInt32LE(0);
const approvalIx = createApproveAuthoritySignerInstruction(
contracts.token_bridge,
fromAddress,
new PublicKey(fromOwnerAddress),
amount,
);
const message = Keypair.generate();
const isSolanaNative =
tokenChainId === undefined || tokenChainId === CHAIN_ID_SOLANA;
const tokenBridgeTransferIx = isSolanaNative
? payload
? createTransferNativeWithPayloadInstruction(
this.connection,
contracts.token_bridge,
contracts.core,
senderAddress,
message.publicKey,
fromAddress,
mintAddress,
nonce,
amount,
recipientAddress,
recipientChainId,
payload,
)
: createTransferNativeInstruction(
this.connection,
contracts.token_bridge,
contracts.core,
senderAddress,
message.publicKey,
fromAddress,
mintAddress,
nonce,
amount,
relayerFee || BigInt(0),
recipientAddress,
recipientChainId,
)
: payload
? createTransferWrappedWithPayloadInstruction(
this.connection,
contracts.token_bridge,
contracts.core,
senderAddress,
message.publicKey,
fromAddress,
fromOwnerAddress,
tokenChainId,
mintAddress,
nonce,
amount,
recipientAddress,
recipientChainId,
payload,
)
: createTransferWrappedInstruction(
this.connection,
contracts.token_bridge,
contracts.core,
senderAddress,
message.publicKey,
fromAddress,
fromOwnerAddress,
tokenChainId,
mintAddress,
nonce,
amount,
relayerFee || BigInt(0),
recipientAddress,
recipientChainId,
);
const transaction = new Transaction(
await this.connection?.getLatestBlockhash(commitment),
);
transaction.add(approvalIx, tokenBridgeTransferIx);
transaction.feePayer = new PublicKey(senderAddress);
await addComputeBudget(this.connection!, transaction, [
new PublicKey(fromAddress),
new PublicKey(mintAddress),
]);
transaction.partialSign(message);
return transaction;
}
async send(
token: TokenId | typeof NATIVE,
amount: string,
sendingChain: ChainName | ChainId,
senderAddress: string,
recipientChain: ChainName | ChainId,
recipientAddress: string,
relayerFee?: string,
commitment?: Commitment,
): Promise<Transaction> {
if (!this.connection) throw new Error('no connection');
const destContext = this.context.getContext(recipientChain);
const formattedRecipient = arrayify(
destContext.formatAddress(recipientAddress),
);
const relayerFeeBN = relayerFee ? BigInt(relayerFee) : undefined;
const amountBN = BigNumber.from(amount).toBigInt();
if (token === NATIVE) {
return await this.transferNativeSol(
senderAddress,
amountBN,
recipientChain,
formattedRecipient,
relayerFeeBN,
undefined,
'finalized',
);
} else {
const tokenContext = this.context.getContext(token.chain);
const formattedTokenAddr = arrayify(
await tokenContext.formatAssetAddress(token.address),
);
const solTokenAddr = await this.mustGetForeignAsset(
token,
SOLANA_CHAIN_NAME,
);
const splToken = await this.connection.getTokenAccountsByOwner(
new PublicKey(senderAddress),
{ mint: new PublicKey(solTokenAddr) },
);
if (!splToken || !splToken.value[0])
throw new Error('account does not have any token balance');
return await this.transferFromSolana(
senderAddress,
amountBN,
recipientChain,
formattedRecipient,
splToken.value[0].pubkey,
this.context.toChainId(token.chain),
formattedTokenAddr,
undefined,
relayerFeeBN,
undefined,
'finalized',
);
}
}
async sendWithPayload(
token: TokenId | typeof NATIVE,
amount: string,
sendingChain: ChainName | ChainId,
senderAddress: string,
recipientChain: ChainName | ChainId,
recipientAddress: string,
payload: Uint8Array | Buffer,
commitment?: Commitment,
): Promise<Transaction> {
if (!this.connection) throw new Error('no connection');
const amountBN = BigInt(amount);
const destContext = this.context.getContext(recipientChain);
const formattedRecipient = arrayify(
destContext.formatAddress(recipientAddress),
);
if (token === NATIVE) {
return await this.transferNativeSol(
senderAddress,
amountBN,
recipientChain,
formattedRecipient,
undefined,
payload,
'finalized',
);
} else {
const tokenContext = this.context.getContext(token.chain);
const formattedTokenAddr = arrayify(
await tokenContext.formatAssetAddress(token.address),
);
const solTokenAddr = await this.mustGetForeignAsset(
token,
SOLANA_CHAIN_NAME,
);
const splToken = await this.connection.getTokenAccountsByOwner(
new PublicKey(senderAddress),
{ mint: new PublicKey(solTokenAddr) },
);
if (!splToken || !splToken.value[0])
throw new Error('account does not have any token balance');
return await this.transferFromSolana(
senderAddress,
amountBN,
recipientChain,
formattedRecipient,
splToken.value[0].pubkey,
this.context.resolveDomain(token.chain),
formattedTokenAddr,
undefined,
undefined,
payload,
'finalized',
);
}
}
async estimateSendGas(
token: TokenId | typeof NATIVE,
amount: string,
sendingChain: ChainName | ChainId,
senderAddress: string,
recipientChain: ChainName | ChainId,
recipientAddress: string,
): Promise<BigNumber> {
throw new Error('not implemented');
}
async estimateClaimGas(
destChain: ChainName | ChainId,
VAA: Uint8Array,
): Promise<BigNumber> {
throw new Error('not implemented');
}
formatAddress(address: PublicKeyInitData): Uint8Array {
const addr =
typeof address === 'string' && address.startsWith('0x')
? arrayify(address)
: address;
return arrayify(zeroPad(new PublicKey(addr).toBytes(), 32));
}
async estimateSendWithRelayGas(
token: TokenId | typeof NATIVE,
amount: string,
sendingChain: ChainName | ChainId,
senderAddress: string,
recipientChain: ChainName | ChainId,
recipientAddress: string,
relayerFee: any,
toNativeToken: string,
): Promise<BigNumber> {
throw new Error('not implemented');
}
parseAddress(address: string): string {
const addr =
typeof address === 'string' && address.startsWith('0x')
? arrayify(address)
: address;
return new PublicKey(addr).toString();
}
async formatAssetAddress(address: string): Promise<Uint8Array> {
return this.formatAddress(address);
}
async parseAssetAddress(address: string): Promise<string> {
return this.parseAddress(address);
}
async getForeignAsset(
tokenId: TokenId,
chain: ChainName | ChainId,
): Promise<string | null> {
const chainName = this.context.toChainName(chain);
if (this.foreignAssetCache.get(tokenId.chain, tokenId.address, chainName)) {
return this.foreignAssetCache.get(
tokenId.chain,
tokenId.address,
chainName,
)!;
}
if (!this.connection) throw new Error('no connection');
const chainId = this.context.toChainId(tokenId.chain);
const toChainId = this.context.toChainId(chain);
if (toChainId === chainId) return tokenId.address;
const contracts = this.context.mustGetContracts(chain);
if (!contracts.token_bridge) throw new Error('contracts not found');
const tokenContext = this.context.getContext(tokenId.chain);
const formattedAddr = await tokenContext.formatAssetAddress(
tokenId.address,
);
const addr = await getForeignAssetSolana(
this.connection,
contracts.token_bridge,
chainId,
arrayify(formattedAddr),
);
if (!addr) return null;
this.foreignAssetCache.set(tokenId.chain, tokenId.address, chainName, addr);
return addr;
}
async getMessage(
tx: string,
chain: ChainName | ChainId,
parseRelayerPayload: boolean = true,
): Promise<ParsedMessage | ParsedRelayerMessage> {
if (!this.connection) throw new Error('no connection');
const contracts = this.contracts.mustGetContracts(SOLANA_CHAIN_NAME);
if (!contracts.core || !contracts.token_bridge)
throw new Error('contracts not found');
const response = await this.connection.getTransaction(tx);
if (!response || !response.meta?.innerInstructions![0].instructions)
throw new Error('transaction not found');
const transaction = await this.connection.getParsedTransaction(tx);
// the first instruction may be creating the associated token account
// for an automatic transfer of the native token
const wormholeInstructionIndex =
response.meta?.innerInstructions.length - 1;
const instructions =
response.meta?.innerInstructions![wormholeInstructionIndex].instructions;
const accounts = response.transaction.message.accountKeys;
// find the instruction where the programId equals the Wormhole ProgramId and the emitter equals the Token Bridge
const bridgeInstructions = instructions.filter((i) => {
const programId = accounts[i.programIdIndex].toString();
const emitterId = accounts[i.accounts[2]];
const wormholeCore = contracts.core;
const tokenBridge = deriveWormholeEmitterKey(contracts.token_bridge!);
return programId === wormholeCore && emitterId.equals(tokenBridge);
});
const messageAccount = accounts[bridgeInstructions[0].accounts[1]];
const { message } = await getPostedMessage(
this.connection,
messageAccount,
'finalized',
);
const parsedInstr = transaction?.meta?.innerInstructions![0].instructions;
const gasFee = parsedInstr
? parsedInstr.reduce((acc, c: any) => {
if (!c.parsed || !c.parsed.info || !c.parsed.info.lamports)
return acc;
return acc + c.parsed.info.lamports;
}, 0)
: 0;
// parse message payload
const transfer = parseTokenTransferPayload(message.payload);
// get sequence
let sequence = response.meta?.logMessages
?.filter((msg) => msg.startsWith(SOLANA_SEQ_LOG))?.[0]
?.replace(SOLANA_SEQ_LOG, '');
if (!sequence) {
// fallback to message account data
const info = await this.connection.getAccountInfo(messageAccount);
sequence = info?.data.readBigUInt64LE(49).toString();
if (!sequence) {
throw new Error('sequence not found');
}
}
// format response
const tokenContext = this.context.getContext(
transfer.tokenChain as ChainId,
);
const destContext = this.context.getContext(transfer.toChain as ChainId);
const tokenAddress = await tokenContext.parseAssetAddress(
hexlify(transfer.tokenAddress),
);
const tokenChain = this.context.toChainName(transfer.tokenChain);
const fromChain = this.context.toChainName(chain);
const toChain = this.context.toChainName(transfer.toChain);
const toAddress = destContext.parseAddress(hexlify(transfer.to));
const parsedMessage: ParsedMessage = {
sendTx: tx,
sender: accounts[0].toString(),
amount: BigNumber.from(transfer.amount),
payloadID: transfer.payloadType,
recipient: toAddress,
toChain,
fromChain,
tokenAddress,
tokenChain,
tokenId: {
chain: tokenChain,
address: tokenAddress,
},
sequence: BigNumber.from(sequence),
emitterAddress:
this.context.conf.env === 'MAINNET'
? SOLANA_MAINNET_EMMITER_ID
: SOLANA_TESTNET_EMITTER_ID,
gasFee: BigNumber.from(gasFee),
block: response.slot,
payload: transfer.tokenTransferPayload.length
? hexlify(transfer.tokenTransferPayload)
: undefined,
};
if (parseRelayerPayload && parsedMessage.payloadID === 3) {
const destContext = this.context.getContext(transfer.toChain as ChainId);
const parsedPayload = destContext.parseRelayerPayload(
transfer.tokenTransferPayload,
);
const parsedPayloadMessage: ParsedRelayerMessage = {
...parsedMessage,
relayerPayloadId: parsedPayload.relayerPayloadId,
recipient: destContext.parseAddress(parsedPayload.to),
to: toAddress,
relayerFee: parsedPayload.relayerFee,
toNativeTokenAmount: parsedPayload.toNativeTokenAmount,
payload: transfer.tokenTransferPayload.length
? hexlify(transfer.tokenTransferPayload)
: undefined,
};
return parsedPayloadMessage;
}
return parsedMessage;
}
async redeem(
destChain: ChainName | ChainId,
signedVAA: Uint8Array,
overrides: any,
payerAddr?: PublicKeyInitData,
): Promise<Transaction> {
if (!payerAddr)
throw new Error(
'receiving wallet address required for redeeming on Solana',
);
if (!this.connection) throw new Error('no connection');
const contracts = this.contracts.mustGetContracts(SOLANA_CHAIN_NAME);
if (!contracts.core || !contracts.token_bridge) {
throw new Error('contracts not found for solana');
}
const parsed = parseTokenTransferVaa(signedVAA);
const tokenKey = new PublicKey(parsed.tokenAddress);
const isNativeSol =
parsed.tokenChain === MAINNET_CHAINS.solana &&
tokenKey.equals(NATIVE_MINT);
const transaction = isNativeSol
? await redeemAndUnwrapOnSolana(
this.connection,
contracts.core,
contracts.token_bridge,
payerAddr,
signedVAA,
)
: await redeemOnSolana(
this.connection,
contracts.core,
contracts.token_bridge,
payerAddr,
signedVAA,
);
await addComputeBudget(this.connection!, transaction, [tokenKey]);
return transaction;
}
async redeemRelay(
destChain: ChainName | ChainId,
signedVAA: Uint8Array,
overrides: any,
payerAddr?: string,
): Promise<Transaction> {
if (!payerAddr)
throw new Error(
'receiving wallet address required for redeeming on Solana',
);
if (!this.connection) throw new Error('no connection');
const { core, token_bridge, relayer } =
this.contracts.mustGetContracts(SOLANA_CHAIN_NAME);
if (!core || !token_bridge || !relayer) {
throw new Error('contracts not found');
}
const parsed = parseTokenTransferVaa(signedVAA);
const { to } = this.parseRelayerPayload(parsed.tokenTransferPayload);
const recipient = new PublicKey(arrayify(to));
if (!recipient.equals(new PublicKey(payerAddr))) {
throw new Error('recipient address does not match payer address');
}
const isNative = parsed.tokenChain === MAINNET_CHAINS.solana;
const mint = isNative
? new PublicKey(parsed.tokenAddress)
: deriveWrappedMintKey(
token_bridge,
parsed.tokenChain,
parsed.tokenAddress,
);
const transaction = new Transaction(
await this.connection?.getLatestBlockhash('finalized'),
);
const recipientTokenAccount = getAssociatedTokenAddressSync(
mint,
recipient,
);
const recipientTokenAccountInfo = await this.connection.getAccountInfo(
recipientTokenAccount,
);
// Create the associated token account if it doesn't exist
if (!recipientTokenAccountInfo) {
transaction.add(
createAssociatedTokenAccountInstruction(
recipient,
recipientTokenAccount,
recipient,
mint,
),
);
}
let redeemIx: TransactionInstruction;
if (isNative) {
redeemIx = await createCompleteNativeTransferWithRelayInstruction(
this.connection,
relayer,
recipient,
token_bridge,
core,
signedVAA,
recipient,
);
} else {
redeemIx = await createCompleteWrappedTransferWithRelayInstruction(
this.connection,
relayer,
recipient,
token_bridge,
core,
signedVAA,
recipient,
);
}
transaction.add(redeemIx);
transaction.feePayer = new PublicKey(recipient);
await addComputeBudget(this.connection!, transaction, [mint]);
return transaction;