@shogun-sdk/swap 0.0.2-test.4 → 0.0.2-test.40

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.
package/dist/index.cjs CHANGED
@@ -3,6 +3,7 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
7
  var __export = (target, all) => {
7
8
  for (var name in all)
8
9
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -16,45 +17,29 @@ var __copyProps = (to, from, except, desc) => {
16
17
  return to;
17
18
  };
18
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
19
21
 
20
22
  // src/index.ts
21
23
  var src_exports = {};
22
24
  __export(src_exports, {
23
- NATIVE_TOKEN: () => NATIVE_TOKEN,
24
- SOLANA_CHAIN_ID: () => SOLANA_CHAIN_ID,
25
+ ChainId: () => ChainId,
26
+ OrderExecutionType: () => OrderExecutionType,
25
27
  SupportedChains: () => SupportedChains,
26
- adaptEthersSigner: () => adaptEthersSigner,
27
- adaptSolanaWallet: () => adaptSolanaWallet,
28
- adaptViemWallet: () => adaptViemWallet,
28
+ SwapSDK: () => SwapSDK,
29
29
  buildQuoteParams: () => buildQuoteParams,
30
- executeOrder: () => executeOrder,
31
- getBalances: () => getBalances,
32
- getQuote: () => getQuote,
33
- getTokenList: () => getTokenList,
34
- isNativeAddress: () => isNativeAddress,
35
- isViemWalletClient: () => isViemWalletClient,
36
- serializeBigIntsToStrings: () => serializeBigIntsToStrings,
37
- useBalances: () => useBalances,
38
- useExecuteOrder: () => useExecuteOrder,
39
- useQuote: () => useQuote,
40
- useTokenList: () => useTokenList
30
+ isEvmChain: () => isEvmChain
41
31
  });
42
32
  module.exports = __toCommonJS(src_exports);
43
33
 
44
- // src/core/token-list.ts
45
- var import_intents_sdk = require("@shogun-sdk/intents-sdk");
46
- async function getTokenList(params) {
47
- return (0, import_intents_sdk.getTokenList)(params);
48
- }
49
-
50
34
  // src/core/getQuote.ts
51
- var import_intents_sdk4 = require("@shogun-sdk/intents-sdk");
52
- var import_viem = require("viem");
53
-
54
- // src/core/executeOrder/normalizeNative.ts
55
35
  var import_intents_sdk3 = require("@shogun-sdk/intents-sdk");
36
+ var import_viem2 = require("viem");
37
+
38
+ // src/core/execute/normalizeNative.ts
39
+ var import_intents_sdk2 = require("@shogun-sdk/intents-sdk");
56
40
 
57
41
  // src/utils/address.ts
42
+ var import_viem = require("viem");
58
43
  var NATIVE_TOKEN = {
59
44
  ETH: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
60
45
  SOL: "So11111111111111111111111111111111111111111",
@@ -65,13 +50,32 @@ var isNativeAddress = (tokenAddress) => {
65
50
  const normalizedTokenAddress = tokenAddress.toLowerCase();
66
51
  return !!tokenAddress && NATIVE_ADDRESSES.includes(normalizedTokenAddress);
67
52
  };
53
+ function normalizeEvmTokenAddress(address) {
54
+ const lower = address.toLowerCase();
55
+ return lower === NATIVE_TOKEN.ETH.toLowerCase() ? import_viem.zeroAddress : address;
56
+ }
68
57
 
69
58
  // src/utils/chain.ts
70
- var import_intents_sdk2 = require("@shogun-sdk/intents-sdk");
71
- var SOLANA_CHAIN_ID = import_intents_sdk2.ChainID.Solana;
72
- var SupportedChains = [
59
+ var import_intents_sdk = require("@shogun-sdk/intents-sdk");
60
+ var SOLANA_CHAIN_ID = import_intents_sdk.ChainID.Solana;
61
+ var CURRENT_SUPPORTED = [
62
+ import_intents_sdk.ChainID.Solana,
63
+ import_intents_sdk.ChainID.BSC,
64
+ import_intents_sdk.ChainID.Base,
65
+ import_intents_sdk.ChainID.MONAD
66
+ ];
67
+ var ChainId = Object.entries(import_intents_sdk.ChainID).reduce(
68
+ (acc, [key, value]) => {
69
+ if (typeof value === "number" && CURRENT_SUPPORTED.includes(value)) {
70
+ acc[key] = value;
71
+ }
72
+ return acc;
73
+ },
74
+ {}
75
+ );
76
+ var SupportedChainsInternal = [
73
77
  {
74
- id: import_intents_sdk2.ChainID.Arbitrum,
78
+ id: import_intents_sdk.ChainID.Arbitrum,
75
79
  name: "Arbitrum",
76
80
  isEVM: true,
77
81
  wrapped: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
@@ -80,7 +84,7 @@ var SupportedChains = [
80
84
  tokenAddress: NATIVE_TOKEN.ETH
81
85
  },
82
86
  {
83
- id: import_intents_sdk2.ChainID.Optimism,
87
+ id: import_intents_sdk.ChainID.Optimism,
84
88
  name: "Optimism",
85
89
  isEVM: true,
86
90
  wrapped: "0x4200000000000000000000000000000000000006",
@@ -89,7 +93,7 @@ var SupportedChains = [
89
93
  tokenAddress: NATIVE_TOKEN.ETH
90
94
  },
91
95
  {
92
- id: import_intents_sdk2.ChainID.Base,
96
+ id: import_intents_sdk.ChainID.Base,
93
97
  name: "Base",
94
98
  isEVM: true,
95
99
  wrapped: "0x4200000000000000000000000000000000000006",
@@ -98,7 +102,7 @@ var SupportedChains = [
98
102
  tokenAddress: NATIVE_TOKEN.ETH
99
103
  },
100
104
  {
101
- id: import_intents_sdk2.ChainID.Hyperliquid,
105
+ id: import_intents_sdk.ChainID.Hyperliquid,
102
106
  name: "Hyperliquid",
103
107
  isEVM: true,
104
108
  wrapped: "0x5555555555555555555555555555555555555555",
@@ -107,7 +111,7 @@ var SupportedChains = [
107
111
  tokenAddress: NATIVE_TOKEN.ETH
108
112
  },
109
113
  {
110
- id: import_intents_sdk2.ChainID.BSC,
114
+ id: import_intents_sdk.ChainID.BSC,
111
115
  name: "BSC",
112
116
  isEVM: true,
113
117
  wrapped: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",
@@ -123,8 +127,21 @@ var SupportedChains = [
123
127
  symbol: "SOL",
124
128
  decimals: 9,
125
129
  tokenAddress: NATIVE_TOKEN.SOL
130
+ },
131
+ {
132
+ id: import_intents_sdk.ChainID.MONAD,
133
+ name: "Monad",
134
+ isEVM: true,
135
+ wrapped: "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
136
+ symbol: "MON",
137
+ decimals: 18,
138
+ tokenAddress: NATIVE_TOKEN.ETH
126
139
  }
127
140
  ];
141
+ var SupportedChains = SupportedChainsInternal.filter(
142
+ (c) => CURRENT_SUPPORTED.includes(c.id)
143
+ );
144
+ var isEvmChain = import_intents_sdk.isEvmChain;
128
145
 
129
146
  // src/utils/viem.ts
130
147
  function isViemWalletClient(wallet) {
@@ -152,9 +169,9 @@ function serializeBigIntsToStrings(obj) {
152
169
  return obj;
153
170
  }
154
171
 
155
- // src/core/executeOrder/normalizeNative.ts
172
+ // src/core/execute/normalizeNative.ts
156
173
  function normalizeNative(chainId, address) {
157
- if ((0, import_intents_sdk3.isEvmChain)(chainId) && isNativeAddress(address)) {
174
+ if ((0, import_intents_sdk2.isEvmChain)(chainId) && isNativeAddress(address)) {
158
175
  const chain = SupportedChains.find((c) => c.id === chainId);
159
176
  if (!chain?.wrapped)
160
177
  throw new Error(`Wrapped token not found for chainId ${chainId}`);
@@ -165,39 +182,43 @@ function normalizeNative(chainId, address) {
165
182
 
166
183
  // src/core/getQuote.ts
167
184
  async function getQuote(params) {
185
+ const amount = BigInt(params.amount);
168
186
  if (!params.tokenIn?.address || !params.tokenOut?.address) {
169
187
  throw new Error("Both tokenIn and tokenOut must include an address.");
170
188
  }
171
189
  if (!params.sourceChainId || !params.destChainId) {
172
190
  throw new Error("Both sourceChainId and destChainId are required.");
173
191
  }
174
- if (params.amount <= 0n) {
192
+ if (amount <= 0n) {
175
193
  throw new Error("Amount must be greater than 0.");
176
194
  }
177
195
  const normalizedTokenIn = normalizeNative(params.sourceChainId, params.tokenIn.address);
178
- const data = await import_intents_sdk4.QuoteProvider.getQuote({
196
+ const data = await import_intents_sdk3.QuoteProvider.getQuote({
179
197
  sourceChainId: params.sourceChainId,
180
198
  destChainId: params.destChainId,
181
199
  tokenIn: normalizedTokenIn,
182
200
  tokenOut: params.tokenOut.address,
183
- amount: params.amount
201
+ amount
184
202
  });
185
- const inputSlippage = params.slippage ?? 5;
186
- const slippageDecimal = inputSlippage / 100;
187
- const slippage = Math.min(Math.max(slippageDecimal, 0), 0.5);
203
+ const slippagePercent = Math.min(Math.max(params.slippage ?? 0.5, 0), 50);
188
204
  let warning;
189
- if (slippage > 0.1) {
190
- warning = `\u26A0\uFE0F High slippage tolerance (${(slippage * 100).toFixed(2)}%) \u2014 price may vary significantly.`;
205
+ if (slippagePercent > 10) {
206
+ warning = `\u26A0\uFE0F High slippage tolerance (${slippagePercent.toFixed(2)}%) \u2014 price may vary significantly.`;
191
207
  }
192
- const estimatedAmountOut = BigInt(data.estimatedAmountOutReduced);
193
- const slippageBps = BigInt(Math.round(slippage * 1e4));
208
+ const estimatedAmountOut = BigInt(data.estimatedAmountOut);
209
+ const slippageBps = BigInt(Math.round(slippagePercent * 100));
194
210
  const estimatedAmountOutAfterSlippage = estimatedAmountOut * (10000n - slippageBps) / 10000n;
211
+ const pricePerTokenOutInUsd = data.estimatedAmountOutUsd / Number(data.estimatedAmountOut);
212
+ const amountOutUsdAfterSlippage = Number(estimatedAmountOutAfterSlippage) * pricePerTokenOutInUsd;
213
+ const minStablecoinsAmountValue = BigInt(data.estimatedAmountInAsMinStablecoinAmount);
214
+ const minStablecoinsAmountAfterSlippage = minStablecoinsAmountValue * (10000n - slippageBps) / 10000n;
195
215
  const pricePerInputToken = estimatedAmountOut * 10n ** BigInt(params.tokenIn.decimals ?? 18) / BigInt(params.amount);
196
216
  return {
197
- amountOut: estimatedAmountOut,
198
- amountOutUsd: data.estimatedAmountOutUsd,
217
+ amountOut: estimatedAmountOutAfterSlippage,
218
+ amountOutUsd: amountOutUsdAfterSlippage,
199
219
  amountInUsd: data.amountInUsd,
200
- minStablecoinsAmount: data.estimatedAmountInAsMinStablecoinAmount,
220
+ // Input USD stays the same
221
+ minStablecoinsAmount: minStablecoinsAmountAfterSlippage,
201
222
  tokenIn: {
202
223
  address: params.tokenIn.address,
203
224
  decimals: params.tokenIn.decimals ?? 18,
@@ -208,12 +229,13 @@ async function getQuote(params) {
208
229
  decimals: params.tokenOut.decimals ?? 18,
209
230
  chainId: params.destChainId
210
231
  },
211
- amountIn: params.amount,
232
+ amountIn: BigInt(params.amount),
212
233
  pricePerInputToken,
213
- slippage,
234
+ slippage: slippagePercent,
214
235
  internal: {
215
236
  ...data,
216
- estimatedAmountOutReduced: estimatedAmountOutAfterSlippage
237
+ estimatedAmountOutReduced: estimatedAmountOutAfterSlippage,
238
+ estimatedAmountOutUsdReduced: amountOutUsdAfterSlippage
217
239
  },
218
240
  warning
219
241
  };
@@ -231,13 +253,13 @@ function buildQuoteParams({
231
253
  tokenOut,
232
254
  sourceChainId,
233
255
  destChainId,
234
- amount: (0, import_viem.parseUnits)(amount.toString(), tokenIn.decimals ?? 18),
256
+ amount: (0, import_viem2.parseUnits)(amount.toString(), tokenIn.decimals ?? 18).toString(),
235
257
  slippage
236
258
  };
237
259
  }
238
260
 
239
261
  // src/core/getBalances.ts
240
- var import_intents_sdk5 = require("@shogun-sdk/intents-sdk");
262
+ var import_intents_sdk4 = require("@shogun-sdk/intents-sdk");
241
263
  async function getBalances(params, options) {
242
264
  const { addresses, cursorEvm, cursorSvm } = params;
243
265
  const { signal } = options ?? {};
@@ -250,7 +272,7 @@ async function getBalances(params, options) {
250
272
  cursorSvm
251
273
  });
252
274
  const start = performance.now();
253
- const response = await fetch(`${import_intents_sdk5.TOKEN_SEARCH_API_BASE_URL}/tokens/balances`, {
275
+ const response = await fetch(`${import_intents_sdk4.TOKEN_SEARCH_API_BASE_URL}/tokens/balances`, {
254
276
  method: "POST",
255
277
  headers: {
256
278
  accept: "application/json",
@@ -278,103 +300,70 @@ async function getBalances(params, options) {
278
300
  const evmItems = data.evm?.items ?? [];
279
301
  const svmItems = data.svm?.items ?? [];
280
302
  const combined = [...evmItems, ...svmItems];
303
+ const filtered = combined.filter(
304
+ (b) => CURRENT_SUPPORTED.includes(b.chainId)
305
+ );
281
306
  return {
282
- results: combined,
307
+ results: filtered,
283
308
  nextCursorEvm: data.evm?.cursor ?? null,
284
309
  nextCursorSvm: data.svm?.cursor ?? null
285
310
  };
286
311
  }
287
312
 
288
- // src/core/executeOrder/execute.ts
289
- var import_intents_sdk9 = require("@shogun-sdk/intents-sdk");
290
- var import_viem4 = require("viem");
291
-
292
- // src/wallet-adapter/svm-wallet-adapter/adapter.ts
293
- var import_web3 = require("@solana/web3.js");
294
- var adaptSolanaWallet = (walletAddress, chainId, rpcUrl, signAndSendTransaction) => {
295
- let _chainId = chainId;
296
- const connection = new import_web3.Connection(rpcUrl, { commitment: "confirmed" });
297
- const getChainId = async () => _chainId;
298
- const sendTransaction = async (transaction) => {
299
- const txHash = await signAndSendTransaction(transaction);
300
- console.log(`\u{1F6F0} Sent transaction: ${txHash}`);
301
- const maxRetries = 20;
302
- const delayMs = 2e3;
303
- for (let attempt = 0; attempt < maxRetries; attempt++) {
304
- const res = await connection.getSignatureStatus(txHash, { searchTransactionHistory: true });
305
- if (res?.value?.confirmationStatus === "confirmed" || res?.value?.confirmationStatus === "finalized") {
306
- return txHash;
307
- }
308
- await new Promise((resolve) => setTimeout(resolve, delayMs));
309
- }
310
- throw new Error(`Transaction not confirmed after ${maxRetries * (delayMs / 1e3)}s`);
311
- };
312
- const signTypedData = async () => {
313
- throw new Error("signTypedData not implemented for Solana");
314
- };
315
- const switchChain = async (newChainId) => {
316
- _chainId = newChainId;
317
- };
313
+ // src/core/token-list.ts
314
+ var import_intents_sdk5 = require("@shogun-sdk/intents-sdk");
315
+ async function getTokenList(params) {
316
+ const url = new URL(`${import_intents_sdk5.TOKEN_SEARCH_API_BASE_URL}/tokens/search`);
317
+ if (params.q) url.searchParams.append("q", params.q);
318
+ if (params.networkId) url.searchParams.append("networkId", String(params.networkId));
319
+ if (params.page) url.searchParams.append("page", String(params.page));
320
+ if (params.limit) url.searchParams.append("limit", String(params.limit));
321
+ const res = await fetch(url.toString(), {
322
+ signal: params.signal
323
+ });
324
+ if (!res.ok) {
325
+ throw new Error(`Failed to fetch tokens: ${res.status} ${res.statusText}`);
326
+ }
327
+ const data = await res.json();
328
+ const filteredResults = data.results.filter(
329
+ (token) => CURRENT_SUPPORTED.includes(token.chainId)
330
+ );
318
331
  return {
319
- vmType: "SVM" /* SVM */,
320
- getChainId,
321
- address: async () => walletAddress,
322
- sendTransaction,
323
- switchChain,
324
- signTypedData,
325
- rpcUrl
332
+ ...data,
333
+ results: filteredResults,
334
+ count: filteredResults.length
326
335
  };
327
- };
336
+ }
337
+
338
+ // src/core/token.ts
339
+ var import_intents_sdk6 = require("@shogun-sdk/intents-sdk");
340
+ async function getTokensData(addresses) {
341
+ if (!addresses?.length) return [];
342
+ const response = await fetch(`${import_intents_sdk6.TOKEN_SEARCH_API_BASE_URL}/tokens/tokens`, {
343
+ method: "POST",
344
+ headers: {
345
+ "Content-Type": "application/json",
346
+ accept: "*/*"
347
+ },
348
+ body: JSON.stringify({ addresses })
349
+ });
350
+ if (!response.ok) {
351
+ throw new Error(`Failed to fetch token data: ${response.statusText}`);
352
+ }
353
+ const data = await response.json();
354
+ const filtered = data.filter((t) => CURRENT_SUPPORTED.includes(Number(t.chainId)));
355
+ return filtered;
356
+ }
357
+
358
+ // src/core/execute/execute.ts
359
+ var import_intents_sdk12 = require("@shogun-sdk/intents-sdk");
360
+ var import_viem7 = require("viem");
328
361
 
329
362
  // src/wallet-adapter/evm-wallet-adapter/adapter.ts
330
- var import_ethers = require("ethers/lib/ethers.js");
331
- var import_utils2 = require("ethers/lib/utils.js");
332
- var import_viem2 = require("viem");
363
+ var import_viem3 = require("viem");
333
364
  function isEVMTransaction(tx) {
334
365
  return typeof tx.from === "string";
335
366
  }
336
- var adaptEthersSigner = (signer, transport) => {
337
- const signTypedData = async (signData) => {
338
- const typedSigner = signer;
339
- return await typedSigner._signTypedData(
340
- signData.domain,
341
- signData.types,
342
- signData.value
343
- );
344
- };
345
- const sendTransaction = async (transaction) => {
346
- if (!isEVMTransaction(transaction)) {
347
- throw new Error("Expected EVMTransaction but got SolanaTransaction");
348
- }
349
- const tx = await signer.sendTransaction({
350
- from: transaction.from,
351
- to: transaction.to,
352
- data: transaction.data,
353
- value: transaction.value
354
- });
355
- return tx.hash;
356
- };
357
- const switchChain = async (chainId) => {
358
- try {
359
- await window.ethereum.request({
360
- method: "wallet_switchEthereumChain",
361
- params: [{ chainId: (0, import_utils2.hexValue)(chainId) }]
362
- });
363
- } catch (error) {
364
- console.error("Failed to switch chain:", error);
365
- throw error;
366
- }
367
- };
368
- return {
369
- vmType: "EVM" /* EVM */,
370
- transport,
371
- getChainId: async () => signer.getChainId(),
372
- address: async () => signer.getAddress(),
373
- sendTransaction,
374
- signTypedData,
375
- switchChain
376
- };
377
- };
378
367
  var adaptViemWallet = (wallet) => {
379
368
  const signTypedData = async (signData) => {
380
369
  return await wallet.signTypedData({
@@ -389,15 +378,26 @@ var adaptViemWallet = (wallet) => {
389
378
  if (!isEVMTransaction(transaction)) {
390
379
  throw new Error("Expected EVMTransaction but got SolanaTransaction");
391
380
  }
392
- const tx = await wallet.sendTransaction({
393
- from: transaction.from,
394
- to: transaction.to,
395
- data: transaction.data,
396
- value: transaction.value,
397
- account: wallet.account?.address,
398
- chain: wallet.chain
399
- });
400
- return tx;
381
+ if (wallet.transport.type === "http") {
382
+ const request = await wallet.prepareTransactionRequest({
383
+ to: transaction.to,
384
+ data: transaction.data,
385
+ value: transaction.value,
386
+ chain: wallet.chain
387
+ });
388
+ const serializedTransaction = await wallet.signTransaction(request);
389
+ const tx = await wallet.sendRawTransaction({ serializedTransaction });
390
+ return tx;
391
+ } else {
392
+ const hash = await wallet.sendTransaction({
393
+ to: transaction.to,
394
+ data: transaction.data,
395
+ value: transaction.value,
396
+ chain: wallet.chain,
397
+ account: wallet.account
398
+ });
399
+ return hash;
400
+ }
401
401
  };
402
402
  const switchChain = async (chainId) => {
403
403
  try {
@@ -420,55 +420,96 @@ var adaptViemWallet = (wallet) => {
420
420
  if (!addr) throw new Error("No address found");
421
421
  return addr;
422
422
  };
423
+ const readContract = async ({
424
+ address: address2,
425
+ abi,
426
+ functionName,
427
+ args = []
428
+ }) => {
429
+ const publicClient = wallet.extend(import_viem3.publicActions);
430
+ return await publicClient.readContract({
431
+ address: address2,
432
+ abi,
433
+ functionName,
434
+ args
435
+ });
436
+ };
423
437
  return {
424
438
  vmType: "EVM" /* EVM */,
425
- transport: (0, import_viem2.custom)(wallet.transport),
439
+ transport: (0, import_viem3.custom)(wallet.transport),
426
440
  getChainId: async () => wallet.getChainId(),
427
441
  address,
428
442
  sendTransaction,
429
443
  signTypedData,
430
- switchChain
444
+ switchChain,
445
+ readContract
431
446
  };
432
447
  };
433
448
 
434
- // src/core/executeOrder/handleEvmExecution.ts
435
- var import_intents_sdk7 = require("@shogun-sdk/intents-sdk");
436
- var import_viem3 = require("viem");
449
+ // src/core/execute/handleEvmExecution.ts
450
+ var import_intents_sdk10 = require("@shogun-sdk/intents-sdk");
451
+ var import_viem6 = require("viem");
437
452
 
438
- // src/core/executeOrder/stageMessages.ts
453
+ // src/core/execute/stageMessages.ts
439
454
  var DEFAULT_STAGE_MESSAGES = {
440
455
  processing: "Preparing transaction for execution",
441
456
  approving: "Approving token allowance",
442
457
  approved: "Token approved successfully",
443
- signing: "Signing order for submission",
444
- submitting: "Submitting order to Auctioneer",
445
- success: "Order executed successfully",
446
- error: "Order execution failed"
458
+ signing: "Signing transaction for submission",
459
+ submitting: "Submitting transaction",
460
+ initiated: "Transaction initiated.",
461
+ success: "Transaction Executed successfully",
462
+ success_limit: "Limit order has been submitted successfully.",
463
+ shogun_processing: "Shogun is processing your transaction",
464
+ error: "Transaction failed during submission"
447
465
  };
448
466
 
449
- // src/core/executeOrder/buildOrder.ts
450
- var import_intents_sdk6 = require("@shogun-sdk/intents-sdk");
467
+ // src/core/execute/buildOrder.ts
468
+ var import_intents_sdk7 = require("@shogun-sdk/intents-sdk");
469
+ var import_viem4 = require("viem");
470
+
471
+ // src/utils/order.ts
472
+ var OrderExecutionType = /* @__PURE__ */ ((OrderExecutionType2) => {
473
+ OrderExecutionType2["LIMIT"] = "limit";
474
+ OrderExecutionType2["MARKET"] = "market";
475
+ return OrderExecutionType2;
476
+ })(OrderExecutionType || {});
477
+
478
+ // src/core/execute/buildOrder.ts
451
479
  async function buildOrder({
452
480
  quote,
453
481
  accountAddress,
454
482
  destination,
455
483
  deadline,
456
- isSingleChain
484
+ isSingleChain,
485
+ orderType,
486
+ options
457
487
  }) {
458
488
  const { tokenIn, tokenOut } = quote;
489
+ let amountOutMin = BigInt(quote.internal.estimatedAmountOutReduced);
490
+ if (orderType === "limit" /* LIMIT */ && options && "executionPrice" in options) {
491
+ const executionPrice = Number(options.executionPrice);
492
+ if (Number.isFinite(executionPrice) && executionPrice > 0) {
493
+ const decimalsIn = tokenIn.decimals ?? 18;
494
+ const decimalsOut = tokenOut.decimals ?? 18;
495
+ const formattedAmountIn = Number((0, import_viem4.formatUnits)(BigInt(quote.amountIn.toString()), decimalsIn));
496
+ const rawAmountOut = formattedAmountIn * executionPrice;
497
+ amountOutMin = (0, import_viem4.parseUnits)(rawAmountOut.toString(), decimalsOut);
498
+ }
499
+ }
459
500
  if (isSingleChain) {
460
- return await import_intents_sdk6.SingleChainOrder.create({
501
+ return await import_intents_sdk7.SingleChainOrder.create({
461
502
  user: accountAddress,
462
503
  chainId: tokenIn.chainId,
463
504
  tokenIn: tokenIn.address,
464
505
  tokenOut: tokenOut.address,
465
506
  amountIn: quote.amountIn,
466
- amountOutMin: quote.internal.estimatedAmountOutReduced,
507
+ amountOutMin,
467
508
  deadline,
468
509
  destinationAddress: destination
469
510
  });
470
511
  }
471
- return await import_intents_sdk6.CrossChainOrder.create({
512
+ return await import_intents_sdk7.CrossChainOrder.create({
472
513
  user: accountAddress,
473
514
  sourceChainId: tokenIn.chainId,
474
515
  sourceTokenAddress: tokenIn.address,
@@ -477,12 +518,166 @@ async function buildOrder({
477
518
  destinationTokenAddress: tokenOut.address,
478
519
  destinationAddress: destination,
479
520
  deadline,
480
- destinationTokenMinAmount: quote.internal.estimatedAmountOutReduced,
521
+ destinationTokenMinAmount: amountOutMin,
481
522
  minStablecoinAmount: quote.minStablecoinsAmount
482
523
  });
483
524
  }
484
525
 
485
- // src/core/executeOrder/handleEvmExecution.ts
526
+ // src/utils/pollOrderStatus.ts
527
+ var import_intents_sdk8 = require("@shogun-sdk/intents-sdk");
528
+ async function pollOrderStatus(address, orderId, options = {}) {
529
+ const { intervalMs = 2e3, timeoutMs = 3e5, authToken } = options;
530
+ const startTime = Date.now();
531
+ const isDebug = process.env.NODE_ENV !== "production";
532
+ const isEvmAddress = /^0x[a-fA-F0-9]{40}$/.test(address);
533
+ const isSuiAddress = /^0x[a-fA-F0-9]{64}$/.test(address);
534
+ const isSolanaAddress = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address);
535
+ let queryParam;
536
+ if (isEvmAddress) queryParam = `evmWallets=${address}`;
537
+ else if (isSuiAddress) queryParam = `suiWallets=${address}`;
538
+ else if (isSolanaAddress) queryParam = `solanaWallets=${address}`;
539
+ else throw new Error(`Unrecognized wallet address format: ${address}`);
540
+ const queryUrl = `${import_intents_sdk8.AUCTIONEER_URL}/user_intent?${queryParam}`;
541
+ return new Promise((resolve, reject) => {
542
+ const pollInterval = setInterval(async () => {
543
+ try {
544
+ if (Date.now() - startTime > timeoutMs) {
545
+ clearInterval(pollInterval);
546
+ return resolve("Timeout");
547
+ }
548
+ const res = await fetch(queryUrl, {
549
+ method: "GET",
550
+ headers: {
551
+ "Content-Type": "application/json",
552
+ // The /user_intent status endpoint requires the SIWE JWT; without it
553
+ // the request 401s after the order has already been submitted.
554
+ ...authToken ? { Authorization: `Bearer ${authToken}` } : {}
555
+ }
556
+ });
557
+ if (!res.ok) {
558
+ clearInterval(pollInterval);
559
+ return reject(
560
+ new Error(`Failed to fetch orders: ${res.status} ${res.statusText}`)
561
+ );
562
+ }
563
+ const json = await res.json();
564
+ const data = json?.data ?? {};
565
+ const allOrders = [
566
+ ...data.crossChainDcaOrders ?? [],
567
+ ...data.crossChainLimitOrders ?? [],
568
+ ...data.singleChainDcaOrders ?? [],
569
+ ...data.singleChainLimitOrders ?? []
570
+ ];
571
+ const targetOrder = allOrders.find((o) => o.orderId === orderId);
572
+ if (!targetOrder) {
573
+ if (isDebug)
574
+ console.debug(`[pollOrderStatus] [${orderId}] Not found yet`);
575
+ return;
576
+ }
577
+ const { orderStatus } = targetOrder;
578
+ if (isDebug) {
579
+ const elapsed = ((Date.now() - startTime) / 1e3).toFixed(1);
580
+ console.debug(`targetOrder`, targetOrder);
581
+ console.debug(
582
+ `[pollOrderStatus] [${orderId}] status=${orderStatus} (elapsed ${elapsed}s)`
583
+ );
584
+ }
585
+ if (["Fulfilled", "Cancelled", "Outdated"].includes(orderStatus)) {
586
+ clearInterval(pollInterval);
587
+ return resolve(orderStatus);
588
+ }
589
+ } catch (error) {
590
+ clearInterval(pollInterval);
591
+ return reject(error);
592
+ }
593
+ }, intervalMs);
594
+ });
595
+ }
596
+
597
+ // src/core/execute/handleOrderPollingResult.ts
598
+ async function handleOrderPollingResult({
599
+ status,
600
+ orderId,
601
+ chainId,
602
+ update,
603
+ messageFor
604
+ }) {
605
+ switch (status) {
606
+ case "Fulfilled":
607
+ update("success", messageFor("success"));
608
+ return {
609
+ status: true,
610
+ orderId,
611
+ chainId,
612
+ finalStatus: status,
613
+ stage: "success"
614
+ };
615
+ case "Cancelled":
616
+ update("error", "Order was cancelled before fulfillment");
617
+ break;
618
+ case "Timeout":
619
+ update("error", "Order polling timed out");
620
+ break;
621
+ case "NotFound":
622
+ default:
623
+ update("error", "Order not found");
624
+ break;
625
+ }
626
+ return {
627
+ status: false,
628
+ orderId,
629
+ chainId,
630
+ finalStatus: status,
631
+ stage: "error"
632
+ };
633
+ }
634
+
635
+ // src/core/execute/ensurePermit2Allowance.ts
636
+ var import_viem5 = require("viem");
637
+ var import_intents_sdk9 = require("@shogun-sdk/intents-sdk");
638
+ async function ensurePermit2Allowance({
639
+ chainId,
640
+ tokenIn,
641
+ wallet,
642
+ accountAddress,
643
+ requiredAmount,
644
+ increaseByDelta = false
645
+ }) {
646
+ const spender = import_intents_sdk9.PERMIT2_ADDRESS[chainId];
647
+ let currentAllowance = 0n;
648
+ try {
649
+ if (!wallet.readContract) {
650
+ throw new Error("Wallet does not implement readContract()");
651
+ }
652
+ currentAllowance = await wallet.readContract({
653
+ address: tokenIn,
654
+ abi: import_viem5.erc20Abi,
655
+ functionName: "allowance",
656
+ args: [accountAddress, spender]
657
+ });
658
+ } catch (error) {
659
+ console.warn(`[Permit2] Failed to read allowance for ${tokenIn}`, error);
660
+ }
661
+ const approvalAmount = increaseByDelta ? currentAllowance + requiredAmount : import_viem5.maxUint256;
662
+ console.debug(
663
+ `[Permit2] Approving ${approvalAmount} for ${tokenIn} (current: ${currentAllowance}, required: ${requiredAmount})`
664
+ );
665
+ await wallet.sendTransaction({
666
+ to: tokenIn,
667
+ from: accountAddress,
668
+ data: (0, import_viem5.encodeFunctionData)({
669
+ abi: import_viem5.erc20Abi,
670
+ functionName: "approve",
671
+ args: [spender, approvalAmount]
672
+ }),
673
+ value: 0n
674
+ });
675
+ console.info(
676
+ `[Permit2] Approval transaction sent for ${tokenIn} on chain ${chainId}`
677
+ );
678
+ }
679
+
680
+ // src/core/execute/handleEvmExecution.ts
486
681
  async function handleEvmExecution({
487
682
  recipientAddress,
488
683
  quote,
@@ -490,18 +685,22 @@ async function handleEvmExecution({
490
685
  accountAddress,
491
686
  wallet,
492
687
  isSingleChain,
493
- deadline,
494
- update
688
+ update,
689
+ orderType,
690
+ options
495
691
  }) {
496
- const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage];
692
+ const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage] ?? "";
693
+ const deadline = options?.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
497
694
  await wallet.switchChain(chainId);
498
695
  const tokenIn = normalizeNative(chainId, quote.tokenIn.address);
696
+ quote.tokenOut.address = normalizeEvmTokenAddress(quote.tokenOut.address);
499
697
  const shouldWrapNative = isNativeAddress(quote.tokenIn.address);
500
698
  update("processing", shouldWrapNative ? `${messageFor("processing")} (wrapping native token)` : messageFor("processing"));
501
699
  if (shouldWrapNative) {
700
+ quote.tokenIn.address === tokenIn;
502
701
  await wallet.sendTransaction({
503
702
  to: tokenIn,
504
- data: (0, import_viem3.encodeFunctionData)({
703
+ data: (0, import_viem6.encodeFunctionData)({
505
704
  abi: [{ type: "function", name: "deposit", stateMutability: "payable", inputs: [], outputs: [] }],
506
705
  functionName: "deposit",
507
706
  args: []
@@ -510,44 +709,71 @@ async function handleEvmExecution({
510
709
  from: accountAddress
511
710
  });
512
711
  }
513
- update("approving", messageFor("approving"));
514
- await wallet.sendTransaction({
515
- to: tokenIn,
516
- data: (0, import_viem3.encodeFunctionData)({
517
- abi: import_viem3.erc20Abi,
518
- functionName: "approve",
519
- args: [import_intents_sdk7.PERMIT2_ADDRESS[chainId], BigInt(quote.amountIn)]
520
- }),
521
- value: 0n,
522
- from: accountAddress
712
+ update("processing", messageFor("approving"));
713
+ await ensurePermit2Allowance({
714
+ chainId,
715
+ tokenIn,
716
+ wallet,
717
+ accountAddress,
718
+ requiredAmount: BigInt(quote.amountIn)
523
719
  });
524
- update("approved", messageFor("approved"));
720
+ update("processing", messageFor("approved"));
525
721
  const destination = recipientAddress ?? accountAddress;
526
722
  const order = await buildOrder({
527
723
  quote,
528
724
  accountAddress,
529
725
  destination,
530
726
  deadline,
531
- isSingleChain
727
+ isSingleChain,
728
+ orderType,
729
+ options
532
730
  });
533
- update("signing", messageFor("signing"));
534
- const { orderTypedData, nonce } = isSingleChain ? await (0, import_intents_sdk7.getEVMSingleChainOrderTypedData)(order) : await (0, import_intents_sdk7.getEVMCrossChainOrderTypedData)(order);
731
+ console.debug(`order`, order);
732
+ update("processing", messageFor("signing"));
733
+ const { orderTypedData, nonce } = isSingleChain ? await (0, import_intents_sdk10.getEVMSingleChainOrderTypedData)(order) : await (0, import_intents_sdk10.getEVMCrossChainOrderTypedData)(order);
734
+ const typedData = serializeBigIntsToStrings(orderTypedData);
535
735
  if (!wallet.signTypedData) {
536
736
  throw new Error("Wallet does not support EIP-712 signing");
537
737
  }
538
- const signature = await wallet.signTypedData(serializeBigIntsToStrings(orderTypedData));
539
- update("submitting", messageFor("submitting"));
738
+ const signature = await wallet.signTypedData({
739
+ domain: typedData.domain,
740
+ types: typedData.types,
741
+ primaryType: typedData.primaryType,
742
+ value: typedData.message,
743
+ message: typedData.message
744
+ });
745
+ update("processing", messageFor("submitting"));
540
746
  const res = await order.sendToAuctioneer({ signature, nonce: nonce.toString() });
541
747
  if (!res.success) {
542
748
  throw new Error("Auctioneer submission failed");
543
749
  }
544
- update("success", messageFor("success"));
545
- return { status: true, txHash: res.data, chainId, stage: "success" };
750
+ update("initiated", messageFor("initiated"));
751
+ const { intentId: orderId } = res.data;
752
+ update("initiated", messageFor("shogun_processing"));
753
+ if (orderType === "limit" /* LIMIT */) {
754
+ update("success", messageFor("success_limit"));
755
+ return {
756
+ status: true,
757
+ orderId,
758
+ chainId,
759
+ finalStatus: "OrderPlaced",
760
+ stage: "success"
761
+ };
762
+ } else {
763
+ const status = await pollOrderStatus(accountAddress, orderId, { authToken: options?.authToken });
764
+ return await handleOrderPollingResult({
765
+ status,
766
+ orderId,
767
+ chainId,
768
+ update,
769
+ messageFor
770
+ });
771
+ }
546
772
  }
547
773
 
548
- // src/core/executeOrder/handleSolanaExecution.ts
549
- var import_intents_sdk8 = require("@shogun-sdk/intents-sdk");
550
- var import_web32 = require("@solana/web3.js");
774
+ // src/core/execute/handleSolanaExecution.ts
775
+ var import_intents_sdk11 = require("@shogun-sdk/intents-sdk");
776
+ var import_web3 = require("@solana/web3.js");
551
777
  async function handleSolanaExecution({
552
778
  recipientAddress,
553
779
  quote,
@@ -555,12 +781,14 @@ async function handleSolanaExecution({
555
781
  isSingleChain,
556
782
  update,
557
783
  accountAddress,
558
- deadline
784
+ orderType,
785
+ options
559
786
  }) {
560
787
  if (!wallet.rpcUrl) {
561
788
  throw new Error("Solana wallet is missing rpcUrl");
562
789
  }
563
- const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage];
790
+ const deadline = options?.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
791
+ const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage] ?? "";
564
792
  update("processing", messageFor("processing"));
565
793
  const destination = recipientAddress ?? accountAddress;
566
794
  const order = await buildOrder({
@@ -568,18 +796,19 @@ async function handleSolanaExecution({
568
796
  accountAddress,
569
797
  destination,
570
798
  deadline,
571
- isSingleChain
799
+ isSingleChain,
800
+ orderType,
801
+ options
572
802
  });
573
803
  const txData = await getSolanaOrderInstructions({
574
804
  order,
575
805
  isSingleChain,
576
806
  rpcUrl: wallet.rpcUrl
577
807
  });
578
- const transaction = import_web32.VersionedTransaction.deserialize(Uint8Array.from(txData.txBytes));
579
- update("signing", messageFor("signing"));
580
- console.log({ order });
581
- const txSignature = await wallet.sendTransaction(transaction);
582
- update("submitting", messageFor("submitting"));
808
+ const transaction = import_web3.VersionedTransaction.deserialize(Uint8Array.from(txData.txBytes));
809
+ update("processing", messageFor("signing"));
810
+ await wallet.sendTransaction(transaction);
811
+ update("processing", messageFor("submitting"));
583
812
  const response = await submitToAuctioneer({
584
813
  order,
585
814
  isSingleChain,
@@ -588,13 +817,28 @@ async function handleSolanaExecution({
588
817
  if (!response.success) {
589
818
  throw new Error("Auctioneer submission failed");
590
819
  }
591
- update("success", messageFor("success"));
592
- return {
593
- status: true,
594
- txHash: txSignature,
595
- chainId: import_intents_sdk8.ChainID.Solana,
596
- stage: "success"
597
- };
820
+ update("initiated", messageFor("initiated"));
821
+ const { intentId: orderId } = response.data;
822
+ update("initiated", messageFor("shogun_processing"));
823
+ if (orderType === "limit" /* LIMIT */) {
824
+ update("success", messageFor("success_limit"));
825
+ return {
826
+ status: true,
827
+ orderId,
828
+ chainId: SOLANA_CHAIN_ID,
829
+ finalStatus: "OrderPlaced",
830
+ stage: "success"
831
+ };
832
+ } else {
833
+ const status = await pollOrderStatus(accountAddress, orderId, { authToken: options?.authToken });
834
+ return await handleOrderPollingResult({
835
+ status,
836
+ orderId,
837
+ chainId: SOLANA_CHAIN_ID,
838
+ update,
839
+ messageFor
840
+ });
841
+ }
598
842
  }
599
843
  async function getSolanaOrderInstructions({
600
844
  order,
@@ -602,11 +846,11 @@ async function getSolanaOrderInstructions({
602
846
  rpcUrl
603
847
  }) {
604
848
  if (isSingleChain) {
605
- return await (0, import_intents_sdk8.getSolanaSingleChainOrderInstructions)(order, {
849
+ return await (0, import_intents_sdk11.getSolanaSingleChainOrderInstructions)(order, {
606
850
  rpcUrl
607
851
  });
608
852
  }
609
- return await (0, import_intents_sdk8.getSolanaCrossChainOrderInstructions)(order, {
853
+ return await (0, import_intents_sdk11.getSolanaCrossChainOrderInstructions)(order, {
610
854
  rpcUrl
611
855
  });
612
856
  }
@@ -627,52 +871,93 @@ async function submitToAuctioneer({
627
871
  });
628
872
  }
629
873
 
630
- // src/core/executeOrder/execute.ts
874
+ // src/core/execute/execute.ts
631
875
  async function executeOrder({
632
876
  quote,
633
877
  accountAddress,
634
878
  recipientAddress,
635
879
  wallet,
636
880
  onStatus,
881
+ orderType = "market" /* MARKET */,
637
882
  options = {}
638
883
  }) {
639
- const deadline = options.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
884
+ const isDev = process.env.NODE_ENV !== "production";
885
+ const log = (...args) => {
886
+ if (isDev) console.debug("[OneShot::executeOrder]", ...args);
887
+ };
640
888
  const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage];
641
- const update = (stage, message) => onStatus?.(stage, message ?? messageFor(stage));
889
+ const update = (stage, message) => {
890
+ log("Stage:", stage, "| Message:", message ?? messageFor(stage));
891
+ onStatus?.(stage, message ?? messageFor(stage));
892
+ };
642
893
  try {
894
+ log("Starting execution:", {
895
+ accountAddress,
896
+ recipientAddress,
897
+ tokenIn: quote?.tokenIn,
898
+ tokenOut: quote?.tokenOut
899
+ });
643
900
  const adapter = normalizeWallet(wallet);
644
901
  if (!adapter) throw new Error("No wallet provided");
645
902
  const { tokenIn, tokenOut } = quote;
903
+ const srcChain = Number(tokenIn.chainId);
904
+ const destChain = Number(tokenOut.chainId);
905
+ if (!CURRENT_SUPPORTED.includes(srcChain) || !CURRENT_SUPPORTED.includes(destChain)) {
906
+ const unsupportedChains = [
907
+ !CURRENT_SUPPORTED.includes(srcChain) ? srcChain : null,
908
+ !CURRENT_SUPPORTED.includes(destChain) ? destChain : null
909
+ ].filter(Boolean).join(", ");
910
+ const errorMsg = `Unsupported chain(s): ${unsupportedChains}`;
911
+ update("error", errorMsg);
912
+ log("Error:", errorMsg);
913
+ throw new Error(errorMsg);
914
+ }
646
915
  const isSingleChain = tokenIn.chainId === tokenOut.chainId;
647
916
  const chainId = Number(tokenIn.chainId);
648
- update("processing", messageFor("processing"));
649
- if ((0, import_intents_sdk9.isEvmChain)(chainId)) {
650
- return await handleEvmExecution({
917
+ update("processing");
918
+ if ((0, import_intents_sdk12.isEvmChain)(chainId)) {
919
+ log("Detected EVM chain:", chainId);
920
+ const result = await handleEvmExecution({
651
921
  recipientAddress,
652
922
  quote,
653
923
  chainId,
654
924
  accountAddress,
655
925
  wallet: adapter,
656
926
  isSingleChain,
657
- deadline,
658
- update
927
+ update,
928
+ orderType,
929
+ options
659
930
  });
931
+ log("EVM execution result:", result);
932
+ return result;
660
933
  }
661
- if (chainId === import_intents_sdk9.ChainID.Solana) {
662
- return await handleSolanaExecution({
934
+ if (chainId === import_intents_sdk12.ChainID.Solana) {
935
+ log("Detected Solana chain");
936
+ const result = await handleSolanaExecution({
663
937
  recipientAddress,
664
938
  quote,
665
939
  accountAddress,
666
940
  wallet: adapter,
667
941
  isSingleChain,
668
- deadline,
669
- update
942
+ update,
943
+ orderType,
944
+ options
670
945
  });
946
+ log("Solana execution result:", result);
947
+ return result;
671
948
  }
672
- update("error", "Unsupported chain");
673
- return { status: false, message: "Unsupported chain", stage: "error" };
949
+ const unsupported = `Unsupported chain: ${chainId}`;
950
+ update("error", unsupported);
951
+ log("Error:", unsupported);
952
+ return { status: false, message: unsupported, stage: "error" };
674
953
  } catch (error) {
675
- const message = error instanceof import_viem4.BaseError ? error.shortMessage : error instanceof Error ? error.message : String(error);
954
+ let message = "An unknown error occurred";
955
+ if (error && typeof error === "object") {
956
+ const err = error;
957
+ message = err.details ?? err.message ?? message;
958
+ } else if (typeof error === "string") {
959
+ message = error;
960
+ }
676
961
  update("error", message);
677
962
  return { status: false, message, stage: "error" };
678
963
  }
@@ -683,319 +968,508 @@ function normalizeWallet(wallet) {
683
968
  return wallet;
684
969
  }
685
970
 
686
- // src/react/useTokenList.ts
687
- var import_react = require("react");
688
- var tokenCache = /* @__PURE__ */ new Map();
689
- function useTokenList(params) {
690
- const [data, setData] = (0, import_react.useState)(null);
691
- const [loading, setLoading] = (0, import_react.useState)(false);
692
- const [error, setError] = (0, import_react.useState)(null);
693
- const controllerRef = (0, import_react.useRef)(null);
694
- const debounceRef = (0, import_react.useRef)(null);
695
- const debounceMs = params.debounceMs ?? 250;
696
- const cacheKey = (0, import_react.useMemo)(() => {
697
- return JSON.stringify({
698
- q: params.q?.trim().toLowerCase() ?? "",
699
- networkId: params.networkId ?? "all",
700
- page: params.page ?? 1,
701
- limit: params.limit ?? 50
702
- });
703
- }, [params.q, params.networkId, params.page, params.limit]);
704
- async function fetchTokens(signal) {
705
- if (tokenCache.has(cacheKey)) {
706
- setData(tokenCache.get(cacheKey));
707
- setLoading(false);
708
- setError(null);
709
- return;
710
- }
711
- try {
712
- setLoading(true);
713
- const result = await getTokenList({ ...params, signal });
714
- tokenCache.set(cacheKey, result);
715
- setData(result);
716
- setError(null);
717
- } catch (err) {
718
- if (err.name !== "AbortError") {
719
- const e = err instanceof Error ? err : new Error("Unknown error while fetching tokens");
720
- setError(e);
721
- }
722
- } finally {
723
- setLoading(false);
724
- }
971
+ // src/core/orders/getOrders.ts
972
+ var import_intents_sdk13 = require("@shogun-sdk/intents-sdk");
973
+ async function getOrders({
974
+ evmAddress,
975
+ solAddress
976
+ }) {
977
+ const wallets = [evmAddress, solAddress].filter(
978
+ (wallet) => Boolean(wallet)
979
+ );
980
+ if (wallets.length === 0) {
981
+ throw new Error("At least one wallet address (EVM, Solana) must be provided.");
725
982
  }
726
- (0, import_react.useEffect)(() => {
727
- if (!params.q && !params.networkId) return;
728
- if (debounceRef.current) clearTimeout(debounceRef.current);
729
- if (controllerRef.current) controllerRef.current.abort();
730
- const controller = new AbortController();
731
- controllerRef.current = controller;
732
- debounceRef.current = setTimeout(() => {
733
- fetchTokens(controller.signal);
734
- }, debounceMs);
735
- return () => {
736
- controller.abort();
737
- if (debounceRef.current) clearTimeout(debounceRef.current);
738
- };
739
- }, [cacheKey, debounceMs]);
740
- return (0, import_react.useMemo)(
741
- () => ({
742
- /** Current fetched data (cached when possible) */
743
- data,
744
- /** Whether a request is in progress */
745
- loading,
746
- /** Error object if a request failed */
747
- error,
748
- /** Manually refetch the token list */
749
- refetch: () => fetchTokens(),
750
- /** Clear all cached token results (shared across hook instances) */
751
- clearCache: () => tokenCache.clear()
752
- }),
753
- [data, loading, error]
983
+ const results = await Promise.all(
984
+ wallets.map((wallet) => (0, import_intents_sdk13.fetchUserOrders)({ wallet }))
754
985
  );
755
- }
756
-
757
- // src/react/useExecuteOrder.ts
758
- var import_react2 = require("react");
759
- function useExecuteOrder() {
760
- const [status, setStatus] = (0, import_react2.useState)("processing");
761
- const [message, setMessage] = (0, import_react2.useState)(null);
762
- const [loading, setLoading] = (0, import_react2.useState)(false);
763
- const [data, setData] = (0, import_react2.useState)(null);
764
- const [error, setError] = (0, import_react2.useState)(null);
765
- const isMounted = (0, import_react2.useRef)(true);
766
- (0, import_react2.useEffect)(() => {
767
- return () => {
768
- isMounted.current = false;
769
- };
770
- }, []);
771
- const execute = (0, import_react2.useCallback)(
772
- async ({
773
- quote,
774
- accountAddress,
775
- recipientAddress,
776
- wallet,
777
- deadline
778
- }) => {
779
- if (!quote || !wallet) {
780
- throw new Error("Quote and wallet are required for order execution.");
781
- }
782
- setLoading(true);
783
- setError(null);
784
- setData(null);
785
- setMessage(null);
786
- try {
787
- const effectiveDeadline = deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
788
- const onStatus = (stage, msg) => {
789
- if (!isMounted.current) return;
790
- setStatus(stage);
791
- if (msg) setMessage(msg);
792
- };
793
- const result = await executeOrder({
794
- quote,
795
- accountAddress,
796
- recipientAddress,
797
- wallet,
798
- onStatus,
799
- options: { deadline: effectiveDeadline }
800
- });
801
- if (!isMounted.current) return result;
802
- setData(result);
803
- setStatus(result.stage);
804
- setMessage("Order executed successfully");
805
- return result;
806
- } catch (err) {
807
- const errorObj = err instanceof Error ? err : new Error(String(err));
808
- if (isMounted.current) {
809
- setError(errorObj);
810
- setStatus("error");
811
- setMessage(errorObj.message);
812
- setData({
813
- status: false,
814
- stage: "error",
815
- message: errorObj.message
816
- });
817
- }
818
- return {
819
- status: false,
820
- stage: "error",
821
- message: errorObj.message
822
- };
823
- } finally {
824
- if (isMounted.current) setLoading(false);
825
- }
986
+ return results.reduce(
987
+ (merged, orders) => {
988
+ merged.singleChainLimitOrders.push(...orders.singleChainLimitOrders);
989
+ merged.crossChainLimitOrders.push(...orders.crossChainLimitOrders);
990
+ return merged;
826
991
  },
827
- []
992
+ { singleChainLimitOrders: [], crossChainLimitOrders: [] }
828
993
  );
829
- return {
830
- /** Executes the swap order. */
831
- execute,
832
- /** Current execution stage. */
833
- status,
834
- /** Human-readable status message. */
835
- message,
836
- /** Whether execution is ongoing. */
837
- loading,
838
- /** Raw SDK response data. */
839
- data,
840
- /** Captured error (if execution failed). */
841
- error
842
- };
843
994
  }
844
995
 
845
- // src/react/useQuote.ts
846
- var import_react3 = require("react");
847
- function useQuote(params, options) {
848
- const [data, setData] = (0, import_react3.useState)(null);
849
- const [loading, setLoading] = (0, import_react3.useState)(false);
850
- const [error, setError] = (0, import_react3.useState)(null);
851
- const [warning, setWarning] = (0, import_react3.useState)(null);
852
- const debounceMs = options?.debounceMs ?? 250;
853
- const autoRefreshMs = options?.autoRefreshMs;
854
- const abortRef = (0, import_react3.useRef)(null);
855
- const debounceRef = (0, import_react3.useRef)(null);
856
- const mounted = (0, import_react3.useRef)(false);
857
- (0, import_react3.useEffect)(() => {
858
- mounted.current = true;
859
- return () => {
860
- mounted.current = false;
861
- abortRef.current?.abort();
862
- if (debounceRef.current) clearTimeout(debounceRef.current);
863
- };
864
- }, []);
865
- const fetchQuote = (0, import_react3.useCallback)(
866
- async () => {
867
- if (!params) return;
868
- try {
869
- setLoading(true);
870
- setWarning(null);
871
- const result = await getQuote(params);
872
- const serializeResult = serializeBigIntsToStrings(result);
873
- if (!mounted.current) return;
874
- setData((prev) => {
875
- if (JSON.stringify(prev) === JSON.stringify(serializeResult)) return prev;
876
- return serializeResult;
877
- });
878
- setWarning(result.warning ?? null);
879
- setError(null);
880
- } catch (err) {
881
- if (err.name === "AbortError") return;
882
- console.error("[useQuote] fetch error:", err);
883
- if (mounted.current) setError(err instanceof Error ? err : new Error(String(err)));
884
- } finally {
885
- if (mounted.current) setLoading(false);
886
- }
887
- },
888
- [params]
889
- );
890
- (0, import_react3.useEffect)(() => {
891
- if (!params) return;
892
- if (debounceRef.current) clearTimeout(debounceRef.current);
893
- debounceRef.current = setTimeout(() => {
894
- fetchQuote();
895
- }, debounceMs);
896
- return () => {
897
- if (debounceRef.current) clearTimeout(debounceRef.current);
898
- abortRef.current?.abort();
899
- };
900
- }, [params, debounceMs, fetchQuote]);
901
- (0, import_react3.useEffect)(() => {
902
- if (!autoRefreshMs || !params) return;
903
- const interval = setInterval(() => fetchQuote(), autoRefreshMs);
904
- return () => clearInterval(interval);
905
- }, [autoRefreshMs, params, fetchQuote]);
906
- return (0, import_react3.useMemo)(
907
- () => ({
908
- data,
909
- loading,
910
- error,
911
- warning,
912
- refetch: () => fetchQuote()
913
- }),
914
- [data, loading, error, warning, fetchQuote]
915
- );
996
+ // src/core/orders/cancelOrder.ts
997
+ var import_intents_sdk14 = require("@shogun-sdk/intents-sdk");
998
+ var import_web32 = require("@solana/web3.js");
999
+ var import_viem8 = require("viem");
1000
+ var inFlightCancels = /* @__PURE__ */ new Map();
1001
+ function cancelIntentsOrder(args) {
1002
+ const srcChain = "srcChainId" in args.order ? args.order.srcChainId : args.order.chainId;
1003
+ const key = `${srcChain}:${args.order.orderId}`;
1004
+ const existing = inFlightCancels.get(key);
1005
+ if (existing) return existing;
1006
+ const pending = performCancel(args).finally(() => {
1007
+ inFlightCancels.delete(key);
1008
+ });
1009
+ inFlightCancels.set(key, pending);
1010
+ return pending;
916
1011
  }
917
-
918
- // src/react/useBalances.ts
919
- var import_react4 = require("react");
920
- function useBalances(params) {
921
- const [data, setData] = (0, import_react4.useState)(null);
922
- const [loading, setLoading] = (0, import_react4.useState)(false);
923
- const [error, setError] = (0, import_react4.useState)(null);
924
- const abortRef = (0, import_react4.useRef)(null);
925
- const stableParams = (0, import_react4.useMemo)(() => {
926
- if (!params) return null;
927
- const { addresses, cursorEvm, cursorSvm } = params;
928
- return {
929
- addresses: {
930
- evm: addresses?.evm ?? void 0,
931
- svm: addresses?.svm ?? void 0
932
- },
933
- cursorEvm,
934
- cursorSvm
935
- };
936
- }, [params?.addresses?.evm, params?.addresses?.svm, params?.cursorEvm, params?.cursorSvm]);
937
- const fetchBalances = (0, import_react4.useCallback)(async () => {
938
- if (!stableParams) return;
939
- if (abortRef.current) abortRef.current.abort();
940
- const controller = new AbortController();
941
- abortRef.current = controller;
942
- setLoading(true);
943
- setError(null);
944
- try {
945
- const result = await getBalances(stableParams, { signal: controller.signal });
946
- setData((prev) => {
947
- if (JSON.stringify(prev) === JSON.stringify(result)) return prev;
948
- return result;
1012
+ async function performCancel({
1013
+ order,
1014
+ wallet,
1015
+ sol_rpc
1016
+ }) {
1017
+ const isCrossChain = "srcChainId" in order && "destChainId" in order && order.srcChainId !== order.destChainId;
1018
+ const srcChain = "srcChainId" in order ? order.srcChainId : order.chainId;
1019
+ const isSolanaOrder = srcChain === import_intents_sdk14.ChainID.Solana;
1020
+ if (isSolanaOrder) {
1021
+ if (!isCrossChain) {
1022
+ const { versionedMessageBytes: versionedMessageBytes2 } = await (0, import_intents_sdk14.cancelSingleChainOrderInstructionsAsBytes)(
1023
+ order.orderId,
1024
+ order.user,
1025
+ { rpcUrl: sol_rpc }
1026
+ );
1027
+ const message2 = import_web32.VersionedMessage.deserialize(
1028
+ versionedMessageBytes2
1029
+ );
1030
+ const tx2 = new import_web32.VersionedTransaction(message2);
1031
+ return await wallet.sendTransaction(tx2);
1032
+ }
1033
+ const { versionedMessageBytes } = await (0, import_intents_sdk14.cancelCrossChainOrderInstructionsAsBytes)(
1034
+ order.orderId,
1035
+ order.user,
1036
+ { rpcUrl: sol_rpc }
1037
+ );
1038
+ const message = import_web32.VersionedMessage.deserialize(
1039
+ versionedMessageBytes
1040
+ );
1041
+ const tx = new import_web32.VersionedTransaction(message);
1042
+ return await wallet.sendTransaction(tx);
1043
+ }
1044
+ const chainId = srcChain;
1045
+ const { readContract } = wallet;
1046
+ if (!readContract) {
1047
+ throw new Error("Wallet does not support readContract");
1048
+ }
1049
+ const nonce = BigInt(order.nonce ?? "0");
1050
+ const nonceWordPos = nonce >> 8n;
1051
+ const nonceBitPos = nonce - nonceWordPos * 256n;
1052
+ if (isCrossChain) {
1053
+ const [orderData = [false, false], currentNonceBitmap = 0n] = await Promise.all([
1054
+ readContract({
1055
+ address: import_intents_sdk14.CROSS_CHAIN_GUARD_ADDRESSES[chainId],
1056
+ abi: [
1057
+ {
1058
+ inputs: [{ name: "orderId", type: "bytes32" }],
1059
+ name: "orderData",
1060
+ outputs: [
1061
+ { name: "initialized", type: "bool" },
1062
+ { name: "deactivated", type: "bool" }
1063
+ ],
1064
+ stateMutability: "view",
1065
+ type: "function"
1066
+ }
1067
+ ],
1068
+ functionName: "orderData",
1069
+ args: [order.orderId]
1070
+ }),
1071
+ readContract({
1072
+ address: import_intents_sdk14.PERMIT2_ADDRESS[chainId],
1073
+ abi: [
1074
+ {
1075
+ inputs: [
1076
+ { name: "owner", type: "address" },
1077
+ { name: "wordPos", type: "uint256" }
1078
+ ],
1079
+ name: "nonceBitmap",
1080
+ outputs: [{ name: "", type: "uint256" }],
1081
+ stateMutability: "view",
1082
+ type: "function"
1083
+ }
1084
+ ],
1085
+ functionName: "nonceBitmap",
1086
+ args: [order.user, nonceWordPos]
1087
+ })
1088
+ ]);
1089
+ const [initialized, deactivated] = orderData;
1090
+ if (initialized) {
1091
+ if (deactivated) {
1092
+ throw new Error("Order is already deactivated");
1093
+ }
1094
+ return await wallet.sendTransaction({
1095
+ to: import_intents_sdk14.CROSS_CHAIN_GUARD_ADDRESSES[order.srcChainId],
1096
+ data: (0, import_viem8.encodeFunctionData)({
1097
+ abi: [
1098
+ {
1099
+ inputs: [
1100
+ {
1101
+ components: [
1102
+ { name: "user", type: "address" },
1103
+ { name: "tokenIn", type: "address" },
1104
+ { name: "srcChainId", type: "uint256" },
1105
+ { name: "deadline", type: "uint256" },
1106
+ { name: "amountIn", type: "uint256" },
1107
+ { name: "minStablecoinsAmount", type: "uint256" },
1108
+ { name: "executionDetailsHash", type: "bytes32" },
1109
+ { name: "nonce", type: "uint256" }
1110
+ ],
1111
+ name: "orderInfo",
1112
+ type: "tuple"
1113
+ }
1114
+ ],
1115
+ name: "cancelOrder",
1116
+ outputs: [],
1117
+ stateMutability: "nonpayable",
1118
+ type: "function"
1119
+ }
1120
+ ],
1121
+ functionName: "cancelOrder",
1122
+ args: [
1123
+ {
1124
+ user: order.user,
1125
+ tokenIn: order.tokenIn,
1126
+ srcChainId: BigInt(order.srcChainId),
1127
+ deadline: BigInt(order.deadline),
1128
+ amountIn: BigInt(order.amountIn),
1129
+ minStablecoinsAmount: BigInt(order.minStablecoinsAmount),
1130
+ executionDetailsHash: order.executionDetailsHash,
1131
+ nonce
1132
+ }
1133
+ ]
1134
+ }),
1135
+ value: BigInt(0),
1136
+ from: order.user
1137
+ });
1138
+ } else {
1139
+ if ((currentNonceBitmap & 1n << nonceBitPos) !== 0n) {
1140
+ throw new Error("Nonce is already invalidated");
1141
+ }
1142
+ const mask2 = 1n << nonceBitPos;
1143
+ return await wallet.sendTransaction({
1144
+ to: import_intents_sdk14.PERMIT2_ADDRESS[order.srcChainId],
1145
+ data: (0, import_viem8.encodeFunctionData)({
1146
+ abi: [
1147
+ {
1148
+ inputs: [
1149
+ { name: "wordPos", type: "uint256" },
1150
+ { name: "mask", type: "uint256" }
1151
+ ],
1152
+ name: "invalidateUnorderedNonces",
1153
+ outputs: [],
1154
+ stateMutability: "nonpayable",
1155
+ type: "function"
1156
+ }
1157
+ ],
1158
+ functionName: "invalidateUnorderedNonces",
1159
+ args: [nonceWordPos, mask2]
1160
+ }),
1161
+ value: BigInt(0),
1162
+ from: order.user
949
1163
  });
950
- return result;
951
- } catch (err) {
952
- if (err.name === "AbortError") return;
953
- const e = err instanceof Error ? err : new Error(String(err));
954
- setError(e);
955
- throw e;
956
- } finally {
957
- setLoading(false);
958
1164
  }
959
- }, [stableParams]);
960
- (0, import_react4.useEffect)(() => {
961
- if (stableParams) fetchBalances().catch(() => {
1165
+ }
1166
+ const [wasManuallyInitialized, currentBitmap = 0n] = await Promise.all([
1167
+ readContract({
1168
+ address: import_intents_sdk14.SINGLE_CHAIN_GUARD_ADDRESSES[chainId],
1169
+ abi: [
1170
+ {
1171
+ inputs: [{ name: "orderHash", type: "bytes32" }],
1172
+ name: "orderManuallyInitialized",
1173
+ outputs: [{ name: "", type: "bool" }],
1174
+ stateMutability: "view",
1175
+ type: "function"
1176
+ }
1177
+ ],
1178
+ functionName: "orderManuallyInitialized",
1179
+ args: [order.orderId]
1180
+ }),
1181
+ readContract({
1182
+ address: import_intents_sdk14.PERMIT2_ADDRESS[chainId],
1183
+ abi: [
1184
+ {
1185
+ inputs: [
1186
+ { name: "owner", type: "address" },
1187
+ { name: "wordPos", type: "uint256" }
1188
+ ],
1189
+ name: "nonceBitmap",
1190
+ outputs: [{ name: "", type: "uint256" }],
1191
+ stateMutability: "view",
1192
+ type: "function"
1193
+ }
1194
+ ],
1195
+ functionName: "nonceBitmap",
1196
+ args: [order.user, nonceWordPos]
1197
+ })
1198
+ ]);
1199
+ if (wasManuallyInitialized) {
1200
+ return await wallet.sendTransaction({
1201
+ to: import_intents_sdk14.SINGLE_CHAIN_GUARD_ADDRESSES[chainId],
1202
+ data: (0, import_viem8.encodeFunctionData)({
1203
+ abi: [
1204
+ {
1205
+ inputs: [
1206
+ {
1207
+ name: "order",
1208
+ type: "tuple",
1209
+ components: [
1210
+ { name: "amountIn", type: "uint256" },
1211
+ { name: "tokenIn", type: "address" },
1212
+ { name: "deadline", type: "uint256" },
1213
+ { name: "nonce", type: "uint256" },
1214
+ { name: "encodedExternalCallData", type: "bytes" },
1215
+ {
1216
+ name: "extraTransfers",
1217
+ type: "tuple[]",
1218
+ components: [
1219
+ { name: "amount", type: "uint256" },
1220
+ { name: "receiver", type: "address" },
1221
+ { name: "token", type: "address" }
1222
+ ]
1223
+ },
1224
+ {
1225
+ name: "requestedOutput",
1226
+ type: "tuple",
1227
+ components: [
1228
+ { name: "amount", type: "uint256" },
1229
+ { name: "receiver", type: "address" },
1230
+ { name: "token", type: "address" }
1231
+ ]
1232
+ },
1233
+ { name: "user", type: "address" }
1234
+ ]
1235
+ }
1236
+ ],
1237
+ name: "cancelManuallyCreatedOrder",
1238
+ outputs: [],
1239
+ stateMutability: "nonpayable",
1240
+ type: "function"
1241
+ }
1242
+ ],
1243
+ functionName: "cancelManuallyCreatedOrder",
1244
+ args: [
1245
+ {
1246
+ amountIn: BigInt(order.amountIn),
1247
+ tokenIn: order.tokenIn,
1248
+ deadline: BigInt(order.deadline),
1249
+ nonce,
1250
+ encodedExternalCallData: "0x",
1251
+ extraTransfers: (order.extraTransfers || []).map((t) => ({
1252
+ amount: BigInt(t.amount),
1253
+ receiver: t.receiver,
1254
+ token: t.token
1255
+ })),
1256
+ requestedOutput: {
1257
+ amount: BigInt(order.amountOutMin),
1258
+ receiver: order.destinationAddress,
1259
+ token: order.tokenOut
1260
+ },
1261
+ user: order.user
1262
+ }
1263
+ ]
1264
+ }),
1265
+ value: 0n,
1266
+ from: order.user
962
1267
  });
963
- return () => {
964
- if (abortRef.current) abortRef.current.abort();
965
- };
966
- }, [fetchBalances]);
967
- return (0, import_react4.useMemo)(
968
- () => ({
969
- /** Latest fetched balance data */
970
- data,
971
- /** Whether the hook is currently fetching */
972
- loading,
973
- /** Error object if fetching failed */
974
- error,
975
- /** Manually trigger a refresh */
976
- refetch: fetchBalances
1268
+ }
1269
+ const mask = 1n << nonceBitPos;
1270
+ if ((currentBitmap & mask) !== 0n) {
1271
+ throw new Error("Nonce is already invalidated");
1272
+ }
1273
+ return await wallet.sendTransaction({
1274
+ to: import_intents_sdk14.PERMIT2_ADDRESS[chainId],
1275
+ data: (0, import_viem8.encodeFunctionData)({
1276
+ abi: [
1277
+ {
1278
+ inputs: [
1279
+ { name: "wordPos", type: "uint256" },
1280
+ { name: "mask", type: "uint256" }
1281
+ ],
1282
+ name: "invalidateUnorderedNonces",
1283
+ outputs: [],
1284
+ stateMutability: "nonpayable",
1285
+ type: "function"
1286
+ }
1287
+ ],
1288
+ functionName: "invalidateUnorderedNonces",
1289
+ args: [nonceWordPos, mask]
977
1290
  }),
978
- [data, loading, error, fetchBalances]
979
- );
1291
+ value: 0n,
1292
+ from: order.user
1293
+ });
980
1294
  }
981
- // Annotate the CommonJS export names for ESM import in node:
982
- 0 && (module.exports = {
983
- NATIVE_TOKEN,
984
- SOLANA_CHAIN_ID,
985
- SupportedChains,
986
- adaptEthersSigner,
987
- adaptSolanaWallet,
988
- adaptViemWallet,
989
- buildQuoteParams,
990
- executeOrder,
991
- getBalances,
992
- getQuote,
993
- getTokenList,
994
- isNativeAddress,
995
- isViemWalletClient,
996
- serializeBigIntsToStrings,
997
- useBalances,
998
- useExecuteOrder,
999
- useQuote,
1000
- useTokenList
1001
- });
1295
+
1296
+ // src/core/client.ts
1297
+ var SwapSDK = class {
1298
+ constructor(config) {
1299
+ __publicField(this, "apiKey");
1300
+ /**
1301
+ * Fetches metadata for one or more tokens from the Shogun Token Search API.
1302
+ *
1303
+ * ---
1304
+ * ### Overview
1305
+ * `getTokensData` retrieves normalized token information — such as symbol, name,
1306
+ * decimals, logo URI, and verified status — for a given list of token addresses.
1307
+ *
1308
+ * It supports both **EVM** and **SVM (Solana)** tokens, returning metadata from
1309
+ * Shogun’s unified token registry.
1310
+ *
1311
+ * ---
1312
+ * @example
1313
+ * ```ts
1314
+ * const tokens = await getTokensData([
1315
+ * "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC
1316
+ * "So11111111111111111111111111111111111111112", // SOL
1317
+ * ]);
1318
+ *
1319
+ * console.log(tokens);
1320
+ * [
1321
+ * { symbol: "USDC", name: "USD Coin", chainId: 1, decimals: 6, ... },
1322
+ * { symbol: "SOL", name: "Solana", chainId: 101, decimals: 9, ... }
1323
+ * ]
1324
+ * ```
1325
+ *
1326
+ * @param addresses - An array of token addresses (EVM or SVM) to fetch metadata for.
1327
+ * @returns A promise resolving to an array of {@link TokenInfo} objects.
1328
+ *
1329
+ * @throws Will throw an error if the network request fails or the API responds with a non-OK status.
1330
+ */
1331
+ __publicField(this, "getTokensData", getTokensData.bind(this));
1332
+ if (!config.apiKey) {
1333
+ throw new Error("SwapSDK: Missing API key");
1334
+ }
1335
+ this.apiKey = config.apiKey;
1336
+ if (this.apiKey) void this.apiKey;
1337
+ }
1338
+ /**
1339
+ * Retrieves a swap quote for the given input and output tokens.
1340
+ *
1341
+ * @param params - Quote parameters including source/destination tokens and amount.
1342
+ * @returns A normalized `SwapQuoteResponse` containing output amount, route, and metadata.
1343
+ */
1344
+ async getQuote(params) {
1345
+ return getQuote(params);
1346
+ }
1347
+ /**
1348
+ * Fetches token balances for the specified user wallet(s).
1349
+ *
1350
+ * Supports both EVM and SVM (Solana) wallet addresses.
1351
+ *
1352
+ * @param params - Wallet address and optional chain filters.
1353
+ * @param options - Optional abort signal for cancellation.
1354
+ * @returns A unified balance response with per-chain token details.
1355
+ */
1356
+ async getBalances(params, options) {
1357
+ return getBalances(params, options);
1358
+ }
1359
+ /**
1360
+ * Retrieves a list of verified tokens based on search query or chain filter.
1361
+ *
1362
+ * @param params - Search parameters (query, chain ID, pagination options).
1363
+ * @returns Paginated `TokenSearchResponse` containing token metadata.
1364
+ */
1365
+ async getTokenList(params) {
1366
+ return getTokenList(params);
1367
+ }
1368
+ /**
1369
+ * Executes a prepared swap quote using the provided wallet and configuration.
1370
+ *
1371
+ * Handles:
1372
+ * - Token approval (if required)
1373
+ * - Transaction signing and broadcasting
1374
+ * - Confirmation polling and stage-based status updates
1375
+ *
1376
+ * Supports both:
1377
+ * - Market orders (with optional deadline)
1378
+ * - Limit orders (requires executionPrice and deadline)
1379
+ *
1380
+ * @param quote - The swap quote to execute, containing route and metadata.
1381
+ * @param accountAddress - The user's wallet address executing the swap.
1382
+ * @param recipientAddress - Optional recipient address for the output tokens (defaults to sender).
1383
+ * @param wallet - Adapted wallet instance (EVM/Solana) or a standard Viem `WalletClient`.
1384
+ * @param onStatus - Optional callback for receiving execution stage updates and messages.
1385
+ * @param orderType - Defines whether this is a market or limit order.
1386
+ * @param options - Execution parameters (different per order type).
1387
+ *
1388
+ * @returns A finalized execution result containing transaction hash, status, and any returned data.
1389
+ *
1390
+ * @example
1391
+ * ```ts
1392
+ * * Market order
1393
+ * const result = await sdk.executeTransaction({
1394
+ * quote,
1395
+ * accountAddress: "0x123...",
1396
+ * wallet,
1397
+ * orderType: OrderExecutionType.MARKET,
1398
+ * options: { deadline: 1800 },
1399
+ * onStatus: (stage, msg) => console.log(stage, msg),
1400
+ * });
1401
+ *
1402
+ * * Limit order
1403
+ * const result = await sdk.executeTransaction({
1404
+ * quote,
1405
+ * accountAddress: "0x123...",
1406
+ * wallet,
1407
+ * orderType: OrderExecutionType.LIMIT,
1408
+ * options: { executionPrice: "0.0021", deadline: 3600 },
1409
+ * });
1410
+ * ```
1411
+ */
1412
+ async executeTransaction({
1413
+ quote,
1414
+ accountAddress,
1415
+ recipientAddress,
1416
+ wallet,
1417
+ onStatus,
1418
+ orderType,
1419
+ options
1420
+ }) {
1421
+ return executeOrder({
1422
+ quote,
1423
+ wallet,
1424
+ accountAddress,
1425
+ recipientAddress,
1426
+ onStatus,
1427
+ orderType,
1428
+ options
1429
+ });
1430
+ }
1431
+ /**
1432
+ * Fetches all user orders (Market, Limit, Cross-chain) for connected wallets.
1433
+ *
1434
+ * ---
1435
+ * ### Overview
1436
+ * Retrieves both **single-chain** and **cross-chain** orders from the Shogun Intents API.
1437
+ * Works across EVM, Solana
1438
+ *
1439
+ * ---
1440
+ * @example
1441
+ * ```ts
1442
+ * const orders = await sdk.getOrders({
1443
+ * evmAddress: "0x123...",
1444
+ * solAddress: "9d12hF...abc",
1445
+ * });
1446
+ *
1447
+ * console.log(orders.singleChainLimitOrders);
1448
+ * ```
1449
+ *
1450
+ * @param params - Wallet addresses to fetch orders for (EVM, Solana).
1451
+ * @returns A structured {@link ApiUserOrders} object containing all user orders.
1452
+ */
1453
+ async getOrders(params) {
1454
+ return getOrders(params);
1455
+ }
1456
+ /**
1457
+ * Cancels an order (single-chain or cross-chain) on EVM or Solana.
1458
+ *
1459
+ * Internally routes to the correct guard contract or Solana program to
1460
+ * deactivate the order or invalidate its nonce.
1461
+ *
1462
+ * @param params.order - Order payload returned from the Intents API.
1463
+ * @param params.wallet - Adapted wallet used to submit the cancellation transaction.
1464
+ * @param params.solRpc - Solana RPC URL used for SVM cancellations.
1465
+ *
1466
+ * @returns A transaction signature or hash from the underlying wallet.
1467
+ */
1468
+ async cancelOrder(params) {
1469
+ return cancelIntentsOrder({
1470
+ order: params.order,
1471
+ wallet: params.wallet,
1472
+ sol_rpc: params.solRpc
1473
+ });
1474
+ }
1475
+ };