@skip-go/client 1.6.0-alpha.3 → 1.6.0-alpha.5

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