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

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 (51) hide show
  1. package/dist/api/getAssets.mjs +2 -25
  2. package/dist/api/getAssetsBetweenChains.mjs +2 -9
  3. package/dist/api/getBridges.mjs +2 -10
  4. package/dist/api/getChains.mjs +2 -16
  5. package/dist/api/getVenues.mjs +2 -10
  6. package/dist/api/postAssetsFromSource.mjs +3 -14
  7. package/dist/api/postBalances.mjs +2 -16
  8. package/dist/api/postIbcOriginAssets.mjs +2 -11
  9. package/dist/api/postMessages.d.mts +183 -183
  10. package/dist/api/postMessages.mjs +2 -10
  11. package/dist/api/postMessagesDirect.d.mts +183 -183
  12. package/dist/api/postMessagesDirect.mjs +2 -10
  13. package/dist/api/postRecommendAssets.mjs +2 -13
  14. package/dist/api/postRoute.d.mts +160 -160
  15. package/dist/api/postRoute.mjs +2 -16
  16. package/dist/api/postSubmitTransaction.mjs +2 -10
  17. package/dist/api/postTrackTransaction.mjs +2 -11
  18. package/dist/api/postTransactionStatus.mjs +2 -10
  19. package/dist/chunk-2ETF4N4H.mjs +45 -0
  20. package/dist/chunk-2F4MBSMT.mjs +99 -0
  21. package/dist/chunk-2FYLP573.mjs +15 -0
  22. package/dist/chunk-7TBBV2YY.mjs +13 -0
  23. package/dist/chunk-B72MYSG5.mjs +273 -0
  24. package/dist/chunk-C5CGY2X7.mjs +10 -0
  25. package/dist/chunk-CAAR7GDJ.mjs +11 -0
  26. package/dist/chunk-CZ27FEZ7.mjs +11 -0
  27. package/dist/chunk-DKIWPD5I.mjs +124 -0
  28. package/dist/chunk-IGD32L7C.mjs +9 -0
  29. package/dist/chunk-J7GGREYX.mjs +10 -0
  30. package/dist/chunk-KPK3Z6QZ.mjs +10 -0
  31. package/dist/chunk-KSMJWLEH.mjs +2315 -0
  32. package/dist/chunk-LJVI5DLG.mjs +10 -0
  33. package/dist/chunk-NNZFCKHP.mjs +10 -0
  34. package/dist/chunk-NU7MCJOK.mjs +187 -0
  35. package/dist/chunk-OTLFF5OB.mjs +3634 -0
  36. package/dist/chunk-PEZHVPSR.mjs +2237 -0
  37. package/dist/chunk-QZ3X6MP3.mjs +10 -0
  38. package/dist/chunk-RXWDHQLG.mjs +231 -0
  39. package/dist/chunk-TUBI6VE6.mjs +1344 -0
  40. package/dist/chunk-WDMGUHWR.mjs +23 -0
  41. package/dist/chunk-YWYU6P7W.mjs +14 -0
  42. package/dist/chunk-ZAF3Z56R.mjs +7 -0
  43. package/dist/index.mjs +24 -24
  44. package/dist/public-functions/executeRoute.mjs +12 -100
  45. package/dist/public-functions/getFeeInfoForChain.mjs +5 -47
  46. package/dist/public-functions/getRecommendedGasPrice.mjs +7 -1366
  47. package/dist/public-functions/getSigningStargateClient.mjs +4 -32
  48. package/dist/public-functions/setApiOptions.mjs +2 -46
  49. package/dist/public-functions/setClientOptions.mjs +4 -34
  50. package/package.json +1 -8
  51. package/dist/chunk-AXBFBHS2.mjs +0 -41
@@ -0,0 +1,2315 @@
1
+ import { BigNumber } from './chunk-TUBI6VE6.mjs';
2
+ import { GAS_STATION_CHAIN_IDS } from './chunk-ZAF3Z56R.mjs';
3
+ import { getSigningStargateClient, getRpcEndpointForChain, accountParser } from './chunk-B72MYSG5.mjs';
4
+ import { chains, findFirstWorkingEndpoint, getIsEthermint, getIsInitia } from './chunk-NU7MCJOK.mjs';
5
+ import { MsgDepositForBurn, MsgDepositForBurnWithCaller, MsgExecute, MsgInitiateTokenDeposit, BaseVestingAccount, Timestamp, toTimestamp, Period, fromTimestamp, isSet, fromJsonTimestamp } from './chunk-OTLFF5OB.mjs';
6
+ import { messages } from './chunk-KPK3Z6QZ.mjs';
7
+ import { submitTransaction } from './chunk-LJVI5DLG.mjs';
8
+ import { trackTransaction } from './chunk-CAAR7GDJ.mjs';
9
+ import { transactionStatus } from './chunk-C5CGY2X7.mjs';
10
+ import { ClientState, balances } from './chunk-DKIWPD5I.mjs';
11
+ import { __spreadValues, __async, __objRest, __spreadProps, ApiState, wait, createRequestClient, toCamel } from './chunk-RXWDHQLG.mjs';
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 { fromBase64 } from '@cosmjs/encoding/build/base64';
18
+ import { toUtf8, fromBase64 as fromBase64$1, toBase64 } from '@cosmjs/encoding';
19
+ import { ChainRestTendermintApi, MsgTransfer as MsgTransfer$1, MsgExecuteContractCompat, createTransactionWithSigners } from '@injectivelabs/sdk-ts';
20
+ import { MsgSend } from 'cosmjs-types/cosmos/bank/v1beta1/tx';
21
+ import { MsgExecuteContract } from 'cosmjs-types/cosmwasm/wasm/v1/tx';
22
+ import { MsgTransfer } from 'cosmjs-types/ibc/applications/transfer/v1/tx';
23
+ import * as _m0 from 'protobufjs/minimal';
24
+ import { BigNumberInBase, DEFAULT_BLOCK_TIMEOUT_HEIGHT, DEFAULT_STD_FEE } from '@injectivelabs/utils';
25
+ import { makeAuthInfoBytes, makeSignDoc } from '@cosmjs/proto-signing/build/signing';
26
+ import { pubkeyType as pubkeyType$1, makeSignDoc as makeSignDoc$1, encodeSecp256k1Pubkey } from '@cosmjs/amino';
27
+ import { encodePubkey } from '@cosmjs/proto-signing';
28
+ import { PubKey } from 'cosmjs-types/cosmos/crypto/secp256k1/keys';
29
+ import { Any } from 'cosmjs-types/google/protobuf/any';
30
+ import { Int53 } from '@cosmjs/math/build/integers';
31
+ import { SignMode } from 'cosmjs-types/cosmos/tx/signing/v1beta1/signing';
32
+ import { isAddress, publicActions, maxUint256, formatUnits } from 'viem';
33
+ import { Decimal } from '@cosmjs/math/build/decimal';
34
+
35
+ // src/types/swaggerTypes.ts
36
+ var AutopilotAction = /* @__PURE__ */ ((AutopilotAction2) => {
37
+ AutopilotAction2["LIQUID_STAKE"] = "LIQUID_STAKE";
38
+ AutopilotAction2["CLAIM"] = "CLAIM";
39
+ return AutopilotAction2;
40
+ })(AutopilotAction || {});
41
+ var AxelarTransferState = /* @__PURE__ */ ((AxelarTransferState2) => {
42
+ AxelarTransferState2["AXELAR_TRANSFER_UNKNOWN"] = "AXELAR_TRANSFER_UNKNOWN";
43
+ AxelarTransferState2["AXELAR_TRANSFER_PENDING_CONFIRMATION"] = "AXELAR_TRANSFER_PENDING_CONFIRMATION";
44
+ AxelarTransferState2["AXELAR_TRANSFER_PENDING_RECEIPT"] = "AXELAR_TRANSFER_PENDING_RECEIPT";
45
+ AxelarTransferState2["AXELAR_TRANSFER_SUCCESS"] = "AXELAR_TRANSFER_SUCCESS";
46
+ AxelarTransferState2["AXELAR_TRANSFER_FAILURE"] = "AXELAR_TRANSFER_FAILURE";
47
+ return AxelarTransferState2;
48
+ })(AxelarTransferState || {});
49
+ var AxelarTransferType = /* @__PURE__ */ ((AxelarTransferType2) => {
50
+ AxelarTransferType2["AXELAR_TRANSFER_CONTRACT_CALL_WITH_TOKEN"] = "AXELAR_TRANSFER_CONTRACT_CALL_WITH_TOKEN";
51
+ AxelarTransferType2["AXELAR_TRANSFER_SEND_TOKEN"] = "AXELAR_TRANSFER_SEND_TOKEN";
52
+ return AxelarTransferType2;
53
+ })(AxelarTransferType || {});
54
+ var CCTPTransferState = /* @__PURE__ */ ((CCTPTransferState2) => {
55
+ CCTPTransferState2["CCTP_TRANSFER_UNKNOWN"] = "CCTP_TRANSFER_UNKNOWN";
56
+ CCTPTransferState2["CCTP_TRANSFER_SENT"] = "CCTP_TRANSFER_SENT";
57
+ CCTPTransferState2["CCTP_TRANSFER_PENDING_CONFIRMATION"] = "CCTP_TRANSFER_PENDING_CONFIRMATION";
58
+ CCTPTransferState2["CCTP_TRANSFER_CONFIRMED"] = "CCTP_TRANSFER_CONFIRMED";
59
+ CCTPTransferState2["CCTP_TRANSFER_RECEIVED"] = "CCTP_TRANSFER_RECEIVED";
60
+ return CCTPTransferState2;
61
+ })(CCTPTransferState || {});
62
+ var StargateTransferState = /* @__PURE__ */ ((StargateTransferState2) => {
63
+ StargateTransferState2["STARGATE_TRANSFER_UNKNOWN"] = "STARGATE_TRANSFER_UNKNOWN";
64
+ StargateTransferState2["STARGATE_TRANSFER_SENT"] = "STARGATE_TRANSFER_SENT";
65
+ StargateTransferState2["STARGATE_TRANSFER_PENDING_CONFIRMATION"] = "STARGATE_TRANSFER_PENDING_CONFIRMATION";
66
+ StargateTransferState2["STARGATE_TRANSFER_CONFIRMED"] = "STARGATE_TRANSFER_CONFIRMED";
67
+ StargateTransferState2["STARGATE_TRANSFER_RECEIVED"] = "STARGATE_TRANSFER_RECEIVED";
68
+ StargateTransferState2["STARGATE_TRANSFER_FAILED"] = "STARGATE_TRANSFER_FAILED";
69
+ return StargateTransferState2;
70
+ })(StargateTransferState || {});
71
+ var GoFastTransferState = /* @__PURE__ */ ((GoFastTransferState2) => {
72
+ GoFastTransferState2["GO_FAST_TRANSFER_UNKNOWN"] = "GO_FAST_TRANSFER_UNKNOWN";
73
+ GoFastTransferState2["GO_FAST_TRANSFER_SENT"] = "GO_FAST_TRANSFER_SENT";
74
+ GoFastTransferState2["GO_FAST_POST_ACTION_FAILED"] = "GO_FAST_POST_ACTION_FAILED";
75
+ GoFastTransferState2["GO_FAST_TRANSFER_TIMEOUT"] = "GO_FAST_TRANSFER_TIMEOUT";
76
+ GoFastTransferState2["GO_FAST_TRANSFER_FILLED"] = "GO_FAST_TRANSFER_FILLED";
77
+ GoFastTransferState2["GO_FAST_TRANSFER_REFUNDED"] = "GO_FAST_TRANSFER_REFUNDED";
78
+ return GoFastTransferState2;
79
+ })(GoFastTransferState || {});
80
+ var BridgeType = /* @__PURE__ */ ((BridgeType2) => {
81
+ BridgeType2["IBC"] = "IBC";
82
+ BridgeType2["AXELAR"] = "AXELAR";
83
+ BridgeType2["CCTP"] = "CCTP";
84
+ BridgeType2["HYPERLANE"] = "HYPERLANE";
85
+ BridgeType2["OPINIT"] = "OPINIT";
86
+ BridgeType2["GO_FAST"] = "GO_FAST";
87
+ BridgeType2["STARGATE"] = "STARGATE";
88
+ BridgeType2["EUREKA"] = "EUREKA";
89
+ return BridgeType2;
90
+ })(BridgeType || {});
91
+ var ChainType = /* @__PURE__ */ ((ChainType2) => {
92
+ ChainType2["Cosmos"] = "cosmos";
93
+ ChainType2["Evm"] = "evm";
94
+ ChainType2["Svm"] = "svm";
95
+ return ChainType2;
96
+ })(ChainType || {});
97
+ var ContractCallWithTokenErrorType = /* @__PURE__ */ ((ContractCallWithTokenErrorType2) => {
98
+ ContractCallWithTokenErrorType2["CONTRACT_CALL_WITH_TOKEN_EXECUTION_ERROR"] = "CONTRACT_CALL_WITH_TOKEN_EXECUTION_ERROR";
99
+ return ContractCallWithTokenErrorType2;
100
+ })(ContractCallWithTokenErrorType || {});
101
+ var HyperlaneTransferState = /* @__PURE__ */ ((HyperlaneTransferState2) => {
102
+ HyperlaneTransferState2["HYPERLANE_TRANSFER_UNKNOWN"] = "HYPERLANE_TRANSFER_UNKNOWN";
103
+ HyperlaneTransferState2["HYPERLANE_TRANSFER_SENT"] = "HYPERLANE_TRANSFER_SENT";
104
+ HyperlaneTransferState2["HYPERLANE_TRANSFER_FAILED"] = "HYPERLANE_TRANSFER_FAILED";
105
+ HyperlaneTransferState2["HYPERLANE_TRANSFER_RECEIVED"] = "HYPERLANE_TRANSFER_RECEIVED";
106
+ return HyperlaneTransferState2;
107
+ })(HyperlaneTransferState || {});
108
+ var PacketErrorType = /* @__PURE__ */ ((PacketErrorType2) => {
109
+ PacketErrorType2["PACKET_ERROR_UNKNOWN"] = "PACKET_ERROR_UNKNOWN";
110
+ PacketErrorType2["PACKET_ERROR_ACKNOWLEDGEMENT"] = "PACKET_ERROR_ACKNOWLEDGEMENT";
111
+ PacketErrorType2["PACKET_ERROR_TIMEOUT"] = "PACKET_ERROR_TIMEOUT";
112
+ return PacketErrorType2;
113
+ })(PacketErrorType || {});
114
+ var Reason = /* @__PURE__ */ ((Reason2) => {
115
+ Reason2["UNKNOWN"] = "UNKNOWN";
116
+ Reason2["MOST_LIQUID"] = "MOST_LIQUID";
117
+ Reason2["BASE_TOKEN"] = "BASE_TOKEN";
118
+ Reason2["DIRECT"] = "DIRECT";
119
+ return Reason2;
120
+ })(Reason || {});
121
+ var RoutePriceWarningType = /* @__PURE__ */ ((RoutePriceWarningType2) => {
122
+ RoutePriceWarningType2["LOW_INFO_WARNING"] = "LOW_INFO_WARNING";
123
+ RoutePriceWarningType2["BAD_PRICE_WARNING"] = "BAD_PRICE_WARNING";
124
+ return RoutePriceWarningType2;
125
+ })(RoutePriceWarningType || {});
126
+ var SendTokenErrorType = /* @__PURE__ */ ((SendTokenErrorType2) => {
127
+ SendTokenErrorType2["SEND_TOKEN_EXECUTION_ERROR"] = "SEND_TOKEN_EXECUTION_ERROR";
128
+ return SendTokenErrorType2;
129
+ })(SendTokenErrorType || {});
130
+ var StatusErrorType = /* @__PURE__ */ ((StatusErrorType2) => {
131
+ StatusErrorType2["STATUS_ERROR_UNKNOWN"] = "STATUS_ERROR_UNKNOWN";
132
+ StatusErrorType2["STATUS_ERROR_TRANSACTION_EXECUTION"] = "STATUS_ERROR_TRANSACTION_EXECUTION";
133
+ StatusErrorType2["STATUS_ERROR_INDEXING"] = "STATUS_ERROR_INDEXING";
134
+ StatusErrorType2["STATUS_ERROR_TRANSFER"] = "STATUS_ERROR_TRANSFER";
135
+ return StatusErrorType2;
136
+ })(StatusErrorType || {});
137
+ var TransactionState = /* @__PURE__ */ ((TransactionState2) => {
138
+ TransactionState2["STATE_SUBMITTED"] = "STATE_SUBMITTED";
139
+ TransactionState2["STATE_PENDING"] = "STATE_PENDING";
140
+ TransactionState2["STATE_COMPLETED_SUCCESS"] = "STATE_COMPLETED_SUCCESS";
141
+ TransactionState2["STATE_COMPLETED_ERROR"] = "STATE_COMPLETED_ERROR";
142
+ TransactionState2["STATE_ABANDONED"] = "STATE_ABANDONED";
143
+ TransactionState2["STATE_PENDING_ERROR"] = "STATE_PENDING_ERROR";
144
+ return TransactionState2;
145
+ })(TransactionState || {});
146
+ var OPInitTransferState = /* @__PURE__ */ ((OPInitTransferState2) => {
147
+ OPInitTransferState2["OPINIT_TRANSFER_UNKNOWN"] = "OPINIT_TRANSFER_UNKNOWN";
148
+ OPInitTransferState2["OPINIT_TRANSFER_SENT"] = "OPINIT_TRANSFER_SENT";
149
+ OPInitTransferState2["OPINIT_TRANSFER_RECEIVED"] = "OPINIT_TRANSFER_RECEIVED";
150
+ return OPInitTransferState2;
151
+ })(OPInitTransferState || {});
152
+ var LayerZeroTransferState = /* @__PURE__ */ ((LayerZeroTransferState2) => {
153
+ LayerZeroTransferState2["LAYER_ZERO_TRANSFER_UNKNOWN"] = "LAYER_ZERO_TRANSFER_UNKNOWN";
154
+ LayerZeroTransferState2["LAYER_ZERO_TRANSFER_SENT"] = "LAYER_ZERO_TRANSFER_SENT";
155
+ LayerZeroTransferState2["LAYER_ZERO_TRANSFER_RECEIVED"] = "LAYER_ZERO_TRANSFER_RECEIVED";
156
+ LayerZeroTransferState2["LAYER_ZERO_TRANSFER_FAILED"] = "LAYER_ZERO_TRANSFER_FAILED";
157
+ return LayerZeroTransferState2;
158
+ })(LayerZeroTransferState || {});
159
+ var TransferState = /* @__PURE__ */ ((TransferState2) => {
160
+ TransferState2["TRANSFER_UNKNOWN"] = "TRANSFER_UNKNOWN";
161
+ TransferState2["TRANSFER_PENDING"] = "TRANSFER_PENDING";
162
+ TransferState2["TRANSFER_RECEIVED"] = "TRANSFER_RECEIVED";
163
+ TransferState2["TRANSFER_SUCCESS"] = "TRANSFER_SUCCESS";
164
+ TransferState2["TRANSFER_FAILURE"] = "TRANSFER_FAILURE";
165
+ return TransferState2;
166
+ })(TransferState || {});
167
+ var FeeType = /* @__PURE__ */ ((FeeType2) => {
168
+ FeeType2["SMART_RELAY"] = "SMART_RELAY";
169
+ return FeeType2;
170
+ })(FeeType || {});
171
+ var ContentType = /* @__PURE__ */ ((ContentType2) => {
172
+ ContentType2["Json"] = "application/json";
173
+ ContentType2["FormData"] = "multipart/form-data";
174
+ ContentType2["UrlEncoded"] = "application/x-www-form-urlencoded";
175
+ ContentType2["Text"] = "text/plain";
176
+ return ContentType2;
177
+ })(ContentType || {});
178
+ var HttpClient = class {
179
+ constructor(apiConfig = {}) {
180
+ this.baseUrl = "https://api.skip.build";
181
+ this.securityData = null;
182
+ this.abortControllers = /* @__PURE__ */ new Map();
183
+ this.customFetch = (...fetchParams) => fetch(...fetchParams);
184
+ this.baseApiParams = {
185
+ credentials: "same-origin",
186
+ headers: {},
187
+ redirect: "follow",
188
+ referrerPolicy: "no-referrer"
189
+ };
190
+ this.setSecurityData = (data) => {
191
+ this.securityData = data;
192
+ };
193
+ this.contentFormatters = {
194
+ ["application/json" /* Json */]: (input) => input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input,
195
+ ["text/plain" /* Text */]: (input) => input !== null && typeof input !== "string" ? JSON.stringify(input) : input,
196
+ ["multipart/form-data" /* FormData */]: (input) => Object.keys(input || {}).reduce((formData, key) => {
197
+ const property = input[key];
198
+ formData.append(
199
+ key,
200
+ property instanceof Blob ? property : typeof property === "object" && property !== null ? JSON.stringify(property) : `${property}`
201
+ );
202
+ return formData;
203
+ }, new FormData()),
204
+ ["application/x-www-form-urlencoded" /* UrlEncoded */]: (input) => this.toQueryString(input)
205
+ };
206
+ this.createAbortSignal = (cancelToken) => {
207
+ if (this.abortControllers.has(cancelToken)) {
208
+ const abortController2 = this.abortControllers.get(cancelToken);
209
+ if (abortController2) {
210
+ return abortController2.signal;
211
+ }
212
+ return void 0;
213
+ }
214
+ const abortController = new AbortController();
215
+ this.abortControllers.set(cancelToken, abortController);
216
+ return abortController.signal;
217
+ };
218
+ this.abortRequest = (cancelToken) => {
219
+ const abortController = this.abortControllers.get(cancelToken);
220
+ if (abortController) {
221
+ abortController.abort();
222
+ this.abortControllers.delete(cancelToken);
223
+ }
224
+ };
225
+ this.request = (_a) => __async(this, null, function* () {
226
+ var _b = _a, {
227
+ body,
228
+ secure,
229
+ path,
230
+ type,
231
+ query,
232
+ format,
233
+ baseUrl,
234
+ cancelToken
235
+ } = _b, params = __objRest(_b, [
236
+ "body",
237
+ "secure",
238
+ "path",
239
+ "type",
240
+ "query",
241
+ "format",
242
+ "baseUrl",
243
+ "cancelToken"
244
+ ]);
245
+ const secureParams = (typeof secure === "boolean" ? secure : this.baseApiParams.secure) && this.securityWorker && (yield this.securityWorker(this.securityData)) || {};
246
+ const requestParams = this.mergeRequestParams(params, secureParams);
247
+ const queryString = query && this.toQueryString(query);
248
+ const payloadFormatter = this.contentFormatters[type || "application/json" /* Json */];
249
+ const responseFormat = format || requestParams.format;
250
+ return this.customFetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, __spreadProps(__spreadValues({}, requestParams), {
251
+ headers: __spreadValues(__spreadValues({}, requestParams.headers || {}), type && type !== "multipart/form-data" /* FormData */ ? { "Content-Type": type } : {}),
252
+ signal: (cancelToken ? this.createAbortSignal(cancelToken) : requestParams.signal) || null,
253
+ body: typeof body === "undefined" || body === null ? null : payloadFormatter(body)
254
+ })).then((response) => __async(this, null, function* () {
255
+ const r = response.clone();
256
+ r.data = null;
257
+ r.error = null;
258
+ const data = !responseFormat ? r : yield response[responseFormat]().then((data2) => {
259
+ if (r.ok) {
260
+ r.data = data2;
261
+ } else {
262
+ r.error = data2;
263
+ }
264
+ return r;
265
+ }).catch((e) => {
266
+ r.error = e;
267
+ return r;
268
+ });
269
+ if (cancelToken) {
270
+ this.abortControllers.delete(cancelToken);
271
+ }
272
+ if (!response.ok) throw data;
273
+ return data;
274
+ }));
275
+ });
276
+ Object.assign(this, apiConfig);
277
+ }
278
+ encodeQueryParam(key, value) {
279
+ const encodedKey = encodeURIComponent(key);
280
+ return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`;
281
+ }
282
+ addQueryParam(query, key) {
283
+ return this.encodeQueryParam(key, query[key]);
284
+ }
285
+ addArrayQueryParam(query, key) {
286
+ const value = query[key];
287
+ return value.map((v) => this.encodeQueryParam(key, v)).join("&");
288
+ }
289
+ toQueryString(rawQuery) {
290
+ const query = rawQuery || {};
291
+ const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]);
292
+ return keys.map((key) => Array.isArray(query[key]) ? this.addArrayQueryParam(query, key) : this.addQueryParam(query, key)).join("&");
293
+ }
294
+ addQueryParams(rawQuery) {
295
+ const queryString = this.toQueryString(rawQuery);
296
+ return queryString ? `?${queryString}` : "";
297
+ }
298
+ mergeRequestParams(params1, params2) {
299
+ return __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, this.baseApiParams), params1), params2 || {}), {
300
+ headers: __spreadValues(__spreadValues(__spreadValues({}, this.baseApiParams.headers || {}), params1.headers || {}), params2 && params2.headers || {})
301
+ });
302
+ }
303
+ };
304
+ var Api = class extends HttpClient {
305
+ constructor() {
306
+ super(...arguments);
307
+ /**
308
+ * @description Get all supported chains along with additional data useful for building applications + frontends that interface with them (e.g. logo URI, IBC capabilities, fee assets, bech32 prefix, etc...)
309
+ *
310
+ * @tags Info
311
+ * @name GetChains
312
+ * @request GET:/v2/info/chains
313
+ */
314
+ this.getChains = (query, params = {}) => this.request(__spreadValues({
315
+ path: `/v2/info/chains`,
316
+ method: "GET",
317
+ query,
318
+ format: "json"
319
+ }, params));
320
+ /**
321
+ * @description Get the balances of a given set of assets on a given chain and wallet address. Compatible with all Skip Go-supported assets, excluding CW20 assets, across SVM, EVM, and Cosmos chains.
322
+ *
323
+ * @tags Info
324
+ * @name GetBalances
325
+ * @request POST:/v2/info/balances
326
+ */
327
+ this.getBalances = (data, params = {}) => this.request(__spreadValues({
328
+ path: `/v2/info/balances`,
329
+ method: "POST",
330
+ body: data,
331
+ type: "application/json" /* Json */,
332
+ format: "json"
333
+ }, params));
334
+ /**
335
+ * @description Get all supported bridges
336
+ *
337
+ * @tags Info
338
+ * @name GetBridges
339
+ * @request GET:/v2/info/bridges
340
+ */
341
+ this.getBridges = (params = {}) => this.request(__spreadValues({
342
+ path: `/v2/info/bridges`,
343
+ method: "GET",
344
+ format: "json"
345
+ }, params));
346
+ /**
347
+ * @description Get supported swap venues.
348
+ *
349
+ * @tags Fungible
350
+ * @name GetVenues
351
+ * @request GET:/v2/fungible/venues
352
+ */
353
+ this.getVenues = (query, params = {}) => this.request(__spreadValues({
354
+ path: `/v2/fungible/venues`,
355
+ method: "GET",
356
+ query,
357
+ format: "json"
358
+ }, params));
359
+ /**
360
+ * @description Get supported assets. Optionally limit to assets on a given chain and/or native assets.
361
+ *
362
+ * @tags Fungible
363
+ * @name GetAssets
364
+ * @request GET:/v2/fungible/assets
365
+ */
366
+ this.getAssets = (query, params = {}) => this.request(__spreadValues({
367
+ path: `/v2/fungible/assets`,
368
+ method: "GET",
369
+ query,
370
+ format: "json"
371
+ }, params));
372
+ /**
373
+ * @description Get assets that can be reached from a source via transfers under different conditions (e.g. single vs multiple txs)
374
+ *
375
+ * @tags Fungible
376
+ * @name GetAssetsFromSource
377
+ * @request POST:/v2/fungible/assets_from_source
378
+ */
379
+ this.getAssetsFromSource = (data, params = {}) => this.request(__spreadValues({
380
+ path: `/v2/fungible/assets_from_source`,
381
+ method: "POST",
382
+ body: data,
383
+ type: "application/json" /* Json */,
384
+ format: "json"
385
+ }, params));
386
+ /**
387
+ * @description This supports cross-chain actions among EVM chains, Cosmos chains, and between them. Returns the sequence of transfers and/or swaps to reach the given destination asset from the given source asset, along with estimated amount out. Commonly called before /msgs to generate route info and quote.
388
+ *
389
+ * @tags Fungible
390
+ * @name GetRouteV2
391
+ * @request POST:/v2/fungible/route
392
+ */
393
+ this.getRouteV2 = (data, params = {}) => this.request(__spreadValues({
394
+ path: `/v2/fungible/route`,
395
+ method: "POST",
396
+ body: data,
397
+ type: "application/json" /* Json */,
398
+ format: "json"
399
+ }, params));
400
+ /**
401
+ * @description This supports cross-chain actions among EVM chains, Cosmos chains, and between them. Returns minimal number of messages required to execute a multi-chain swap or transfer. Input consists of the output of route with additional information required for message construction (e.g. destination addresses for each chain)
402
+ *
403
+ * @tags Fungible
404
+ * @name GetMsgsV2
405
+ * @request POST:/v2/fungible/msgs
406
+ */
407
+ this.getMsgsV2 = (data, params = {}) => this.request(__spreadValues({
408
+ path: `/v2/fungible/msgs`,
409
+ method: "POST",
410
+ body: data,
411
+ type: "application/json" /* Json */,
412
+ format: "json"
413
+ }, params));
414
+ /**
415
+ * @description This supports cross-chain actions among EVM chains, Cosmos chains, and between them. Returns minimal number of messages required to execute a multi-chain swap or transfer. This is a convenience endpoint that combines /route and /msgs into a single call.
416
+ *
417
+ * @tags Fungible
418
+ * @name GetMsgsDirectV2
419
+ * @request POST:/v2/fungible/msgs_direct
420
+ */
421
+ this.getMsgsDirectV2 = (data, params = {}) => this.request(__spreadValues({
422
+ path: `/v2/fungible/msgs_direct`,
423
+ method: "POST",
424
+ body: data,
425
+ type: "application/json" /* Json */,
426
+ format: "json"
427
+ }, params));
428
+ /**
429
+ * @description Request asset recommendations for the given source assets on a given destination chain. The response includes recommended destination assets and recommendation reasons.
430
+ *
431
+ * @tags Fungible
432
+ * @name GetAssetRecommendations
433
+ * @request POST:/v2/fungible/recommend_assets
434
+ */
435
+ this.getAssetRecommendations = (data, params = {}) => this.request(__spreadValues({
436
+ path: `/v2/fungible/recommend_assets`,
437
+ method: "POST",
438
+ body: data,
439
+ type: "application/json" /* Json */,
440
+ format: "json"
441
+ }, params));
442
+ /**
443
+ * @description Submit a signed base64 encoded transaction to be broadcast to the specified network. On successful submission, the status of the transaction and any subsequent IBC or Axelar transfers can be queried through the /status endpoint.
444
+ *
445
+ * @tags Transaction
446
+ * @name SubmitTransactionV2
447
+ * @request POST:/v2/tx/submit
448
+ */
449
+ this.submitTransactionV2 = (data, params = {}) => this.request(__spreadValues({
450
+ path: `/v2/tx/submit`,
451
+ method: "POST",
452
+ body: data,
453
+ type: "application/json" /* Json */,
454
+ format: "json"
455
+ }, params));
456
+ /**
457
+ * @description Requests tracking of a transaction that has already landed on-chain but was not broadcast through the Skip Go API. The status of a tracked transaction and subsequent IBC or Axelar transfers if routing assets cross chain can be queried through the /status endpoint.
458
+ *
459
+ * @tags Transaction
460
+ * @name TrackTransactionV2
461
+ * @request POST:/v2/tx/track
462
+ */
463
+ this.trackTransactionV2 = (data, params = {}) => this.request(__spreadValues({
464
+ path: `/v2/tx/track`,
465
+ method: "POST",
466
+ body: data,
467
+ type: "application/json" /* Json */,
468
+ format: "json"
469
+ }, params));
470
+ /**
471
+ * @description Get the status of the specified transaction and any subsequent IBC or Axelar transfers if routing assets cross chain. The transaction must have previously been submitted to either the /submit or /track endpoints.
472
+ *
473
+ * @tags Transaction
474
+ * @name GetTransactionStatusV2
475
+ * @request GET:/v2/tx/status
476
+ */
477
+ this.getTransactionStatusV2 = (query, params = {}) => this.request(__spreadValues({
478
+ path: `/v2/tx/status`,
479
+ method: "GET",
480
+ query,
481
+ format: "json"
482
+ }, params));
483
+ /**
484
+ * @description Get origin assets from a given list of denoms and chain IDs.
485
+ *
486
+ * @tags Fungible
487
+ * @name GetOriginAssets
488
+ * @request POST:/v2/fungible/ibc_origin_assets
489
+ */
490
+ this.getOriginAssets = (data, params = {}) => this.request(__spreadValues({
491
+ path: `/v2/fungible/ibc_origin_assets`,
492
+ method: "POST",
493
+ body: data,
494
+ type: "application/json" /* Json */,
495
+ format: "json"
496
+ }, params));
497
+ /**
498
+ * @description Given 2 chain IDs, returns a list of equivalent assets that can be transferred
499
+ *
500
+ * @tags Fungible
501
+ * @name FungibleAssetsBetweenChainsCreate
502
+ * @request POST:/v2/fungible/assets_between_chains
503
+ */
504
+ this.fungibleAssetsBetweenChainsCreate = (data, params = {}) => this.request(__spreadValues({
505
+ path: `/v2/fungible/assets_between_chains`,
506
+ method: "POST",
507
+ body: data,
508
+ type: "application/json" /* Json */,
509
+ format: "json"
510
+ }, params));
511
+ }
512
+ };
513
+
514
+ // src/private-functions/getRestEndpointForChain.ts
515
+ var getRestEndpointForChain = (chainId) => __async(void 0, null, function* () {
516
+ var _a, _b, _c, _d, _e;
517
+ if (ClientState.endpointOptions.getRestEndpointForChain) {
518
+ return ClientState.endpointOptions.getRestEndpointForChain(chainId);
519
+ }
520
+ if (ClientState.endpointOptions.endpoints && ClientState.endpointOptions.endpoints[chainId]) {
521
+ const endpointOptions = ClientState.endpointOptions.endpoints[chainId];
522
+ if (endpointOptions == null ? void 0 : endpointOptions.rest) {
523
+ return endpointOptions.rest;
524
+ }
525
+ }
526
+ const chain = chains().find((chain2) => chain2.chain_id === chainId);
527
+ if (!chain) {
528
+ throw new Error(
529
+ `getRestEndpointForChain error: failed to find chain id '${chainId}' in registry`
530
+ );
531
+ }
532
+ if (((_b = (_a = chain.apis) == null ? void 0 : _a.rest) == null ? void 0 : _b.length) === 0 || !((_c = chain.apis) == null ? void 0 : _c.rest)) {
533
+ throw new Error(
534
+ `getRpcEndpointForChain error: failed to find RPC endpoint for chain '${chainId}'`
535
+ );
536
+ }
537
+ const endpoints = (_e = (_d = chain.apis) == null ? void 0 : _d.rest) == null ? void 0 : _e.map((api) => api.address);
538
+ const endpoint = yield findFirstWorkingEndpoint(endpoints, "rest");
539
+ if (!endpoint) {
540
+ throw new Error(
541
+ `getRestEndpointForChain error: failed to find REST endpoint for chain '${chainId}'`
542
+ );
543
+ }
544
+ return endpoint;
545
+ });
546
+
547
+ // src/private-functions/getAccountNumberAndSequence.ts
548
+ var getAccountNumberAndSequence = (address, chainId) => __async(void 0, null, function* () {
549
+ var _a;
550
+ if (chainId.includes("dymension")) {
551
+ return getAccountNumberAndSequenceFromDymension(address, chainId);
552
+ }
553
+ const endpoint = yield getRpcEndpointForChain(chainId);
554
+ const client = (_a = ClientState.signingStargateClientByChainId[chainId]) != null ? _a : yield StargateClient.connect(endpoint, {
555
+ accountParser
556
+ });
557
+ const account = yield client.getAccount(address);
558
+ if (!account) {
559
+ throw new Error("getAccountNumberAndSequence: failed to retrieve account");
560
+ }
561
+ client.disconnect();
562
+ return {
563
+ accountNumber: account.accountNumber,
564
+ sequence: account.sequence
565
+ };
566
+ });
567
+ var getAccountNumberAndSequenceFromDymension = (address, chainId) => __async(void 0, null, function* () {
568
+ const endpoint = yield getRestEndpointForChain(chainId);
569
+ const jsonResponse = yield createRequestClient({
570
+ baseUrl: `${endpoint}/cosmos/auth/v1beta1/accounts/${address}`
571
+ }).get();
572
+ const response = toCamel(jsonResponse);
573
+ let sequence = 0;
574
+ let accountNumber = 0;
575
+ if (response.account.baseAccount) {
576
+ sequence = response.account.baseAccount.sequence;
577
+ accountNumber = response.account.baseAccount.accountNumber;
578
+ } else {
579
+ sequence = response.account.sequence;
580
+ accountNumber = response.account.accountNumber;
581
+ }
582
+ return {
583
+ accountNumber,
584
+ sequence
585
+ };
586
+ });
587
+ function createBaseClawbackVestingAccount() {
588
+ return {
589
+ baseVestingAccount: void 0,
590
+ funderAddress: "",
591
+ startTime: /* @__PURE__ */ new Date(),
592
+ lockupPeriods: [],
593
+ vestingPeriods: []
594
+ };
595
+ }
596
+ var ClawbackVestingAccount = {
597
+ typeUrl: "/evmos.vesting.v2.ClawbackVestingAccount",
598
+ encode(message, writer = _m0.Writer.create()) {
599
+ if (message.baseVestingAccount !== void 0) {
600
+ BaseVestingAccount.encode(message.baseVestingAccount, writer.uint32(10).fork()).ldelim();
601
+ }
602
+ if (message.funderAddress !== "") {
603
+ writer.uint32(18).string(message.funderAddress);
604
+ }
605
+ if (message.startTime !== void 0) {
606
+ Timestamp.encode(toTimestamp(message.startTime), writer.uint32(26).fork()).ldelim();
607
+ }
608
+ for (const v of message.lockupPeriods) {
609
+ Period.encode(v, writer.uint32(34).fork()).ldelim();
610
+ }
611
+ for (const v of message.vestingPeriods) {
612
+ Period.encode(v, writer.uint32(42).fork()).ldelim();
613
+ }
614
+ return writer;
615
+ },
616
+ decode(input, length) {
617
+ const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
618
+ let end = length === void 0 ? reader.len : reader.pos + length;
619
+ const message = createBaseClawbackVestingAccount();
620
+ while (reader.pos < end) {
621
+ const tag = reader.uint32();
622
+ switch (tag >>> 3) {
623
+ case 1:
624
+ message.baseVestingAccount = BaseVestingAccount.decode(reader, reader.uint32());
625
+ break;
626
+ case 2:
627
+ message.funderAddress = reader.string();
628
+ break;
629
+ case 3:
630
+ message.startTime = fromTimestamp(Timestamp.decode(reader, reader.uint32()));
631
+ break;
632
+ case 4:
633
+ message.lockupPeriods.push(Period.decode(reader, reader.uint32()));
634
+ break;
635
+ case 5:
636
+ message.vestingPeriods.push(Period.decode(reader, reader.uint32()));
637
+ break;
638
+ default:
639
+ reader.skipType(tag & 7);
640
+ break;
641
+ }
642
+ }
643
+ return message;
644
+ },
645
+ fromJSON(object) {
646
+ return {
647
+ baseVestingAccount: isSet(object.baseVestingAccount) ? BaseVestingAccount.fromJSON(object.baseVestingAccount) : void 0,
648
+ funderAddress: isSet(object.funderAddress) ? String(object.funderAddress) : "",
649
+ startTime: isSet(object.startTime) ? fromJsonTimestamp(object.startTime) : void 0,
650
+ lockupPeriods: Array.isArray(object == null ? void 0 : object.lockupPeriods) ? object.lockupPeriods.map((e) => Period.fromJSON(e)) : [],
651
+ vestingPeriods: Array.isArray(object == null ? void 0 : object.vestingPeriods) ? object.vestingPeriods.map((e) => Period.fromJSON(e)) : []
652
+ };
653
+ },
654
+ toJSON(message) {
655
+ const obj = {};
656
+ message.baseVestingAccount !== void 0 && (obj.baseVestingAccount = message.baseVestingAccount ? BaseVestingAccount.toJSON(message.baseVestingAccount) : void 0);
657
+ message.funderAddress !== void 0 && (obj.funderAddress = message.funderAddress);
658
+ message.startTime !== void 0 && (obj.startTime = message.startTime.toISOString());
659
+ if (message.lockupPeriods) {
660
+ obj.lockupPeriods = message.lockupPeriods.map((e) => e ? Period.toJSON(e) : void 0);
661
+ } else {
662
+ obj.lockupPeriods = [];
663
+ }
664
+ if (message.vestingPeriods) {
665
+ obj.vestingPeriods = message.vestingPeriods.map((e) => e ? Period.toJSON(e) : void 0);
666
+ } else {
667
+ obj.vestingPeriods = [];
668
+ }
669
+ return obj;
670
+ },
671
+ fromPartial(object) {
672
+ var _a, _b, _c, _d;
673
+ const message = createBaseClawbackVestingAccount();
674
+ message.baseVestingAccount = object.baseVestingAccount !== void 0 && object.baseVestingAccount !== null ? BaseVestingAccount.fromPartial(object.baseVestingAccount) : void 0;
675
+ message.funderAddress = (_a = object.funderAddress) != null ? _a : "";
676
+ message.startTime = (_b = object.startTime) != null ? _b : void 0;
677
+ message.lockupPeriods = ((_c = object.lockupPeriods) == null ? void 0 : _c.map((e) => Period.fromPartial(e))) || [];
678
+ message.vestingPeriods = ((_d = object.vestingPeriods) == null ? void 0 : _d.map((e) => Period.fromPartial(e))) || [];
679
+ return message;
680
+ },
681
+ fromAmino(object) {
682
+ var _a, _b;
683
+ const message = createBaseClawbackVestingAccount();
684
+ if (object.base_vesting_account !== void 0 && object.base_vesting_account !== null) {
685
+ message.baseVestingAccount = BaseVestingAccount.fromAmino(object.base_vesting_account);
686
+ }
687
+ if (object.funder_address !== void 0 && object.funder_address !== null) {
688
+ message.funderAddress = object.funder_address;
689
+ }
690
+ if (object.start_time !== void 0 && object.start_time !== null) {
691
+ message.startTime = fromTimestamp(Timestamp.fromAmino(object.start_time));
692
+ }
693
+ message.lockupPeriods = ((_a = object.lockup_periods) == null ? void 0 : _a.map((e) => Period.fromAmino(e))) || [];
694
+ message.vestingPeriods = ((_b = object.vesting_periods) == null ? void 0 : _b.map((e) => Period.fromAmino(e))) || [];
695
+ return message;
696
+ },
697
+ toAmino(message) {
698
+ const obj = {};
699
+ obj.base_vesting_account = message.baseVestingAccount ? BaseVestingAccount.toAmino(message.baseVestingAccount) : void 0;
700
+ obj.funder_address = message.funderAddress === "" ? void 0 : message.funderAddress;
701
+ obj.start_time = message.startTime ? Timestamp.toAmino(toTimestamp(message.startTime)) : void 0;
702
+ if (message.lockupPeriods) {
703
+ obj.lockup_periods = message.lockupPeriods.map((e) => e ? Period.toAmino(e) : void 0);
704
+ } else {
705
+ obj.lockup_periods = message.lockupPeriods;
706
+ }
707
+ if (message.vestingPeriods) {
708
+ obj.vesting_periods = message.vestingPeriods.map((e) => e ? Period.toAmino(e) : void 0);
709
+ } else {
710
+ obj.vesting_periods = message.vestingPeriods;
711
+ }
712
+ return obj;
713
+ },
714
+ fromAminoMsg(object) {
715
+ return ClawbackVestingAccount.fromAmino(object.value);
716
+ },
717
+ toAminoMsg(message) {
718
+ return {
719
+ type: "vesting/ClawbackVestingAccount",
720
+ value: ClawbackVestingAccount.toAmino(message)
721
+ };
722
+ },
723
+ fromProtoMsg(message) {
724
+ return ClawbackVestingAccount.decode(message.value);
725
+ },
726
+ toProto(message) {
727
+ return ClawbackVestingAccount.encode(message).finish();
728
+ },
729
+ toProtoMsg(message) {
730
+ return {
731
+ typeUrl: "/evmos.vesting.v2.ClawbackVestingAccount",
732
+ value: ClawbackVestingAccount.encode(message).finish()
733
+ };
734
+ }
735
+ };
736
+
737
+ // src/private-functions/cosmos/getEncodeObjectFromCosmosMessage.ts
738
+ function getEncodeObjectFromCosmosMessage(message) {
739
+ var _a, _b;
740
+ const msgJson = JSON.parse((_a = message.msg) != null ? _a : "");
741
+ if (message.msgTypeUrl === "/ibc.applications.transfer.v1.MsgTransfer") {
742
+ return {
743
+ typeUrl: "/ibc.applications.transfer.v1.MsgTransfer",
744
+ value: MsgTransfer.fromJSON({
745
+ sourcePort: msgJson.source_port,
746
+ sourceChannel: msgJson.source_channel,
747
+ token: msgJson.token,
748
+ sender: msgJson.sender,
749
+ receiver: msgJson.receiver,
750
+ timeoutHeight: msgJson.timeout_height,
751
+ timeoutTimestamp: msgJson.timeout_timestamp,
752
+ memo: msgJson.memo
753
+ })
754
+ };
755
+ }
756
+ if (message.msgTypeUrl === "/cosmwasm.wasm.v1.MsgExecuteContract") {
757
+ return {
758
+ typeUrl: message.msgTypeUrl,
759
+ value: MsgExecuteContract.fromPartial({
760
+ sender: msgJson.sender,
761
+ contract: msgJson.contract,
762
+ msg: toUtf8(JSON.stringify(msgJson.msg)),
763
+ funds: msgJson.funds
764
+ })
765
+ };
766
+ }
767
+ if (message.msgTypeUrl === "/cosmos.bank.v1beta1.MsgSend") {
768
+ return {
769
+ typeUrl: message.msgTypeUrl,
770
+ value: MsgSend.fromPartial({
771
+ fromAddress: msgJson.from_address,
772
+ toAddress: msgJson.to_address,
773
+ amount: msgJson.amount
774
+ })
775
+ };
776
+ }
777
+ if (message.msgTypeUrl === "/circle.cctp.v1.MsgDepositForBurn") {
778
+ return {
779
+ typeUrl: message.msgTypeUrl,
780
+ value: MsgDepositForBurn.fromAmino(msgJson)
781
+ };
782
+ }
783
+ if (message.msgTypeUrl === "/circle.cctp.v1.MsgDepositForBurnWithCaller") {
784
+ return {
785
+ typeUrl: message.msgTypeUrl,
786
+ value: MsgDepositForBurnWithCaller.fromAmino(msgJson)
787
+ };
788
+ }
789
+ if (message.msgTypeUrl === "/initia.move.v1.MsgExecute") {
790
+ return {
791
+ typeUrl: message.msgTypeUrl,
792
+ value: MsgExecute.fromPartial({
793
+ sender: msgJson.sender,
794
+ moduleAddress: msgJson.module_address,
795
+ moduleName: msgJson.module_name,
796
+ functionName: msgJson.function_name,
797
+ args: msgJson.args
798
+ })
799
+ };
800
+ }
801
+ if (message.msgTypeUrl === "/opinit.ophost.v1.MsgInitiateTokenDeposit") {
802
+ return {
803
+ typeUrl: message.msgTypeUrl,
804
+ value: MsgInitiateTokenDeposit.fromPartial({
805
+ sender: msgJson.sender,
806
+ to: msgJson.to,
807
+ amount: msgJson.amount,
808
+ bridgeId: msgJson.bridge_id
809
+ })
810
+ };
811
+ }
812
+ if (message.msgTypeUrl === "/evmos.vesting.v2.ClawbackVestingAccount") {
813
+ return {
814
+ typeUrl: message.msgTypeUrl,
815
+ value: ClawbackVestingAccount.fromPartial({
816
+ baseVestingAccount: msgJson.base_vesting_account,
817
+ funderAddress: msgJson.funder_address,
818
+ lockupPeriods: msgJson.lockup_periods,
819
+ startTime: msgJson.start_time,
820
+ vestingPeriods: msgJson.vesting_periods
821
+ })
822
+ };
823
+ }
824
+ return {
825
+ typeUrl: (_b = message.msgTypeUrl) != null ? _b : "",
826
+ value: msgJson
827
+ };
828
+ }
829
+ function getEncodeObjectFromCosmosMessageInjective(message) {
830
+ var _a;
831
+ const msgJson = JSON.parse((_a = message.msg) != null ? _a : "");
832
+ if (message.msgTypeUrl === "/ibc.applications.transfer.v1.MsgTransfer") {
833
+ return MsgTransfer$1.fromJSON({
834
+ port: msgJson.source_port,
835
+ channelId: msgJson.source_channel,
836
+ amount: msgJson.token,
837
+ sender: msgJson.sender,
838
+ receiver: msgJson.receiver,
839
+ timeout: msgJson.timeout_timestamp,
840
+ memo: msgJson.memo
841
+ });
842
+ }
843
+ if (message.msgTypeUrl === "/cosmwasm.wasm.v1.MsgExecuteContract") {
844
+ return MsgExecuteContractCompat.fromJSON({
845
+ sender: msgJson.sender,
846
+ contractAddress: msgJson.contract,
847
+ msg: msgJson.msg,
848
+ funds: msgJson.funds
849
+ });
850
+ }
851
+ throw new Error("Unsupported message type");
852
+ }
853
+ function createTransaction({
854
+ chainId,
855
+ message,
856
+ timeoutHeight,
857
+ memo = "",
858
+ fee = DEFAULT_STD_FEE,
859
+ signMode = 1,
860
+ pubKey,
861
+ accountNumber,
862
+ sequence
863
+ }) {
864
+ const signers = {
865
+ pubKey,
866
+ accountNumber,
867
+ sequence
868
+ };
869
+ return createTransactionWithSigners({
870
+ fee,
871
+ memo,
872
+ message,
873
+ signers,
874
+ chainId,
875
+ signMode,
876
+ timeoutHeight
877
+ });
878
+ }
879
+
880
+ // src/private-functions/cosmos/signCosmosMessageDirectEvmos.ts
881
+ var signCosmosMessageDirectEvmos = (_0, _1, _2, _3, _4) => __async(void 0, [_0, _1, _2, _3, _4], function* (signerAddress, signer, cosmosMsgs, fee, { accountNumber, sequence, chainId }) {
882
+ const accounts = yield signer.getAccounts();
883
+ const accountFromSigner = accounts.find((account) => account.address === signerAddress);
884
+ if (!accountFromSigner) {
885
+ throw new Error("signCosmosMessageDirectEvmos: failed to retrieve account from signer");
886
+ }
887
+ const messages2 = cosmosMsgs.map(
888
+ (cosmosMsg) => getEncodeObjectFromCosmosMessageInjective(cosmosMsg)
889
+ );
890
+ const pk = Buffer.from(accountFromSigner.pubkey).toString("base64");
891
+ const { signDoc } = createTransaction({
892
+ pubKey: pk,
893
+ chainId,
894
+ message: messages2,
895
+ sequence,
896
+ accountNumber,
897
+ timeoutHeight: 0,
898
+ fee
899
+ });
900
+ const directSignResponse = yield signer.signDirect(signerAddress, signDoc);
901
+ return TxRaw.fromPartial({
902
+ bodyBytes: directSignResponse.signed.bodyBytes,
903
+ authInfoBytes: directSignResponse.signed.authInfoBytes,
904
+ signatures: [fromBase64(directSignResponse.signature.signature)]
905
+ });
906
+ });
907
+ var signCosmosMessageDirectInjective = (_0, _1, _2, _3, _4) => __async(void 0, [_0, _1, _2, _3, _4], function* (signerAddress, signer, cosmosMsgs, fee, { accountNumber, sequence, chainId }) {
908
+ const accounts = yield signer.getAccounts();
909
+ const accountFromSigner = accounts.find((account) => account.address === signerAddress);
910
+ if (!accountFromSigner) {
911
+ throw new Error("signCosmosMessageDirectInjective: failed to retrieve account from signer");
912
+ }
913
+ const restEndpoint = yield getRestEndpointForChain(chainId);
914
+ const chainRestTendermintApi = new ChainRestTendermintApi(restEndpoint);
915
+ const latestBlock = yield chainRestTendermintApi.fetchLatestBlock();
916
+ const latestHeight = latestBlock.header.height;
917
+ const timeoutHeight = new BigNumberInBase(latestHeight).plus(DEFAULT_BLOCK_TIMEOUT_HEIGHT);
918
+ const pk = Buffer.from(accountFromSigner.pubkey).toString("base64");
919
+ const messages2 = cosmosMsgs.map(
920
+ (cosmosMsg) => getEncodeObjectFromCosmosMessageInjective(cosmosMsg)
921
+ );
922
+ const { signDoc } = createTransaction({
923
+ pubKey: pk,
924
+ chainId,
925
+ message: messages2,
926
+ sequence,
927
+ accountNumber,
928
+ timeoutHeight: timeoutHeight.toNumber(),
929
+ fee
930
+ });
931
+ const directSignResponse = yield signer.signDirect(
932
+ signerAddress,
933
+ // @ts-expect-error TODO: Fix this
934
+ signDoc
935
+ );
936
+ return TxRaw.fromPartial({
937
+ bodyBytes: directSignResponse.signed.bodyBytes,
938
+ authInfoBytes: directSignResponse.signed.authInfoBytes,
939
+ signatures: [fromBase64(directSignResponse.signature.signature)]
940
+ });
941
+ });
942
+ var pubkeyType = __spreadValues({
943
+ ethsecp256k1: "ethermint/PubKeyEthSecp256k1"
944
+ }, pubkeyType$1);
945
+
946
+ // src/amino/encoding.ts
947
+ function encodeEthSecp256k1Pubkey(pubkey) {
948
+ if (pubkey.length !== 33 || pubkey[0] !== 2 && pubkey[0] !== 3) {
949
+ throw new Error(
950
+ "Public key must be compressed secp256k1, i.e. 33 bytes starting with 0x02 or 0x03"
951
+ );
952
+ }
953
+ return {
954
+ type: pubkeyType.ethsecp256k1,
955
+ value: toBase64(pubkey)
956
+ };
957
+ }
958
+
959
+ // src/proto-signing/pubkey.ts
960
+ function makePubkeyAnyFromAccount(account, chainId) {
961
+ const isEthermint = getIsEthermint(chainId);
962
+ const pubkey = isEthermint ? encodeEthSecp256k1Pubkey(account.pubkey) : encodeSecp256k1Pubkey(account.pubkey);
963
+ const pubkeyAny = encodePubkeyToAny(pubkey, chainId, isEthermint);
964
+ return pubkeyAny;
965
+ }
966
+ function encodePubkeyToAny(pubkey, chainId, isEthermint) {
967
+ if (isEthermint) {
968
+ const pubkeyProto = PubKey.fromPartial({
969
+ key: fromBase64$1(pubkey.value)
970
+ });
971
+ let typeUrl = "";
972
+ if (chainId == null ? void 0 : chainId.includes("injective")) {
973
+ typeUrl = "/injective.crypto.v1beta1.ethsecp256k1.PubKey";
974
+ } else {
975
+ typeUrl = "/ethermint.crypto.v1.ethsecp256k1.PubKey";
976
+ }
977
+ return Any.fromPartial({
978
+ typeUrl,
979
+ value: Uint8Array.from(PubKey.encode(pubkeyProto).finish())
980
+ });
981
+ } else {
982
+ const isInitia = getIsInitia(chainId);
983
+ const pubkeyProto = PubKey.fromPartial({
984
+ key: fromBase64$1(pubkey.value)
985
+ });
986
+ if (isInitia) {
987
+ return Any.fromPartial({
988
+ typeUrl: "/initia.crypto.v1beta1.ethsecp256k1.PubKey",
989
+ value: Uint8Array.from(PubKey.encode(pubkeyProto).finish())
990
+ });
991
+ }
992
+ return encodePubkey(pubkey);
993
+ }
994
+ }
995
+ var signCosmosMessageDirect = (options) => __async(void 0, null, function* () {
996
+ const {
997
+ signer,
998
+ signerAddress,
999
+ chainId,
1000
+ cosmosMsgs,
1001
+ fee,
1002
+ signerData: { accountNumber, sequence, chainId: signerChainId }
1003
+ } = options;
1004
+ if (chainId.includes("evmos")) {
1005
+ return signCosmosMessageDirectEvmos(signerAddress, signer, cosmosMsgs, fee, {
1006
+ accountNumber,
1007
+ sequence,
1008
+ chainId: signerChainId
1009
+ });
1010
+ }
1011
+ if (chainId.includes("injective")) {
1012
+ return signCosmosMessageDirectInjective(signerAddress, signer, cosmosMsgs, fee, {
1013
+ accountNumber,
1014
+ sequence,
1015
+ chainId: signerChainId
1016
+ });
1017
+ }
1018
+ const accounts = yield signer.getAccounts();
1019
+ const accountFromSigner = accounts.find((account) => account.address === signerAddress);
1020
+ if (!accountFromSigner) {
1021
+ throw new Error("signCosmosMessageDirect error: failed to retrieve account from signer");
1022
+ }
1023
+ const messages2 = cosmosMsgs.map((cosmosMsg) => getEncodeObjectFromCosmosMessage(cosmosMsg));
1024
+ const txBodyEncodeObject = {
1025
+ typeUrl: "/cosmos.tx.v1beta1.TxBody",
1026
+ value: {
1027
+ messages: messages2
1028
+ }
1029
+ };
1030
+ const txBodyBytes = ClientState.registry.encode(txBodyEncodeObject);
1031
+ const gasLimit = Int53.fromString(fee.gas).toNumber();
1032
+ const pubkeyAny = makePubkeyAnyFromAccount(accountFromSigner, chainId);
1033
+ const authInfoBytes = makeAuthInfoBytes(
1034
+ [{ pubkey: pubkeyAny, sequence }],
1035
+ fee.amount,
1036
+ gasLimit,
1037
+ fee.granter,
1038
+ fee.payer
1039
+ );
1040
+ const signDoc = makeSignDoc(txBodyBytes, authInfoBytes, chainId, accountNumber);
1041
+ const { signature, signed } = yield signer.signDirect(signerAddress, signDoc);
1042
+ return TxRaw.fromPartial({
1043
+ bodyBytes: signed.bodyBytes,
1044
+ authInfoBytes: signed.authInfoBytes,
1045
+ signatures: [fromBase64(signature.signature)]
1046
+ });
1047
+ });
1048
+ var signCosmosMessageAmino = (options) => __async(void 0, null, function* () {
1049
+ const {
1050
+ signer,
1051
+ signerAddress,
1052
+ chainId,
1053
+ cosmosMsgs,
1054
+ fee,
1055
+ signerData: { accountNumber, sequence, chainId: signerChainId }
1056
+ } = options;
1057
+ const accounts = yield signer.getAccounts();
1058
+ const accountFromSigner = accounts.find((account) => account.address === signerAddress);
1059
+ if (!accountFromSigner) {
1060
+ throw new Error("signCosmosMessageAmino: failed to retrieve account from signer");
1061
+ }
1062
+ const messages2 = cosmosMsgs.map((cosmosMsg) => getEncodeObjectFromCosmosMessage(cosmosMsg));
1063
+ const signMode = SignMode.SIGN_MODE_LEGACY_AMINO_JSON;
1064
+ const msgs = messages2.map((msg) => ClientState.aminoTypes.toAmino(msg));
1065
+ console.log("sign cosmos message amino", msgs, fee, signerChainId, "", accountNumber, sequence);
1066
+ const signDoc = makeSignDoc$1(msgs, fee, signerChainId, "", accountNumber, sequence);
1067
+ const { signature, signed } = yield signer.signAmino(signerAddress, signDoc);
1068
+ const signedTxBody = {
1069
+ messages: signed.msgs.map((msg) => ClientState.aminoTypes.fromAmino(msg)),
1070
+ memo: signed.memo
1071
+ };
1072
+ signedTxBody.messages[0].value.memo = messages2[0].value.memo;
1073
+ const signedTxBodyEncodeObject = {
1074
+ typeUrl: "/cosmos.tx.v1beta1.TxBody",
1075
+ value: signedTxBody
1076
+ };
1077
+ const signedTxBodyBytes = ClientState.registry.encode(signedTxBodyEncodeObject);
1078
+ const signedGasLimit = Int53.fromString(signed.fee.gas).toNumber();
1079
+ const signedSequence = Int53.fromString(signed.sequence).toNumber();
1080
+ const pubkeyAny = makePubkeyAnyFromAccount(accountFromSigner, chainId);
1081
+ const signedAuthInfoBytes = makeAuthInfoBytes(
1082
+ [{ pubkey: pubkeyAny, sequence: signedSequence }],
1083
+ signed.fee.amount,
1084
+ signedGasLimit,
1085
+ signed.fee.granter,
1086
+ signed.fee.payer,
1087
+ signMode
1088
+ );
1089
+ return TxRaw.fromPartial({
1090
+ bodyBytes: signedTxBodyBytes,
1091
+ authInfoBytes: signedAuthInfoBytes,
1092
+ signatures: [fromBase64(signature.signature)]
1093
+ });
1094
+ });
1095
+
1096
+ // src/private-functions/cosmos/executeCosmosTransaction.ts
1097
+ var executeCosmosTransaction = (_0) => __async(void 0, [_0], function* ({
1098
+ tx,
1099
+ options,
1100
+ index
1101
+ }) {
1102
+ var _a, _b, _c, _d, _e, _f, _g;
1103
+ const { userAddresses } = options;
1104
+ if (tx === void 0) {
1105
+ throw new Error("executeCosmosTransaction error: tx is undefined");
1106
+ }
1107
+ const chainId = (_a = tx.cosmosTx) == null ? void 0 : _a.chainId;
1108
+ const messages2 = (_b = tx.cosmosTx) == null ? void 0 : _b.msgs;
1109
+ const currentUserAddress = (_c = userAddresses.find((x) => {
1110
+ var _a2;
1111
+ return x.chainId === ((_a2 = tx.cosmosTx) == null ? void 0 : _a2.chainId);
1112
+ })) == null ? void 0 : _c.address;
1113
+ const gasArray = ClientState.validateGasResults;
1114
+ const gas = gasArray == null ? void 0 : gasArray.find((gas2) => (gas2 == null ? void 0 : gas2.error) !== null && (gas2 == null ? void 0 : gas2.error) !== void 0);
1115
+ if (typeof (gas == null ? void 0 : gas.error) === "string") {
1116
+ throw new Error(gas == null ? void 0 : gas.error);
1117
+ }
1118
+ const gasUsed = gasArray == null ? void 0 : gasArray[index];
1119
+ if (!gasUsed) {
1120
+ throw new Error(`executeRoute error: invalid gas at index ${index}`);
1121
+ }
1122
+ if (chainId === void 0) {
1123
+ throw new Error("no chainId found for tx");
1124
+ }
1125
+ if (messages2 === void 0) {
1126
+ throw new Error("no messages found for tx");
1127
+ }
1128
+ const { stargateClient, signer } = yield getSigningStargateClient({
1129
+ chainId,
1130
+ getOfflineSigner: options == null ? void 0 : options.getCosmosSigner
1131
+ });
1132
+ if (!currentUserAddress) {
1133
+ throw new Error(
1134
+ `executeCosmosTransaction error: invalid address for chain '${(_d = tx.cosmosTx) == null ? void 0 : _d.chainId}'`
1135
+ );
1136
+ }
1137
+ const accounts = yield signer.getAccounts();
1138
+ const accountFromSigner = accounts.find((account) => account.address === currentUserAddress);
1139
+ if (!accountFromSigner) {
1140
+ throw new Error("executeCosmosTransaction error: failed to retrieve account from signer");
1141
+ }
1142
+ const fee = gasUsed == null ? void 0 : gasUsed.fee;
1143
+ if (!fee) {
1144
+ throw new Error("executeCosmosTransaction error: failed to retrieve fee from gas");
1145
+ }
1146
+ const { accountNumber, sequence } = yield getAccountNumberAndSequence(
1147
+ currentUserAddress,
1148
+ chainId
1149
+ );
1150
+ let rawTx;
1151
+ const commonRawTxBody = {
1152
+ signerAddress: currentUserAddress,
1153
+ chainId,
1154
+ cosmosMsgs: messages2,
1155
+ fee,
1156
+ signerData: {
1157
+ accountNumber,
1158
+ sequence,
1159
+ chainId
1160
+ }
1161
+ };
1162
+ if (isOfflineDirectSigner(signer)) {
1163
+ rawTx = yield signCosmosMessageDirect(__spreadProps(__spreadValues({}, commonRawTxBody), {
1164
+ signer
1165
+ }));
1166
+ } else {
1167
+ rawTx = yield signCosmosMessageAmino(__spreadProps(__spreadValues({}, commonRawTxBody), { signer }));
1168
+ }
1169
+ (_e = options == null ? void 0 : options.onTransactionSigned) == null ? void 0 : _e.call(options, {
1170
+ chainId
1171
+ });
1172
+ const txBytes = TxRaw.encode(rawTx).finish();
1173
+ const txResponse = yield stargateClient.broadcastTx(txBytes);
1174
+ return {
1175
+ chainId: (_g = (_f = tx == null ? void 0 : tx.cosmosTx) == null ? void 0 : _f.chainId) != null ? _g : "",
1176
+ txHash: txResponse.transactionHash
1177
+ };
1178
+ });
1179
+
1180
+ // src/constants/abis.ts
1181
+ function createAbi(abi) {
1182
+ return abi;
1183
+ }
1184
+ var erc20ABI = /* @__PURE__ */ createAbi([
1185
+ {
1186
+ type: "event",
1187
+ name: "Approval",
1188
+ inputs: [
1189
+ {
1190
+ indexed: true,
1191
+ name: "owner",
1192
+ type: "address"
1193
+ },
1194
+ {
1195
+ indexed: true,
1196
+ name: "spender",
1197
+ type: "address"
1198
+ },
1199
+ {
1200
+ indexed: false,
1201
+ name: "value",
1202
+ type: "uint256"
1203
+ }
1204
+ ]
1205
+ },
1206
+ {
1207
+ type: "event",
1208
+ name: "Transfer",
1209
+ inputs: [
1210
+ {
1211
+ indexed: true,
1212
+ name: "from",
1213
+ type: "address"
1214
+ },
1215
+ {
1216
+ indexed: true,
1217
+ name: "to",
1218
+ type: "address"
1219
+ },
1220
+ {
1221
+ indexed: false,
1222
+ name: "value",
1223
+ type: "uint256"
1224
+ }
1225
+ ]
1226
+ },
1227
+ {
1228
+ type: "function",
1229
+ name: "allowance",
1230
+ stateMutability: "view",
1231
+ inputs: [
1232
+ {
1233
+ name: "owner",
1234
+ type: "address"
1235
+ },
1236
+ {
1237
+ name: "spender",
1238
+ type: "address"
1239
+ }
1240
+ ],
1241
+ outputs: [
1242
+ {
1243
+ name: "",
1244
+ type: "uint256"
1245
+ }
1246
+ ]
1247
+ },
1248
+ {
1249
+ type: "function",
1250
+ name: "approve",
1251
+ stateMutability: "nonpayable",
1252
+ inputs: [
1253
+ {
1254
+ name: "spender",
1255
+ type: "address"
1256
+ },
1257
+ {
1258
+ name: "amount",
1259
+ type: "uint256"
1260
+ }
1261
+ ],
1262
+ outputs: [
1263
+ {
1264
+ name: "",
1265
+ type: "bool"
1266
+ }
1267
+ ]
1268
+ },
1269
+ {
1270
+ type: "function",
1271
+ name: "balanceOf",
1272
+ stateMutability: "view",
1273
+ inputs: [
1274
+ {
1275
+ name: "account",
1276
+ type: "address"
1277
+ }
1278
+ ],
1279
+ outputs: [
1280
+ {
1281
+ name: "",
1282
+ type: "uint256"
1283
+ }
1284
+ ]
1285
+ },
1286
+ {
1287
+ type: "function",
1288
+ name: "decimals",
1289
+ stateMutability: "view",
1290
+ inputs: [],
1291
+ outputs: [
1292
+ {
1293
+ name: "",
1294
+ type: "uint8"
1295
+ }
1296
+ ]
1297
+ },
1298
+ {
1299
+ type: "function",
1300
+ name: "name",
1301
+ stateMutability: "view",
1302
+ inputs: [],
1303
+ outputs: [
1304
+ {
1305
+ name: "",
1306
+ type: "string"
1307
+ }
1308
+ ]
1309
+ },
1310
+ {
1311
+ type: "function",
1312
+ name: "symbol",
1313
+ stateMutability: "view",
1314
+ inputs: [],
1315
+ outputs: [
1316
+ {
1317
+ name: "",
1318
+ type: "string"
1319
+ }
1320
+ ]
1321
+ },
1322
+ {
1323
+ type: "function",
1324
+ name: "totalSupply",
1325
+ stateMutability: "view",
1326
+ inputs: [],
1327
+ outputs: [
1328
+ {
1329
+ name: "",
1330
+ type: "uint256"
1331
+ }
1332
+ ]
1333
+ },
1334
+ {
1335
+ type: "function",
1336
+ name: "transfer",
1337
+ stateMutability: "nonpayable",
1338
+ inputs: [
1339
+ {
1340
+ name: "recipient",
1341
+ type: "address"
1342
+ },
1343
+ {
1344
+ name: "amount",
1345
+ type: "uint256"
1346
+ }
1347
+ ],
1348
+ outputs: [
1349
+ {
1350
+ name: "",
1351
+ type: "bool"
1352
+ }
1353
+ ]
1354
+ },
1355
+ {
1356
+ type: "function",
1357
+ name: "transferFrom",
1358
+ stateMutability: "nonpayable",
1359
+ inputs: [
1360
+ {
1361
+ name: "sender",
1362
+ type: "address"
1363
+ },
1364
+ {
1365
+ name: "recipient",
1366
+ type: "address"
1367
+ },
1368
+ {
1369
+ name: "amount",
1370
+ type: "uint256"
1371
+ }
1372
+ ],
1373
+ outputs: [
1374
+ {
1375
+ name: "",
1376
+ type: "bool"
1377
+ }
1378
+ ]
1379
+ }
1380
+ ]);
1381
+
1382
+ // src/private-functions/evm/executeEvmTransaction.ts
1383
+ var executeEvmTransaction = (message, options) => __async(void 0, null, function* () {
1384
+ const gasArray = ClientState.validateGasResults;
1385
+ const gas = gasArray == null ? void 0 : gasArray.find((gas2) => (gas2 == null ? void 0 : gas2.error) !== null && (gas2 == null ? void 0 : gas2.error) !== void 0);
1386
+ if (typeof (gas == null ? void 0 : gas.error) === "string") {
1387
+ throw new Error(gas == null ? void 0 : gas.error);
1388
+ }
1389
+ const { evmTx } = message;
1390
+ const getEvmSigner = options.getEvmSigner || ClientState.getEvmSigner;
1391
+ if (!getEvmSigner) {
1392
+ throw new Error("Unable to get EVM signer");
1393
+ }
1394
+ if (!(evmTx == null ? void 0 : evmTx.chainId)) {
1395
+ throw new Error("chain id not found in evmTx");
1396
+ }
1397
+ const evmSigner = yield getEvmSigner(evmTx.chainId);
1398
+ if (!evmSigner.account) {
1399
+ throw new Error("executeEVMTransaction error: failed to retrieve account from signer");
1400
+ }
1401
+ if (!evmTx.chainId) {
1402
+ throw new Error("executeEVMTransaction error: chainId not found for evmTx");
1403
+ }
1404
+ if (!evmTx.value) {
1405
+ throw new Error("executeEVMTransaction error: no value found in evmTx");
1406
+ }
1407
+ const { onApproveAllowance, onTransactionSigned, bypassApprovalCheck, useUnlimitedApproval } = options;
1408
+ const extendedSigner = evmSigner.extend(publicActions);
1409
+ if (!bypassApprovalCheck && evmTx.requiredErc20Approvals) {
1410
+ for (const requiredApproval of evmTx.requiredErc20Approvals) {
1411
+ const allowance = yield extendedSigner.readContract({
1412
+ address: requiredApproval.tokenContract,
1413
+ abi: erc20ABI,
1414
+ functionName: "allowance",
1415
+ args: [
1416
+ evmSigner.account.address,
1417
+ requiredApproval.spender
1418
+ ]
1419
+ });
1420
+ if (!requiredApproval.amount) {
1421
+ throw new Error("executeEVMTransaction error: no amount found in a requiredApproval");
1422
+ }
1423
+ if (allowance > BigInt(requiredApproval.amount)) {
1424
+ continue;
1425
+ }
1426
+ onApproveAllowance == null ? void 0 : onApproveAllowance({
1427
+ status: "pending",
1428
+ allowance: requiredApproval
1429
+ });
1430
+ const txHash2 = yield extendedSigner.writeContract({
1431
+ account: evmSigner.account,
1432
+ address: requiredApproval.tokenContract,
1433
+ abi: erc20ABI,
1434
+ functionName: "approve",
1435
+ args: [
1436
+ requiredApproval.spender,
1437
+ useUnlimitedApproval ? maxUint256 : BigInt(requiredApproval.amount) + BigInt(1e3)
1438
+ ],
1439
+ chain: evmSigner.chain
1440
+ });
1441
+ const receipt2 = yield extendedSigner.waitForTransactionReceipt({
1442
+ hash: txHash2
1443
+ });
1444
+ if (receipt2.status === "reverted") {
1445
+ throw new Error(
1446
+ `executeEVMTransaction error: evm tx reverted for hash ${receipt2.transactionHash}`
1447
+ );
1448
+ }
1449
+ }
1450
+ onApproveAllowance == null ? void 0 : onApproveAllowance({
1451
+ status: "completed"
1452
+ });
1453
+ }
1454
+ const txHash = yield extendedSigner.sendTransaction({
1455
+ account: evmSigner.account,
1456
+ to: evmTx.to,
1457
+ data: `0x${evmTx.data}`,
1458
+ chain: evmSigner.chain,
1459
+ value: evmTx.value === "" ? void 0 : BigInt(evmTx.value)
1460
+ });
1461
+ onTransactionSigned == null ? void 0 : onTransactionSigned({
1462
+ chainId: evmTx.chainId
1463
+ });
1464
+ const receipt = yield extendedSigner.waitForTransactionReceipt({
1465
+ hash: txHash
1466
+ });
1467
+ return receipt;
1468
+ });
1469
+ var executeSvmTransaction = (tx, options) => __async(void 0, null, function* () {
1470
+ var _a, _b, _c;
1471
+ const gasArray = ClientState.validateGasResults;
1472
+ if (tx === void 0) {
1473
+ throw new Error("executeSvmTransaction error: tx is undefined");
1474
+ }
1475
+ const gas = gasArray == null ? void 0 : gasArray.find((gas2) => (gas2 == null ? void 0 : gas2.error) !== null && (gas2 == null ? void 0 : gas2.error) !== void 0);
1476
+ if (typeof (gas == null ? void 0 : gas.error) === "string") {
1477
+ throw new Error(gas == null ? void 0 : gas.error);
1478
+ }
1479
+ const svmTx = tx == null ? void 0 : tx.svmTx;
1480
+ const getSvmSigner = (options == null ? void 0 : options.getSvmSigner) || ClientState.getSvmSigner;
1481
+ if (!getSvmSigner) {
1482
+ throw new Error(
1483
+ "executeRoute error: 'getSVMSigner' is not provided or configured in skip router"
1484
+ );
1485
+ }
1486
+ const signer = yield getSvmSigner();
1487
+ if (!(svmTx == null ? void 0 : svmTx.chainId)) {
1488
+ throw new Error("executeSvmTransaction error: chainId not found in svmTx");
1489
+ }
1490
+ const txBuffer = Buffer.from((_a = svmTx.tx) != null ? _a : "", "base64");
1491
+ const transaction = Transaction.from(txBuffer);
1492
+ const endpoint = yield getRpcEndpointForChain(svmTx.chainId);
1493
+ const connection = new Connection(endpoint);
1494
+ let signature;
1495
+ if ("signTransaction" in signer) {
1496
+ const signedTx = yield signer.signTransaction(transaction);
1497
+ (_b = options == null ? void 0 : options.onTransactionSigned) == null ? void 0 : _b.call(options, { chainId: svmTx.chainId });
1498
+ const serializedTx = signedTx.serialize();
1499
+ yield submitTransaction({
1500
+ chainId: svmTx.chainId,
1501
+ tx: serializedTx.toString("base64")
1502
+ }).then((res) => {
1503
+ signature = res == null ? void 0 : res.txHash;
1504
+ });
1505
+ const rpcSig = yield connection.sendRawTransaction(serializedTx, {
1506
+ preflightCommitment: "confirmed",
1507
+ maxRetries: 5
1508
+ });
1509
+ signature = rpcSig;
1510
+ }
1511
+ if (!signature) {
1512
+ throw new Error("executeSvmTransaction error: signature not found");
1513
+ }
1514
+ let getStatusCount = 0;
1515
+ let errorCount = 0;
1516
+ while (true) {
1517
+ try {
1518
+ const status = yield connection.getSignatureStatus(signature, {
1519
+ searchTransactionHistory: true
1520
+ });
1521
+ if (((_c = status == null ? void 0 : status.value) == null ? void 0 : _c.confirmationStatus) === "confirmed") {
1522
+ return {
1523
+ chainId: svmTx.chainId,
1524
+ txHash: signature
1525
+ };
1526
+ }
1527
+ if (getStatusCount > 12) {
1528
+ yield wait(3e3);
1529
+ throw new Error(
1530
+ `executeSvmTransaction error: waiting finalized status timed out for ${signature}`
1531
+ );
1532
+ }
1533
+ getStatusCount++;
1534
+ yield wait(3e3);
1535
+ } catch (error) {
1536
+ errorCount++;
1537
+ if (errorCount > 12) {
1538
+ throw error;
1539
+ }
1540
+ }
1541
+ }
1542
+ });
1543
+
1544
+ // src/private-functions/cosmos/getCosmosGasAmountForMessage.ts
1545
+ var DEFAULT_GAS_MULTIPLIER = 1.5;
1546
+ function getCosmosGasAmountForMessage(_0, _1, _2, _3, _4) {
1547
+ return __async(this, arguments, function* (client, signerAddress, chainId, messages2, encodedMsgs, multiplier = DEFAULT_GAS_MULTIPLIER) {
1548
+ if (!messages2 && !encodedMsgs) {
1549
+ throw new Error("Either message or encodedMsg must be provided");
1550
+ }
1551
+ const _encodedMsgs = messages2 == null ? void 0 : messages2.map((message) => getEncodeObjectFromCosmosMessage(message));
1552
+ encodedMsgs = encodedMsgs || _encodedMsgs;
1553
+ if (!encodedMsgs) {
1554
+ throw new Error("Either message or encodedMsg must be provided");
1555
+ }
1556
+ if (chainId.includes("evmos") || chainId.includes("injective") || chainId.includes("dymension") || (process == null ? void 0 : process.env.NODE_ENV) === "test") {
1557
+ if (messages2 == null ? void 0 : messages2.find((i) => i.msgTypeUrl === "/cosmwasm.wasm.v1.MsgExecuteContract")) {
1558
+ return "2400000";
1559
+ }
1560
+ return "280000";
1561
+ }
1562
+ const estimatedGas = yield client.simulate(signerAddress, encodedMsgs, "");
1563
+ const estimatedGasWithBuffer = estimatedGas * multiplier;
1564
+ return Math.ceil(estimatedGasWithBuffer).toFixed(0);
1565
+ });
1566
+ }
1567
+
1568
+ // src/private-functions/cosmos/validateCosmosGasBalance.ts
1569
+ var validateCosmosGasBalance = (_0) => __async(void 0, [_0], function* ({
1570
+ chainId,
1571
+ signerAddress,
1572
+ messages: messages2,
1573
+ getFallbackGasAmount,
1574
+ getOfflineSigner,
1575
+ txIndex,
1576
+ simulate
1577
+ }) {
1578
+ var _a, _b, _c;
1579
+ const skipAssets = (_a = yield ClientState.getSkipAssets({ chainId })) == null ? void 0 : _a[chainId];
1580
+ const skipChains = yield ClientState.getSkipChains();
1581
+ const chain = skipChains == null ? void 0 : skipChains.find((c) => c.chainId === chainId);
1582
+ if (!chain) {
1583
+ throw new Error(`failed to find chain id for '${chainId}'`);
1584
+ }
1585
+ const { feeAssets } = chain;
1586
+ if (!feeAssets) {
1587
+ throw new Error(`failed to find fee assets for chain '${chainId}'`);
1588
+ }
1589
+ const estimatedGasAmount = yield (() => __async(void 0, null, function* () {
1590
+ try {
1591
+ if (!simulate) throw new Error("simulate");
1592
+ if (txIndex !== 0 && chainId === "noble-1") {
1593
+ return "0";
1594
+ }
1595
+ const { stargateClient } = yield getSigningStargateClient({
1596
+ chainId,
1597
+ getOfflineSigner
1598
+ });
1599
+ const estimatedGas = yield getCosmosGasAmountForMessage(
1600
+ stargateClient,
1601
+ signerAddress,
1602
+ chainId,
1603
+ messages2
1604
+ );
1605
+ return estimatedGas;
1606
+ } catch (e) {
1607
+ const error = e;
1608
+ if (error.message === "simulate" && !getFallbackGasAmount) {
1609
+ throw new Error(`unable to get gas amount for ${chainId}'s message(s)`);
1610
+ }
1611
+ if (getFallbackGasAmount) {
1612
+ const fallbackGasAmount = yield getFallbackGasAmount(chainId, "cosmos" /* Cosmos */);
1613
+ if (!fallbackGasAmount) {
1614
+ throw new Error(`unable to estimate gas for message(s) ${messages2}`);
1615
+ }
1616
+ return String(fallbackGasAmount);
1617
+ }
1618
+ throw error;
1619
+ }
1620
+ }))();
1621
+ const fees = feeAssets.map((asset) => {
1622
+ const gasPrice = (() => {
1623
+ var _a2;
1624
+ if (!(asset == null ? void 0 : asset.gasPrice)) return void 0;
1625
+ let price = asset.gasPrice.average;
1626
+ if (price === "") {
1627
+ price = asset.gasPrice.high;
1628
+ }
1629
+ if (price === "") {
1630
+ price = asset.gasPrice.low;
1631
+ }
1632
+ if (!price) return;
1633
+ return new GasPrice(
1634
+ Decimal.fromUserInput(BigNumber(price).toFixed(), 18),
1635
+ (_a2 = asset == null ? void 0 : asset.denom) != null ? _a2 : ""
1636
+ );
1637
+ })();
1638
+ if (!gasPrice) {
1639
+ return null;
1640
+ }
1641
+ if (chainId === "noble-1") {
1642
+ const fee = calculateFee(2e5, gasPrice);
1643
+ return fee;
1644
+ }
1645
+ return calculateFee(Math.ceil(parseFloat(estimatedGasAmount)), gasPrice);
1646
+ });
1647
+ const feeBalance = yield balances({
1648
+ chains: {
1649
+ [chainId]: {
1650
+ address: signerAddress,
1651
+ denoms: feeAssets.map((asset) => {
1652
+ var _a2;
1653
+ return (_a2 = asset.denom) != null ? _a2 : "";
1654
+ })
1655
+ }
1656
+ }
1657
+ });
1658
+ const validatedAssets = feeAssets.map((asset, index) => {
1659
+ var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j;
1660
+ const chainAsset = skipAssets == null ? void 0 : skipAssets.find((x) => x.denom === asset.denom);
1661
+ const symbol = (_a2 = chainAsset == null ? void 0 : chainAsset.recommendedSymbol) == null ? void 0 : _a2.toUpperCase();
1662
+ const decimal = Number(chainAsset == null ? void 0 : chainAsset.decimals);
1663
+ if (!chainAsset) {
1664
+ return {
1665
+ error: `(${chain == null ? void 0 : chain.prettyName}) Unable to find asset for ${asset.denom}`
1666
+ };
1667
+ }
1668
+ if (isNaN(decimal))
1669
+ return {
1670
+ error: `(${chain == null ? void 0 : chain.prettyName}) Unable to find decimal for ${symbol}`
1671
+ };
1672
+ const fee = fees[index];
1673
+ if (!fee) {
1674
+ return {
1675
+ error: `(${chain == null ? void 0 : chain.prettyName}) Unable to calculate fee for ${symbol}`,
1676
+ asset
1677
+ };
1678
+ }
1679
+ if (txIndex !== 0 && chainId === "noble-1") {
1680
+ return {
1681
+ error: null,
1682
+ asset,
1683
+ fee
1684
+ };
1685
+ }
1686
+ let balance = (_e = (_c2 = (_b2 = feeBalance == null ? void 0 : feeBalance.chains) == null ? void 0 : _b2[chainId]) == null ? void 0 : _c2.denoms) == null ? void 0 : _e[(_d = asset == null ? void 0 : asset.denom) != null ? _d : ""];
1687
+ if (!balance) {
1688
+ balance = {
1689
+ amount: "0",
1690
+ formattedAmount: "0"
1691
+ };
1692
+ }
1693
+ if (!((_f = fee.amount[0]) == null ? void 0 : _f.amount)) {
1694
+ return {
1695
+ error: `(${chain == null ? void 0 : chain.prettyName}) Unable to get fee for ${symbol}`,
1696
+ asset
1697
+ };
1698
+ }
1699
+ if (parseInt((_g = balance == null ? void 0 : balance.amount) != null ? _g : "") < parseInt((_h = fee.amount[0]) == null ? void 0 : _h.amount)) {
1700
+ const userAmount = new BigNumber(parseFloat((_i = balance == null ? void 0 : balance.amount) != null ? _i : "")).shiftedBy(-decimal).toFixed(decimal);
1701
+ const feeAmount = new BigNumber(parseFloat((_j = fee.amount[0]) == null ? void 0 : _j.amount)).shiftedBy(-decimal).toFixed(decimal);
1702
+ return {
1703
+ error: `Insufficient balance for gas on ${chain == null ? void 0 : chain.prettyName}. Need ${feeAmount} ${symbol} but only have ${userAmount} ${symbol}.`,
1704
+ asset
1705
+ };
1706
+ }
1707
+ return {
1708
+ error: null,
1709
+ asset,
1710
+ fee
1711
+ };
1712
+ });
1713
+ const feeUsed = validatedAssets.find((res) => (res == null ? void 0 : res.error) === null);
1714
+ if (!feeUsed) {
1715
+ if (validatedAssets.length > 1) {
1716
+ throw new Error(
1717
+ ((_b = validatedAssets[0]) == null ? void 0 : _b.error) || `Insufficient fee token to initiate transfer on ${chainId}.`
1718
+ );
1719
+ }
1720
+ throw new Error(
1721
+ ((_c = validatedAssets[0]) == null ? void 0 : _c.error) || `Insufficient fee token to initiate transfer on ${chainId}.`
1722
+ );
1723
+ }
1724
+ return feeUsed;
1725
+ });
1726
+ var validateEvmTokenApproval = (_0) => __async(void 0, [_0], function* ({
1727
+ requiredErc20Approvals,
1728
+ signer,
1729
+ chain,
1730
+ gasBalance,
1731
+ tx,
1732
+ useUnlimitedApproval
1733
+ }) {
1734
+ var _a, _b;
1735
+ if (!((_a = signer.account) == null ? void 0 : _a.address)) {
1736
+ throw new Error("validateEvmGasBalance: Signer address not found");
1737
+ }
1738
+ for (const requiredApproval of requiredErc20Approvals) {
1739
+ const extendedSigner = signer.extend(publicActions);
1740
+ const allowance = yield extendedSigner.readContract({
1741
+ address: requiredApproval.tokenContract,
1742
+ abi: erc20ABI,
1743
+ functionName: "allowance",
1744
+ args: [(_b = signer.account) == null ? void 0 : _b.address, requiredApproval.spender]
1745
+ });
1746
+ if (allowance > BigInt(requiredApproval.amount)) {
1747
+ continue;
1748
+ }
1749
+ const fee = yield extendedSigner.estimateFeesPerGas();
1750
+ const allowanceGasFee = BigInt(fee.maxFeePerGas) * BigInt(1e5);
1751
+ if (!gasBalance) {
1752
+ const chainAssets = (yield ClientState.getSkipAssets({ chainId: tx.chainId }))[tx.chainId];
1753
+ const nativeAsset = chainAssets == null ? void 0 : chainAssets.find((x) => x.denom.includes("-native"));
1754
+ const zeroAddressAsset = chainAssets == null ? void 0 : chainAssets.find(
1755
+ (x) => x.denom.toLowerCase() === "0x0000000000000000000000000000000000000000"
1756
+ );
1757
+ const asset = nativeAsset || zeroAddressAsset;
1758
+ if (!(asset == null ? void 0 : asset.decimals)) {
1759
+ throw new Error(
1760
+ `Insufficient balance for gas on ${chain.prettyName}. Need ${allowanceGasFee} gwei.`
1761
+ );
1762
+ }
1763
+ const formattedGasAmount = formatUnits(allowanceGasFee, asset == null ? void 0 : asset.decimals);
1764
+ throw new Error(
1765
+ `Insufficient balance for gas on ${chain.prettyName}. Need ${formattedGasAmount} ${asset.symbol}.`
1766
+ );
1767
+ }
1768
+ if (BigNumber(gasBalance.amount).lt(Number(allowanceGasFee))) {
1769
+ const chainAssets = (yield ClientState.getSkipAssets({ chainId: tx.chainId }))[tx.chainId];
1770
+ const asset = chainAssets == null ? void 0 : chainAssets.find(
1771
+ (x) => x.denom.includes("-native") || x.denom.toLowerCase() === "0x0000000000000000000000000000000000000000"
1772
+ );
1773
+ if (!(asset == null ? void 0 : asset.decimals)) {
1774
+ return {
1775
+ error: `Insufficient balance for gas on ${chain.prettyName}. Need ${allowanceGasFee} gwei but only have ${gasBalance.amount} gwei.`,
1776
+ asset: null,
1777
+ fee: null
1778
+ };
1779
+ }
1780
+ const formattedGasAmount = formatUnits(allowanceGasFee, asset == null ? void 0 : asset.decimals);
1781
+ return {
1782
+ error: `Insufficient balance for gas on ${chain.prettyName}. Need ${formattedGasAmount} ${asset.symbol} but only have ${gasBalance.formattedAmount} ${asset.symbol}.`,
1783
+ asset: null,
1784
+ fee: null
1785
+ };
1786
+ }
1787
+ const txHash = yield extendedSigner.writeContract({
1788
+ account: signer.account,
1789
+ address: requiredApproval.tokenContract,
1790
+ abi: erc20ABI,
1791
+ functionName: "approve",
1792
+ args: [
1793
+ requiredApproval.spender,
1794
+ useUnlimitedApproval ? maxUint256 : BigInt(requiredApproval.amount) + BigInt(1e3)
1795
+ ],
1796
+ chain: signer.chain
1797
+ });
1798
+ const receipt = yield extendedSigner.waitForTransactionReceipt({
1799
+ hash: txHash
1800
+ });
1801
+ if (receipt.status === "reverted") {
1802
+ throw new Error(
1803
+ `executeEVMTransaction error: evm tx reverted for hash ${receipt.transactionHash}`
1804
+ );
1805
+ }
1806
+ }
1807
+ });
1808
+ function getEVMGasAmountForMessage(signer, tx, getFallbackGasAmount) {
1809
+ return __async(this, null, function* () {
1810
+ var _a;
1811
+ const { to, data, value } = tx;
1812
+ if (!signer.account) throw new Error("estimateGasForEvmTx: No account found");
1813
+ const extendedSigner = signer.extend(publicActions);
1814
+ const fee = yield extendedSigner.estimateFeesPerGas();
1815
+ try {
1816
+ const gasAmount = yield extendedSigner.estimateGas({
1817
+ account: signer.account,
1818
+ to,
1819
+ data: `0x${data}`,
1820
+ value: value === "" ? void 0 : BigInt(value != null ? value : "")
1821
+ });
1822
+ return gasAmount * fee.maxFeePerGas;
1823
+ } catch (error) {
1824
+ const fallbackGasAmount = yield getFallbackGasAmount == null ? void 0 : getFallbackGasAmount((_a = tx.chainId) != null ? _a : "", "evm" /* Evm */);
1825
+ if (fallbackGasAmount) {
1826
+ return BigInt(fallbackGasAmount) * fee.maxFeePerGas;
1827
+ }
1828
+ throw error;
1829
+ }
1830
+ });
1831
+ }
1832
+
1833
+ // src/private-functions/evm/validateEvmGasBalance.ts
1834
+ var validateEvmGasBalance = (_0) => __async(void 0, [_0], function* ({
1835
+ signer,
1836
+ tx,
1837
+ getFallbackGasAmount,
1838
+ useUnlimitedApproval
1839
+ }) {
1840
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
1841
+ const chainId = (_a = tx == null ? void 0 : tx.chainId) != null ? _a : "";
1842
+ const skipAssets = (_b = yield ClientState.getSkipAssets({ chainId })) == null ? void 0 : _b[chainId];
1843
+ const skipChains = yield ClientState.getSkipChains();
1844
+ const chain = (_c = skipChains == null ? void 0 : skipChains.find) == null ? void 0 : _c.call(skipChains, (chain2) => chain2.chainId === chainId);
1845
+ if (!chain) {
1846
+ throw new Error(`failed to find chain for chainId: '${chainId}'`);
1847
+ }
1848
+ if (!((_d = signer.account) == null ? void 0 : _d.address)) {
1849
+ throw new Error("validateEvmGasBalance: Signer address not found");
1850
+ }
1851
+ const skipBalances = (_j = (_i = (_g = yield balances({
1852
+ chains: {
1853
+ [(_e = tx == null ? void 0 : tx.chainId) != null ? _e : ""]: {
1854
+ address: (_f = signer.account) == null ? void 0 : _f.address
1855
+ }
1856
+ }
1857
+ })) == null ? void 0 : _g.chains) == null ? void 0 : _i[(_h = tx == null ? void 0 : tx.chainId) != null ? _h : ""]) == null ? void 0 : _j.denoms;
1858
+ const nativeGasBalance = skipBalances && ((_k = Object.entries(skipBalances).find(([denom]) => denom.includes("-native"))) == null ? void 0 : _k[1]);
1859
+ const zeroAddressGasBalance = skipBalances && ((_l = Object.entries(skipBalances).find(
1860
+ ([denom]) => denom.toLowerCase() === "0x0000000000000000000000000000000000000000"
1861
+ )) == null ? void 0 : _l[1]);
1862
+ const gasBalance = nativeGasBalance || zeroAddressGasBalance;
1863
+ const { requiredErc20Approvals } = tx;
1864
+ if (requiredErc20Approvals) {
1865
+ try {
1866
+ yield validateEvmTokenApproval({
1867
+ requiredErc20Approvals,
1868
+ signer,
1869
+ chain,
1870
+ gasBalance,
1871
+ tx,
1872
+ useUnlimitedApproval
1873
+ });
1874
+ } catch (error) {
1875
+ const err = error;
1876
+ return {
1877
+ error: err.message,
1878
+ asset: null,
1879
+ fee: null
1880
+ };
1881
+ }
1882
+ }
1883
+ const gasAmount = yield getEVMGasAmountForMessage(signer, tx, getFallbackGasAmount);
1884
+ if (!gasBalance) {
1885
+ const nativeAsset = skipAssets == null ? void 0 : skipAssets.find((x) => {
1886
+ var _a2;
1887
+ return (_a2 = x.denom) == null ? void 0 : _a2.includes("-native");
1888
+ });
1889
+ const zeroAddressAsset = skipAssets == null ? void 0 : skipAssets.find(
1890
+ (x) => {
1891
+ var _a2;
1892
+ return ((_a2 = x.denom) == null ? void 0 : _a2.toLowerCase()) === "0x0000000000000000000000000000000000000000";
1893
+ }
1894
+ );
1895
+ const asset = nativeAsset || zeroAddressAsset;
1896
+ if (!(asset == null ? void 0 : asset.decimals)) {
1897
+ return {
1898
+ error: `Insufficient balance for gas on ${chain.prettyName}. Need ${gasAmount} gwei.`,
1899
+ asset: null,
1900
+ fee: null
1901
+ };
1902
+ }
1903
+ const formattedGasAmount = formatUnits(gasAmount, asset == null ? void 0 : asset.decimals);
1904
+ return {
1905
+ error: `Insufficient balance for gas on ${chain.prettyName}. Need ${formattedGasAmount} ${asset.symbol}.`,
1906
+ asset: null,
1907
+ fee: null
1908
+ };
1909
+ }
1910
+ if (BigNumber((_m = gasBalance.amount) != null ? _m : "").lt(Number(gasAmount))) {
1911
+ const asset = skipAssets == null ? void 0 : skipAssets.find(
1912
+ (x) => {
1913
+ var _a2, _b2;
1914
+ return ((_a2 = x.denom) == null ? void 0 : _a2.includes("-native")) || ((_b2 = x.denom) == null ? void 0 : _b2.toLowerCase()) === "0x0000000000000000000000000000000000000000";
1915
+ }
1916
+ );
1917
+ if (!(asset == null ? void 0 : asset.decimals)) {
1918
+ return {
1919
+ error: `Insufficient balance for gas on ${chain.prettyName}. Need ${gasAmount} gwei but only have ${gasBalance.amount} gwei.`,
1920
+ asset: null,
1921
+ fee: null
1922
+ };
1923
+ }
1924
+ const formattedGasAmount = formatUnits(gasAmount, asset == null ? void 0 : asset.decimals);
1925
+ return {
1926
+ error: `Insufficient balance for gas on ${chain.prettyName}. Need ${formattedGasAmount} ${asset.symbol} but only have ${gasBalance.formattedAmount} ${asset.symbol}.`,
1927
+ asset: null,
1928
+ fee: null
1929
+ };
1930
+ }
1931
+ });
1932
+ var validateSvmGasBalance = (_0) => __async(void 0, [_0], function* ({
1933
+ tx
1934
+ }) {
1935
+ var _a, _b, _c;
1936
+ if (!tx) throw new Error("Transaction is required");
1937
+ const endpoint = yield getRpcEndpointForChain((_a = tx.chainId) != null ? _a : "");
1938
+ const connection = new Connection(endpoint);
1939
+ if (!connection) throw new Error(`Failed to connect to ${tx.chainId}`);
1940
+ if (!tx.tx) {
1941
+ throw new Error("Transaction is required");
1942
+ }
1943
+ const txBuffer = Buffer.from(tx.tx, "base64");
1944
+ let transaction;
1945
+ try {
1946
+ transaction = Transaction.from(txBuffer);
1947
+ } catch (decodeError) {
1948
+ return {
1949
+ success: false,
1950
+ error: { decodeError: decodeError.message },
1951
+ asset: null,
1952
+ fee: null
1953
+ };
1954
+ }
1955
+ const simulation = yield connection.simulateTransaction(transaction);
1956
+ if (simulation.value.err) {
1957
+ const logs = (_b = simulation.value.logs) != null ? _b : [];
1958
+ const shortfall = getSolShortfall(logs);
1959
+ const insufficientLamports = logs.some((log) => log.includes("insufficient lamports")) && shortfall !== null;
1960
+ const insufficientFundsForRent = Object.keys(simulation.value.err).includes(
1961
+ "InsufficientFundsForRent"
1962
+ );
1963
+ 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";
1964
+ return {
1965
+ success: false,
1966
+ logs,
1967
+ error: errMsg,
1968
+ asset: null,
1969
+ fee: null
1970
+ };
1971
+ }
1972
+ return {
1973
+ success: true,
1974
+ logs: (_c = simulation.value.logs) != null ? _c : [],
1975
+ error: null,
1976
+ asset: null,
1977
+ fee: null
1978
+ };
1979
+ });
1980
+ function getSolShortfall(logs) {
1981
+ var _a, _b;
1982
+ const line = logs.find((l) => l.includes("insufficient lamports"));
1983
+ if (!line) return null;
1984
+ const m = line.match(/insufficient lamports (\d+), need (\d+)/);
1985
+ if (!m) return null;
1986
+ const have = parseInt((_a = m[1]) != null ? _a : "0", 10);
1987
+ const need = parseInt((_b = m[2]) != null ? _b : "0", 10);
1988
+ const shortfallLamports = need - have;
1989
+ return shortfallLamports / LAMPORTS_PER_SOL;
1990
+ }
1991
+
1992
+ // src/private-functions/validateGasBalances.ts
1993
+ var validateGasBalances = (_0) => __async(void 0, [_0], function* ({
1994
+ txs,
1995
+ onValidateGasBalance,
1996
+ getFallbackGasAmount,
1997
+ getCosmosSigner,
1998
+ getEvmSigner,
1999
+ simulate,
2000
+ disabledChainIds,
2001
+ enabledChainIds,
2002
+ useUnlimitedApproval
2003
+ }) {
2004
+ if (txs.every((tx) => "cosmosTx" in tx === void 0) || txs.every((tx) => "svmTx" in tx === void 0)) {
2005
+ return;
2006
+ }
2007
+ onValidateGasBalance == null ? void 0 : onValidateGasBalance({
2008
+ status: "pending"
2009
+ });
2010
+ const validateResult = yield Promise.all(
2011
+ txs.map((tx, i) => __async(void 0, null, function* () {
2012
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
2013
+ if (!tx) {
2014
+ throw new Error(`invalid tx at index ${i}`);
2015
+ }
2016
+ if ("cosmosTx" in tx && !(disabledChainIds == null ? void 0 : disabledChainIds.includes((_b = (_a = tx == null ? void 0 : tx.cosmosTx) == null ? void 0 : _a.chainId) != null ? _b : "")) && (enabledChainIds === void 0 || enabledChainIds.includes((_d = (_c = tx == null ? void 0 : tx.cosmosTx) == null ? void 0 : _c.chainId) != null ? _d : ""))) {
2017
+ if (!((_e = tx == null ? void 0 : tx.cosmosTx) == null ? void 0 : _e.msgs)) {
2018
+ throw new Error(`invalid msgs ${(_f = tx == null ? void 0 : tx.cosmosTx) == null ? void 0 : _f.msgs}`);
2019
+ }
2020
+ try {
2021
+ const res = yield validateCosmosGasBalance({
2022
+ chainId: (_g = tx.cosmosTx.chainId) != null ? _g : "",
2023
+ signerAddress: (_h = tx.cosmosTx.signerAddress) != null ? _h : "",
2024
+ messages: tx.cosmosTx.msgs,
2025
+ getFallbackGasAmount,
2026
+ getOfflineSigner: getCosmosSigner,
2027
+ txIndex: i,
2028
+ simulate
2029
+ });
2030
+ return res;
2031
+ } catch (e) {
2032
+ const error = e;
2033
+ return {
2034
+ error: error.message,
2035
+ asset: null,
2036
+ fee: null
2037
+ };
2038
+ }
2039
+ }
2040
+ if ("evmTx" in tx && !(disabledChainIds == null ? void 0 : disabledChainIds.includes((_j = (_i = tx == null ? void 0 : tx.evmTx) == null ? void 0 : _i.chainId) != null ? _j : "")) && (enabledChainIds === void 0 || enabledChainIds.includes((_l = (_k = tx == null ? void 0 : tx.evmTx) == null ? void 0 : _k.chainId) != null ? _l : ""))) {
2041
+ const signer = yield getEvmSigner == null ? void 0 : getEvmSigner((_n = (_m = tx == null ? void 0 : tx.evmTx) == null ? void 0 : _m.chainId) != null ? _n : "");
2042
+ if (!signer) {
2043
+ throw new Error(`failed to get signer for chain ${(_o = tx == null ? void 0 : tx.evmTx) == null ? void 0 : _o.chainId}`);
2044
+ }
2045
+ try {
2046
+ const res = yield validateEvmGasBalance({
2047
+ tx: tx.evmTx,
2048
+ signer,
2049
+ getFallbackGasAmount,
2050
+ useUnlimitedApproval
2051
+ });
2052
+ return res;
2053
+ } catch (e) {
2054
+ const error = e;
2055
+ return {
2056
+ error: error.message,
2057
+ asset: null,
2058
+ fee: null
2059
+ };
2060
+ }
2061
+ }
2062
+ if ("svmTx" in tx && !(disabledChainIds == null ? void 0 : disabledChainIds.includes((_q = (_p = tx == null ? void 0 : tx.svmTx) == null ? void 0 : _p.chainId) != null ? _q : "")) && (enabledChainIds === void 0 || enabledChainIds.includes((_s = (_r = tx == null ? void 0 : tx.svmTx) == null ? void 0 : _r.chainId) != null ? _s : ""))) {
2063
+ try {
2064
+ const res = yield validateSvmGasBalance({
2065
+ tx: tx.svmTx
2066
+ });
2067
+ return res;
2068
+ } catch (e) {
2069
+ const error = e;
2070
+ return {
2071
+ error: error.message,
2072
+ asset: null,
2073
+ fee: null
2074
+ };
2075
+ }
2076
+ }
2077
+ }))
2078
+ );
2079
+ if (validateResult.filter(Boolean).length === 0) {
2080
+ return;
2081
+ }
2082
+ const txError = validateResult.find((res) => res && (res == null ? void 0 : res.error) !== null);
2083
+ if (txError) {
2084
+ onValidateGasBalance == null ? void 0 : onValidateGasBalance({
2085
+ status: "error"
2086
+ });
2087
+ ClientState.validateGasResults = validateResult;
2088
+ throw new Error(`${txError.error}`);
2089
+ }
2090
+ onValidateGasBalance == null ? void 0 : onValidateGasBalance({
2091
+ status: "completed"
2092
+ });
2093
+ ClientState.validateGasResults = validateResult;
2094
+ });
2095
+
2096
+ // src/private-functions/waitForTransaction.ts
2097
+ var waitForTransaction = (_0) => __async(void 0, [_0], function* ({
2098
+ chainId,
2099
+ txHash,
2100
+ onTransactionTracked
2101
+ }) {
2102
+ var _a, _b;
2103
+ const { explorerLink } = yield trackTransaction({
2104
+ chainId,
2105
+ txHash
2106
+ });
2107
+ yield onTransactionTracked == null ? void 0 : onTransactionTracked({ txHash, chainId, explorerLink });
2108
+ while (true) {
2109
+ const txStatusResponse = yield transactionStatus({
2110
+ chainId,
2111
+ txHash
2112
+ });
2113
+ if (txStatusResponse.state === "STATE_COMPLETED_SUCCESS") {
2114
+ return txStatusResponse;
2115
+ }
2116
+ if (txStatusResponse.state === "STATE_COMPLETED_ERROR") {
2117
+ throw new Error(`${(_a = txStatusResponse.error) == null ? void 0 : _a.type}: ${(_b = txStatusResponse.error) == null ? void 0 : _b.message}`);
2118
+ }
2119
+ if (txStatusResponse.state === "STATE_ABANDONED") {
2120
+ throw new Error("Tracking for the transaction has been abandoned");
2121
+ }
2122
+ yield wait(1e3);
2123
+ }
2124
+ });
2125
+
2126
+ // src/private-functions/executeTransactions.ts
2127
+ var executeTransactions = (options) => __async(void 0, null, function* () {
2128
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2129
+ const {
2130
+ txs,
2131
+ onTransactionBroadcast,
2132
+ onTransactionCompleted,
2133
+ simulate = true,
2134
+ batchSimulate = true
2135
+ } = options;
2136
+ if (txs === void 0) {
2137
+ throw new Error("executeTransactions error: txs is undefined in executeTransactions");
2138
+ }
2139
+ const chainIds = txs.map((tx) => {
2140
+ var _a2, _b2, _c2;
2141
+ if ("cosmosTx" in tx) {
2142
+ return {
2143
+ chainType: "cosmos",
2144
+ chainId: (_a2 = tx.cosmosTx) == null ? void 0 : _a2.chainId
2145
+ };
2146
+ }
2147
+ if ("svmTx" in tx) {
2148
+ return {
2149
+ chainType: "svm",
2150
+ chainId: (_b2 = tx.svmTx) == null ? void 0 : _b2.chainId
2151
+ };
2152
+ }
2153
+ if ("evmTx" in tx) {
2154
+ return {
2155
+ chainType: "evm",
2156
+ chainId: (_c2 = tx.evmTx) == null ? void 0 : _c2.chainId
2157
+ };
2158
+ }
2159
+ });
2160
+ const isGasStationSourceEVM = chainIds.find((item, i, array) => {
2161
+ var _a2, _b2;
2162
+ return GAS_STATION_CHAIN_IDS.includes((_a2 = item == null ? void 0 : item.chainId) != null ? _a2 : "") && ((_b2 = array[i - 1]) == null ? void 0 : _b2.chainType) === "evm";
2163
+ });
2164
+ ClientState.validateGasResults = void 0;
2165
+ const validateChainIds = !batchSimulate ? chainIds.map((x) => {
2166
+ var _a2;
2167
+ return (_a2 = x == null ? void 0 : x.chainId) != null ? _a2 : "";
2168
+ }) : isGasStationSourceEVM ? GAS_STATION_CHAIN_IDS : [];
2169
+ yield validateGasBalances({
2170
+ txs,
2171
+ getFallbackGasAmount: options.getFallbackGasAmount,
2172
+ getCosmosSigner: options.getCosmosSigner,
2173
+ getEvmSigner: options.getEvmSigner,
2174
+ onValidateGasBalance: options.onValidateGasBalance,
2175
+ simulate,
2176
+ disabledChainIds: validateChainIds
2177
+ });
2178
+ const validateEnabledChainIds = (chainId) => __async(void 0, null, function* () {
2179
+ yield validateGasBalances({
2180
+ txs,
2181
+ getFallbackGasAmount: options.getFallbackGasAmount,
2182
+ getCosmosSigner: options.getCosmosSigner,
2183
+ getEvmSigner: options.getEvmSigner,
2184
+ onValidateGasBalance: options.onValidateGasBalance,
2185
+ simulate,
2186
+ enabledChainIds: !batchSimulate ? [chainId] : validateChainIds
2187
+ });
2188
+ });
2189
+ for (let i = 0; i < txs.length; i++) {
2190
+ const tx = txs[i];
2191
+ if (!tx) {
2192
+ throw new Error(`executeRoute error: invalid message at index ${i}`);
2193
+ }
2194
+ let txResult;
2195
+ if ("cosmosTx" in tx) {
2196
+ yield validateEnabledChainIds((_b = (_a = tx.cosmosTx) == null ? void 0 : _a.chainId) != null ? _b : "");
2197
+ txResult = yield executeCosmosTransaction({
2198
+ tx,
2199
+ options,
2200
+ index: i
2201
+ });
2202
+ } else if ("evmTx" in tx) {
2203
+ yield validateEnabledChainIds((_d = (_c = tx.evmTx) == null ? void 0 : _c.chainId) != null ? _d : "");
2204
+ const txResponse = yield executeEvmTransaction(tx, options);
2205
+ txResult = {
2206
+ chainId: (_f = (_e = tx == null ? void 0 : tx.evmTx) == null ? void 0 : _e.chainId) != null ? _f : "",
2207
+ txHash: txResponse.transactionHash
2208
+ };
2209
+ } else if ("svmTx" in tx) {
2210
+ yield validateEnabledChainIds((_h = (_g = tx.svmTx) == null ? void 0 : _g.chainId) != null ? _h : "");
2211
+ txResult = yield executeSvmTransaction(tx, options);
2212
+ } else {
2213
+ throw new Error("executeRoute error: invalid message type");
2214
+ }
2215
+ yield onTransactionBroadcast == null ? void 0 : onTransactionBroadcast(__spreadValues({}, txResult));
2216
+ const txStatusResponse = yield waitForTransaction(__spreadProps(__spreadValues({}, txResult), {
2217
+ onTransactionTracked: options.onTransactionTracked
2218
+ }));
2219
+ yield onTransactionCompleted == null ? void 0 : onTransactionCompleted({
2220
+ chainId: txResult.chainId,
2221
+ txHash: txResult.txHash,
2222
+ status: txStatusResponse
2223
+ });
2224
+ }
2225
+ });
2226
+ var executeRoute = (options) => __async(void 0, null, function* () {
2227
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
2228
+ const { route, userAddresses, beforeMsg, afterMsg, timeoutSeconds } = options;
2229
+ let addressList = [];
2230
+ userAddresses.forEach((userAddress, index) => {
2231
+ const requiredChainAddress = route.requiredChainAddresses[index];
2232
+ if (requiredChainAddress === (userAddress == null ? void 0 : userAddress.chainId)) {
2233
+ addressList.push(userAddress.address);
2234
+ }
2235
+ });
2236
+ if (addressList.length !== route.requiredChainAddresses.length) {
2237
+ addressList = userAddresses.map((x) => x.address);
2238
+ }
2239
+ const validLength = addressList.length === route.requiredChainAddresses.length || addressList.length === ((_a = route.chainIds) == null ? void 0 : _a.length);
2240
+ if (!validLength) {
2241
+ throw new Error("executeRoute error: invalid address list");
2242
+ }
2243
+ const isUserAddressesValid = yield validateUserAddresses(userAddresses);
2244
+ if (!isUserAddressesValid) {
2245
+ throw new Error("executeRoute error: invalid user addresses");
2246
+ }
2247
+ const response = yield messages({
2248
+ timeoutSeconds,
2249
+ amountIn: route == null ? void 0 : route.amountIn,
2250
+ amountOut: route.estimatedAmountOut || "0",
2251
+ sourceAssetChainId: route == null ? void 0 : route.sourceAssetChainId,
2252
+ sourceAssetDenom: route == null ? void 0 : route.sourceAssetDenom,
2253
+ destAssetChainId: route == null ? void 0 : route.destAssetChainId,
2254
+ destAssetDenom: route == null ? void 0 : route.destAssetDenom,
2255
+ operations: route == null ? void 0 : route.operations,
2256
+ addressList,
2257
+ slippageTolerancePercent: options.slippageTolerancePercent || "1",
2258
+ chainIdsToAffiliates: ApiState.chainIdsToAffiliates
2259
+ });
2260
+ if (beforeMsg && ((_c = (_b = response == null ? void 0 : response.txs) == null ? void 0 : _b.length) != null ? _c : 0) > 0) {
2261
+ const firstTx = (_d = response == null ? void 0 : response.txs) == null ? void 0 : _d[0];
2262
+ if (firstTx && "cosmosTx" in firstTx) {
2263
+ (_f = (_e = firstTx.cosmosTx) == null ? void 0 : _e.msgs) == null ? void 0 : _f.unshift(beforeMsg);
2264
+ }
2265
+ }
2266
+ if (afterMsg && ((_h = (_g = response == null ? void 0 : response.txs) == null ? void 0 : _g.length) != null ? _h : 0) > 0) {
2267
+ const lastTx = (_i = response == null ? void 0 : response.txs) == null ? void 0 : _i[response.txs.length - 1];
2268
+ if (lastTx && "cosmosTx" in lastTx) {
2269
+ (_k = (_j = lastTx.cosmosTx) == null ? void 0 : _j.msgs) == null ? void 0 : _k.push(afterMsg);
2270
+ }
2271
+ }
2272
+ yield executeTransactions(__spreadProps(__spreadValues({}, options), { txs: response == null ? void 0 : response.txs }));
2273
+ });
2274
+ var validateUserAddresses = (userAddresses) => __async(void 0, null, function* () {
2275
+ const chains2 = yield ClientState.getSkipChains();
2276
+ const validations = userAddresses.map((userAddress) => {
2277
+ var _a, _b;
2278
+ const chain = chains2.find((chain2) => chain2.chainId === userAddress.chainId);
2279
+ switch (chain == null ? void 0 : chain.chainType) {
2280
+ case "cosmos" /* Cosmos */:
2281
+ try {
2282
+ if ((_a = chain.chainId) == null ? void 0 : _a.includes("penumbra")) {
2283
+ try {
2284
+ return chain.bech32Prefix === ((_b = bech32m.decode(userAddress.address, 143)) == null ? void 0 : _b.prefix);
2285
+ } catch (e) {
2286
+ return ["penumbracompat1", "tpenumbra"].includes(
2287
+ bech32.decode(userAddress.address, 1023).prefix
2288
+ );
2289
+ }
2290
+ }
2291
+ return chain.bech32Prefix === bech32.decode(userAddress.address, 1023).prefix;
2292
+ } catch (e) {
2293
+ return false;
2294
+ }
2295
+ case "evm" /* Evm */:
2296
+ try {
2297
+ return isAddress(userAddress.address);
2298
+ } catch (_error) {
2299
+ return false;
2300
+ }
2301
+ case "svm" /* Svm */:
2302
+ try {
2303
+ const publicKey = new PublicKey(userAddress.address);
2304
+ return PublicKey.isOnCurve(publicKey);
2305
+ } catch (_error) {
2306
+ return false;
2307
+ }
2308
+ default:
2309
+ return false;
2310
+ }
2311
+ });
2312
+ return validations.every((validation) => validation);
2313
+ });
2314
+
2315
+ export { Api, AutopilotAction, AxelarTransferState, AxelarTransferType, BridgeType, CCTPTransferState, ChainType, ContentType, ContractCallWithTokenErrorType, FeeType, GoFastTransferState, HttpClient, HyperlaneTransferState, LayerZeroTransferState, OPInitTransferState, PacketErrorType, Reason, RoutePriceWarningType, SendTokenErrorType, StargateTransferState, StatusErrorType, TransactionState, TransferState, executeRoute };