@skip-go/client 1.5.3-alpha.0 → 1.5.3-alpha.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 (47) hide show
  1. package/dist/cjs/{chunk-CZKIE576.cjs → chunk-APJDSXWR.cjs} +2 -2
  2. package/dist/cjs/{chunk-GWRZ6MPC.cjs → chunk-I2FDWZZJ.cjs} +16 -16
  3. package/dist/cjs/{chunk-GGSF5JZH.cjs → chunk-NWD4MAMT.cjs} +4 -4
  4. package/dist/cjs/{chunk-J7HZ6VJE.cjs → chunk-PDTIT3JO.cjs} +3 -3
  5. package/dist/cjs/{chunk-MOWOIPUG.cjs → chunk-RC73RNNQ.cjs} +2 -2
  6. package/dist/cjs/chunk-UMBMSRZZ.cjs +185 -0
  7. package/dist/cjs/index.cjs +35 -35
  8. package/dist/cjs/public-functions/executeMultipleRoutes.cjs +7 -7
  9. package/dist/cjs/public-functions/executeRoute.cjs +7 -7
  10. package/dist/cjs/public-functions/getFeeInfoForChain.cjs +3 -3
  11. package/dist/cjs/public-functions/getRecommendedGasPrice.cjs +4 -4
  12. package/dist/cjs/public-functions/getRouteWithGasOnReceive.cjs +7 -7
  13. package/dist/cjs/public-functions/getSigningStargateClient.cjs +3 -3
  14. package/dist/cjs/public-functions/validateCosmosGasBalance.cjs +4 -4
  15. package/dist/esm/{chunk-SOVU5NCL.js → chunk-2PWROHHX.js} +1 -1
  16. package/dist/esm/{chunk-RJ35JBT4.js → chunk-IKWC55JU.js} +4 -4
  17. package/dist/esm/chunk-O4J7DHZA.js +180 -0
  18. package/dist/esm/{chunk-YWG4XR5A.js → chunk-QRKO56DH.js} +1 -1
  19. package/dist/esm/{chunk-47HN6VKU.js → chunk-SFWTQBQT.js} +1 -1
  20. package/dist/esm/{chunk-JNVGNIOE.js → chunk-V7VKYD4J.js} +1 -1
  21. package/dist/esm/index.js +6 -6
  22. package/dist/esm/public-functions/executeMultipleRoutes.js +6 -6
  23. package/dist/esm/public-functions/executeRoute.js +6 -6
  24. package/dist/esm/public-functions/getFeeInfoForChain.js +2 -2
  25. package/dist/esm/public-functions/getRecommendedGasPrice.js +3 -3
  26. package/dist/esm/public-functions/getRouteWithGasOnReceive.js +6 -6
  27. package/dist/esm/public-functions/getSigningStargateClient.js +2 -2
  28. package/dist/esm/public-functions/validateCosmosGasBalance.js +3 -3
  29. package/package.json +1 -1
  30. package/dist/cjs/chunk-ARCCHERF.cjs +0 -1478
  31. package/dist/cjs/chunk-BQDOKZFX.cjs +0 -214
  32. package/dist/cjs/chunk-EVEVOW2U.cjs +0 -2179
  33. package/dist/cjs/chunk-H2T4LMS2.cjs +0 -55
  34. package/dist/cjs/chunk-I6VYDEUV.cjs +0 -454
  35. package/dist/cjs/chunk-KSJ5QYMR.cjs +0 -185
  36. package/dist/cjs/chunk-KZOSEIWH.cjs +0 -10
  37. package/dist/cjs/chunk-UY5LWG5D.cjs +0 -95
  38. package/dist/cjs/chunk-W6ID22B6.cjs +0 -24
  39. package/dist/esm/chunk-DL374PFE.js +0 -53
  40. package/dist/esm/chunk-FDRLM2JD.js +0 -431
  41. package/dist/esm/chunk-H3MY23AH.js +0 -93
  42. package/dist/esm/chunk-IGK7LJCM.js +0 -1475
  43. package/dist/esm/chunk-RHGDUD76.js +0 -180
  44. package/dist/esm/chunk-RHLE3EW7.js +0 -212
  45. package/dist/esm/chunk-SWYON2RG.js +0 -7
  46. package/dist/esm/chunk-X2IBEHMZ.js +0 -2154
  47. package/dist/esm/chunk-XHLXJGVB.js +0 -22
@@ -1,1478 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkBCX2D6TE_cjs = require('./chunk-BCX2D6TE.cjs');
4
- var chunkCZKIE576_cjs = require('./chunk-CZKIE576.cjs');
5
- var chunkKM2D7PJL_cjs = require('./chunk-KM2D7PJL.cjs');
6
- var chunkF3EB2AQG_cjs = require('./chunk-F3EB2AQG.cjs');
7
- var chunkWKYP2NMS_cjs = require('./chunk-WKYP2NMS.cjs');
8
- var chunkKZOSEIWH_cjs = require('./chunk-KZOSEIWH.cjs');
9
- var chunkJ7HZ6VJE_cjs = require('./chunk-J7HZ6VJE.cjs');
10
- var chunkKSJ5QYMR_cjs = require('./chunk-KSJ5QYMR.cjs');
11
- var chunk262HFM6V_cjs = require('./chunk-262HFM6V.cjs');
12
- var chunkT5EGKQAT_cjs = require('./chunk-T5EGKQAT.cjs');
13
- var chunkQAHHTQ7V_cjs = require('./chunk-QAHHTQ7V.cjs');
14
- var chunkHFEMNOJS_cjs = require('./chunk-HFEMNOJS.cjs');
15
- var stargate = require('@cosmjs/stargate');
16
- var tx_js = require('cosmjs-types/cosmos/tx/v1beta1/tx.js');
17
- var protoSigning = require('@cosmjs/proto-signing');
18
- var amino = require('@cosmjs/amino');
19
- var encoding = require('@cosmjs/encoding');
20
- var keys_js = require('cosmjs-types/cosmos/crypto/secp256k1/keys.js');
21
- var any_js = require('cosmjs-types/google/protobuf/any.js');
22
- var math = require('@cosmjs/math');
23
- var signing_js = require('cosmjs-types/cosmos/tx/signing/v1beta1/signing.js');
24
- var viem = require('viem');
25
- var web3_js = require('@solana/web3.js');
26
- var bech32 = require('bech32');
27
-
28
- // src/private-functions/getRestEndpointForChain.ts
29
- var getRestEndpointForChain = async (chainId) => {
30
- if (chunkQAHHTQ7V_cjs.ClientState.endpointOptions.getRestEndpointForChain) {
31
- return chunkQAHHTQ7V_cjs.ClientState.endpointOptions.getRestEndpointForChain(chainId);
32
- }
33
- if (chunkQAHHTQ7V_cjs.ClientState.endpointOptions.endpoints && chunkQAHHTQ7V_cjs.ClientState.endpointOptions.endpoints[chainId]) {
34
- const endpointOptions = chunkQAHHTQ7V_cjs.ClientState.endpointOptions.endpoints[chainId];
35
- if (endpointOptions?.rest) {
36
- return endpointOptions.rest;
37
- }
38
- }
39
- const chain = chunkKSJ5QYMR_cjs.chains().find((chain2) => chain2.chainId === chainId);
40
- if (!chain) {
41
- throw new Error(
42
- `getRestEndpointForChain error: failed to find chain id '${chainId}' in registry`
43
- );
44
- }
45
- if (chain.apis?.rest?.length === 0 || !chain.apis?.rest) {
46
- throw new Error(
47
- `getRestEndpointForChain error: failed to find REST endpoint for chain id '${chainId}'`
48
- );
49
- }
50
- const endpoints = chain.apis?.rest?.map((api) => api.address);
51
- const endpoint = await chunkKSJ5QYMR_cjs.findFirstWorkingEndpoint(endpoints, "rest");
52
- if (!endpoint) {
53
- throw new Error(
54
- `getRestEndpointForChain error: failed to find REST endpoint for chain id '${chainId}'`
55
- );
56
- }
57
- return endpoint;
58
- };
59
-
60
- // src/private-functions/getAccountNumberAndSequence.ts
61
- var getAccountNumberAndSequence = async (address, chainId) => {
62
- if (chainId.includes("dymension")) {
63
- return getAccountNumberAndSequenceFromDymension(address, chainId);
64
- }
65
- const endpoint = await chunkJ7HZ6VJE_cjs.getRpcEndpointForChain(chainId);
66
- const client = chunkQAHHTQ7V_cjs.ClientState.signingStargateClientByChainId[chainId] ?? await stargate.StargateClient.connect(endpoint, {
67
- accountParser: chunkJ7HZ6VJE_cjs.accountParser
68
- });
69
- const account = await client.getAccount(address);
70
- if (!account) {
71
- throw new Error("getAccountNumberAndSequence: failed to retrieve account");
72
- }
73
- client.disconnect();
74
- return {
75
- accountNumber: account.accountNumber,
76
- sequence: account.sequence
77
- };
78
- };
79
- var getAccountNumberAndSequenceFromDymension = async (address, chainId) => {
80
- const endpoint = await getRestEndpointForChain(chainId);
81
- const res = await fetch(
82
- `${endpoint}/cosmos/auth/v1beta1/accounts/${address}`,
83
- {
84
- headers: {
85
- "Content-Type": "application/json"
86
- }
87
- }
88
- );
89
- if (!res.ok) {
90
- throw new Error(`Failed to fetch account data: ${res.statusText}`);
91
- }
92
- const jsonResponse = await res.json();
93
- const response = chunkHFEMNOJS_cjs.toCamel(jsonResponse);
94
- let sequence = 0;
95
- let accountNumber = 0;
96
- if (response.account.baseAccount) {
97
- sequence = response.account.baseAccount.sequence;
98
- accountNumber = response.account.baseAccount.accountNumber;
99
- } else {
100
- sequence = response.account.sequence;
101
- accountNumber = response.account.accountNumber;
102
- }
103
- return {
104
- accountNumber,
105
- sequence
106
- };
107
- };
108
- var pubkeyType = {
109
- ethsecp256k1: "ethermint/PubKeyEthSecp256k1",
110
- ...amino.pubkeyType
111
- };
112
-
113
- // src/amino/encoding.ts
114
- function encodeEthSecp256k1Pubkey(pubkey) {
115
- if (pubkey.length !== 33 || pubkey[0] !== 2 && pubkey[0] !== 3) {
116
- throw new Error(
117
- "Public key must be compressed secp256k1, i.e. 33 bytes starting with 0x02 or 0x03"
118
- );
119
- }
120
- return {
121
- type: pubkeyType.ethsecp256k1,
122
- value: encoding.toBase64(pubkey)
123
- };
124
- }
125
-
126
- // src/proto-signing/pubkey.ts
127
- function makePubkeyAnyFromAccount(account, chainId) {
128
- const isEthermint = chunkKSJ5QYMR_cjs.getIsEthermint(chainId);
129
- const pubkey = isEthermint ? encodeEthSecp256k1Pubkey(account.pubkey) : amino.encodeSecp256k1Pubkey(account.pubkey);
130
- const pubkeyAny = encodePubkeyToAny(pubkey, chainId, isEthermint);
131
- return pubkeyAny;
132
- }
133
- function encodePubkeyToAny(pubkey, chainId, isEthermint) {
134
- if (isEthermint) {
135
- const pubkeyProto = keys_js.PubKey.fromPartial({
136
- key: encoding.fromBase64(pubkey.value)
137
- });
138
- let typeUrl = "";
139
- if (chainId?.includes("injective")) {
140
- typeUrl = "/injective.crypto.v1beta1.ethsecp256k1.PubKey";
141
- } else {
142
- typeUrl = "/ethermint.crypto.v1.ethsecp256k1.PubKey";
143
- }
144
- return any_js.Any.fromPartial({
145
- typeUrl,
146
- value: Uint8Array.from(keys_js.PubKey.encode(pubkeyProto).finish())
147
- });
148
- } else {
149
- const isInitia = chunkKSJ5QYMR_cjs.getIsInitia(chainId);
150
- const pubkeyProto = keys_js.PubKey.fromPartial({
151
- key: encoding.fromBase64(pubkey.value)
152
- });
153
- if (isInitia) {
154
- return any_js.Any.fromPartial({
155
- typeUrl: "/initia.crypto.v1beta1.ethsecp256k1.PubKey",
156
- value: Uint8Array.from(keys_js.PubKey.encode(pubkeyProto).finish())
157
- });
158
- }
159
- return protoSigning.encodePubkey(pubkey);
160
- }
161
- }
162
- var signCosmosMessageDirect = async (options) => {
163
- const {
164
- signer,
165
- signerAddress,
166
- chainId,
167
- cosmosMsgs,
168
- fee,
169
- signerData: { accountNumber, sequence, chainId: signerChainId }
170
- } = options;
171
- const accounts = await signer.getAccounts();
172
- const accountFromSigner = accounts.find((account) => account.address === signerAddress);
173
- if (!accountFromSigner) {
174
- throw new Error("signCosmosMessageDirect error: failed to retrieve account from signer");
175
- }
176
- const messages = cosmosMsgs.map((cosmosMsg) => chunkKM2D7PJL_cjs.getEncodeObjectFromCosmosMessage(cosmosMsg));
177
- const txBodyEncodeObject = {
178
- typeUrl: "/cosmos.tx.v1beta1.TxBody",
179
- value: {
180
- messages
181
- }
182
- };
183
- const txBodyBytes = chunkQAHHTQ7V_cjs.ClientState.registry.encode(txBodyEncodeObject);
184
- const gasLimit = math.Int53.fromString(fee.gas).toNumber();
185
- const pubkeyAny = makePubkeyAnyFromAccount(accountFromSigner, chainId);
186
- const authInfoBytes = protoSigning.makeAuthInfoBytes(
187
- [{ pubkey: pubkeyAny, sequence }],
188
- fee.amount,
189
- gasLimit,
190
- fee.granter,
191
- fee.payer
192
- );
193
- const signDoc = protoSigning.makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber);
194
- const { signature, signed } = await signer.signDirect(signerAddress, signDoc);
195
- return tx_js.TxRaw.fromPartial({
196
- bodyBytes: signed.bodyBytes,
197
- authInfoBytes: signed.authInfoBytes,
198
- signatures: [encoding.fromBase64(signature.signature)]
199
- });
200
- };
201
- var signCosmosMessageAmino = async (options) => {
202
- const {
203
- signer,
204
- signerAddress,
205
- chainId,
206
- cosmosMsgs,
207
- fee,
208
- signerData: { accountNumber, sequence, chainId: signerChainId }
209
- } = options;
210
- const accounts = await signer.getAccounts();
211
- const accountFromSigner = accounts.find(
212
- (account) => account.address === signerAddress
213
- );
214
- if (!accountFromSigner) {
215
- throw new Error(
216
- "signCosmosMessageAmino: failed to retrieve account from signer"
217
- );
218
- }
219
- const messages = cosmosMsgs.map(
220
- (cosmosMsg) => chunkKM2D7PJL_cjs.getEncodeObjectFromCosmosMessage(cosmosMsg)
221
- );
222
- const signMode = signing_js.SignMode.SIGN_MODE_LEGACY_AMINO_JSON;
223
- const msgs = messages.map((msg) => chunkQAHHTQ7V_cjs.ClientState.aminoTypes.toAmino(msg));
224
- const signDoc = amino.makeSignDoc(
225
- msgs,
226
- fee,
227
- signerChainId,
228
- "",
229
- accountNumber,
230
- sequence
231
- );
232
- const { signature, signed } = await signer.signAmino(signerAddress, signDoc);
233
- const signedTxBody = {
234
- messages: signed.msgs.map((msg) => chunkQAHHTQ7V_cjs.ClientState.aminoTypes.fromAmino(msg)),
235
- memo: signed.memo
236
- };
237
- signedTxBody.messages[0].value.memo = messages[0].value.memo;
238
- const signedTxBodyEncodeObject = {
239
- typeUrl: "/cosmos.tx.v1beta1.TxBody",
240
- value: signedTxBody
241
- };
242
- const signedTxBodyBytes = chunkQAHHTQ7V_cjs.ClientState.registry.encode(
243
- signedTxBodyEncodeObject
244
- );
245
- const signedGasLimit = math.Int53.fromString(signed.fee.gas).toNumber();
246
- const signedSequence = math.Int53.fromString(signed.sequence).toNumber();
247
- const pubkeyAny = makePubkeyAnyFromAccount(accountFromSigner, chainId);
248
- const signedAuthInfoBytes = protoSigning.makeAuthInfoBytes(
249
- [{ pubkey: pubkeyAny, sequence: signedSequence }],
250
- signed.fee.amount,
251
- signedGasLimit,
252
- signed.fee.granter,
253
- signed.fee.payer,
254
- signMode
255
- );
256
- return tx_js.TxRaw.fromPartial({
257
- bodyBytes: signedTxBodyBytes,
258
- authInfoBytes: signedAuthInfoBytes,
259
- signatures: [encoding.fromBase64(signature.signature)]
260
- });
261
- };
262
-
263
- // src/private-functions/cosmos/signCosmosTransaction.ts
264
- var signCosmosTransaction = async ({
265
- tx,
266
- options,
267
- index,
268
- routeId
269
- }) => {
270
- const { userAddresses } = options;
271
- if (tx === void 0) {
272
- throw new Error("executeCosmosTransaction error: tx is undefined");
273
- }
274
- const chainId = tx.cosmosTx?.chainId;
275
- const messages = tx.cosmosTx?.msgs;
276
- const currentUserAddress = userAddresses.find((x) => x.chainId === tx.cosmosTx?.chainId)?.address;
277
- const gasArray = chunkQAHHTQ7V_cjs.ClientState.validateGasResults;
278
- const gas = gasArray?.find((gas2) => gas2?.error !== null && gas2?.error !== void 0);
279
- if (typeof gas?.error === "string") {
280
- throw new Error(gas?.error);
281
- }
282
- const gasUsed = gasArray?.[index];
283
- if (!gasUsed) {
284
- throw new Error(`executeRoute error: invalid gas at index ${index}`);
285
- }
286
- if (chainId === void 0) {
287
- throw new Error("no chainId found for tx");
288
- }
289
- if (messages === void 0) {
290
- throw new Error("no messages found for tx");
291
- }
292
- const { signer } = await chunkJ7HZ6VJE_cjs.getSigningStargateClient({
293
- chainId,
294
- getOfflineSigner: options?.getCosmosSigner
295
- });
296
- if (!currentUserAddress) {
297
- throw new Error(
298
- `executeCosmosTransaction error: invalid address for chain '${tx.cosmosTx?.chainId}'`
299
- );
300
- }
301
- const accounts = await signer.getAccounts();
302
- const accountFromSigner = accounts.find((account) => account.address === currentUserAddress);
303
- if (!accountFromSigner) {
304
- throw new Error("executeCosmosTransaction error: failed to retrieve account from signer");
305
- }
306
- const fee = gasUsed?.fee;
307
- if (!fee) {
308
- throw new Error("executeCosmosTransaction error: failed to retrieve fee from gas");
309
- }
310
- const { accountNumber, sequence } = await getAccountNumberAndSequence(
311
- currentUserAddress,
312
- chainId
313
- );
314
- let rawTx;
315
- const commonRawTxBody = {
316
- signerAddress: currentUserAddress,
317
- chainId,
318
- cosmosMsgs: messages,
319
- fee,
320
- signerData: {
321
- accountNumber,
322
- sequence,
323
- chainId
324
- }
325
- };
326
- options.onTransactionSignRequested?.({
327
- chainId,
328
- txIndex: index,
329
- signerAddress: currentUserAddress
330
- });
331
- chunkBCX2D6TE_cjs.updateRouteDetails({
332
- status: "signing",
333
- routeId,
334
- options
335
- });
336
- if (protoSigning.isOfflineDirectSigner(signer)) {
337
- rawTx = await signCosmosMessageDirect({
338
- ...commonRawTxBody,
339
- signer
340
- });
341
- } else {
342
- rawTx = await signCosmosMessageAmino({ ...commonRawTxBody, signer });
343
- }
344
- options?.onTransactionSigned?.({
345
- chainId
346
- });
347
- chunkBCX2D6TE_cjs.updateRouteDetails({
348
- status: "pending",
349
- routeId,
350
- options
351
- });
352
- const txBytes = tx_js.TxRaw.encode(rawTx).finish();
353
- const rawTxBase64 = Buffer.from(txBytes).toString("base64");
354
- return rawTxBase64;
355
- };
356
-
357
- // src/private-functions/cosmos/executeCosmosTransaction.ts
358
- var executeCosmosTransaction = async ({
359
- tx,
360
- options,
361
- index,
362
- routeId
363
- }) => {
364
- if (tx === void 0) {
365
- throw new Error("executeCosmosTransaction error: tx is undefined");
366
- }
367
- const rawTxBase64 = await signCosmosTransaction({
368
- tx,
369
- options,
370
- index,
371
- routeId
372
- });
373
- const chainId = tx.cosmosTx?.chainId;
374
- const txResponse = await chunk262HFM6V_cjs.submitTransaction({
375
- chainId,
376
- tx: rawTxBase64
377
- });
378
- return {
379
- chainId: tx?.cosmosTx?.chainId ?? "",
380
- txHash: txResponse?.txHash ?? "",
381
- explorerLink: txResponse?.explorerLink ?? ""
382
- };
383
- };
384
- function createAbi(abi) {
385
- return abi;
386
- }
387
- var erc20ABI = /* @__PURE__ */ createAbi([
388
- {
389
- type: "event",
390
- name: "Approval",
391
- inputs: [
392
- {
393
- indexed: true,
394
- name: "owner",
395
- type: "address"
396
- },
397
- {
398
- indexed: true,
399
- name: "spender",
400
- type: "address"
401
- },
402
- {
403
- indexed: false,
404
- name: "value",
405
- type: "uint256"
406
- }
407
- ]
408
- },
409
- {
410
- type: "event",
411
- name: "Transfer",
412
- inputs: [
413
- {
414
- indexed: true,
415
- name: "from",
416
- type: "address"
417
- },
418
- {
419
- indexed: true,
420
- name: "to",
421
- type: "address"
422
- },
423
- {
424
- indexed: false,
425
- name: "value",
426
- type: "uint256"
427
- }
428
- ]
429
- },
430
- {
431
- type: "function",
432
- name: "allowance",
433
- stateMutability: "view",
434
- inputs: [
435
- {
436
- name: "owner",
437
- type: "address"
438
- },
439
- {
440
- name: "spender",
441
- type: "address"
442
- }
443
- ],
444
- outputs: [
445
- {
446
- name: "",
447
- type: "uint256"
448
- }
449
- ]
450
- },
451
- {
452
- type: "function",
453
- name: "approve",
454
- stateMutability: "nonpayable",
455
- inputs: [
456
- {
457
- name: "spender",
458
- type: "address"
459
- },
460
- {
461
- name: "amount",
462
- type: "uint256"
463
- }
464
- ],
465
- outputs: [
466
- {
467
- name: "",
468
- type: "bool"
469
- }
470
- ]
471
- },
472
- {
473
- type: "function",
474
- name: "balanceOf",
475
- stateMutability: "view",
476
- inputs: [
477
- {
478
- name: "account",
479
- type: "address"
480
- }
481
- ],
482
- outputs: [
483
- {
484
- name: "",
485
- type: "uint256"
486
- }
487
- ]
488
- },
489
- {
490
- type: "function",
491
- name: "decimals",
492
- stateMutability: "view",
493
- inputs: [],
494
- outputs: [
495
- {
496
- name: "",
497
- type: "uint8"
498
- }
499
- ]
500
- },
501
- {
502
- type: "function",
503
- name: "name",
504
- stateMutability: "view",
505
- inputs: [],
506
- outputs: [
507
- {
508
- name: "",
509
- type: "string"
510
- }
511
- ]
512
- },
513
- {
514
- type: "function",
515
- name: "symbol",
516
- stateMutability: "view",
517
- inputs: [],
518
- outputs: [
519
- {
520
- name: "",
521
- type: "string"
522
- }
523
- ]
524
- },
525
- {
526
- type: "function",
527
- name: "totalSupply",
528
- stateMutability: "view",
529
- inputs: [],
530
- outputs: [
531
- {
532
- name: "",
533
- type: "uint256"
534
- }
535
- ]
536
- },
537
- {
538
- type: "function",
539
- name: "transfer",
540
- stateMutability: "nonpayable",
541
- inputs: [
542
- {
543
- name: "recipient",
544
- type: "address"
545
- },
546
- {
547
- name: "amount",
548
- type: "uint256"
549
- }
550
- ],
551
- outputs: [
552
- {
553
- name: "",
554
- type: "bool"
555
- }
556
- ]
557
- },
558
- {
559
- type: "function",
560
- name: "transferFrom",
561
- stateMutability: "nonpayable",
562
- inputs: [
563
- {
564
- name: "sender",
565
- type: "address"
566
- },
567
- {
568
- name: "recipient",
569
- type: "address"
570
- },
571
- {
572
- name: "amount",
573
- type: "uint256"
574
- }
575
- ],
576
- outputs: [
577
- {
578
- name: "",
579
- type: "bool"
580
- }
581
- ]
582
- }
583
- ]);
584
-
585
- // src/private-functions/evm/executeEvmTransaction.ts
586
- var executeEvmTransaction = async (message, options, index, routeId) => {
587
- const gasArray = chunkQAHHTQ7V_cjs.ClientState.validateGasResults;
588
- const gas = gasArray?.find((gas2) => gas2?.error !== null && gas2?.error !== void 0);
589
- if (typeof gas?.error === "string") {
590
- throw new Error(gas?.error);
591
- }
592
- const { evmTx } = message;
593
- const getEvmSigner = options.getEvmSigner;
594
- if (!getEvmSigner) {
595
- throw new Error("executeEVMTransaction error: getEvmSigner is not provided");
596
- }
597
- if (!evmTx?.chainId) {
598
- throw new Error("chain id not found in evmTx");
599
- }
600
- const evmSigner = await getEvmSigner(evmTx.chainId);
601
- if (!evmSigner.account) {
602
- throw new Error("executeEVMTransaction error: failed to retrieve account from signer");
603
- }
604
- if (!evmTx.chainId) {
605
- throw new Error("executeEVMTransaction error: chainId not found for evmTx");
606
- }
607
- if (!evmTx.value && evmTx.value !== "") {
608
- throw new Error("executeEVMTransaction error: no value found in evmTx");
609
- }
610
- const { onApproveAllowance, onTransactionSigned, bypassApprovalCheck, useUnlimitedApproval } = options;
611
- const extendedSigner = evmSigner.extend(viem.publicActions);
612
- if (!bypassApprovalCheck && evmTx.requiredErc20Approvals) {
613
- for (const requiredApproval of evmTx.requiredErc20Approvals) {
614
- const allowance = await extendedSigner.readContract({
615
- address: requiredApproval.tokenContract,
616
- abi: erc20ABI,
617
- functionName: "allowance",
618
- args: [
619
- evmSigner.account.address,
620
- requiredApproval.spender
621
- ]
622
- });
623
- if (!requiredApproval.amount) {
624
- throw new Error("executeEVMTransaction error: no amount found in a requiredApproval");
625
- }
626
- if (allowance > BigInt(requiredApproval.amount)) {
627
- continue;
628
- }
629
- onApproveAllowance?.({
630
- status: "pending",
631
- allowance: requiredApproval
632
- });
633
- chunkBCX2D6TE_cjs.updateRouteDetails({
634
- status: "allowance",
635
- routeId,
636
- options
637
- });
638
- const txHash2 = await extendedSigner.writeContract({
639
- account: evmSigner.account,
640
- address: requiredApproval.tokenContract,
641
- abi: erc20ABI,
642
- functionName: "approve",
643
- args: [
644
- requiredApproval.spender,
645
- useUnlimitedApproval ? viem.maxUint256 : BigInt(requiredApproval.amount) + BigInt(1e3)
646
- ],
647
- chain: evmSigner.chain
648
- });
649
- const receipt2 = await extendedSigner.waitForTransactionReceipt({
650
- hash: txHash2
651
- });
652
- if (receipt2.status === "reverted") {
653
- throw new Error(
654
- `executeEVMTransaction error: evm tx reverted for hash ${receipt2.transactionHash}`
655
- );
656
- }
657
- }
658
- onApproveAllowance?.({
659
- status: "completed"
660
- });
661
- }
662
- options?.onTransactionSignRequested?.({
663
- chainId: evmTx.chainId,
664
- signerAddress: evmSigner.account.address,
665
- txIndex: index
666
- });
667
- chunkBCX2D6TE_cjs.updateRouteDetails({
668
- status: "signing",
669
- routeId,
670
- options
671
- });
672
- const txHash = await extendedSigner.sendTransaction({
673
- account: evmSigner.account,
674
- to: evmTx.to,
675
- data: `0x${evmTx.data}`,
676
- chain: evmSigner.chain,
677
- value: evmTx.value === "" ? void 0 : BigInt(evmTx.value)
678
- });
679
- chunkBCX2D6TE_cjs.updateRouteDetails({
680
- status: "pending",
681
- routeId,
682
- options
683
- });
684
- onTransactionSigned?.({
685
- chainId: evmTx.chainId
686
- });
687
- const receipt = await extendedSigner.waitForTransactionReceipt({
688
- hash: txHash
689
- });
690
- return receipt;
691
- };
692
- var signSvmTransaction = async ({
693
- tx,
694
- options,
695
- index,
696
- routeId
697
- }) => {
698
- const gasArray = chunkQAHHTQ7V_cjs.ClientState.validateGasResults;
699
- if (tx === void 0) {
700
- throw new Error("executeSvmTransaction error: tx is undefined");
701
- }
702
- const gas = gasArray?.find(
703
- (gas2) => gas2?.error !== null && gas2?.error !== void 0
704
- );
705
- if (typeof gas?.error === "string") {
706
- throw new Error(gas?.error);
707
- }
708
- const svmTx = tx?.svmTx;
709
- const getSvmSigner = options?.getSvmSigner;
710
- if (!getSvmSigner) {
711
- throw new Error(
712
- "executeSvmTransaction error: getSvmSigner is not provided"
713
- );
714
- }
715
- const signer = await getSvmSigner();
716
- if (!svmTx?.chainId) {
717
- throw new Error("executeSvmTransaction error: chainId not found in svmTx");
718
- }
719
- const txBuffer = Buffer.from(svmTx.tx ?? "", "base64");
720
- const transaction = web3_js.Transaction.from(txBuffer);
721
- if (options.svmFeePayer) {
722
- const message = transaction.serializeMessage();
723
- const resSignTx = await options.svmFeePayer.signTransaction(message);
724
- transaction.addSignature(
725
- new web3_js.PublicKey(options.svmFeePayer.address),
726
- Buffer.from(resSignTx)
727
- );
728
- }
729
- if (!("signTransaction" in signer)) return;
730
- options?.onTransactionSignRequested?.({
731
- chainId: svmTx.chainId,
732
- signerAddress: signer.publicKey?.toBase58(),
733
- txIndex: index
734
- });
735
- chunkBCX2D6TE_cjs.updateRouteDetails({
736
- status: "signing",
737
- routeId,
738
- options
739
- });
740
- const signedTx = await signer.signTransaction(transaction);
741
- options?.onTransactionSigned?.({ chainId: svmTx.chainId });
742
- chunkBCX2D6TE_cjs.updateRouteDetails({
743
- status: "pending",
744
- routeId,
745
- options
746
- });
747
- const serializedTx = signedTx.serialize();
748
- return serializedTx;
749
- };
750
-
751
- // src/private-functions/svm/executeSvmTransaction.ts
752
- var executeSvmTransaction = async (tx, options, index, routeId) => {
753
- const svmTx = tx?.svmTx;
754
- if (!svmTx?.chainId) {
755
- throw new Error("executeSvmTransaction error: chainId not found in svmTx");
756
- }
757
- const signedTx = await signSvmTransaction({ tx, options, index, routeId });
758
- if (!signedTx) {
759
- throw new Error("executeSvmTransaction error: signedTx is undefined");
760
- }
761
- const endpoint = await chunkJ7HZ6VJE_cjs.getRpcEndpointForChain(svmTx.chainId);
762
- const connection = new web3_js.Connection(endpoint);
763
- let signature;
764
- const submitTxResponse = await chunk262HFM6V_cjs.submitTransaction({
765
- chainId: svmTx.chainId,
766
- tx: signedTx.toString("base64")
767
- });
768
- signature = submitTxResponse?.txHash;
769
- const rpcSig = await connection.sendRawTransaction(signedTx, {
770
- preflightCommitment: "confirmed",
771
- maxRetries: 5
772
- });
773
- signature = rpcSig;
774
- if (!signature) {
775
- throw new Error("executeSvmTransaction error: signature not found");
776
- }
777
- let getStatusCount = 0;
778
- let errorCount = 0;
779
- while (true) {
780
- try {
781
- const status = await connection.getSignatureStatus(signature, {
782
- searchTransactionHistory: true
783
- });
784
- if (status?.value?.confirmationStatus === "confirmed") {
785
- return {
786
- chainId: svmTx.chainId,
787
- txHash: signature,
788
- explorerLink: submitTxResponse?.explorerLink ?? ""
789
- };
790
- }
791
- if (getStatusCount > 12) {
792
- await chunkHFEMNOJS_cjs.wait(3e3);
793
- throw new Error(
794
- `executeSvmTransaction error: waiting finalized status timed out for ${signature}`
795
- );
796
- }
797
- getStatusCount++;
798
- await chunkHFEMNOJS_cjs.wait(3e3);
799
- } catch (error) {
800
- errorCount++;
801
- if (errorCount > 12) {
802
- throw error;
803
- }
804
- }
805
- }
806
- };
807
- var validateEvmTokenApproval = async ({
808
- requiredErc20Approvals,
809
- signer,
810
- chain,
811
- gasBalance,
812
- tx,
813
- useUnlimitedApproval
814
- }) => {
815
- if (!signer.account?.address) {
816
- throw new Error("validateEvmGasBalance: Signer address not found");
817
- }
818
- for (const requiredApproval of requiredErc20Approvals) {
819
- const extendedSigner = signer.extend(viem.publicActions);
820
- const allowance = await extendedSigner.readContract({
821
- address: requiredApproval.tokenContract,
822
- abi: erc20ABI,
823
- functionName: "allowance",
824
- args: [signer.account?.address, requiredApproval.spender]
825
- });
826
- if (allowance > BigInt(requiredApproval.amount)) {
827
- continue;
828
- }
829
- const fee = await extendedSigner.estimateFeesPerGas();
830
- const allowanceGasFee = BigInt(fee.maxFeePerGas) * BigInt(1e5);
831
- if (!gasBalance) {
832
- const chainAssets = (await chunkQAHHTQ7V_cjs.ClientState.getSkipAssets({ chainId: tx.chainId }))[tx.chainId];
833
- const nativeAsset = chainAssets?.find((x) => x.denom.includes("-native"));
834
- const zeroAddressAsset = chainAssets?.find(
835
- (x) => x.denom.toLowerCase() === "0x0000000000000000000000000000000000000000"
836
- );
837
- const asset = nativeAsset || zeroAddressAsset;
838
- if (!asset?.decimals) {
839
- throw new Error(
840
- `Insufficient balance for gas on ${chain.prettyName}. Need ${allowanceGasFee} gwei.`
841
- );
842
- }
843
- const formattedGasAmount = viem.formatUnits(allowanceGasFee, asset?.decimals);
844
- throw new Error(
845
- `Insufficient balance for gas on ${chain.prettyName}. Need ${formattedGasAmount} ${asset.symbol}.`
846
- );
847
- }
848
- if (chunkWKYP2NMS_cjs.BigNumber(gasBalance.amount).lt(Number(allowanceGasFee))) {
849
- const chainAssets = (await chunkQAHHTQ7V_cjs.ClientState.getSkipAssets({ chainId: tx.chainId }))[tx.chainId];
850
- const asset = chainAssets?.find(
851
- (x) => x.denom.includes("-native") || x.denom.toLowerCase() === "0x0000000000000000000000000000000000000000"
852
- );
853
- if (!asset?.decimals) {
854
- return {
855
- error: `Insufficient balance for gas on ${chain.prettyName}. Need ${allowanceGasFee} gwei but only have ${gasBalance.amount} gwei.`,
856
- asset: null,
857
- fee: null
858
- };
859
- }
860
- const formattedGasAmount = viem.formatUnits(allowanceGasFee, asset?.decimals);
861
- return {
862
- error: `Insufficient balance for gas on ${chain.prettyName}. Need ${formattedGasAmount} ${asset.symbol} but only have ${gasBalance.formattedAmount} ${asset.symbol}.`,
863
- asset: null,
864
- fee: null
865
- };
866
- }
867
- const txHash = await extendedSigner.writeContract({
868
- account: signer.account,
869
- address: requiredApproval.tokenContract,
870
- abi: erc20ABI,
871
- functionName: "approve",
872
- args: [
873
- requiredApproval.spender,
874
- useUnlimitedApproval ? viem.maxUint256 : BigInt(requiredApproval.amount) + BigInt(1e3)
875
- ],
876
- chain: signer.chain
877
- });
878
- const receipt = await extendedSigner.waitForTransactionReceipt({
879
- hash: txHash
880
- });
881
- if (receipt.status === "reverted") {
882
- throw new Error(
883
- `executeEVMTransaction error: evm tx reverted for hash ${receipt.transactionHash}`
884
- );
885
- }
886
- }
887
- };
888
-
889
- // src/private-functions/evm/validateEvmGasBalance.ts
890
- var validateEvmGasBalance = async ({
891
- signer,
892
- tx,
893
- getFallbackGasAmount,
894
- useUnlimitedApproval,
895
- bypassApprovalCheck
896
- }) => {
897
- const chainId = tx?.chainId ?? "";
898
- const skipAssets = (await chunkQAHHTQ7V_cjs.ClientState.getSkipAssets({ chainId }))?.[chainId];
899
- const skipChains = await chunkQAHHTQ7V_cjs.ClientState.getSkipChains();
900
- const chain = skipChains?.find?.((chain2) => chain2.chainId === chainId);
901
- if (!chain) {
902
- throw new Error(`failed to find chain for chainId: '${chainId}'`);
903
- }
904
- if (!signer.account?.address) {
905
- throw new Error("validateEvmGasBalance: Signer address not found");
906
- }
907
- const skipBalances = (await chunkQAHHTQ7V_cjs.balances({
908
- chains: {
909
- [tx?.chainId ?? ""]: {
910
- address: signer.account?.address
911
- }
912
- }
913
- }))?.chains?.[tx?.chainId ?? ""]?.denoms;
914
- const nativeGasBalance = skipBalances && Object.entries(skipBalances).find(([denom]) => denom.includes("-native"))?.[1];
915
- const zeroAddressGasBalance = skipBalances && Object.entries(skipBalances).find(
916
- ([denom]) => denom.toLowerCase() === "0x0000000000000000000000000000000000000000"
917
- )?.[1];
918
- const gasBalance = nativeGasBalance || zeroAddressGasBalance;
919
- const { requiredErc20Approvals } = tx;
920
- if (!bypassApprovalCheck && requiredErc20Approvals) {
921
- try {
922
- await validateEvmTokenApproval({
923
- requiredErc20Approvals,
924
- signer,
925
- chain,
926
- gasBalance,
927
- tx,
928
- useUnlimitedApproval
929
- });
930
- } catch (error) {
931
- const err = error;
932
- return {
933
- error: err.message,
934
- asset: null,
935
- fee: null
936
- };
937
- }
938
- }
939
- const gasAmount = await chunkF3EB2AQG_cjs.getEVMGasAmountForMessage(signer, tx, getFallbackGasAmount);
940
- if (!gasBalance) {
941
- const nativeAsset = skipAssets?.find((x) => x.denom?.includes("-native"));
942
- const zeroAddressAsset = skipAssets?.find(
943
- (x) => x.denom?.toLowerCase() === "0x0000000000000000000000000000000000000000"
944
- );
945
- const asset = nativeAsset || zeroAddressAsset;
946
- if (!asset?.decimals) {
947
- return {
948
- error: `Insufficient balance for gas on ${chain.prettyName}. Need ${gasAmount} gwei.`,
949
- asset: null,
950
- fee: null
951
- };
952
- }
953
- const formattedGasAmount = viem.formatUnits(gasAmount, asset?.decimals);
954
- return {
955
- error: `Insufficient balance for gas on ${chain.prettyName}. Need ${formattedGasAmount} ${asset.symbol}.`,
956
- asset: null,
957
- fee: null
958
- };
959
- }
960
- if (chunkWKYP2NMS_cjs.BigNumber(gasBalance.amount ?? "").lt(Number(gasAmount))) {
961
- const asset = skipAssets?.find(
962
- (x) => x.denom?.includes("-native") || x.denom?.toLowerCase() === "0x0000000000000000000000000000000000000000"
963
- );
964
- if (!asset?.decimals) {
965
- return {
966
- error: `Insufficient balance for gas on ${chain.prettyName}. Need ${gasAmount} gwei but only have ${gasBalance.amount} gwei.`,
967
- asset: null,
968
- fee: null
969
- };
970
- }
971
- const formattedGasAmount = viem.formatUnits(gasAmount, asset?.decimals);
972
- return {
973
- error: `Insufficient balance for gas on ${chain.prettyName}. Need ${formattedGasAmount} ${asset.symbol} but only have ${gasBalance.formattedAmount} ${asset.symbol}.`,
974
- asset: null,
975
- fee: null
976
- };
977
- }
978
- };
979
- var validateSvmGasBalance = async ({
980
- tx,
981
- simulate
982
- }) => {
983
- if (!tx) throw new Error("Transaction is required");
984
- if (simulate === false) {
985
- return {
986
- success: true,
987
- logs: [],
988
- error: null,
989
- asset: null,
990
- fee: null
991
- };
992
- }
993
- const endpoint = await chunkJ7HZ6VJE_cjs.getRpcEndpointForChain(tx.chainId ?? "");
994
- const connection = new web3_js.Connection(endpoint);
995
- if (!connection) throw new Error(`Failed to connect to ${tx.chainId}`);
996
- if (!tx.tx) {
997
- throw new Error("Transaction is required");
998
- }
999
- const txBuffer = Buffer.from(tx.tx, "base64");
1000
- let transaction;
1001
- try {
1002
- transaction = web3_js.Transaction.from(txBuffer);
1003
- } catch (decodeError) {
1004
- return {
1005
- success: false,
1006
- error: { decodeError: decodeError.message },
1007
- asset: null,
1008
- fee: null
1009
- };
1010
- }
1011
- const simulation = await connection.simulateTransaction(transaction);
1012
- if (simulation.value.err) {
1013
- const logs = simulation.value.logs ?? [];
1014
- const shortfall = getSolShortfall(logs);
1015
- const insufficientLamports = logs.some((log) => log.includes("insufficient lamports")) && shortfall !== null;
1016
- const insufficientFundsForRent = Object.keys(simulation.value.err).includes(
1017
- "InsufficientFundsForRent"
1018
- );
1019
- const errMsg = insufficientLamports ? `Insufficient balance for gas on Solana. You need ${shortfall.toFixed(6)} SOL to proceed.` : insufficientFundsForRent ? "Insufficient funds for rent on Solana. You need to fund your account." : "Simulation failed";
1020
- return {
1021
- success: false,
1022
- logs,
1023
- error: errMsg,
1024
- asset: null,
1025
- fee: null
1026
- };
1027
- }
1028
- return {
1029
- success: true,
1030
- logs: simulation.value.logs ?? [],
1031
- error: null,
1032
- asset: null,
1033
- fee: null
1034
- };
1035
- };
1036
- function getSolShortfall(logs) {
1037
- const line = logs.find((l) => l.includes("insufficient lamports"));
1038
- if (!line) return null;
1039
- const m = line.match(/insufficient lamports (\d+), need (\d+)/);
1040
- if (!m) return null;
1041
- const have = parseInt(m[1] ?? "0", 10);
1042
- const need = parseInt(m[2] ?? "0", 10);
1043
- const shortfallLamports = need - have;
1044
- return shortfallLamports / web3_js.LAMPORTS_PER_SOL;
1045
- }
1046
-
1047
- // src/private-functions/validateGasBalances.ts
1048
- var validateGasBalances = async ({
1049
- txs,
1050
- onValidateGasBalance,
1051
- getFallbackGasAmount,
1052
- getCosmosSigner,
1053
- getEvmSigner,
1054
- simulate,
1055
- disabledChainIds,
1056
- enabledChainIds,
1057
- getCosmosPriorityFeeDenom,
1058
- routeId,
1059
- options,
1060
- isMultiRoutes
1061
- }) => {
1062
- const validateResult = await Promise.all(
1063
- txs.map(async (tx, i) => {
1064
- if (!tx) {
1065
- throw new Error(`invalid tx at index ${i}`);
1066
- }
1067
- if ("cosmosTx" in tx && !disabledChainIds?.includes(tx?.cosmosTx?.chainId ?? "") && (enabledChainIds === void 0 || enabledChainIds.includes(tx?.cosmosTx?.chainId ?? ""))) {
1068
- onValidateGasBalance?.({
1069
- status: "pending"
1070
- });
1071
- chunkBCX2D6TE_cjs.updateRouteDetails({
1072
- status: "validating",
1073
- routeId,
1074
- options
1075
- });
1076
- if (!tx?.cosmosTx?.msgs) {
1077
- throw new Error(`invalid msgs ${tx?.cosmosTx?.msgs}`);
1078
- }
1079
- try {
1080
- const res = await chunkCZKIE576_cjs.validateCosmosGasBalance({
1081
- chainId: tx.cosmosTx.chainId ?? "",
1082
- signerAddress: tx.cosmosTx.signerAddress ?? "",
1083
- messages: tx.cosmosTx.msgs,
1084
- getFallbackGasAmount,
1085
- getOfflineSigner: getCosmosSigner,
1086
- txIndex: i,
1087
- simulate,
1088
- getCosmosPriorityFeeDenom,
1089
- isMultiRoutes
1090
- });
1091
- return res;
1092
- } catch (e) {
1093
- const error = e;
1094
- return {
1095
- error: error.message,
1096
- asset: null,
1097
- fee: null
1098
- };
1099
- }
1100
- }
1101
- if ("evmTx" in tx && !disabledChainIds?.includes(tx?.evmTx?.chainId ?? "") && (enabledChainIds === void 0 || enabledChainIds.includes(tx?.evmTx?.chainId ?? ""))) {
1102
- onValidateGasBalance?.({
1103
- status: "pending"
1104
- });
1105
- chunkBCX2D6TE_cjs.updateRouteDetails({
1106
- status: "validating",
1107
- routeId,
1108
- options
1109
- });
1110
- const signer = await getEvmSigner?.(tx?.evmTx?.chainId ?? "");
1111
- if (!signer) {
1112
- throw new Error(
1113
- `failed to get signer for chain ${tx?.evmTx?.chainId}`
1114
- );
1115
- }
1116
- try {
1117
- const res = await validateEvmGasBalance({
1118
- tx: tx.evmTx,
1119
- signer,
1120
- getFallbackGasAmount,
1121
- useUnlimitedApproval: options?.useUnlimitedApproval,
1122
- bypassApprovalCheck: options?.bypassApprovalCheck
1123
- });
1124
- return res;
1125
- } catch (e) {
1126
- const error = e;
1127
- return {
1128
- error: error.message,
1129
- asset: null,
1130
- fee: null
1131
- };
1132
- }
1133
- }
1134
- if ("svmTx" in tx && !disabledChainIds?.includes(tx?.svmTx?.chainId ?? "") && (enabledChainIds === void 0 || enabledChainIds.includes(tx?.svmTx?.chainId ?? ""))) {
1135
- onValidateGasBalance?.({
1136
- status: "pending"
1137
- });
1138
- chunkBCX2D6TE_cjs.updateRouteDetails({
1139
- status: "validating",
1140
- routeId,
1141
- options
1142
- });
1143
- try {
1144
- const res = await validateSvmGasBalance({
1145
- tx: tx.svmTx,
1146
- simulate
1147
- });
1148
- return res;
1149
- } catch (e) {
1150
- const error = e;
1151
- return {
1152
- error: error.message,
1153
- asset: null,
1154
- fee: null
1155
- };
1156
- }
1157
- }
1158
- })
1159
- );
1160
- if (validateResult.filter(Boolean).length === 0) {
1161
- return;
1162
- }
1163
- const txError = validateResult.find((res) => res && res?.error !== null);
1164
- if (txError) {
1165
- onValidateGasBalance?.({
1166
- status: "error"
1167
- });
1168
- chunkQAHHTQ7V_cjs.ClientState.validateGasResults = validateResult;
1169
- throw new Error(`${txError.error}`);
1170
- }
1171
- onValidateGasBalance?.({
1172
- status: "completed"
1173
- });
1174
- chunkQAHHTQ7V_cjs.ClientState.validateGasResults = validateResult;
1175
- };
1176
-
1177
- // src/private-functions/getChainIdsFromTxs.ts
1178
- var getChainIdsFromTxs = (txs) => {
1179
- return txs.map((tx) => {
1180
- if ("cosmosTx" in tx) {
1181
- return {
1182
- chainType: "cosmos" /* Cosmos */,
1183
- chainId: tx.cosmosTx?.chainId
1184
- };
1185
- }
1186
- if ("svmTx" in tx) {
1187
- return {
1188
- chainType: "svm" /* Svm */,
1189
- chainId: tx.svmTx?.chainId
1190
- };
1191
- }
1192
- if ("evmTx" in tx) {
1193
- return {
1194
- chainType: "evm" /* Evm */,
1195
- chainId: tx.evmTx?.chainId
1196
- };
1197
- }
1198
- });
1199
- };
1200
-
1201
- // src/private-functions/executeTransactions.ts
1202
- var executeTransactions = async (options) => {
1203
- const {
1204
- txs,
1205
- onTransactionBroadcast,
1206
- simulate = true,
1207
- batchSimulate = true,
1208
- getFallbackGasAmount = getDefaultFallbackGasAmount,
1209
- getCosmosSigner,
1210
- getEvmSigner,
1211
- onValidateGasBalance,
1212
- trackTxPollingOptions,
1213
- batchSignTxs = true,
1214
- routeId,
1215
- isMultiRoutes
1216
- } = options;
1217
- if (txs === void 0) {
1218
- throw new Error(
1219
- "executeTransactions error: txs is undefined in executeTransactions"
1220
- );
1221
- }
1222
- const chainIds = getChainIdsFromTxs(txs);
1223
- const transactionDetails = txs.map((tx) => {
1224
- if ("cosmosTx" in tx) {
1225
- return { chainId: tx.cosmosTx?.chainId, chainType: "cosmos" /* Cosmos */ };
1226
- } else if ("evmTx" in tx) {
1227
- return { chainId: tx.evmTx?.chainId, chainType: "evm" /* Evm */ };
1228
- } else if ("svmTx" in tx) {
1229
- return { chainId: tx.svmTx?.chainId, chainType: "svm" /* Svm */ };
1230
- } else {
1231
- throw new Error("executeRoute error: invalid message type");
1232
- }
1233
- });
1234
- chunkBCX2D6TE_cjs.updateRouteDetails({
1235
- transactionDetails,
1236
- routeId,
1237
- options
1238
- });
1239
- const isGasStationSourceEVM = chainIds.find((item, i, array) => {
1240
- return chunkKZOSEIWH_cjs.GAS_STATION_CHAIN_IDS.includes(item?.chainId ?? "") && array[i - 1]?.chainType === "evm" /* Evm */;
1241
- });
1242
- chunkQAHHTQ7V_cjs.ClientState.validateGasResults = void 0;
1243
- const validateChainIds = !batchSimulate ? chainIds.map((x) => x?.chainId ?? "") : isGasStationSourceEVM ? chunkKZOSEIWH_cjs.GAS_STATION_CHAIN_IDS : [];
1244
- await validateGasBalances({
1245
- txs,
1246
- getFallbackGasAmount,
1247
- getCosmosSigner,
1248
- getEvmSigner,
1249
- onValidateGasBalance,
1250
- simulate,
1251
- disabledChainIds: validateChainIds,
1252
- getCosmosPriorityFeeDenom: options.getCosmosPriorityFeeDenom,
1253
- options,
1254
- routeId,
1255
- isMultiRoutes
1256
- });
1257
- const validateEnabledChainIds = async (chainId) => {
1258
- await validateGasBalances({
1259
- txs,
1260
- getFallbackGasAmount,
1261
- getCosmosSigner,
1262
- getEvmSigner,
1263
- onValidateGasBalance,
1264
- simulate,
1265
- enabledChainIds: !batchSimulate ? [chainId] : validateChainIds,
1266
- getCosmosPriorityFeeDenom: options.getCosmosPriorityFeeDenom,
1267
- options,
1268
- routeId,
1269
- isMultiRoutes
1270
- });
1271
- };
1272
- let signedTxs = [];
1273
- if (batchSignTxs) {
1274
- for (let i = 0; i < txs.length; i++) {
1275
- const tx = txs[i];
1276
- if (!tx) {
1277
- throw new Error(`executeRoute error: invalid message at index ${i}`);
1278
- }
1279
- if ("cosmosTx" in tx) {
1280
- await validateEnabledChainIds(tx.cosmosTx?.chainId ?? "");
1281
- const isAllowedToBatchSignTxsUpfront = await (async () => {
1282
- try {
1283
- const currentUserAddress = options.userAddresses.find(
1284
- (x) => x.chainId === tx.cosmosTx?.chainId
1285
- )?.address;
1286
- if (!currentUserAddress) {
1287
- return false;
1288
- }
1289
- const { accountNumber } = await getAccountNumberAndSequence(
1290
- currentUserAddress,
1291
- tx.cosmosTx?.chainId
1292
- );
1293
- if (accountNumber) {
1294
- return true;
1295
- }
1296
- return false;
1297
- } catch (_error) {
1298
- return false;
1299
- }
1300
- })();
1301
- if (!isAllowedToBatchSignTxsUpfront) {
1302
- continue;
1303
- }
1304
- const signedTx = await signCosmosTransaction({
1305
- tx,
1306
- options,
1307
- index: i,
1308
- routeId
1309
- });
1310
- signedTxs.push({
1311
- index: i,
1312
- chainId: tx.cosmosTx?.chainId ?? "",
1313
- tx: signedTx,
1314
- chainType: "cosmos" /* Cosmos */
1315
- });
1316
- }
1317
- if ("svmTx" in tx) {
1318
- await validateEnabledChainIds(tx.svmTx?.chainId ?? "");
1319
- const signedTx = await signSvmTransaction({
1320
- tx,
1321
- options,
1322
- index: i,
1323
- routeId
1324
- });
1325
- if (!signedTx) {
1326
- throw new Error(`executeRoute error: signedTx is undefined`);
1327
- }
1328
- signedTxs.push({
1329
- index: i,
1330
- chainId: tx.svmTx?.chainId ?? "",
1331
- tx: signedTx.toString("base64"),
1332
- chainType: "svm" /* Svm */
1333
- });
1334
- }
1335
- }
1336
- }
1337
- const executeTransaction = async (index) => {
1338
- const tx = txs[index];
1339
- if (!tx) {
1340
- throw new Error(`executeRoute error: invalid message at index ${index}`);
1341
- }
1342
- let txResult;
1343
- const txSigned = signedTxs.find((item) => item.index === index);
1344
- if (txSigned) {
1345
- const txResponse = await chunk262HFM6V_cjs.submitTransaction({
1346
- chainId: txSigned.chainId,
1347
- tx: txSigned.tx
1348
- });
1349
- txResult = {
1350
- chainId: txSigned.chainId,
1351
- txHash: txResponse?.txHash ?? "",
1352
- explorerLink: txResponse?.explorerLink ?? ""
1353
- };
1354
- } else {
1355
- if ("cosmosTx" in tx) {
1356
- await validateEnabledChainIds(tx.cosmosTx?.chainId ?? "");
1357
- txResult = await executeCosmosTransaction({
1358
- tx,
1359
- options,
1360
- index,
1361
- routeId
1362
- });
1363
- } else if ("evmTx" in tx) {
1364
- await validateEnabledChainIds(tx.evmTx?.chainId ?? "");
1365
- const txResponse = await executeEvmTransaction(
1366
- tx,
1367
- options,
1368
- index,
1369
- routeId
1370
- );
1371
- txResult = {
1372
- chainId: tx?.evmTx?.chainId ?? "",
1373
- txHash: txResponse.transactionHash
1374
- };
1375
- } else if ("svmTx" in tx) {
1376
- await validateEnabledChainIds(tx.svmTx?.chainId ?? "");
1377
- txResult = await executeSvmTransaction(tx, options, index, routeId);
1378
- } else {
1379
- throw new Error("executeRoute error: invalid message type");
1380
- }
1381
- }
1382
- await onTransactionBroadcast?.({ ...txResult });
1383
- return txResult;
1384
- };
1385
- return {
1386
- transactionDetails,
1387
- executeTransaction
1388
- };
1389
- };
1390
- var EVM_GAS_AMOUNT = 15e4;
1391
- var COSMOS_GAS_AMOUNT = {
1392
- DEFAULT: 3e5,
1393
- SWAP: 28e5,
1394
- CARBON: 1e6
1395
- };
1396
- var getDefaultFallbackGasAmount = async (chainId, chainType) => {
1397
- if (chainType === "evm" /* Evm */) {
1398
- return EVM_GAS_AMOUNT;
1399
- }
1400
- if (chainType !== "cosmos" /* Cosmos */) return void 0;
1401
- const venuesResult = await chunkT5EGKQAT_cjs.venues();
1402
- const isSwapChain = venuesResult?.some(
1403
- (venue) => venue.chainId === chainId
1404
- ) ?? false;
1405
- const defaultGasAmount = Math.ceil(
1406
- isSwapChain ? COSMOS_GAS_AMOUNT.SWAP : COSMOS_GAS_AMOUNT.DEFAULT
1407
- );
1408
- if (chainId === "carbon-1") {
1409
- return COSMOS_GAS_AMOUNT.CARBON;
1410
- }
1411
- return defaultGasAmount;
1412
- };
1413
- var validateUserAddresses = async (userAddresses) => {
1414
- const chains2 = await chunkQAHHTQ7V_cjs.ClientState.getSkipChains();
1415
- const validations = userAddresses.map((userAddress) => {
1416
- const chain = chains2.find((chain2) => chain2.chainId === userAddress.chainId);
1417
- switch (chain?.chainType) {
1418
- case "cosmos" /* Cosmos */:
1419
- try {
1420
- if (chain.chainId?.includes("penumbra")) {
1421
- try {
1422
- return chain.bech32Prefix === bech32.bech32m.decode(userAddress.address, 143)?.prefix;
1423
- } catch {
1424
- return ["penumbracompat1", "tpenumbra"].includes(
1425
- bech32.bech32.decode(userAddress.address, 1023).prefix
1426
- );
1427
- }
1428
- }
1429
- return chain.bech32Prefix === bech32.bech32.decode(userAddress.address, 1023).prefix;
1430
- } catch {
1431
- return false;
1432
- }
1433
- case "evm" /* Evm */:
1434
- try {
1435
- return viem.isAddress(userAddress.address);
1436
- } catch (_error) {
1437
- return false;
1438
- }
1439
- case "svm" /* Svm */:
1440
- try {
1441
- const publicKey = new web3_js.PublicKey(userAddress.address);
1442
- return web3_js.PublicKey.isOnCurve(publicKey);
1443
- } catch (_error) {
1444
- return false;
1445
- }
1446
- default:
1447
- return false;
1448
- }
1449
- });
1450
- return validations.every((validation) => validation);
1451
- };
1452
- var createValidAddressList = async ({
1453
- userAddresses,
1454
- route
1455
- }) => {
1456
- let addressList = [];
1457
- userAddresses.forEach((userAddress, index) => {
1458
- const requiredChainAddress = route.requiredChainAddresses[index];
1459
- if (requiredChainAddress === userAddress?.chainId) {
1460
- addressList.push(userAddress.address);
1461
- }
1462
- });
1463
- if (addressList.length !== route.requiredChainAddresses.length) {
1464
- addressList = userAddresses.map((x) => x.address);
1465
- }
1466
- const validLength = addressList.length === route.requiredChainAddresses.length || addressList.length === route.chainIds?.length;
1467
- if (!validLength) {
1468
- throw new Error("createValidAddressList error: invalid address list");
1469
- }
1470
- const isUserAddressesValid = await validateUserAddresses(userAddresses);
1471
- if (!isUserAddressesValid) {
1472
- throw new Error("createValidAddressList error: invalid user addresses");
1473
- }
1474
- return addressList;
1475
- };
1476
-
1477
- exports.createValidAddressList = createValidAddressList;
1478
- exports.executeTransactions = executeTransactions;