@aptos-labs/cross-chain-core 4.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +201 -0
  2. package/dist/CrossChainCore.d.ts +36 -0
  3. package/dist/CrossChainCore.d.ts.map +1 -0
  4. package/dist/config/index.d.ts +4 -0
  5. package/dist/config/index.d.ts.map +1 -0
  6. package/dist/config/mainnet/chains.d.ts +17 -0
  7. package/dist/config/mainnet/chains.d.ts.map +1 -0
  8. package/dist/config/mainnet/index.d.ts +3 -0
  9. package/dist/config/mainnet/index.d.ts.map +1 -0
  10. package/dist/config/mainnet/tokens.d.ts +4 -0
  11. package/dist/config/mainnet/tokens.d.ts.map +1 -0
  12. package/dist/config/testnet/chains.d.ts +19 -0
  13. package/dist/config/testnet/chains.d.ts.map +1 -0
  14. package/dist/config/testnet/index.d.ts +3 -0
  15. package/dist/config/testnet/index.d.ts.map +1 -0
  16. package/dist/config/testnet/tokens.d.ts +4 -0
  17. package/dist/config/testnet/tokens.d.ts.map +1 -0
  18. package/dist/config/types.d.ts +41 -0
  19. package/dist/config/types.d.ts.map +1 -0
  20. package/dist/index.d.ts +6 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +989 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/index.mjs +957 -0
  25. package/dist/index.mjs.map +1 -0
  26. package/dist/providers/wormhole/index.d.ts +5 -0
  27. package/dist/providers/wormhole/index.d.ts.map +1 -0
  28. package/dist/providers/wormhole/signers/AptosLocalSigner.d.ts +18 -0
  29. package/dist/providers/wormhole/signers/AptosLocalSigner.d.ts.map +1 -0
  30. package/dist/providers/wormhole/signers/EthereumSigner.d.ts +5 -0
  31. package/dist/providers/wormhole/signers/EthereumSigner.d.ts.map +1 -0
  32. package/dist/providers/wormhole/signers/Signer.d.ts +17 -0
  33. package/dist/providers/wormhole/signers/Signer.d.ts.map +1 -0
  34. package/dist/providers/wormhole/signers/SolanaSigner.d.ts +28 -0
  35. package/dist/providers/wormhole/signers/SolanaSigner.d.ts.map +1 -0
  36. package/dist/providers/wormhole/types.d.ts +39 -0
  37. package/dist/providers/wormhole/types.d.ts.map +1 -0
  38. package/dist/providers/wormhole/wormhole.d.ts +35 -0
  39. package/dist/providers/wormhole/wormhole.d.ts.map +1 -0
  40. package/dist/utils/getUsdcBalance.d.ts +5 -0
  41. package/dist/utils/getUsdcBalance.d.ts.map +1 -0
  42. package/dist/utils/logger.d.ts +6 -0
  43. package/dist/utils/logger.d.ts.map +1 -0
  44. package/dist/version.d.ts +2 -0
  45. package/dist/version.d.ts.map +1 -0
  46. package/package.json +83 -0
  47. package/src/CrossChainCore.ts +130 -0
  48. package/src/config/index.ts +3 -0
  49. package/src/config/mainnet/chains.ts +64 -0
  50. package/src/config/mainnet/index.ts +2 -0
  51. package/src/config/mainnet/tokens.ts +43 -0
  52. package/src/config/testnet/chains.ts +69 -0
  53. package/src/config/testnet/index.ts +2 -0
  54. package/src/config/testnet/tokens.ts +43 -0
  55. package/src/config/types.ts +45 -0
  56. package/src/index.ts +5 -0
  57. package/src/providers/wormhole/index.ts +4 -0
  58. package/src/providers/wormhole/signers/AptosLocalSigner.ts +136 -0
  59. package/src/providers/wormhole/signers/EthereumSigner.ts +49 -0
  60. package/src/providers/wormhole/signers/Signer.ts +102 -0
  61. package/src/providers/wormhole/signers/SolanaSigner.ts +418 -0
  62. package/src/providers/wormhole/types.ts +59 -0
  63. package/src/providers/wormhole/wormhole.ts +320 -0
  64. package/src/utils/getUsdcBalance.ts +82 -0
  65. package/src/utils/logger.ts +17 -0
  66. package/src/version.ts +1 -0
package/dist/index.js ADDED
@@ -0,0 +1,989 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // src/index.ts
27
+ var src_exports = {};
28
+ __export(src_exports, {
29
+ AptosLocalSigner: () => AptosLocalSigner,
30
+ AptosMainnetChain: () => AptosMainnetChain,
31
+ AptosMainnetUSDCToken: () => AptosMainnetUSDCToken,
32
+ AptosTestnetChain: () => AptosTestnetChain,
33
+ AptosTestnetUSDCToken: () => AptosTestnetUSDCToken,
34
+ Context: () => Context,
35
+ CrossChainCore: () => CrossChainCore,
36
+ Network: () => import_ts_sdk6.Network,
37
+ NetworkToChainId: () => import_ts_sdk5.NetworkToChainId,
38
+ NetworkToNodeAPI: () => import_ts_sdk5.NetworkToNodeAPI,
39
+ WormholeProvider: () => WormholeProvider,
40
+ mainnetChains: () => mainnetChains,
41
+ mainnetTokens: () => mainnetTokens,
42
+ signAndSendTransaction: () => signAndSendTransaction,
43
+ testnetChains: () => testnetChains,
44
+ testnetTokens: () => testnetTokens
45
+ });
46
+ module.exports = __toCommonJS(src_exports);
47
+
48
+ // src/CrossChainCore.ts
49
+ var import_ts_sdk4 = require("@aptos-labs/ts-sdk");
50
+
51
+ // src/providers/wormhole/wormhole.ts
52
+ var import_sdk = require("@wormhole-foundation/sdk");
53
+ var import_ts_sdk2 = require("@aptos-labs/ts-sdk");
54
+ var import_aptos = __toESM(require("@wormhole-foundation/sdk/aptos"));
55
+ var import_solana = __toESM(require("@wormhole-foundation/sdk/solana"));
56
+ var import_evm = __toESM(require("@wormhole-foundation/sdk/evm"));
57
+
58
+ // src/utils/logger.ts
59
+ var logger = {
60
+ log: (...args) => {
61
+ if (process.env.NODE_ENV === "development") {
62
+ console.log(...args);
63
+ }
64
+ },
65
+ warn: (...args) => {
66
+ if (process.env.NODE_ENV === "development") {
67
+ console.warn(...args);
68
+ }
69
+ },
70
+ error: (...args) => {
71
+ if (process.env.NODE_ENV === "development") {
72
+ console.error(...args);
73
+ }
74
+ }
75
+ };
76
+
77
+ // src/providers/wormhole/signers/AptosLocalSigner.ts
78
+ var import_ts_sdk = require("@aptos-labs/ts-sdk");
79
+ var AptosLocalSigner = class {
80
+ constructor(chain, options, wallet, feePayerAccount) {
81
+ this._chain = chain;
82
+ this._options = options;
83
+ this._wallet = wallet;
84
+ this._sponsorAccount = feePayerAccount;
85
+ this._claimedTransactionHashes = "";
86
+ }
87
+ chain() {
88
+ return this._chain;
89
+ }
90
+ address() {
91
+ return this._wallet.accountAddress.toString();
92
+ }
93
+ claimedTransactionHashes() {
94
+ return this._claimedTransactionHashes;
95
+ }
96
+ async signAndSend(txs) {
97
+ const txHashes = [];
98
+ for (const tx of txs) {
99
+ const txId = await signAndSendTransaction(
100
+ tx,
101
+ this._wallet,
102
+ this._sponsorAccount
103
+ );
104
+ txHashes.push(txId);
105
+ this._claimedTransactionHashes = txId;
106
+ }
107
+ return txHashes;
108
+ }
109
+ };
110
+ async function signAndSendTransaction(request, wallet, sponsorAccount) {
111
+ if (!wallet) {
112
+ throw new Error("Wallet is undefined");
113
+ }
114
+ const payload = request.transaction;
115
+ payload.functionArguments = payload.functionArguments.map((a) => {
116
+ if (a instanceof Uint8Array) {
117
+ return Array.from(a);
118
+ } else if (typeof a === "bigint") {
119
+ return a.toString();
120
+ } else {
121
+ return a;
122
+ }
123
+ });
124
+ const aptosConfig = new import_ts_sdk.AptosConfig({
125
+ network: import_ts_sdk.Network.TESTNET
126
+ });
127
+ const aptos2 = new import_ts_sdk.Aptos(aptosConfig);
128
+ const txnToSign = await aptos2.transaction.build.simple({
129
+ data: payload,
130
+ sender: wallet.accountAddress.toString(),
131
+ withFeePayer: sponsorAccount ? true : false
132
+ });
133
+ const senderAuthenticator = await aptos2.transaction.sign({
134
+ signer: wallet,
135
+ transaction: txnToSign
136
+ });
137
+ const txnToSubmit = {
138
+ transaction: txnToSign,
139
+ senderAuthenticator
140
+ };
141
+ if (sponsorAccount) {
142
+ if (typeof sponsorAccount === "string") {
143
+ } else {
144
+ const feePayerSignerAuthenticator = aptos2.transaction.signAsFeePayer({
145
+ signer: sponsorAccount,
146
+ transaction: txnToSign
147
+ });
148
+ txnToSubmit.feePayerAuthenticator = feePayerSignerAuthenticator;
149
+ }
150
+ }
151
+ const response = await aptos2.transaction.submit.simple(txnToSubmit);
152
+ const tx = await aptos2.waitForTransaction({
153
+ transactionHash: response.hash
154
+ });
155
+ return tx.hash;
156
+ }
157
+
158
+ // src/providers/wormhole/signers/SolanaSigner.ts
159
+ var import_web3 = require("@solana/web3.js");
160
+ var import_sdk_solana = require("@wormhole-foundation/sdk-solana");
161
+ var import_web32 = require("@solana/web3.js");
162
+ var import_derived_wallet_solana = require("@aptos-labs/derived-wallet-solana");
163
+ async function signAndSendTransaction2(request, wallet, options, crossChainCore) {
164
+ var _a, _b, _c, _d;
165
+ if (!wallet || !(wallet instanceof import_derived_wallet_solana.SolanaDerivedWallet)) {
166
+ throw new Error("Invalid wallet type or missing Solana wallet").message;
167
+ }
168
+ const commitment = (_a = options == null ? void 0 : options.commitment) != null ? _a : "finalized";
169
+ const connection = new import_web32.Connection(
170
+ (_d = (_c = (_b = crossChainCore == null ? void 0 : crossChainCore._dappConfig) == null ? void 0 : _b.solanaConfig) == null ? void 0 : _c.rpc) != null ? _d : "https://api.devnet.solana.com"
171
+ );
172
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash(commitment);
173
+ const transaction = request.transaction.transaction;
174
+ const unsignedTx = await setPriorityFeeInstructions(
175
+ connection,
176
+ blockhash,
177
+ lastValidBlockHeight,
178
+ request,
179
+ crossChainCore
180
+ );
181
+ let confirmTransactionPromise = null;
182
+ let confirmedTx = null;
183
+ let txSendAttempts = 1;
184
+ let signature = "";
185
+ if (!wallet.solanaWallet.signTransaction) {
186
+ throw new Error("Wallet does not support signing transactions").message;
187
+ }
188
+ const tx = await wallet.solanaWallet.signTransaction(unsignedTx);
189
+ if (!tx)
190
+ throw new Error("Failed to sign transaction").message;
191
+ const serializedTx = tx.serialize();
192
+ const sendOptions = {
193
+ skipPreflight: true,
194
+ maxRetries: 0,
195
+ preFlightCommitment: commitment
196
+ };
197
+ signature = await connection.sendRawTransaction(serializedTx, sendOptions);
198
+ confirmTransactionPromise = connection.confirmTransaction(
199
+ {
200
+ signature,
201
+ blockhash,
202
+ lastValidBlockHeight
203
+ },
204
+ commitment
205
+ );
206
+ const txRetryInterval = 5e3;
207
+ while (!confirmedTx) {
208
+ confirmedTx = await Promise.race([
209
+ confirmTransactionPromise,
210
+ new Promise(
211
+ (resolve) => setTimeout(() => {
212
+ resolve(null);
213
+ }, txRetryInterval)
214
+ )
215
+ ]);
216
+ if (confirmedTx) {
217
+ break;
218
+ }
219
+ console.log(
220
+ `Tx not confirmed after ${txRetryInterval * txSendAttempts++}ms, resending`
221
+ );
222
+ try {
223
+ await connection.sendRawTransaction(serializedTx, sendOptions);
224
+ } catch (e) {
225
+ console.error("Failed to resend transaction:", e);
226
+ }
227
+ }
228
+ if (confirmedTx.value.err) {
229
+ let errorMessage = `Transaction failed: ${confirmedTx.value.err}`;
230
+ if (typeof confirmedTx.value.err === "object") {
231
+ try {
232
+ errorMessage = `Transaction failed: ${JSON.stringify(
233
+ confirmedTx.value.err,
234
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
235
+ )}`;
236
+ } catch (e) {
237
+ errorMessage = `Transaction failed: Unknown error`;
238
+ }
239
+ }
240
+ throw new Error(`Transaction failed: ${errorMessage}`).message;
241
+ }
242
+ return signature;
243
+ }
244
+ async function setPriorityFeeInstructions(connection, blockhash, lastValidBlockHeight, request, crossChainCore) {
245
+ const unsignedTx = request.transaction.transaction;
246
+ const computeBudgetIxFilter = (ix) => ix.programId.toString() !== "ComputeBudget111111111111111111111111111111";
247
+ unsignedTx.recentBlockhash = blockhash;
248
+ unsignedTx.lastValidBlockHeight = lastValidBlockHeight;
249
+ unsignedTx.instructions = unsignedTx.instructions.filter(
250
+ computeBudgetIxFilter
251
+ );
252
+ unsignedTx.add(
253
+ ...await createPriorityFeeInstructions(
254
+ connection,
255
+ unsignedTx,
256
+ crossChainCore
257
+ )
258
+ );
259
+ if (request.transaction.signers) {
260
+ unsignedTx.partialSign(...request.transaction.signers);
261
+ }
262
+ return unsignedTx;
263
+ }
264
+ async function createPriorityFeeInstructions(connection, transaction, crossChainCore) {
265
+ var _a, _b, _c;
266
+ let unitsUsed = 2e5;
267
+ let simulationAttempts = 0;
268
+ simulationLoop:
269
+ while (true) {
270
+ const response = await connection.simulateTransaction(
271
+ transaction
272
+ );
273
+ if (response.value.err) {
274
+ if (checkKnownSimulationError(response.value)) {
275
+ if (simulationAttempts < 5) {
276
+ simulationAttempts++;
277
+ await sleep(1e3);
278
+ continue simulationLoop;
279
+ }
280
+ } else if (simulationAttempts < 3) {
281
+ simulationAttempts++;
282
+ await sleep(1e3);
283
+ continue simulationLoop;
284
+ }
285
+ throw new Error(
286
+ `Simulation failed: ${JSON.stringify(response.value.err)}
287
+ Logs:
288
+ ${(response.value.logs || []).join("\n ")}`
289
+ ).message;
290
+ } else {
291
+ if (response.value.unitsConsumed) {
292
+ unitsUsed = response.value.unitsConsumed;
293
+ }
294
+ break;
295
+ }
296
+ }
297
+ const unitBudget = Math.floor(unitsUsed * 1.2);
298
+ const instructions = [];
299
+ instructions.push(
300
+ import_web3.ComputeBudgetProgram.setComputeUnitLimit({
301
+ units: unitBudget
302
+ })
303
+ );
304
+ const {
305
+ percentile = 0.9,
306
+ percentileMultiple = 1,
307
+ min = 1e5,
308
+ max = 1e8
309
+ } = (_c = (_b = (_a = crossChainCore == null ? void 0 : crossChainCore._dappConfig) == null ? void 0 : _a.solanaConfig) == null ? void 0 : _b.priorityFeeConfig) != null ? _c : {};
310
+ const calculateFee = async (rpcProvider2) => {
311
+ if (rpcProvider2 === "triton") {
312
+ try {
313
+ const fee2 = await (0, import_sdk_solana.determinePriorityFeeTritonOne)(
314
+ connection,
315
+ transaction,
316
+ percentile,
317
+ percentileMultiple,
318
+ min,
319
+ max
320
+ );
321
+ return {
322
+ fee: fee2,
323
+ methodUsed: "triton"
324
+ };
325
+ } catch (e) {
326
+ console.warn(`Failed to determine priority fee using Triton RPC:`, e);
327
+ }
328
+ }
329
+ try {
330
+ const fee2 = await (0, import_sdk_solana.determinePriorityFee)(
331
+ connection,
332
+ transaction,
333
+ percentile,
334
+ percentileMultiple,
335
+ min,
336
+ max
337
+ );
338
+ return {
339
+ fee: fee2,
340
+ methodUsed: "default"
341
+ };
342
+ } catch (e) {
343
+ console.warn(`Failed to determine priority fee using Triton RPC:`, e);
344
+ return {
345
+ fee: min,
346
+ methodUsed: "minimum"
347
+ };
348
+ }
349
+ };
350
+ const rpcProvider = determineRpcProvider(connection.rpcEndpoint);
351
+ const { fee, methodUsed } = await calculateFee(rpcProvider);
352
+ const maxFeeInSol = fee / 1e6 / import_web3.LAMPORTS_PER_SOL * unitBudget;
353
+ console.table({
354
+ "RPC Provider": rpcProvider,
355
+ "Method used": methodUsed,
356
+ "Percentile used": percentile,
357
+ "Multiple used": percentileMultiple,
358
+ "Compute budget": unitBudget,
359
+ "Priority fee": fee,
360
+ "Max fee in SOL": maxFeeInSol
361
+ });
362
+ instructions.push(
363
+ import_web3.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: fee })
364
+ );
365
+ return instructions;
366
+ }
367
+ function checkKnownSimulationError(response) {
368
+ const errors = {};
369
+ if (response.err === "BlockhashNotFound") {
370
+ errors["BlockhashNotFound"] = "Blockhash not found during simulation. Trying again.";
371
+ }
372
+ if (response.logs) {
373
+ for (const line of response.logs) {
374
+ if (line.includes("SlippageToleranceExceeded")) {
375
+ errors["SlippageToleranceExceeded"] = "Slippage failure during simulation. Trying again.";
376
+ }
377
+ if (line.includes("RequireGteViolated")) {
378
+ errors["RequireGteViolated"] = "Swap instruction failure during simulation. Trying again.";
379
+ }
380
+ }
381
+ }
382
+ if (isEmptyObject(errors)) {
383
+ return false;
384
+ }
385
+ console.table(errors);
386
+ return true;
387
+ }
388
+ async function sleep(timeout) {
389
+ return new Promise((resolve) => setTimeout(resolve, timeout));
390
+ }
391
+ var isEmptyObject = (value) => {
392
+ if (value === null || value === void 0) {
393
+ return true;
394
+ }
395
+ for (const key in value) {
396
+ if (value.hasOwnProperty.call(value, key)) {
397
+ return false;
398
+ }
399
+ }
400
+ return true;
401
+ };
402
+ function determineRpcProvider(endpoint) {
403
+ try {
404
+ const url = new URL(endpoint);
405
+ const hostname = url.hostname;
406
+ if (hostname === "rpcpool.com") {
407
+ return "triton";
408
+ } else if (hostname === "helius-rpc.com") {
409
+ return "helius";
410
+ } else if (hostname === "rpc.ankr.com") {
411
+ return "ankr";
412
+ } else {
413
+ return "unknown";
414
+ }
415
+ } catch (e) {
416
+ return "unknown";
417
+ }
418
+ }
419
+
420
+ // src/providers/wormhole/signers/EthereumSigner.ts
421
+ var import_ethers = require("ethers");
422
+ async function signAndSendTransaction3(request, wallet, chainName, options) {
423
+ if (!wallet) {
424
+ throw new Error("wallet.sendTransaction is undefined").message;
425
+ }
426
+ const chainId = await wallet.eip1193Provider.request({
427
+ method: "eth_chainId"
428
+ });
429
+ const actualChainId = parseInt(chainId, 16);
430
+ if (!actualChainId)
431
+ throw new Error("No signer found for chain" + chainName).message;
432
+ const expectedChainId = request.transaction.chainId ? (0, import_ethers.getBigInt)(request.transaction.chainId) : void 0;
433
+ if (!actualChainId || !expectedChainId || BigInt(actualChainId) !== expectedChainId) {
434
+ throw new Error(
435
+ `Signer is not connected to the right chain. Expected ${expectedChainId}, got ${actualChainId}`
436
+ ).message;
437
+ }
438
+ const provider = new import_ethers.ethers.BrowserProvider(
439
+ wallet.eip1193Provider
440
+ );
441
+ const signer = await provider.getSigner();
442
+ const response = await signer.sendTransaction(request.transaction);
443
+ const receipt = await response.wait();
444
+ return (receipt == null ? void 0 : receipt.hash) || "";
445
+ }
446
+
447
+ // src/providers/wormhole/signers/Signer.ts
448
+ var Signer = class {
449
+ constructor(chain, address, options, wallet, crossChainCore) {
450
+ this._chain = chain;
451
+ this._address = address;
452
+ this._options = options;
453
+ this._wallet = wallet;
454
+ this._crossChainCore = crossChainCore;
455
+ }
456
+ chain() {
457
+ return this._chain.displayName;
458
+ }
459
+ address() {
460
+ return this._address;
461
+ }
462
+ async signAndSend(txs) {
463
+ const txHashes = [];
464
+ for (const tx of txs) {
465
+ const txId = await signAndSendTransaction4(
466
+ this._chain,
467
+ tx,
468
+ this._wallet,
469
+ this._options,
470
+ this._crossChainCore
471
+ );
472
+ txHashes.push(txId);
473
+ }
474
+ return txHashes;
475
+ }
476
+ };
477
+ var signAndSendTransaction4 = async (chain, request, wallet, options = {}, crossChainCore) => {
478
+ if (!wallet) {
479
+ throw new Error("wallet is undefined");
480
+ }
481
+ if (chain.context === "Solana") {
482
+ const signature = await signAndSendTransaction2(
483
+ request,
484
+ wallet,
485
+ options,
486
+ crossChainCore
487
+ );
488
+ return signature;
489
+ } else if (chain.context === "Ethereum") {
490
+ const tx = await signAndSendTransaction3(
491
+ request,
492
+ wallet,
493
+ chain.displayName,
494
+ options
495
+ );
496
+ return tx;
497
+ } else {
498
+ throw new Error(`Unsupported chain: ${chain}`);
499
+ }
500
+ };
501
+
502
+ // src/providers/wormhole/wormhole.ts
503
+ var WormholeProvider = class {
504
+ constructor(core) {
505
+ this.crossChainCore = core;
506
+ }
507
+ get wormholeContext() {
508
+ return this._wormholeContext;
509
+ }
510
+ async setWormholeContext(sourceChain) {
511
+ var _a;
512
+ const dappNetwork = (_a = this.crossChainCore._dappConfig) == null ? void 0 : _a.aptosNetwork;
513
+ if (dappNetwork === import_ts_sdk2.Network.DEVNET) {
514
+ throw new Error("Devnet is not supported on Wormhole");
515
+ }
516
+ if (!sourceChain) {
517
+ throw new Error("Origin chain not selected");
518
+ }
519
+ const isMainnet = dappNetwork === import_ts_sdk2.Network.MAINNET;
520
+ const platforms = [import_aptos.default, import_solana.default, import_evm.default];
521
+ const wh = await (0, import_sdk.wormhole)(isMainnet ? "Mainnet" : "Testnet", platforms);
522
+ this._wormholeContext = wh;
523
+ }
524
+ async getRoute(sourceChain) {
525
+ if (!this._wormholeContext) {
526
+ throw new Error("Wormhole context not initialized");
527
+ }
528
+ const { sourceToken, destToken } = this.getTokenInfo(sourceChain);
529
+ const sourceContext = this._wormholeContext.getPlatform((0, import_sdk.chainToPlatform)(sourceChain)).getChain(sourceChain);
530
+ logger.log("sourceContext", sourceContext);
531
+ const destContext = this._wormholeContext.getPlatform((0, import_sdk.chainToPlatform)("Aptos")).getChain("Aptos");
532
+ logger.log("destContext", destContext);
533
+ const request = await import_sdk.routes.RouteTransferRequest.create(
534
+ this._wormholeContext,
535
+ {
536
+ source: sourceToken,
537
+ destination: destToken
538
+ },
539
+ sourceContext,
540
+ destContext
541
+ );
542
+ const resolver = this._wormholeContext.resolver([
543
+ import_sdk.routes.CCTPRoute
544
+ ]);
545
+ const route = await resolver.findRoutes(request);
546
+ const cctpRoute = route[0];
547
+ this.wormholeRoute = cctpRoute;
548
+ this.wormholeRequest = request;
549
+ return { route: cctpRoute, request };
550
+ }
551
+ async getQuote(input) {
552
+ const { amount, sourceChain } = input;
553
+ if (!this._wormholeContext) {
554
+ await this.setWormholeContext(sourceChain);
555
+ }
556
+ const { route, request } = await this.getRoute(sourceChain);
557
+ const transferParams = {
558
+ amount,
559
+ options: { nativeGas: 0 }
560
+ };
561
+ const validated = await route.validate(request, transferParams);
562
+ if (!validated.valid) {
563
+ logger.log("invalid", validated.valid);
564
+ throw new Error(`Invalid quote: ${validated.error}`).message;
565
+ }
566
+ const quote = await route.quote(request, validated.params);
567
+ if (!quote.success) {
568
+ logger.log("quote failed", quote.success);
569
+ throw new Error(`Invalid quote: ${quote.error}`).message;
570
+ }
571
+ this.wormholeQuote = quote;
572
+ logger.log("quote", quote);
573
+ return quote;
574
+ }
575
+ async submitCCTPTransfer(input) {
576
+ var _a;
577
+ const { sourceChain, wallet, destinationAddress } = input;
578
+ if (!this._wormholeContext) {
579
+ await this.setWormholeContext(sourceChain);
580
+ }
581
+ if (!this.wormholeRoute || !this.wormholeRequest || !this.wormholeQuote) {
582
+ throw new Error("Wormhole route, request, or quote not initialized");
583
+ }
584
+ let signerAddress;
585
+ const chainContext = this.getChainConfig(sourceChain).context;
586
+ if (chainContext === "Solana") {
587
+ signerAddress = ((_a = wallet.solanaWallet.publicKey) == null ? void 0 : _a.toBase58()) || "";
588
+ } else {
589
+ [signerAddress] = await wallet.eip1193Provider.request({
590
+ method: "eth_requestAccounts"
591
+ });
592
+ }
593
+ logger.log("signerAddress", signerAddress);
594
+ const signer = new Signer(
595
+ this.getChainConfig(sourceChain),
596
+ signerAddress,
597
+ {},
598
+ wallet
599
+ );
600
+ let receipt = await this.wormholeRoute.initiate(
601
+ this.wormholeRequest,
602
+ signer,
603
+ this.wormholeQuote,
604
+ import_sdk.Wormhole.chainAddress("Aptos", destinationAddress.toString())
605
+ );
606
+ const originChainTxnId = "originTxs" in receipt ? receipt.originTxs[receipt.originTxs.length - 1].txid : void 0;
607
+ return { originChainTxnId: originChainTxnId || "", receipt };
608
+ }
609
+ async claimCCTPTransfer(input) {
610
+ let { receipt, mainSigner, sponsorAccount } = input;
611
+ if (!this.wormholeRoute) {
612
+ throw new Error("Wormhole route not initialized");
613
+ }
614
+ logger.log("mainSigner", mainSigner.accountAddress.toString());
615
+ let retries = 0;
616
+ const maxRetries = 5;
617
+ const baseDelay = 1e3;
618
+ while (retries < maxRetries) {
619
+ try {
620
+ for await (receipt of this.wormholeRoute.track(receipt, 120 * 1e3)) {
621
+ if (receipt.state >= import_sdk.TransferState.SourceInitiated) {
622
+ logger.log("Receipt is on track ", receipt);
623
+ try {
624
+ const signer = new AptosLocalSigner(
625
+ "Aptos",
626
+ {},
627
+ mainSigner,
628
+ sponsorAccount ? sponsorAccount : void 0
629
+ );
630
+ if (import_sdk.routes.isManual(this.wormholeRoute)) {
631
+ const circleAttestationReceipt = await this.wormholeRoute.complete(signer, receipt);
632
+ logger.log("Claim receipt: ", circleAttestationReceipt);
633
+ const destinationChainTxnId = signer.claimedTransactionHashes();
634
+ return { destinationChainTxnId };
635
+ } else {
636
+ return { destinationChainTxnId: "" };
637
+ }
638
+ } catch (e) {
639
+ console.error("Failed to claim", e);
640
+ return { destinationChainTxnId: "" };
641
+ }
642
+ }
643
+ }
644
+ } catch (e) {
645
+ console.error(
646
+ `Error tracking transfer (attempt ${retries + 1} / ${maxRetries}):`,
647
+ e
648
+ );
649
+ const delay = baseDelay * Math.pow(2, retries);
650
+ await (0, import_ts_sdk2.sleep)(delay);
651
+ retries++;
652
+ }
653
+ }
654
+ return { destinationChainTxnId: "" };
655
+ }
656
+ async initiateCCTPTransfer(input) {
657
+ var _a;
658
+ if (((_a = this.crossChainCore._dappConfig) == null ? void 0 : _a.aptosNetwork) === import_ts_sdk2.Network.DEVNET) {
659
+ throw new Error("Devnet is not supported on Wormhole");
660
+ }
661
+ if (input.amount) {
662
+ await this.getQuote({
663
+ amount: input.amount,
664
+ sourceChain: input.sourceChain
665
+ });
666
+ }
667
+ let { originChainTxnId, receipt } = await this.submitCCTPTransfer(input);
668
+ const { destinationChainTxnId } = await this.claimCCTPTransfer({
669
+ receipt,
670
+ mainSigner: input.mainSigner,
671
+ sponsorAccount: input.sponsorAccount
672
+ });
673
+ return { originChainTxnId, destinationChainTxnId };
674
+ }
675
+ getChainConfig(chain) {
676
+ const chainConfig = this.crossChainCore.CHAINS[chain];
677
+ if (!chainConfig) {
678
+ throw new Error(`Chain config not found for chain: ${chain}`);
679
+ }
680
+ return chainConfig;
681
+ }
682
+ getTokenInfo(sourceChain) {
683
+ const sourceToken = import_sdk.Wormhole.tokenId(
684
+ this.crossChainCore.TOKENS[sourceChain].tokenId.chain,
685
+ this.crossChainCore.TOKENS[sourceChain].tokenId.address
686
+ );
687
+ const destToken = import_sdk.Wormhole.tokenId(
688
+ this.crossChainCore.APTOS_TOKEN.tokenId.chain,
689
+ this.crossChainCore.APTOS_TOKEN.tokenId.address
690
+ );
691
+ return { sourceToken, destToken };
692
+ }
693
+ };
694
+
695
+ // src/config/types.ts
696
+ var Context = /* @__PURE__ */ ((Context2) => {
697
+ Context2["ETH"] = "Ethereum";
698
+ Context2["SOLANA"] = "Solana";
699
+ Context2["APTOS"] = "Aptos";
700
+ return Context2;
701
+ })(Context || {});
702
+
703
+ // src/config/testnet/chains.ts
704
+ var testnetChains = {
705
+ Sepolia: {
706
+ key: "Sepolia",
707
+ id: 10002,
708
+ context: "Ethereum" /* ETH */,
709
+ finalityThreshold: 0,
710
+ displayName: "Sepolia",
711
+ explorerUrl: "https://sepolia.etherscan.io/",
712
+ explorerName: "Etherscan",
713
+ gasToken: "ETHsepolia",
714
+ chainId: 11155111,
715
+ icon: "Ethereum",
716
+ maxBlockSearch: 2e3,
717
+ symbol: "ETH",
718
+ defaultRpc: "https://eth-sepolia.public.blastapi.io",
719
+ wrappedGasToken: "0xeef12A83EE5b7161D3873317c8E0E7B76e0B5D9c"
720
+ },
721
+ Solana: {
722
+ key: "Solana",
723
+ id: 1,
724
+ context: "Solana" /* SOLANA */,
725
+ finalityThreshold: 32,
726
+ displayName: "Solana",
727
+ explorerUrl: "https://explorer.solana.com/",
728
+ explorerName: "Solana Explorer",
729
+ gasToken: "SOL",
730
+ chainId: 0,
731
+ icon: "Solana",
732
+ maxBlockSearch: 2e3,
733
+ symbol: "SOL",
734
+ defaultRpc: "https://api.devnet.solana.com",
735
+ wrappedGasToken: "So11111111111111111111111111111111111111112"
736
+ }
737
+ };
738
+ var AptosTestnetChain = {
739
+ key: "Aptos",
740
+ id: 22,
741
+ context: "Aptos" /* APTOS */,
742
+ finalityThreshold: 0,
743
+ displayName: "Aptos",
744
+ explorerUrl: "https://explorer.aptoslabs.com?network=testnet",
745
+ explorerName: "Aptos Explorer",
746
+ gasToken: "APT",
747
+ chainId: 0,
748
+ icon: "Aptos",
749
+ maxBlockSearch: 0,
750
+ symbol: "APT",
751
+ sdkName: "Aptos"
752
+ };
753
+
754
+ // src/config/testnet/tokens.ts
755
+ var testnetTokens = {
756
+ Sepolia: {
757
+ symbol: "USDC",
758
+ icon: "USDC",
759
+ decimals: 6,
760
+ tokenId: {
761
+ chain: "Sepolia",
762
+ address: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"
763
+ }
764
+ },
765
+ Solana: {
766
+ symbol: "USDC",
767
+ tokenId: {
768
+ chain: "Solana",
769
+ address: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU"
770
+ },
771
+ icon: "USDC",
772
+ decimals: 6
773
+ }
774
+ };
775
+ var AptosTestnetUSDCToken = {
776
+ symbol: "USDC",
777
+ decimals: 6,
778
+ tokenId: {
779
+ chain: "Aptos",
780
+ address: "0x69091fbab5f7d635ee7ac5098cf0c1efbe31d68fec0f2cd565e8d168daf52832"
781
+ },
782
+ icon: "USDC"
783
+ };
784
+
785
+ // src/config/mainnet/chains.ts
786
+ var mainnetChains = {
787
+ Ethereum: {
788
+ key: "Ethereum",
789
+ id: 2,
790
+ context: "Ethereum" /* ETH */,
791
+ finalityThreshold: 64,
792
+ displayName: "Ethereum",
793
+ explorerUrl: "https://etherscan.io/",
794
+ explorerName: "Etherscan",
795
+ gasToken: "ETH",
796
+ chainId: 1,
797
+ icon: "Ethereum",
798
+ maxBlockSearch: 2e3,
799
+ symbol: "ETH",
800
+ defaultRpc: "https://rpc.ankr.com/eth"
801
+ },
802
+ Solana: {
803
+ key: "Solana",
804
+ id: 1,
805
+ context: "Solana" /* SOLANA */,
806
+ finalityThreshold: 32,
807
+ displayName: "Solana",
808
+ explorerUrl: "https://explorer.solana.com/",
809
+ explorerName: "Solana Explorer",
810
+ gasToken: "SOL",
811
+ chainId: 0,
812
+ icon: "Solana",
813
+ maxBlockSearch: 2e3,
814
+ symbol: "SOL",
815
+ defaultRpc: "https://solana-mainnet.rpc.extrnode.com"
816
+ }
817
+ };
818
+ var AptosMainnetChain = {
819
+ key: "Aptos",
820
+ id: 22,
821
+ context: "Aptos",
822
+ finalityThreshold: 0,
823
+ displayName: "Aptos",
824
+ explorerUrl: "https://explorer.aptoslabs.com/",
825
+ explorerName: "Aptos Explorer",
826
+ gasToken: "APT",
827
+ chainId: 0,
828
+ icon: "Aptos",
829
+ maxBlockSearch: 0,
830
+ symbol: "APT"
831
+ };
832
+
833
+ // src/config/mainnet/tokens.ts
834
+ var mainnetTokens = {
835
+ Ethereum: {
836
+ symbol: "USDC",
837
+ tokenId: {
838
+ chain: "Ethereum",
839
+ address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
840
+ },
841
+ icon: "USDC",
842
+ decimals: 6
843
+ },
844
+ Solana: {
845
+ symbol: "USDC",
846
+ tokenId: {
847
+ chain: "Solana",
848
+ address: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
849
+ },
850
+ icon: "USDC",
851
+ decimals: 6
852
+ }
853
+ };
854
+ var AptosMainnetUSDCToken = {
855
+ symbol: "USDC",
856
+ tokenId: {
857
+ chain: "Aptos",
858
+ address: "0xbae207659db88bea0cbead6da0ed00aac12edcdda169e591cd41c94180b46f3b"
859
+ },
860
+ icon: "USDC",
861
+ decimals: 6
862
+ };
863
+
864
+ // src/utils/getUsdcBalance.ts
865
+ var import_ts_sdk3 = require("@aptos-labs/ts-sdk");
866
+ var import_web33 = require("@solana/web3.js");
867
+ var import_ethers2 = require("ethers");
868
+ var getSolanaWalletUSDCBalance = async (walletAddress, aptosNetwork, rpc) => {
869
+ var _a;
870
+ const address = new import_web33.PublicKey(walletAddress);
871
+ const tokenAddress = aptosNetwork === import_ts_sdk3.Network.MAINNET ? mainnetTokens["Solana"].tokenId.address : testnetTokens["Solana"].tokenId.address;
872
+ const connection = new import_web33.Connection(rpc);
873
+ const splToken = await connection.getTokenAccountsByOwner(address, {
874
+ mint: new import_web33.PublicKey(tokenAddress)
875
+ });
876
+ const checkAddress = splToken.value.length > 0 ? splToken.value[0].pubkey : address;
877
+ const balance = await connection.getTokenAccountBalance(checkAddress);
878
+ console.log("balance", balance);
879
+ return (_a = balance.value.uiAmountString) != null ? _a : (Number(balance.value.amount) / 10 ** balance.value.decimals).toString();
880
+ };
881
+ var getEthereumWalletUSDCBalance = async (walletAddress, aptosNetwork, rpc) => {
882
+ const token = aptosNetwork === import_ts_sdk3.Network.MAINNET ? mainnetTokens["Ethereum"] : testnetTokens["Sepolia"];
883
+ const tokenAddress = token.tokenId.address;
884
+ const connection = new import_ethers2.JsonRpcProvider(rpc);
885
+ const abi = ["function balanceOf(address owner) view returns (uint256)"];
886
+ const contract = new import_ethers2.ethers.Contract(tokenAddress, abi, connection);
887
+ const balance = await contract.balanceOf(walletAddress);
888
+ return import_ethers2.ethers.formatUnits(balance, token.decimals).toString();
889
+ };
890
+ var getAptosWalletUSDCBalance = async (walletAddress, aptosNetwork) => {
891
+ const token = aptosNetwork === import_ts_sdk3.Network.MAINNET ? AptosMainnetUSDCToken : AptosTestnetUSDCToken;
892
+ const tokenAddress = token.tokenId.address;
893
+ const aptosConfig = new import_ts_sdk3.AptosConfig({ network: aptosNetwork });
894
+ const connection = new import_ts_sdk3.Aptos(aptosConfig);
895
+ const response = await connection.getCurrentFungibleAssetBalances({
896
+ options: {
897
+ where: {
898
+ owner_address: { _eq: walletAddress },
899
+ asset_type: { _eq: tokenAddress }
900
+ }
901
+ }
902
+ });
903
+ const balance = (Number(response[0].amount) / 10 ** token.decimals).toString();
904
+ return balance;
905
+ };
906
+
907
+ // src/CrossChainCore.ts
908
+ var import_ts_sdk5 = require("@aptos-labs/ts-sdk");
909
+ var CrossChainCore = class {
910
+ constructor(args) {
911
+ this._dappConfig = {
912
+ aptosNetwork: import_ts_sdk4.Network.TESTNET
913
+ };
914
+ this.CHAINS = testnetChains;
915
+ this.TOKENS = testnetTokens;
916
+ this.APTOS_TOKEN = AptosTestnetUSDCToken;
917
+ var _a;
918
+ this._dappConfig = args.dappConfig;
919
+ if (((_a = args.dappConfig) == null ? void 0 : _a.aptosNetwork) === import_ts_sdk4.Network.MAINNET) {
920
+ this.CHAINS = mainnetChains;
921
+ this.TOKENS = mainnetTokens;
922
+ this.APTOS_TOKEN = AptosMainnetUSDCToken;
923
+ } else {
924
+ this.CHAINS = testnetChains;
925
+ this.TOKENS = testnetTokens;
926
+ this.APTOS_TOKEN = AptosTestnetUSDCToken;
927
+ }
928
+ }
929
+ getProvider(providerType) {
930
+ switch (providerType) {
931
+ case "Wormhole":
932
+ return new WormholeProvider(this);
933
+ default:
934
+ throw new Error(`Unknown provider: ${providerType}`);
935
+ }
936
+ }
937
+ async getWalletUSDCBalance(walletAddress, sourceChain) {
938
+ var _a, _b, _c;
939
+ if (sourceChain === "Aptos") {
940
+ return await getAptosWalletUSDCBalance(
941
+ walletAddress,
942
+ this._dappConfig.aptosNetwork
943
+ );
944
+ }
945
+ if (!this.CHAINS[sourceChain]) {
946
+ throw new Error(`Unsupported chain: ${sourceChain}`);
947
+ }
948
+ switch (sourceChain) {
949
+ case "Solana":
950
+ return await getSolanaWalletUSDCBalance(
951
+ walletAddress,
952
+ this._dappConfig.aptosNetwork,
953
+ (_c = (_b = (_a = this._dappConfig) == null ? void 0 : _a.solanaConfig) == null ? void 0 : _b.rpc) != null ? _c : this.CHAINS[sourceChain].defaultRpc
954
+ );
955
+ case "Ethereum":
956
+ case "Sepolia":
957
+ return await getEthereumWalletUSDCBalance(
958
+ walletAddress,
959
+ this._dappConfig.aptosNetwork,
960
+ this.CHAINS[sourceChain].defaultRpc
961
+ );
962
+ default:
963
+ throw new Error(`Unsupported chain: ${sourceChain}`);
964
+ }
965
+ }
966
+ };
967
+
968
+ // src/index.ts
969
+ var import_ts_sdk6 = require("@aptos-labs/ts-sdk");
970
+ // Annotate the CommonJS export names for ESM import in node:
971
+ 0 && (module.exports = {
972
+ AptosLocalSigner,
973
+ AptosMainnetChain,
974
+ AptosMainnetUSDCToken,
975
+ AptosTestnetChain,
976
+ AptosTestnetUSDCToken,
977
+ Context,
978
+ CrossChainCore,
979
+ Network,
980
+ NetworkToChainId,
981
+ NetworkToNodeAPI,
982
+ WormholeProvider,
983
+ mainnetChains,
984
+ mainnetTokens,
985
+ signAndSendTransaction,
986
+ testnetChains,
987
+ testnetTokens
988
+ });
989
+ //# sourceMappingURL=index.js.map