@skip-go/client 1.0.0-alpha-3 → 1.0.0-alpha-4

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