@skip-go/client 1.0.1 → 1.0.3-alpha-0

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 (65) hide show
  1. package/dist/api/getAssets.js +2 -15
  2. package/dist/api/getAssetsBetweenChains.js +2 -11
  3. package/dist/api/getBridges.js +2 -11
  4. package/dist/api/getChains.js +2 -11
  5. package/dist/api/getVenues.js +2 -11
  6. package/dist/api/postAssetsFromSource.js +3 -12
  7. package/dist/api/postBalances.js +2 -11
  8. package/dist/api/postIbcOriginAssets.js +2 -11
  9. package/dist/api/postMessages.d.ts +183 -183
  10. package/dist/api/postMessages.js +2 -11
  11. package/dist/api/postMessagesDirect.d.ts +183 -183
  12. package/dist/api/postMessagesDirect.js +2 -11
  13. package/dist/api/postRecommendAssets.js +2 -11
  14. package/dist/api/postRoute.d.ts +160 -160
  15. package/dist/api/postRoute.js +2 -11
  16. package/dist/api/postSubmitTransaction.js +2 -11
  17. package/dist/api/postTrackTransaction.js +2 -11
  18. package/dist/api/postTransactionStatus.js +2 -11
  19. package/dist/chunk-33K6EESX.js +10 -0
  20. package/dist/{chunk-Z4ZKOUGH.js → chunk-4JJWOILI.js} +3 -5
  21. package/dist/chunk-BQTQJQ5E.js +10 -0
  22. package/dist/chunk-BRMONS6A.js +130 -0
  23. package/dist/{chunk-ZG23Z3WY.js → chunk-C2EDPY6J.js} +3 -5
  24. package/dist/chunk-DW4U6YI6.js +10 -0
  25. package/dist/chunk-F75DC5RW.js +1786 -0
  26. package/dist/chunk-GARVPN2H.js +16 -0
  27. package/dist/{chunk-CG5CQQBW.js → chunk-JTIHU43D.js} +33 -42
  28. package/dist/{chunk-5ZJBR5AQ.js → chunk-KNV72XRZ.js} +3 -5
  29. package/dist/chunk-MGVXJ2U4.js +11 -0
  30. package/dist/chunk-MTMPHY3Y.js +9 -0
  31. package/dist/{chunk-GFRPLEJR.js → chunk-PHTQQIAH.js} +278 -311
  32. package/dist/{chunk-RE2QZJWE.js → chunk-PRQ2NHRZ.js} +3 -5
  33. package/dist/chunk-RDRDFJQE.js +10 -0
  34. package/dist/chunk-RMP3HM5N.js +14 -0
  35. package/dist/{chunk-X2YPYBVN.js → chunk-SONZJVQM.js} +59 -68
  36. package/dist/chunk-SWYON2RG.js +1 -4
  37. package/dist/{chunk-RT5TZAMU.js → chunk-TD63P2AG.js} +212 -312
  38. package/dist/{chunk-PKPZTO4H.js → chunk-TW77BXMT.js} +10 -13
  39. package/dist/chunk-UNF72WYO.js +22 -0
  40. package/dist/{chunk-4XWIXR2P.js → chunk-VMPFHQ7U.js} +19 -27
  41. package/dist/chunk-VQ5SIQWU.js +1 -3
  42. package/dist/chunk-W6TBGBV3.js +675 -0
  43. package/dist/index.d.ts +0 -3
  44. package/dist/index.js +24 -209
  45. package/dist/public-functions/executeRoute.js +12 -21
  46. package/dist/public-functions/getFeeInfoForChain.js +5 -14
  47. package/dist/public-functions/getRecommendedGasPrice.d.ts +1 -1
  48. package/dist/public-functions/getRecommendedGasPrice.js +7 -16
  49. package/dist/public-functions/getSigningStargateClient.d.ts +2 -2
  50. package/dist/public-functions/getSigningStargateClient.js +4 -13
  51. package/dist/public-functions/setApiOptions.js +2 -11
  52. package/dist/public-functions/setClientOptions.js +4 -13
  53. package/package.json +12 -3
  54. package/dist/chunk-2WHYWV4Y.js +0 -12
  55. package/dist/chunk-5KVRQLI5.js +0 -17
  56. package/dist/chunk-6BTWKTNM.js +0 -16
  57. package/dist/chunk-6GJEXV5J.js +0 -130
  58. package/dist/chunk-ASPVKNJ7.js +0 -242
  59. package/dist/chunk-EQLA2SEZ.js +0 -2361
  60. package/dist/chunk-FVSSCQ6C.js +0 -12
  61. package/dist/chunk-KYFTM3PI.js +0 -12
  62. package/dist/chunk-L2Q5RP6O.js +0 -25
  63. package/dist/chunk-LRIPQQ4M.js +0 -11
  64. package/dist/chunk-X2E2TKVR.js +0 -12
  65. package/dist/chunk-YYNIFO2A.js +0 -13
@@ -0,0 +1,1786 @@
1
+ import { BigNumber } from './chunk-VQ5SIQWU.js';
2
+ import { GAS_STATION_CHAIN_IDS } from './chunk-SWYON2RG.js';
3
+ import { getSigningStargateClient, getRpcEndpointForChain, accountParser } from './chunk-SONZJVQM.js';
4
+ import { chains, findFirstWorkingEndpoint, getIsEthermint, getIsInitia } from './chunk-JTIHU43D.js';
5
+ import { MsgDepositForBurn, MsgDepositForBurnWithCaller, MsgExecute, MsgInitiateTokenDeposit, BaseVestingAccount, Timestamp, toTimestamp, Period, fromTimestamp, isSet, fromJsonTimestamp } from './chunk-TD63P2AG.js';
6
+ import { messages } from './chunk-DW4U6YI6.js';
7
+ import { submitTransaction } from './chunk-RDRDFJQE.js';
8
+ import { trackTransaction } from './chunk-MGVXJ2U4.js';
9
+ import { transactionStatus } from './chunk-33K6EESX.js';
10
+ import { ClientState, balances } from './chunk-BRMONS6A.js';
11
+ import { ApiState, wait, createRequestClient, toCamel } from './chunk-W6TBGBV3.js';
12
+ import { PublicKey, Transaction, Connection, LAMPORTS_PER_SOL } from '@solana/web3.js';
13
+ import { bech32m, bech32 } from 'bech32';
14
+ import { StargateClient, GasPrice, calculateFee } from '@cosmjs/stargate';
15
+ import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx.js';
16
+ import { isOfflineDirectSigner, makeAuthInfoBytes, makeSignDoc, encodePubkey } from '@cosmjs/proto-signing';
17
+ import { fromBase64, toUtf8, toBase64 } from '@cosmjs/encoding';
18
+ import { ChainRestTendermintApi, MsgTransfer as MsgTransfer$1, MsgExecuteContractCompat, createTransactionWithSigners } from '@injectivelabs/sdk-ts';
19
+ import { MsgSend } from 'cosmjs-types/cosmos/bank/v1beta1/tx.js';
20
+ import { MsgExecuteContract } from 'cosmjs-types/cosmwasm/wasm/v1/tx.js';
21
+ import { MsgTransfer } from 'cosmjs-types/ibc/applications/transfer/v1/tx.js';
22
+ import _m0 from 'protobufjs/minimal.js';
23
+ import { BigNumberInBase, DEFAULT_BLOCK_TIMEOUT_HEIGHT, DEFAULT_STD_FEE } from '@injectivelabs/utils';
24
+ import { pubkeyType as pubkeyType$1, makeSignDoc as makeSignDoc$1, encodeSecp256k1Pubkey } from '@cosmjs/amino';
25
+ import { PubKey } from 'cosmjs-types/cosmos/crypto/secp256k1/keys.js';
26
+ import { Any } from 'cosmjs-types/google/protobuf/any.js';
27
+ import { Int53, Decimal } from '@cosmjs/math';
28
+ import { SignMode } from 'cosmjs-types/cosmos/tx/signing/v1beta1/signing.js';
29
+ import { isAddress, publicActions, maxUint256, formatUnits } from 'viem';
30
+
31
+ // src/private-functions/getRestEndpointForChain.ts
32
+ var getRestEndpointForChain = async (chainId) => {
33
+ if (ClientState.endpointOptions.getRestEndpointForChain) {
34
+ return ClientState.endpointOptions.getRestEndpointForChain(chainId);
35
+ }
36
+ if (ClientState.endpointOptions.endpoints && ClientState.endpointOptions.endpoints[chainId]) {
37
+ const endpointOptions = ClientState.endpointOptions.endpoints[chainId];
38
+ if (endpointOptions?.rest) {
39
+ return endpointOptions.rest;
40
+ }
41
+ }
42
+ const chain = chains().find((chain2) => chain2.chain_id === chainId);
43
+ if (!chain) {
44
+ throw new Error(
45
+ `getRestEndpointForChain error: failed to find chain id '${chainId}' in registry`
46
+ );
47
+ }
48
+ if (chain.apis?.rest?.length === 0 || !chain.apis?.rest) {
49
+ throw new Error(
50
+ `getRpcEndpointForChain error: failed to find RPC endpoint for chain '${chainId}'`
51
+ );
52
+ }
53
+ const endpoints = chain.apis?.rest?.map((api) => api.address);
54
+ const endpoint = await findFirstWorkingEndpoint(endpoints, "rest");
55
+ if (!endpoint) {
56
+ throw new Error(
57
+ `getRestEndpointForChain error: failed to find REST endpoint for chain '${chainId}'`
58
+ );
59
+ }
60
+ return endpoint;
61
+ };
62
+
63
+ // src/private-functions/getAccountNumberAndSequence.ts
64
+ var getAccountNumberAndSequence = async (address, chainId) => {
65
+ if (chainId.includes("dymension")) {
66
+ return getAccountNumberAndSequenceFromDymension(address, chainId);
67
+ }
68
+ const endpoint = await getRpcEndpointForChain(chainId);
69
+ const client = ClientState.signingStargateClientByChainId[chainId] ?? await StargateClient.connect(endpoint, {
70
+ accountParser
71
+ });
72
+ const account = await client.getAccount(address);
73
+ if (!account) {
74
+ throw new Error("getAccountNumberAndSequence: failed to retrieve account");
75
+ }
76
+ client.disconnect();
77
+ return {
78
+ accountNumber: account.accountNumber,
79
+ sequence: account.sequence
80
+ };
81
+ };
82
+ var getAccountNumberAndSequenceFromDymension = async (address, chainId) => {
83
+ const endpoint = await getRestEndpointForChain(chainId);
84
+ const jsonResponse = await createRequestClient({
85
+ baseUrl: `${endpoint}/cosmos/auth/v1beta1/accounts/${address}`
86
+ }).get();
87
+ const response = toCamel(jsonResponse);
88
+ let sequence = 0;
89
+ let accountNumber = 0;
90
+ if (response.account.baseAccount) {
91
+ sequence = response.account.baseAccount.sequence;
92
+ accountNumber = response.account.baseAccount.accountNumber;
93
+ } else {
94
+ sequence = response.account.sequence;
95
+ accountNumber = response.account.accountNumber;
96
+ }
97
+ return {
98
+ accountNumber,
99
+ sequence
100
+ };
101
+ };
102
+ function createBaseClawbackVestingAccount() {
103
+ return {
104
+ baseVestingAccount: void 0,
105
+ funderAddress: "",
106
+ startTime: /* @__PURE__ */ new Date(),
107
+ lockupPeriods: [],
108
+ vestingPeriods: []
109
+ };
110
+ }
111
+ var ClawbackVestingAccount = {
112
+ typeUrl: "/evmos.vesting.v2.ClawbackVestingAccount",
113
+ encode(message, writer = _m0.Writer.create()) {
114
+ if (message.baseVestingAccount !== void 0) {
115
+ BaseVestingAccount.encode(message.baseVestingAccount, writer.uint32(10).fork()).ldelim();
116
+ }
117
+ if (message.funderAddress !== "") {
118
+ writer.uint32(18).string(message.funderAddress);
119
+ }
120
+ if (message.startTime !== void 0) {
121
+ Timestamp.encode(toTimestamp(message.startTime), writer.uint32(26).fork()).ldelim();
122
+ }
123
+ for (const v of message.lockupPeriods) {
124
+ Period.encode(v, writer.uint32(34).fork()).ldelim();
125
+ }
126
+ for (const v of message.vestingPeriods) {
127
+ Period.encode(v, writer.uint32(42).fork()).ldelim();
128
+ }
129
+ return writer;
130
+ },
131
+ decode(input, length) {
132
+ const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
133
+ let end = length === void 0 ? reader.len : reader.pos + length;
134
+ const message = createBaseClawbackVestingAccount();
135
+ while (reader.pos < end) {
136
+ const tag = reader.uint32();
137
+ switch (tag >>> 3) {
138
+ case 1:
139
+ message.baseVestingAccount = BaseVestingAccount.decode(reader, reader.uint32());
140
+ break;
141
+ case 2:
142
+ message.funderAddress = reader.string();
143
+ break;
144
+ case 3:
145
+ message.startTime = fromTimestamp(Timestamp.decode(reader, reader.uint32()));
146
+ break;
147
+ case 4:
148
+ message.lockupPeriods.push(Period.decode(reader, reader.uint32()));
149
+ break;
150
+ case 5:
151
+ message.vestingPeriods.push(Period.decode(reader, reader.uint32()));
152
+ break;
153
+ default:
154
+ reader.skipType(tag & 7);
155
+ break;
156
+ }
157
+ }
158
+ return message;
159
+ },
160
+ fromJSON(object) {
161
+ return {
162
+ baseVestingAccount: isSet(object.baseVestingAccount) ? BaseVestingAccount.fromJSON(object.baseVestingAccount) : void 0,
163
+ funderAddress: isSet(object.funderAddress) ? String(object.funderAddress) : "",
164
+ startTime: isSet(object.startTime) ? fromJsonTimestamp(object.startTime) : void 0,
165
+ lockupPeriods: Array.isArray(object?.lockupPeriods) ? object.lockupPeriods.map((e) => Period.fromJSON(e)) : [],
166
+ vestingPeriods: Array.isArray(object?.vestingPeriods) ? object.vestingPeriods.map((e) => Period.fromJSON(e)) : []
167
+ };
168
+ },
169
+ toJSON(message) {
170
+ const obj = {};
171
+ message.baseVestingAccount !== void 0 && (obj.baseVestingAccount = message.baseVestingAccount ? BaseVestingAccount.toJSON(message.baseVestingAccount) : void 0);
172
+ message.funderAddress !== void 0 && (obj.funderAddress = message.funderAddress);
173
+ message.startTime !== void 0 && (obj.startTime = message.startTime.toISOString());
174
+ if (message.lockupPeriods) {
175
+ obj.lockupPeriods = message.lockupPeriods.map((e) => e ? Period.toJSON(e) : void 0);
176
+ } else {
177
+ obj.lockupPeriods = [];
178
+ }
179
+ if (message.vestingPeriods) {
180
+ obj.vestingPeriods = message.vestingPeriods.map((e) => e ? Period.toJSON(e) : void 0);
181
+ } else {
182
+ obj.vestingPeriods = [];
183
+ }
184
+ return obj;
185
+ },
186
+ fromPartial(object) {
187
+ const message = createBaseClawbackVestingAccount();
188
+ message.baseVestingAccount = object.baseVestingAccount !== void 0 && object.baseVestingAccount !== null ? BaseVestingAccount.fromPartial(object.baseVestingAccount) : void 0;
189
+ message.funderAddress = object.funderAddress ?? "";
190
+ message.startTime = object.startTime ?? void 0;
191
+ message.lockupPeriods = object.lockupPeriods?.map((e) => Period.fromPartial(e)) || [];
192
+ message.vestingPeriods = object.vestingPeriods?.map((e) => Period.fromPartial(e)) || [];
193
+ return message;
194
+ },
195
+ fromAmino(object) {
196
+ const message = createBaseClawbackVestingAccount();
197
+ if (object.base_vesting_account !== void 0 && object.base_vesting_account !== null) {
198
+ message.baseVestingAccount = BaseVestingAccount.fromAmino(object.base_vesting_account);
199
+ }
200
+ if (object.funder_address !== void 0 && object.funder_address !== null) {
201
+ message.funderAddress = object.funder_address;
202
+ }
203
+ if (object.start_time !== void 0 && object.start_time !== null) {
204
+ message.startTime = fromTimestamp(Timestamp.fromAmino(object.start_time));
205
+ }
206
+ message.lockupPeriods = object.lockup_periods?.map((e) => Period.fromAmino(e)) || [];
207
+ message.vestingPeriods = object.vesting_periods?.map((e) => Period.fromAmino(e)) || [];
208
+ return message;
209
+ },
210
+ toAmino(message) {
211
+ const obj = {};
212
+ obj.base_vesting_account = message.baseVestingAccount ? BaseVestingAccount.toAmino(message.baseVestingAccount) : void 0;
213
+ obj.funder_address = message.funderAddress === "" ? void 0 : message.funderAddress;
214
+ obj.start_time = message.startTime ? Timestamp.toAmino(toTimestamp(message.startTime)) : void 0;
215
+ if (message.lockupPeriods) {
216
+ obj.lockup_periods = message.lockupPeriods.map((e) => e ? Period.toAmino(e) : void 0);
217
+ } else {
218
+ obj.lockup_periods = message.lockupPeriods;
219
+ }
220
+ if (message.vestingPeriods) {
221
+ obj.vesting_periods = message.vestingPeriods.map((e) => e ? Period.toAmino(e) : void 0);
222
+ } else {
223
+ obj.vesting_periods = message.vestingPeriods;
224
+ }
225
+ return obj;
226
+ },
227
+ fromAminoMsg(object) {
228
+ return ClawbackVestingAccount.fromAmino(object.value);
229
+ },
230
+ toAminoMsg(message) {
231
+ return {
232
+ type: "vesting/ClawbackVestingAccount",
233
+ value: ClawbackVestingAccount.toAmino(message)
234
+ };
235
+ },
236
+ fromProtoMsg(message) {
237
+ return ClawbackVestingAccount.decode(message.value);
238
+ },
239
+ toProto(message) {
240
+ return ClawbackVestingAccount.encode(message).finish();
241
+ },
242
+ toProtoMsg(message) {
243
+ return {
244
+ typeUrl: "/evmos.vesting.v2.ClawbackVestingAccount",
245
+ value: ClawbackVestingAccount.encode(message).finish()
246
+ };
247
+ }
248
+ };
249
+
250
+ // src/private-functions/cosmos/getEncodeObjectFromCosmosMessage.ts
251
+ function getEncodeObjectFromCosmosMessage(message) {
252
+ const msgJson = JSON.parse(message.msg ?? "");
253
+ if (message.msgTypeUrl === "/ibc.applications.transfer.v1.MsgTransfer") {
254
+ return {
255
+ typeUrl: "/ibc.applications.transfer.v1.MsgTransfer",
256
+ value: MsgTransfer.fromJSON({
257
+ sourcePort: msgJson.source_port,
258
+ sourceChannel: msgJson.source_channel,
259
+ token: msgJson.token,
260
+ sender: msgJson.sender,
261
+ receiver: msgJson.receiver,
262
+ timeoutHeight: msgJson.timeout_height,
263
+ timeoutTimestamp: msgJson.timeout_timestamp,
264
+ memo: msgJson.memo
265
+ })
266
+ };
267
+ }
268
+ if (message.msgTypeUrl === "/cosmwasm.wasm.v1.MsgExecuteContract") {
269
+ return {
270
+ typeUrl: message.msgTypeUrl,
271
+ value: MsgExecuteContract.fromPartial({
272
+ sender: msgJson.sender,
273
+ contract: msgJson.contract,
274
+ msg: toUtf8(JSON.stringify(msgJson.msg)),
275
+ funds: msgJson.funds
276
+ })
277
+ };
278
+ }
279
+ if (message.msgTypeUrl === "/cosmos.bank.v1beta1.MsgSend") {
280
+ return {
281
+ typeUrl: message.msgTypeUrl,
282
+ value: MsgSend.fromPartial({
283
+ fromAddress: msgJson.from_address,
284
+ toAddress: msgJson.to_address,
285
+ amount: msgJson.amount
286
+ })
287
+ };
288
+ }
289
+ if (message.msgTypeUrl === "/circle.cctp.v1.MsgDepositForBurn") {
290
+ return {
291
+ typeUrl: message.msgTypeUrl,
292
+ value: MsgDepositForBurn.fromAmino(msgJson)
293
+ };
294
+ }
295
+ if (message.msgTypeUrl === "/circle.cctp.v1.MsgDepositForBurnWithCaller") {
296
+ return {
297
+ typeUrl: message.msgTypeUrl,
298
+ value: MsgDepositForBurnWithCaller.fromAmino(msgJson)
299
+ };
300
+ }
301
+ if (message.msgTypeUrl === "/initia.move.v1.MsgExecute") {
302
+ return {
303
+ typeUrl: message.msgTypeUrl,
304
+ value: MsgExecute.fromPartial({
305
+ sender: msgJson.sender,
306
+ moduleAddress: msgJson.module_address,
307
+ moduleName: msgJson.module_name,
308
+ functionName: msgJson.function_name,
309
+ args: msgJson.args
310
+ })
311
+ };
312
+ }
313
+ if (message.msgTypeUrl === "/opinit.ophost.v1.MsgInitiateTokenDeposit") {
314
+ return {
315
+ typeUrl: message.msgTypeUrl,
316
+ value: MsgInitiateTokenDeposit.fromPartial({
317
+ sender: msgJson.sender,
318
+ to: msgJson.to,
319
+ amount: msgJson.amount,
320
+ bridgeId: msgJson.bridge_id
321
+ })
322
+ };
323
+ }
324
+ if (message.msgTypeUrl === "/evmos.vesting.v2.ClawbackVestingAccount") {
325
+ return {
326
+ typeUrl: message.msgTypeUrl,
327
+ value: ClawbackVestingAccount.fromPartial({
328
+ baseVestingAccount: msgJson.base_vesting_account,
329
+ funderAddress: msgJson.funder_address,
330
+ lockupPeriods: msgJson.lockup_periods,
331
+ startTime: msgJson.start_time,
332
+ vestingPeriods: msgJson.vesting_periods
333
+ })
334
+ };
335
+ }
336
+ return {
337
+ typeUrl: message.msgTypeUrl ?? "",
338
+ value: msgJson
339
+ };
340
+ }
341
+ function getEncodeObjectFromCosmosMessageInjective(message) {
342
+ const msgJson = JSON.parse(message.msg ?? "");
343
+ if (message.msgTypeUrl === "/ibc.applications.transfer.v1.MsgTransfer") {
344
+ return MsgTransfer$1.fromJSON({
345
+ port: msgJson.source_port,
346
+ channelId: msgJson.source_channel,
347
+ amount: msgJson.token,
348
+ sender: msgJson.sender,
349
+ receiver: msgJson.receiver,
350
+ timeout: msgJson.timeout_timestamp,
351
+ memo: msgJson.memo
352
+ });
353
+ }
354
+ if (message.msgTypeUrl === "/cosmwasm.wasm.v1.MsgExecuteContract") {
355
+ return MsgExecuteContractCompat.fromJSON({
356
+ sender: msgJson.sender,
357
+ contractAddress: msgJson.contract,
358
+ msg: msgJson.msg,
359
+ funds: msgJson.funds
360
+ });
361
+ }
362
+ throw new Error("Unsupported message type");
363
+ }
364
+ function createTransaction({
365
+ chainId,
366
+ message,
367
+ timeoutHeight,
368
+ memo = "",
369
+ fee = DEFAULT_STD_FEE,
370
+ signMode = 1,
371
+ pubKey,
372
+ accountNumber,
373
+ sequence
374
+ }) {
375
+ const signers = {
376
+ pubKey,
377
+ accountNumber,
378
+ sequence
379
+ };
380
+ return createTransactionWithSigners({
381
+ fee,
382
+ memo,
383
+ message,
384
+ signers,
385
+ chainId,
386
+ signMode,
387
+ timeoutHeight
388
+ });
389
+ }
390
+
391
+ // src/private-functions/cosmos/signCosmosMessageDirectEvmos.ts
392
+ var signCosmosMessageDirectEvmos = async (signerAddress, signer, cosmosMsgs, fee, { accountNumber, sequence, chainId }) => {
393
+ const accounts = await signer.getAccounts();
394
+ const accountFromSigner = accounts.find((account) => account.address === signerAddress);
395
+ if (!accountFromSigner) {
396
+ throw new Error("signCosmosMessageDirectEvmos: failed to retrieve account from signer");
397
+ }
398
+ const messages2 = cosmosMsgs.map(
399
+ (cosmosMsg) => getEncodeObjectFromCosmosMessageInjective(cosmosMsg)
400
+ );
401
+ const pk = Buffer.from(accountFromSigner.pubkey).toString("base64");
402
+ const { signDoc } = createTransaction({
403
+ pubKey: pk,
404
+ chainId,
405
+ message: messages2,
406
+ sequence,
407
+ accountNumber,
408
+ timeoutHeight: 0,
409
+ fee
410
+ });
411
+ const directSignResponse = await signer.signDirect(signerAddress, signDoc);
412
+ return TxRaw.fromPartial({
413
+ bodyBytes: directSignResponse.signed.bodyBytes,
414
+ authInfoBytes: directSignResponse.signed.authInfoBytes,
415
+ signatures: [fromBase64(directSignResponse.signature.signature)]
416
+ });
417
+ };
418
+ var signCosmosMessageDirectInjective = async (signerAddress, signer, cosmosMsgs, fee, { accountNumber, sequence, chainId }) => {
419
+ const accounts = await signer.getAccounts();
420
+ const accountFromSigner = accounts.find((account) => account.address === signerAddress);
421
+ if (!accountFromSigner) {
422
+ throw new Error("signCosmosMessageDirectInjective: failed to retrieve account from signer");
423
+ }
424
+ const restEndpoint = await getRestEndpointForChain(chainId);
425
+ const chainRestTendermintApi = new ChainRestTendermintApi(restEndpoint);
426
+ const latestBlock = await chainRestTendermintApi.fetchLatestBlock();
427
+ const latestHeight = latestBlock.header.height;
428
+ const timeoutHeight = new BigNumberInBase(latestHeight).plus(DEFAULT_BLOCK_TIMEOUT_HEIGHT);
429
+ const pk = Buffer.from(accountFromSigner.pubkey).toString("base64");
430
+ const messages2 = cosmosMsgs.map(
431
+ (cosmosMsg) => getEncodeObjectFromCosmosMessageInjective(cosmosMsg)
432
+ );
433
+ const { signDoc } = createTransaction({
434
+ pubKey: pk,
435
+ chainId,
436
+ message: messages2,
437
+ sequence,
438
+ accountNumber,
439
+ timeoutHeight: timeoutHeight.toNumber(),
440
+ fee
441
+ });
442
+ const directSignResponse = await signer.signDirect(
443
+ signerAddress,
444
+ // @ts-expect-error TODO: Fix this
445
+ signDoc
446
+ );
447
+ return TxRaw.fromPartial({
448
+ bodyBytes: directSignResponse.signed.bodyBytes,
449
+ authInfoBytes: directSignResponse.signed.authInfoBytes,
450
+ signatures: [fromBase64(directSignResponse.signature.signature)]
451
+ });
452
+ };
453
+ var pubkeyType = {
454
+ ethsecp256k1: "ethermint/PubKeyEthSecp256k1",
455
+ ...pubkeyType$1
456
+ };
457
+
458
+ // src/amino/encoding.ts
459
+ function encodeEthSecp256k1Pubkey(pubkey) {
460
+ if (pubkey.length !== 33 || pubkey[0] !== 2 && pubkey[0] !== 3) {
461
+ throw new Error(
462
+ "Public key must be compressed secp256k1, i.e. 33 bytes starting with 0x02 or 0x03"
463
+ );
464
+ }
465
+ return {
466
+ type: pubkeyType.ethsecp256k1,
467
+ value: toBase64(pubkey)
468
+ };
469
+ }
470
+
471
+ // src/proto-signing/pubkey.ts
472
+ function makePubkeyAnyFromAccount(account, chainId) {
473
+ const isEthermint = getIsEthermint(chainId);
474
+ const pubkey = isEthermint ? encodeEthSecp256k1Pubkey(account.pubkey) : encodeSecp256k1Pubkey(account.pubkey);
475
+ const pubkeyAny = encodePubkeyToAny(pubkey, chainId, isEthermint);
476
+ return pubkeyAny;
477
+ }
478
+ function encodePubkeyToAny(pubkey, chainId, isEthermint) {
479
+ if (isEthermint) {
480
+ const pubkeyProto = PubKey.fromPartial({
481
+ key: fromBase64(pubkey.value)
482
+ });
483
+ let typeUrl = "";
484
+ if (chainId?.includes("injective")) {
485
+ typeUrl = "/injective.crypto.v1beta1.ethsecp256k1.PubKey";
486
+ } else {
487
+ typeUrl = "/ethermint.crypto.v1.ethsecp256k1.PubKey";
488
+ }
489
+ return Any.fromPartial({
490
+ typeUrl,
491
+ value: Uint8Array.from(PubKey.encode(pubkeyProto).finish())
492
+ });
493
+ } else {
494
+ const isInitia = getIsInitia(chainId);
495
+ const pubkeyProto = PubKey.fromPartial({
496
+ key: fromBase64(pubkey.value)
497
+ });
498
+ if (isInitia) {
499
+ return Any.fromPartial({
500
+ typeUrl: "/initia.crypto.v1beta1.ethsecp256k1.PubKey",
501
+ value: Uint8Array.from(PubKey.encode(pubkeyProto).finish())
502
+ });
503
+ }
504
+ return encodePubkey(pubkey);
505
+ }
506
+ }
507
+ var signCosmosMessageDirect = async (options) => {
508
+ const {
509
+ signer,
510
+ signerAddress,
511
+ chainId,
512
+ cosmosMsgs,
513
+ fee,
514
+ signerData: { accountNumber, sequence, chainId: signerChainId }
515
+ } = options;
516
+ if (chainId.includes("evmos")) {
517
+ return signCosmosMessageDirectEvmos(signerAddress, signer, cosmosMsgs, fee, {
518
+ accountNumber,
519
+ sequence,
520
+ chainId: signerChainId
521
+ });
522
+ }
523
+ if (chainId.includes("injective")) {
524
+ return signCosmosMessageDirectInjective(signerAddress, signer, cosmosMsgs, fee, {
525
+ accountNumber,
526
+ sequence,
527
+ chainId: signerChainId
528
+ });
529
+ }
530
+ const accounts = await signer.getAccounts();
531
+ const accountFromSigner = accounts.find((account) => account.address === signerAddress);
532
+ if (!accountFromSigner) {
533
+ throw new Error("signCosmosMessageDirect error: failed to retrieve account from signer");
534
+ }
535
+ const messages2 = cosmosMsgs.map((cosmosMsg) => getEncodeObjectFromCosmosMessage(cosmosMsg));
536
+ const txBodyEncodeObject = {
537
+ typeUrl: "/cosmos.tx.v1beta1.TxBody",
538
+ value: {
539
+ messages: messages2
540
+ }
541
+ };
542
+ const txBodyBytes = ClientState.registry.encode(txBodyEncodeObject);
543
+ const gasLimit = Int53.fromString(fee.gas).toNumber();
544
+ const pubkeyAny = makePubkeyAnyFromAccount(accountFromSigner, chainId);
545
+ const authInfoBytes = makeAuthInfoBytes(
546
+ [{ pubkey: pubkeyAny, sequence }],
547
+ fee.amount,
548
+ gasLimit,
549
+ fee.granter,
550
+ fee.payer
551
+ );
552
+ const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber);
553
+ const { signature, signed } = await signer.signDirect(signerAddress, signDoc);
554
+ return TxRaw.fromPartial({
555
+ bodyBytes: signed.bodyBytes,
556
+ authInfoBytes: signed.authInfoBytes,
557
+ signatures: [fromBase64(signature.signature)]
558
+ });
559
+ };
560
+ var signCosmosMessageAmino = async (options) => {
561
+ const {
562
+ signer,
563
+ signerAddress,
564
+ chainId,
565
+ cosmosMsgs,
566
+ fee,
567
+ signerData: { accountNumber, sequence, chainId: signerChainId }
568
+ } = options;
569
+ const accounts = await signer.getAccounts();
570
+ const accountFromSigner = accounts.find((account) => account.address === signerAddress);
571
+ if (!accountFromSigner) {
572
+ throw new Error("signCosmosMessageAmino: failed to retrieve account from signer");
573
+ }
574
+ const messages2 = cosmosMsgs.map((cosmosMsg) => getEncodeObjectFromCosmosMessage(cosmosMsg));
575
+ const signMode = SignMode.SIGN_MODE_LEGACY_AMINO_JSON;
576
+ const msgs = messages2.map((msg) => ClientState.aminoTypes.toAmino(msg));
577
+ console.log("sign cosmos message amino", msgs, fee, signerChainId, "", accountNumber, sequence);
578
+ const signDoc = makeSignDoc$1(msgs, fee, signerChainId, "", accountNumber, sequence);
579
+ const { signature, signed } = await signer.signAmino(signerAddress, signDoc);
580
+ const signedTxBody = {
581
+ messages: signed.msgs.map((msg) => ClientState.aminoTypes.fromAmino(msg)),
582
+ memo: signed.memo
583
+ };
584
+ signedTxBody.messages[0].value.memo = messages2[0].value.memo;
585
+ const signedTxBodyEncodeObject = {
586
+ typeUrl: "/cosmos.tx.v1beta1.TxBody",
587
+ value: signedTxBody
588
+ };
589
+ const signedTxBodyBytes = ClientState.registry.encode(signedTxBodyEncodeObject);
590
+ const signedGasLimit = Int53.fromString(signed.fee.gas).toNumber();
591
+ const signedSequence = Int53.fromString(signed.sequence).toNumber();
592
+ const pubkeyAny = makePubkeyAnyFromAccount(accountFromSigner, chainId);
593
+ const signedAuthInfoBytes = makeAuthInfoBytes(
594
+ [{ pubkey: pubkeyAny, sequence: signedSequence }],
595
+ signed.fee.amount,
596
+ signedGasLimit,
597
+ signed.fee.granter,
598
+ signed.fee.payer,
599
+ signMode
600
+ );
601
+ return TxRaw.fromPartial({
602
+ bodyBytes: signedTxBodyBytes,
603
+ authInfoBytes: signedAuthInfoBytes,
604
+ signatures: [fromBase64(signature.signature)]
605
+ });
606
+ };
607
+
608
+ // src/private-functions/cosmos/executeCosmosTransaction.ts
609
+ var executeCosmosTransaction = async ({
610
+ tx,
611
+ options,
612
+ index
613
+ }) => {
614
+ const { userAddresses } = options;
615
+ if (tx === void 0) {
616
+ throw new Error("executeCosmosTransaction error: tx is undefined");
617
+ }
618
+ const chainId = tx.cosmosTx?.chainId;
619
+ const messages2 = tx.cosmosTx?.msgs;
620
+ const currentUserAddress = userAddresses.find((x) => x.chainId === tx.cosmosTx?.chainId)?.address;
621
+ const gasArray = ClientState.validateGasResults;
622
+ const gas = gasArray?.find((gas2) => gas2?.error !== null && gas2?.error !== void 0);
623
+ if (typeof gas?.error === "string") {
624
+ throw new Error(gas?.error);
625
+ }
626
+ const gasUsed = gasArray?.[index];
627
+ if (!gasUsed) {
628
+ throw new Error(`executeRoute error: invalid gas at index ${index}`);
629
+ }
630
+ if (chainId === void 0) {
631
+ throw new Error("no chainId found for tx");
632
+ }
633
+ if (messages2 === void 0) {
634
+ throw new Error("no messages found for tx");
635
+ }
636
+ const { stargateClient, signer } = await getSigningStargateClient({
637
+ chainId,
638
+ getOfflineSigner: options?.getCosmosSigner
639
+ });
640
+ if (!currentUserAddress) {
641
+ throw new Error(
642
+ `executeCosmosTransaction error: invalid address for chain '${tx.cosmosTx?.chainId}'`
643
+ );
644
+ }
645
+ const accounts = await signer.getAccounts();
646
+ const accountFromSigner = accounts.find((account) => account.address === currentUserAddress);
647
+ if (!accountFromSigner) {
648
+ throw new Error("executeCosmosTransaction error: failed to retrieve account from signer");
649
+ }
650
+ const fee = gasUsed?.fee;
651
+ if (!fee) {
652
+ throw new Error("executeCosmosTransaction error: failed to retrieve fee from gas");
653
+ }
654
+ const { accountNumber, sequence } = await getAccountNumberAndSequence(
655
+ currentUserAddress,
656
+ chainId
657
+ );
658
+ let rawTx;
659
+ const commonRawTxBody = {
660
+ signerAddress: currentUserAddress,
661
+ chainId,
662
+ cosmosMsgs: messages2,
663
+ fee,
664
+ signerData: {
665
+ accountNumber,
666
+ sequence,
667
+ chainId
668
+ }
669
+ };
670
+ if (isOfflineDirectSigner(signer)) {
671
+ rawTx = await signCosmosMessageDirect({
672
+ ...commonRawTxBody,
673
+ signer
674
+ });
675
+ } else {
676
+ rawTx = await signCosmosMessageAmino({ ...commonRawTxBody, signer });
677
+ }
678
+ options?.onTransactionSigned?.({
679
+ chainId
680
+ });
681
+ const txBytes = TxRaw.encode(rawTx).finish();
682
+ const txResponse = await stargateClient.broadcastTx(txBytes);
683
+ return {
684
+ chainId: tx?.cosmosTx?.chainId ?? "",
685
+ txHash: txResponse.transactionHash
686
+ };
687
+ };
688
+ function createAbi(abi) {
689
+ return abi;
690
+ }
691
+ var erc20ABI = /* @__PURE__ */ createAbi([
692
+ {
693
+ type: "event",
694
+ name: "Approval",
695
+ inputs: [
696
+ {
697
+ indexed: true,
698
+ name: "owner",
699
+ type: "address"
700
+ },
701
+ {
702
+ indexed: true,
703
+ name: "spender",
704
+ type: "address"
705
+ },
706
+ {
707
+ indexed: false,
708
+ name: "value",
709
+ type: "uint256"
710
+ }
711
+ ]
712
+ },
713
+ {
714
+ type: "event",
715
+ name: "Transfer",
716
+ inputs: [
717
+ {
718
+ indexed: true,
719
+ name: "from",
720
+ type: "address"
721
+ },
722
+ {
723
+ indexed: true,
724
+ name: "to",
725
+ type: "address"
726
+ },
727
+ {
728
+ indexed: false,
729
+ name: "value",
730
+ type: "uint256"
731
+ }
732
+ ]
733
+ },
734
+ {
735
+ type: "function",
736
+ name: "allowance",
737
+ stateMutability: "view",
738
+ inputs: [
739
+ {
740
+ name: "owner",
741
+ type: "address"
742
+ },
743
+ {
744
+ name: "spender",
745
+ type: "address"
746
+ }
747
+ ],
748
+ outputs: [
749
+ {
750
+ name: "",
751
+ type: "uint256"
752
+ }
753
+ ]
754
+ },
755
+ {
756
+ type: "function",
757
+ name: "approve",
758
+ stateMutability: "nonpayable",
759
+ inputs: [
760
+ {
761
+ name: "spender",
762
+ type: "address"
763
+ },
764
+ {
765
+ name: "amount",
766
+ type: "uint256"
767
+ }
768
+ ],
769
+ outputs: [
770
+ {
771
+ name: "",
772
+ type: "bool"
773
+ }
774
+ ]
775
+ },
776
+ {
777
+ type: "function",
778
+ name: "balanceOf",
779
+ stateMutability: "view",
780
+ inputs: [
781
+ {
782
+ name: "account",
783
+ type: "address"
784
+ }
785
+ ],
786
+ outputs: [
787
+ {
788
+ name: "",
789
+ type: "uint256"
790
+ }
791
+ ]
792
+ },
793
+ {
794
+ type: "function",
795
+ name: "decimals",
796
+ stateMutability: "view",
797
+ inputs: [],
798
+ outputs: [
799
+ {
800
+ name: "",
801
+ type: "uint8"
802
+ }
803
+ ]
804
+ },
805
+ {
806
+ type: "function",
807
+ name: "name",
808
+ stateMutability: "view",
809
+ inputs: [],
810
+ outputs: [
811
+ {
812
+ name: "",
813
+ type: "string"
814
+ }
815
+ ]
816
+ },
817
+ {
818
+ type: "function",
819
+ name: "symbol",
820
+ stateMutability: "view",
821
+ inputs: [],
822
+ outputs: [
823
+ {
824
+ name: "",
825
+ type: "string"
826
+ }
827
+ ]
828
+ },
829
+ {
830
+ type: "function",
831
+ name: "totalSupply",
832
+ stateMutability: "view",
833
+ inputs: [],
834
+ outputs: [
835
+ {
836
+ name: "",
837
+ type: "uint256"
838
+ }
839
+ ]
840
+ },
841
+ {
842
+ type: "function",
843
+ name: "transfer",
844
+ stateMutability: "nonpayable",
845
+ inputs: [
846
+ {
847
+ name: "recipient",
848
+ type: "address"
849
+ },
850
+ {
851
+ name: "amount",
852
+ type: "uint256"
853
+ }
854
+ ],
855
+ outputs: [
856
+ {
857
+ name: "",
858
+ type: "bool"
859
+ }
860
+ ]
861
+ },
862
+ {
863
+ type: "function",
864
+ name: "transferFrom",
865
+ stateMutability: "nonpayable",
866
+ inputs: [
867
+ {
868
+ name: "sender",
869
+ type: "address"
870
+ },
871
+ {
872
+ name: "recipient",
873
+ type: "address"
874
+ },
875
+ {
876
+ name: "amount",
877
+ type: "uint256"
878
+ }
879
+ ],
880
+ outputs: [
881
+ {
882
+ name: "",
883
+ type: "bool"
884
+ }
885
+ ]
886
+ }
887
+ ]);
888
+
889
+ // src/private-functions/evm/executeEvmTransaction.ts
890
+ var executeEvmTransaction = async (message, options) => {
891
+ const gasArray = ClientState.validateGasResults;
892
+ const gas = gasArray?.find((gas2) => gas2?.error !== null && gas2?.error !== void 0);
893
+ if (typeof gas?.error === "string") {
894
+ throw new Error(gas?.error);
895
+ }
896
+ const { evmTx } = message;
897
+ const getEvmSigner = options.getEvmSigner || ClientState.getEvmSigner;
898
+ if (!getEvmSigner) {
899
+ throw new Error("Unable to get EVM signer");
900
+ }
901
+ if (!evmTx?.chainId) {
902
+ throw new Error("chain id not found in evmTx");
903
+ }
904
+ const evmSigner = await getEvmSigner(evmTx.chainId);
905
+ if (!evmSigner.account) {
906
+ throw new Error("executeEVMTransaction error: failed to retrieve account from signer");
907
+ }
908
+ if (!evmTx.chainId) {
909
+ throw new Error("executeEVMTransaction error: chainId not found for evmTx");
910
+ }
911
+ if (!evmTx.value) {
912
+ throw new Error("executeEVMTransaction error: no value found in evmTx");
913
+ }
914
+ const { onApproveAllowance, onTransactionSigned, bypassApprovalCheck, useUnlimitedApproval } = options;
915
+ const extendedSigner = evmSigner.extend(publicActions);
916
+ if (!bypassApprovalCheck && evmTx.requiredErc20Approvals) {
917
+ for (const requiredApproval of evmTx.requiredErc20Approvals) {
918
+ const allowance = await extendedSigner.readContract({
919
+ address: requiredApproval.tokenContract,
920
+ abi: erc20ABI,
921
+ functionName: "allowance",
922
+ args: [
923
+ evmSigner.account.address,
924
+ requiredApproval.spender
925
+ ]
926
+ });
927
+ if (!requiredApproval.amount) {
928
+ throw new Error("executeEVMTransaction error: no amount found in a requiredApproval");
929
+ }
930
+ if (allowance > BigInt(requiredApproval.amount)) {
931
+ continue;
932
+ }
933
+ onApproveAllowance?.({
934
+ status: "pending",
935
+ allowance: requiredApproval
936
+ });
937
+ const txHash2 = await extendedSigner.writeContract({
938
+ account: evmSigner.account,
939
+ address: requiredApproval.tokenContract,
940
+ abi: erc20ABI,
941
+ functionName: "approve",
942
+ args: [
943
+ requiredApproval.spender,
944
+ useUnlimitedApproval ? maxUint256 : BigInt(requiredApproval.amount) + BigInt(1e3)
945
+ ],
946
+ chain: evmSigner.chain
947
+ });
948
+ const receipt2 = await extendedSigner.waitForTransactionReceipt({
949
+ hash: txHash2
950
+ });
951
+ if (receipt2.status === "reverted") {
952
+ throw new Error(
953
+ `executeEVMTransaction error: evm tx reverted for hash ${receipt2.transactionHash}`
954
+ );
955
+ }
956
+ }
957
+ onApproveAllowance?.({
958
+ status: "completed"
959
+ });
960
+ }
961
+ const txHash = await extendedSigner.sendTransaction({
962
+ account: evmSigner.account,
963
+ to: evmTx.to,
964
+ data: `0x${evmTx.data}`,
965
+ chain: evmSigner.chain,
966
+ value: evmTx.value === "" ? void 0 : BigInt(evmTx.value)
967
+ });
968
+ onTransactionSigned?.({
969
+ chainId: evmTx.chainId
970
+ });
971
+ const receipt = await extendedSigner.waitForTransactionReceipt({
972
+ hash: txHash
973
+ });
974
+ return receipt;
975
+ };
976
+ var executeSvmTransaction = async (tx, options) => {
977
+ const gasArray = ClientState.validateGasResults;
978
+ if (tx === void 0) {
979
+ throw new Error("executeSvmTransaction error: tx is undefined");
980
+ }
981
+ const gas = gasArray?.find((gas2) => gas2?.error !== null && gas2?.error !== void 0);
982
+ if (typeof gas?.error === "string") {
983
+ throw new Error(gas?.error);
984
+ }
985
+ const svmTx = tx?.svmTx;
986
+ const getSvmSigner = options?.getSvmSigner || ClientState.getSvmSigner;
987
+ if (!getSvmSigner) {
988
+ throw new Error(
989
+ "executeRoute error: 'getSVMSigner' is not provided or configured in skip router"
990
+ );
991
+ }
992
+ const signer = await getSvmSigner();
993
+ if (!svmTx?.chainId) {
994
+ throw new Error("executeSvmTransaction error: chainId not found in svmTx");
995
+ }
996
+ const txBuffer = Buffer.from(svmTx.tx ?? "", "base64");
997
+ const transaction = Transaction.from(txBuffer);
998
+ const endpoint = await getRpcEndpointForChain(svmTx.chainId);
999
+ const connection = new Connection(endpoint);
1000
+ let signature;
1001
+ if ("signTransaction" in signer) {
1002
+ const signedTx = await signer.signTransaction(transaction);
1003
+ options?.onTransactionSigned?.({ chainId: svmTx.chainId });
1004
+ const serializedTx = signedTx.serialize();
1005
+ await submitTransaction({
1006
+ chainId: svmTx.chainId,
1007
+ tx: serializedTx.toString("base64")
1008
+ }).then((res) => {
1009
+ signature = res?.txHash;
1010
+ });
1011
+ const rpcSig = await connection.sendRawTransaction(serializedTx, {
1012
+ preflightCommitment: "confirmed",
1013
+ maxRetries: 5
1014
+ });
1015
+ signature = rpcSig;
1016
+ }
1017
+ if (!signature) {
1018
+ throw new Error("executeSvmTransaction error: signature not found");
1019
+ }
1020
+ let getStatusCount = 0;
1021
+ let errorCount = 0;
1022
+ while (true) {
1023
+ try {
1024
+ const status = await connection.getSignatureStatus(signature, {
1025
+ searchTransactionHistory: true
1026
+ });
1027
+ if (status?.value?.confirmationStatus === "confirmed") {
1028
+ return {
1029
+ chainId: svmTx.chainId,
1030
+ txHash: signature
1031
+ };
1032
+ }
1033
+ if (getStatusCount > 12) {
1034
+ await wait(3e3);
1035
+ throw new Error(
1036
+ `executeSvmTransaction error: waiting finalized status timed out for ${signature}`
1037
+ );
1038
+ }
1039
+ getStatusCount++;
1040
+ await wait(3e3);
1041
+ } catch (error) {
1042
+ errorCount++;
1043
+ if (errorCount > 12) {
1044
+ throw error;
1045
+ }
1046
+ }
1047
+ }
1048
+ };
1049
+ var DEFAULT_GAS_MULTIPLIER = 1.5;
1050
+ async function getCosmosGasAmountForMessage(client, signerAddress, chainId, messages2, encodedMsgs, multiplier = DEFAULT_GAS_MULTIPLIER) {
1051
+ if (!messages2 && !encodedMsgs) {
1052
+ throw new Error("Either message or encodedMsg must be provided");
1053
+ }
1054
+ const _encodedMsgs = messages2?.map((message) => getEncodeObjectFromCosmosMessage(message));
1055
+ encodedMsgs = encodedMsgs || _encodedMsgs;
1056
+ if (!encodedMsgs) {
1057
+ throw new Error("Either message or encodedMsg must be provided");
1058
+ }
1059
+ if (chainId.includes("evmos") || chainId.includes("injective") || chainId.includes("dymension") || process?.env.NODE_ENV === "test") {
1060
+ if (messages2?.find((i) => i.msgTypeUrl === "/cosmwasm.wasm.v1.MsgExecuteContract")) {
1061
+ return "2400000";
1062
+ }
1063
+ return "280000";
1064
+ }
1065
+ const estimatedGas = await client.simulate(signerAddress, encodedMsgs, "");
1066
+ const estimatedGasWithBuffer = estimatedGas * multiplier;
1067
+ return Math.ceil(estimatedGasWithBuffer).toFixed(0);
1068
+ }
1069
+
1070
+ // src/private-functions/cosmos/validateCosmosGasBalance.ts
1071
+ var validateCosmosGasBalance = async ({
1072
+ chainId,
1073
+ signerAddress,
1074
+ messages: messages2,
1075
+ getFallbackGasAmount,
1076
+ getOfflineSigner,
1077
+ txIndex,
1078
+ simulate
1079
+ }) => {
1080
+ const skipAssets = (await ClientState.getSkipAssets({ chainId }))?.[chainId];
1081
+ const skipChains = await ClientState.getSkipChains();
1082
+ const chain = skipChains?.find((c) => c.chainId === chainId);
1083
+ if (!chain) {
1084
+ throw new Error(`failed to find chain id for '${chainId}'`);
1085
+ }
1086
+ const { feeAssets } = chain;
1087
+ if (!feeAssets) {
1088
+ throw new Error(`failed to find fee assets for chain '${chainId}'`);
1089
+ }
1090
+ const estimatedGasAmount = await (async () => {
1091
+ try {
1092
+ if (!simulate) throw new Error("simulate");
1093
+ if (txIndex !== 0 && chainId === "noble-1") {
1094
+ return "0";
1095
+ }
1096
+ const { stargateClient } = await getSigningStargateClient({
1097
+ chainId,
1098
+ getOfflineSigner
1099
+ });
1100
+ const estimatedGas = await getCosmosGasAmountForMessage(
1101
+ stargateClient,
1102
+ signerAddress,
1103
+ chainId,
1104
+ messages2
1105
+ );
1106
+ return estimatedGas;
1107
+ } catch (e) {
1108
+ const error = e;
1109
+ if (error.message === "simulate" && !getFallbackGasAmount) {
1110
+ throw new Error(`unable to get gas amount for ${chainId}'s message(s)`);
1111
+ }
1112
+ if (getFallbackGasAmount) {
1113
+ const fallbackGasAmount = await getFallbackGasAmount(chainId, "cosmos" /* Cosmos */);
1114
+ if (!fallbackGasAmount) {
1115
+ throw new Error(`unable to estimate gas for message(s) ${messages2}`);
1116
+ }
1117
+ return String(fallbackGasAmount);
1118
+ }
1119
+ throw error;
1120
+ }
1121
+ })();
1122
+ const fees = feeAssets.map((asset) => {
1123
+ const gasPrice = (() => {
1124
+ if (!asset?.gasPrice) return void 0;
1125
+ let price = asset.gasPrice.average;
1126
+ if (price === "") {
1127
+ price = asset.gasPrice.high;
1128
+ }
1129
+ if (price === "") {
1130
+ price = asset.gasPrice.low;
1131
+ }
1132
+ if (!price) return;
1133
+ return new GasPrice(
1134
+ Decimal.fromUserInput(BigNumber(price).toFixed(), 18),
1135
+ asset?.denom ?? ""
1136
+ );
1137
+ })();
1138
+ if (!gasPrice) {
1139
+ return null;
1140
+ }
1141
+ if (chainId === "noble-1") {
1142
+ const fee = calculateFee(2e5, gasPrice);
1143
+ return fee;
1144
+ }
1145
+ return calculateFee(Math.ceil(parseFloat(estimatedGasAmount)), gasPrice);
1146
+ });
1147
+ const feeBalance = await balances({
1148
+ chains: {
1149
+ [chainId]: {
1150
+ address: signerAddress,
1151
+ denoms: feeAssets.map((asset) => asset.denom ?? "")
1152
+ }
1153
+ }
1154
+ });
1155
+ const validatedAssets = feeAssets.map((asset, index) => {
1156
+ const chainAsset = skipAssets?.find((x) => x.denom === asset.denom);
1157
+ const symbol = chainAsset?.recommendedSymbol?.toUpperCase();
1158
+ const decimal = Number(chainAsset?.decimals);
1159
+ if (!chainAsset) {
1160
+ return {
1161
+ error: `(${chain?.prettyName}) Unable to find asset for ${asset.denom}`
1162
+ };
1163
+ }
1164
+ if (isNaN(decimal))
1165
+ return {
1166
+ error: `(${chain?.prettyName}) Unable to find decimal for ${symbol}`
1167
+ };
1168
+ const fee = fees[index];
1169
+ if (!fee) {
1170
+ return {
1171
+ error: `(${chain?.prettyName}) Unable to calculate fee for ${symbol}`,
1172
+ asset
1173
+ };
1174
+ }
1175
+ if (txIndex !== 0 && chainId === "noble-1") {
1176
+ return {
1177
+ error: null,
1178
+ asset,
1179
+ fee
1180
+ };
1181
+ }
1182
+ let balance = feeBalance?.chains?.[chainId]?.denoms?.[asset?.denom ?? ""];
1183
+ if (!balance) {
1184
+ balance = {
1185
+ amount: "0",
1186
+ formattedAmount: "0"
1187
+ };
1188
+ }
1189
+ if (!fee.amount[0]?.amount) {
1190
+ return {
1191
+ error: `(${chain?.prettyName}) Unable to get fee for ${symbol}`,
1192
+ asset
1193
+ };
1194
+ }
1195
+ if (parseInt(balance?.amount ?? "") < parseInt(fee.amount[0]?.amount)) {
1196
+ const userAmount = new BigNumber(parseFloat(balance?.amount ?? "")).shiftedBy(-decimal).toFixed(decimal);
1197
+ const feeAmount = new BigNumber(parseFloat(fee.amount[0]?.amount)).shiftedBy(-decimal).toFixed(decimal);
1198
+ return {
1199
+ error: `Insufficient balance for gas on ${chain?.prettyName}. Need ${feeAmount} ${symbol} but only have ${userAmount} ${symbol}.`,
1200
+ asset
1201
+ };
1202
+ }
1203
+ return {
1204
+ error: null,
1205
+ asset,
1206
+ fee
1207
+ };
1208
+ });
1209
+ const feeUsed = validatedAssets.find((res) => res?.error === null);
1210
+ if (!feeUsed) {
1211
+ if (validatedAssets.length > 1) {
1212
+ throw new Error(
1213
+ validatedAssets[0]?.error || `Insufficient fee token to initiate transfer on ${chainId}.`
1214
+ );
1215
+ }
1216
+ throw new Error(
1217
+ validatedAssets[0]?.error || `Insufficient fee token to initiate transfer on ${chainId}.`
1218
+ );
1219
+ }
1220
+ return feeUsed;
1221
+ };
1222
+ var validateEvmTokenApproval = async ({
1223
+ requiredErc20Approvals,
1224
+ signer,
1225
+ chain,
1226
+ gasBalance,
1227
+ tx,
1228
+ useUnlimitedApproval
1229
+ }) => {
1230
+ if (!signer.account?.address) {
1231
+ throw new Error("validateEvmGasBalance: Signer address not found");
1232
+ }
1233
+ for (const requiredApproval of requiredErc20Approvals) {
1234
+ const extendedSigner = signer.extend(publicActions);
1235
+ const allowance = await extendedSigner.readContract({
1236
+ address: requiredApproval.tokenContract,
1237
+ abi: erc20ABI,
1238
+ functionName: "allowance",
1239
+ args: [signer.account?.address, requiredApproval.spender]
1240
+ });
1241
+ if (allowance > BigInt(requiredApproval.amount)) {
1242
+ continue;
1243
+ }
1244
+ const fee = await extendedSigner.estimateFeesPerGas();
1245
+ const allowanceGasFee = BigInt(fee.maxFeePerGas) * BigInt(1e5);
1246
+ if (!gasBalance) {
1247
+ const chainAssets = (await ClientState.getSkipAssets({ chainId: tx.chainId }))[tx.chainId];
1248
+ const nativeAsset = chainAssets?.find((x) => x.denom.includes("-native"));
1249
+ const zeroAddressAsset = chainAssets?.find(
1250
+ (x) => x.denom.toLowerCase() === "0x0000000000000000000000000000000000000000"
1251
+ );
1252
+ const asset = nativeAsset || zeroAddressAsset;
1253
+ if (!asset?.decimals) {
1254
+ throw new Error(
1255
+ `Insufficient balance for gas on ${chain.prettyName}. Need ${allowanceGasFee} gwei.`
1256
+ );
1257
+ }
1258
+ const formattedGasAmount = formatUnits(allowanceGasFee, asset?.decimals);
1259
+ throw new Error(
1260
+ `Insufficient balance for gas on ${chain.prettyName}. Need ${formattedGasAmount} ${asset.symbol}.`
1261
+ );
1262
+ }
1263
+ if (BigNumber(gasBalance.amount).lt(Number(allowanceGasFee))) {
1264
+ const chainAssets = (await ClientState.getSkipAssets({ chainId: tx.chainId }))[tx.chainId];
1265
+ const asset = chainAssets?.find(
1266
+ (x) => x.denom.includes("-native") || x.denom.toLowerCase() === "0x0000000000000000000000000000000000000000"
1267
+ );
1268
+ if (!asset?.decimals) {
1269
+ return {
1270
+ error: `Insufficient balance for gas on ${chain.prettyName}. Need ${allowanceGasFee} gwei but only have ${gasBalance.amount} gwei.`,
1271
+ asset: null,
1272
+ fee: null
1273
+ };
1274
+ }
1275
+ const formattedGasAmount = formatUnits(allowanceGasFee, asset?.decimals);
1276
+ return {
1277
+ error: `Insufficient balance for gas on ${chain.prettyName}. Need ${formattedGasAmount} ${asset.symbol} but only have ${gasBalance.formattedAmount} ${asset.symbol}.`,
1278
+ asset: null,
1279
+ fee: null
1280
+ };
1281
+ }
1282
+ const txHash = await extendedSigner.writeContract({
1283
+ account: signer.account,
1284
+ address: requiredApproval.tokenContract,
1285
+ abi: erc20ABI,
1286
+ functionName: "approve",
1287
+ args: [
1288
+ requiredApproval.spender,
1289
+ useUnlimitedApproval ? maxUint256 : BigInt(requiredApproval.amount) + BigInt(1e3)
1290
+ ],
1291
+ chain: signer.chain
1292
+ });
1293
+ const receipt = await extendedSigner.waitForTransactionReceipt({
1294
+ hash: txHash
1295
+ });
1296
+ if (receipt.status === "reverted") {
1297
+ throw new Error(
1298
+ `executeEVMTransaction error: evm tx reverted for hash ${receipt.transactionHash}`
1299
+ );
1300
+ }
1301
+ }
1302
+ };
1303
+ async function getEVMGasAmountForMessage(signer, tx, getFallbackGasAmount) {
1304
+ const { to, data, value } = tx;
1305
+ if (!signer.account) throw new Error("estimateGasForEvmTx: No account found");
1306
+ const extendedSigner = signer.extend(publicActions);
1307
+ const fee = await extendedSigner.estimateFeesPerGas();
1308
+ try {
1309
+ const gasAmount = await extendedSigner.estimateGas({
1310
+ account: signer.account,
1311
+ to,
1312
+ data: `0x${data}`,
1313
+ value: value === "" ? void 0 : BigInt(value ?? "")
1314
+ });
1315
+ return gasAmount * fee.maxFeePerGas;
1316
+ } catch (error) {
1317
+ const fallbackGasAmount = await getFallbackGasAmount?.(tx.chainId ?? "", "evm" /* Evm */);
1318
+ if (fallbackGasAmount) {
1319
+ return BigInt(fallbackGasAmount) * fee.maxFeePerGas;
1320
+ }
1321
+ throw error;
1322
+ }
1323
+ }
1324
+
1325
+ // src/private-functions/evm/validateEvmGasBalance.ts
1326
+ var validateEvmGasBalance = async ({
1327
+ signer,
1328
+ tx,
1329
+ getFallbackGasAmount,
1330
+ useUnlimitedApproval
1331
+ }) => {
1332
+ const chainId = tx?.chainId ?? "";
1333
+ const skipAssets = (await ClientState.getSkipAssets({ chainId }))?.[chainId];
1334
+ const skipChains = await ClientState.getSkipChains();
1335
+ const chain = skipChains?.find?.((chain2) => chain2.chainId === chainId);
1336
+ if (!chain) {
1337
+ throw new Error(`failed to find chain for chainId: '${chainId}'`);
1338
+ }
1339
+ if (!signer.account?.address) {
1340
+ throw new Error("validateEvmGasBalance: Signer address not found");
1341
+ }
1342
+ const skipBalances = (await balances({
1343
+ chains: {
1344
+ [tx?.chainId ?? ""]: {
1345
+ address: signer.account?.address
1346
+ }
1347
+ }
1348
+ }))?.chains?.[tx?.chainId ?? ""]?.denoms;
1349
+ const nativeGasBalance = skipBalances && Object.entries(skipBalances).find(([denom]) => denom.includes("-native"))?.[1];
1350
+ const zeroAddressGasBalance = skipBalances && Object.entries(skipBalances).find(
1351
+ ([denom]) => denom.toLowerCase() === "0x0000000000000000000000000000000000000000"
1352
+ )?.[1];
1353
+ const gasBalance = nativeGasBalance || zeroAddressGasBalance;
1354
+ const { requiredErc20Approvals } = tx;
1355
+ if (requiredErc20Approvals) {
1356
+ try {
1357
+ await validateEvmTokenApproval({
1358
+ requiredErc20Approvals,
1359
+ signer,
1360
+ chain,
1361
+ gasBalance,
1362
+ tx,
1363
+ useUnlimitedApproval
1364
+ });
1365
+ } catch (error) {
1366
+ const err = error;
1367
+ return {
1368
+ error: err.message,
1369
+ asset: null,
1370
+ fee: null
1371
+ };
1372
+ }
1373
+ }
1374
+ const gasAmount = await getEVMGasAmountForMessage(signer, tx, getFallbackGasAmount);
1375
+ if (!gasBalance) {
1376
+ const nativeAsset = skipAssets?.find((x) => x.denom?.includes("-native"));
1377
+ const zeroAddressAsset = skipAssets?.find(
1378
+ (x) => x.denom?.toLowerCase() === "0x0000000000000000000000000000000000000000"
1379
+ );
1380
+ const asset = nativeAsset || zeroAddressAsset;
1381
+ if (!asset?.decimals) {
1382
+ return {
1383
+ error: `Insufficient balance for gas on ${chain.prettyName}. Need ${gasAmount} gwei.`,
1384
+ asset: null,
1385
+ fee: null
1386
+ };
1387
+ }
1388
+ const formattedGasAmount = formatUnits(gasAmount, asset?.decimals);
1389
+ return {
1390
+ error: `Insufficient balance for gas on ${chain.prettyName}. Need ${formattedGasAmount} ${asset.symbol}.`,
1391
+ asset: null,
1392
+ fee: null
1393
+ };
1394
+ }
1395
+ if (BigNumber(gasBalance.amount ?? "").lt(Number(gasAmount))) {
1396
+ const asset = skipAssets?.find(
1397
+ (x) => x.denom?.includes("-native") || x.denom?.toLowerCase() === "0x0000000000000000000000000000000000000000"
1398
+ );
1399
+ if (!asset?.decimals) {
1400
+ return {
1401
+ error: `Insufficient balance for gas on ${chain.prettyName}. Need ${gasAmount} gwei but only have ${gasBalance.amount} gwei.`,
1402
+ asset: null,
1403
+ fee: null
1404
+ };
1405
+ }
1406
+ const formattedGasAmount = formatUnits(gasAmount, asset?.decimals);
1407
+ return {
1408
+ error: `Insufficient balance for gas on ${chain.prettyName}. Need ${formattedGasAmount} ${asset.symbol} but only have ${gasBalance.formattedAmount} ${asset.symbol}.`,
1409
+ asset: null,
1410
+ fee: null
1411
+ };
1412
+ }
1413
+ };
1414
+ var validateSvmGasBalance = async ({
1415
+ tx
1416
+ }) => {
1417
+ if (!tx) throw new Error("Transaction is required");
1418
+ const endpoint = await getRpcEndpointForChain(tx.chainId ?? "");
1419
+ const connection = new Connection(endpoint);
1420
+ if (!connection) throw new Error(`Failed to connect to ${tx.chainId}`);
1421
+ if (!tx.tx) {
1422
+ throw new Error("Transaction is required");
1423
+ }
1424
+ const txBuffer = Buffer.from(tx.tx, "base64");
1425
+ let transaction;
1426
+ try {
1427
+ transaction = Transaction.from(txBuffer);
1428
+ } catch (decodeError) {
1429
+ return {
1430
+ success: false,
1431
+ error: { decodeError: decodeError.message },
1432
+ asset: null,
1433
+ fee: null
1434
+ };
1435
+ }
1436
+ const simulation = await connection.simulateTransaction(transaction);
1437
+ if (simulation.value.err) {
1438
+ const logs = simulation.value.logs ?? [];
1439
+ const shortfall = getSolShortfall(logs);
1440
+ const insufficientLamports = logs.some((log) => log.includes("insufficient lamports")) && shortfall !== null;
1441
+ const insufficientFundsForRent = Object.keys(simulation.value.err).includes(
1442
+ "InsufficientFundsForRent"
1443
+ );
1444
+ 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";
1445
+ return {
1446
+ success: false,
1447
+ logs,
1448
+ error: errMsg,
1449
+ asset: null,
1450
+ fee: null
1451
+ };
1452
+ }
1453
+ return {
1454
+ success: true,
1455
+ logs: simulation.value.logs ?? [],
1456
+ error: null,
1457
+ asset: null,
1458
+ fee: null
1459
+ };
1460
+ };
1461
+ function getSolShortfall(logs) {
1462
+ const line = logs.find((l) => l.includes("insufficient lamports"));
1463
+ if (!line) return null;
1464
+ const m = line.match(/insufficient lamports (\d+), need (\d+)/);
1465
+ if (!m) return null;
1466
+ const have = parseInt(m[1] ?? "0", 10);
1467
+ const need = parseInt(m[2] ?? "0", 10);
1468
+ const shortfallLamports = need - have;
1469
+ return shortfallLamports / LAMPORTS_PER_SOL;
1470
+ }
1471
+
1472
+ // src/private-functions/validateGasBalances.ts
1473
+ var validateGasBalances = async ({
1474
+ txs,
1475
+ onValidateGasBalance,
1476
+ getFallbackGasAmount,
1477
+ getCosmosSigner,
1478
+ getEvmSigner,
1479
+ simulate,
1480
+ disabledChainIds,
1481
+ enabledChainIds,
1482
+ useUnlimitedApproval
1483
+ }) => {
1484
+ if (txs.every((tx) => "cosmosTx" in tx === void 0) || txs.every((tx) => "svmTx" in tx === void 0)) {
1485
+ return;
1486
+ }
1487
+ onValidateGasBalance?.({
1488
+ status: "pending"
1489
+ });
1490
+ const validateResult = await Promise.all(
1491
+ txs.map(async (tx, i) => {
1492
+ if (!tx) {
1493
+ throw new Error(`invalid tx at index ${i}`);
1494
+ }
1495
+ if ("cosmosTx" in tx && !disabledChainIds?.includes(tx?.cosmosTx?.chainId ?? "") && (enabledChainIds === void 0 || enabledChainIds.includes(tx?.cosmosTx?.chainId ?? ""))) {
1496
+ if (!tx?.cosmosTx?.msgs) {
1497
+ throw new Error(`invalid msgs ${tx?.cosmosTx?.msgs}`);
1498
+ }
1499
+ try {
1500
+ const res = await validateCosmosGasBalance({
1501
+ chainId: tx.cosmosTx.chainId ?? "",
1502
+ signerAddress: tx.cosmosTx.signerAddress ?? "",
1503
+ messages: tx.cosmosTx.msgs,
1504
+ getFallbackGasAmount,
1505
+ getOfflineSigner: getCosmosSigner,
1506
+ txIndex: i,
1507
+ simulate
1508
+ });
1509
+ return res;
1510
+ } catch (e) {
1511
+ const error = e;
1512
+ return {
1513
+ error: error.message,
1514
+ asset: null,
1515
+ fee: null
1516
+ };
1517
+ }
1518
+ }
1519
+ if ("evmTx" in tx && !disabledChainIds?.includes(tx?.evmTx?.chainId ?? "") && (enabledChainIds === void 0 || enabledChainIds.includes(tx?.evmTx?.chainId ?? ""))) {
1520
+ const signer = await getEvmSigner?.(tx?.evmTx?.chainId ?? "");
1521
+ if (!signer) {
1522
+ throw new Error(`failed to get signer for chain ${tx?.evmTx?.chainId}`);
1523
+ }
1524
+ try {
1525
+ const res = await validateEvmGasBalance({
1526
+ tx: tx.evmTx,
1527
+ signer,
1528
+ getFallbackGasAmount,
1529
+ useUnlimitedApproval
1530
+ });
1531
+ return res;
1532
+ } catch (e) {
1533
+ const error = e;
1534
+ return {
1535
+ error: error.message,
1536
+ asset: null,
1537
+ fee: null
1538
+ };
1539
+ }
1540
+ }
1541
+ if ("svmTx" in tx && !disabledChainIds?.includes(tx?.svmTx?.chainId ?? "") && (enabledChainIds === void 0 || enabledChainIds.includes(tx?.svmTx?.chainId ?? ""))) {
1542
+ try {
1543
+ const res = await validateSvmGasBalance({
1544
+ tx: tx.svmTx
1545
+ });
1546
+ return res;
1547
+ } catch (e) {
1548
+ const error = e;
1549
+ return {
1550
+ error: error.message,
1551
+ asset: null,
1552
+ fee: null
1553
+ };
1554
+ }
1555
+ }
1556
+ })
1557
+ );
1558
+ if (validateResult.filter(Boolean).length === 0) {
1559
+ return;
1560
+ }
1561
+ const txError = validateResult.find((res) => res && res?.error !== null);
1562
+ if (txError) {
1563
+ onValidateGasBalance?.({
1564
+ status: "error"
1565
+ });
1566
+ ClientState.validateGasResults = validateResult;
1567
+ throw new Error(`${txError.error}`);
1568
+ }
1569
+ onValidateGasBalance?.({
1570
+ status: "completed"
1571
+ });
1572
+ ClientState.validateGasResults = validateResult;
1573
+ };
1574
+
1575
+ // src/private-functions/waitForTransaction.ts
1576
+ var waitForTransaction = async ({
1577
+ chainId,
1578
+ txHash,
1579
+ onTransactionTracked
1580
+ }) => {
1581
+ const { explorerLink } = await trackTransaction({
1582
+ chainId,
1583
+ txHash
1584
+ });
1585
+ await onTransactionTracked?.({ txHash, chainId, explorerLink });
1586
+ while (true) {
1587
+ const txStatusResponse = await transactionStatus({
1588
+ chainId,
1589
+ txHash
1590
+ });
1591
+ if (txStatusResponse.state === "STATE_COMPLETED_SUCCESS") {
1592
+ return txStatusResponse;
1593
+ }
1594
+ if (txStatusResponse.state === "STATE_COMPLETED_ERROR") {
1595
+ throw new Error(`${txStatusResponse.error?.type}: ${txStatusResponse.error?.message}`);
1596
+ }
1597
+ if (txStatusResponse.state === "STATE_ABANDONED") {
1598
+ throw new Error("Tracking for the transaction has been abandoned");
1599
+ }
1600
+ await wait(1e3);
1601
+ }
1602
+ };
1603
+
1604
+ // src/private-functions/executeTransactions.ts
1605
+ var executeTransactions = async (options) => {
1606
+ const {
1607
+ txs,
1608
+ onTransactionBroadcast,
1609
+ onTransactionCompleted,
1610
+ simulate = true,
1611
+ batchSimulate = true
1612
+ } = options;
1613
+ if (txs === void 0) {
1614
+ throw new Error("executeTransactions error: txs is undefined in executeTransactions");
1615
+ }
1616
+ const chainIds = txs.map((tx) => {
1617
+ if ("cosmosTx" in tx) {
1618
+ return {
1619
+ chainType: "cosmos",
1620
+ chainId: tx.cosmosTx?.chainId
1621
+ };
1622
+ }
1623
+ if ("svmTx" in tx) {
1624
+ return {
1625
+ chainType: "svm",
1626
+ chainId: tx.svmTx?.chainId
1627
+ };
1628
+ }
1629
+ if ("evmTx" in tx) {
1630
+ return {
1631
+ chainType: "evm",
1632
+ chainId: tx.evmTx?.chainId
1633
+ };
1634
+ }
1635
+ });
1636
+ const isGasStationSourceEVM = chainIds.find((item, i, array) => {
1637
+ return GAS_STATION_CHAIN_IDS.includes(item?.chainId ?? "") && array[i - 1]?.chainType === "evm";
1638
+ });
1639
+ ClientState.validateGasResults = void 0;
1640
+ const validateChainIds = !batchSimulate ? chainIds.map((x) => x?.chainId ?? "") : isGasStationSourceEVM ? GAS_STATION_CHAIN_IDS : [];
1641
+ await validateGasBalances({
1642
+ txs,
1643
+ getFallbackGasAmount: options.getFallbackGasAmount,
1644
+ getCosmosSigner: options.getCosmosSigner,
1645
+ getEvmSigner: options.getEvmSigner,
1646
+ onValidateGasBalance: options.onValidateGasBalance,
1647
+ simulate,
1648
+ disabledChainIds: validateChainIds
1649
+ });
1650
+ const validateEnabledChainIds = async (chainId) => {
1651
+ await validateGasBalances({
1652
+ txs,
1653
+ getFallbackGasAmount: options.getFallbackGasAmount,
1654
+ getCosmosSigner: options.getCosmosSigner,
1655
+ getEvmSigner: options.getEvmSigner,
1656
+ onValidateGasBalance: options.onValidateGasBalance,
1657
+ simulate,
1658
+ enabledChainIds: !batchSimulate ? [chainId] : validateChainIds
1659
+ });
1660
+ };
1661
+ for (let i = 0; i < txs.length; i++) {
1662
+ const tx = txs[i];
1663
+ if (!tx) {
1664
+ throw new Error(`executeRoute error: invalid message at index ${i}`);
1665
+ }
1666
+ let txResult;
1667
+ if ("cosmosTx" in tx) {
1668
+ await validateEnabledChainIds(tx.cosmosTx?.chainId ?? "");
1669
+ txResult = await executeCosmosTransaction({
1670
+ tx,
1671
+ options,
1672
+ index: i
1673
+ });
1674
+ } else if ("evmTx" in tx) {
1675
+ await validateEnabledChainIds(tx.evmTx?.chainId ?? "");
1676
+ const txResponse = await executeEvmTransaction(tx, options);
1677
+ txResult = {
1678
+ chainId: tx?.evmTx?.chainId ?? "",
1679
+ txHash: txResponse.transactionHash
1680
+ };
1681
+ } else if ("svmTx" in tx) {
1682
+ await validateEnabledChainIds(tx.svmTx?.chainId ?? "");
1683
+ txResult = await executeSvmTransaction(tx, options);
1684
+ } else {
1685
+ throw new Error("executeRoute error: invalid message type");
1686
+ }
1687
+ await onTransactionBroadcast?.({ ...txResult });
1688
+ const txStatusResponse = await waitForTransaction({
1689
+ ...txResult,
1690
+ onTransactionTracked: options.onTransactionTracked
1691
+ });
1692
+ await onTransactionCompleted?.({
1693
+ chainId: txResult.chainId,
1694
+ txHash: txResult.txHash,
1695
+ status: txStatusResponse
1696
+ });
1697
+ }
1698
+ };
1699
+ var executeRoute = async (options) => {
1700
+ const { route, userAddresses, beforeMsg, afterMsg, timeoutSeconds } = options;
1701
+ let addressList = [];
1702
+ userAddresses.forEach((userAddress, index) => {
1703
+ const requiredChainAddress = route.requiredChainAddresses[index];
1704
+ if (requiredChainAddress === userAddress?.chainId) {
1705
+ addressList.push(userAddress.address);
1706
+ }
1707
+ });
1708
+ if (addressList.length !== route.requiredChainAddresses.length) {
1709
+ addressList = userAddresses.map((x) => x.address);
1710
+ }
1711
+ const validLength = addressList.length === route.requiredChainAddresses.length || addressList.length === route.chainIds?.length;
1712
+ if (!validLength) {
1713
+ throw new Error("executeRoute error: invalid address list");
1714
+ }
1715
+ const isUserAddressesValid = await validateUserAddresses(userAddresses);
1716
+ if (!isUserAddressesValid) {
1717
+ throw new Error("executeRoute error: invalid user addresses");
1718
+ }
1719
+ const response = await messages({
1720
+ timeoutSeconds,
1721
+ amountIn: route?.amountIn,
1722
+ amountOut: route.estimatedAmountOut || "0",
1723
+ sourceAssetChainId: route?.sourceAssetChainId,
1724
+ sourceAssetDenom: route?.sourceAssetDenom,
1725
+ destAssetChainId: route?.destAssetChainId,
1726
+ destAssetDenom: route?.destAssetDenom,
1727
+ operations: route?.operations,
1728
+ addressList,
1729
+ slippageTolerancePercent: options.slippageTolerancePercent || "1",
1730
+ chainIdsToAffiliates: ApiState.chainIdsToAffiliates
1731
+ });
1732
+ if (beforeMsg && (response?.txs?.length ?? 0) > 0) {
1733
+ const firstTx = response?.txs?.[0];
1734
+ if (firstTx && "cosmosTx" in firstTx) {
1735
+ firstTx.cosmosTx?.msgs?.unshift(beforeMsg);
1736
+ }
1737
+ }
1738
+ if (afterMsg && (response?.txs?.length ?? 0) > 0) {
1739
+ const lastTx = response?.txs?.[response.txs.length - 1];
1740
+ if (lastTx && "cosmosTx" in lastTx) {
1741
+ lastTx.cosmosTx?.msgs?.push(afterMsg);
1742
+ }
1743
+ }
1744
+ await executeTransactions({ ...options, txs: response?.txs });
1745
+ };
1746
+ var validateUserAddresses = async (userAddresses) => {
1747
+ const chains2 = await ClientState.getSkipChains();
1748
+ const validations = userAddresses.map((userAddress) => {
1749
+ const chain = chains2.find((chain2) => chain2.chainId === userAddress.chainId);
1750
+ switch (chain?.chainType) {
1751
+ case "cosmos" /* Cosmos */:
1752
+ try {
1753
+ if (chain.chainId?.includes("penumbra")) {
1754
+ try {
1755
+ return chain.bech32Prefix === bech32m.decode(userAddress.address, 143)?.prefix;
1756
+ } catch {
1757
+ return ["penumbracompat1", "tpenumbra"].includes(
1758
+ bech32.decode(userAddress.address, 1023).prefix
1759
+ );
1760
+ }
1761
+ }
1762
+ return chain.bech32Prefix === bech32.decode(userAddress.address, 1023).prefix;
1763
+ } catch {
1764
+ return false;
1765
+ }
1766
+ case "evm" /* Evm */:
1767
+ try {
1768
+ return isAddress(userAddress.address);
1769
+ } catch (_error) {
1770
+ return false;
1771
+ }
1772
+ case "svm" /* Svm */:
1773
+ try {
1774
+ const publicKey = new PublicKey(userAddress.address);
1775
+ return PublicKey.isOnCurve(publicKey);
1776
+ } catch (_error) {
1777
+ return false;
1778
+ }
1779
+ default:
1780
+ return false;
1781
+ }
1782
+ });
1783
+ return validations.every((validation) => validation);
1784
+ };
1785
+
1786
+ export { executeRoute };