@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/react.js CHANGED
@@ -1,90 +1,19 @@
1
- // src/react/useTokenList.ts
2
- import { useEffect, useMemo, useRef, useState } from "react";
3
-
4
- // src/core/token-list.ts
5
- import { getTokenList as intentsGetTokenList } from "@shogun-sdk/intents-sdk";
6
- async function getTokenList(params) {
7
- return intentsGetTokenList(params);
8
- }
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
9
4
 
10
- // src/react/useTokenList.ts
11
- var tokenCache = /* @__PURE__ */ new Map();
12
- function useTokenList(params) {
13
- const [data, setData] = useState(null);
14
- const [loading, setLoading] = useState(false);
15
- const [error, setError] = useState(null);
16
- const controllerRef = useRef(null);
17
- const debounceRef = useRef(null);
18
- const debounceMs = params.debounceMs ?? 250;
19
- const cacheKey = useMemo(() => {
20
- return JSON.stringify({
21
- q: params.q?.trim().toLowerCase() ?? "",
22
- networkId: params.networkId ?? "all",
23
- page: params.page ?? 1,
24
- limit: params.limit ?? 50
25
- });
26
- }, [params.q, params.networkId, params.page, params.limit]);
27
- async function fetchTokens(signal) {
28
- if (tokenCache.has(cacheKey)) {
29
- setData(tokenCache.get(cacheKey));
30
- setLoading(false);
31
- setError(null);
32
- return;
33
- }
34
- try {
35
- setLoading(true);
36
- const result = await getTokenList({ ...params, signal });
37
- tokenCache.set(cacheKey, result);
38
- setData(result);
39
- setError(null);
40
- } catch (err) {
41
- if (err.name !== "AbortError") {
42
- const e = err instanceof Error ? err : new Error("Unknown error while fetching tokens");
43
- setError(e);
44
- }
45
- } finally {
46
- setLoading(false);
47
- }
48
- }
49
- useEffect(() => {
50
- if (!params.q && !params.networkId) return;
51
- if (debounceRef.current) clearTimeout(debounceRef.current);
52
- if (controllerRef.current) controllerRef.current.abort();
53
- const controller = new AbortController();
54
- controllerRef.current = controller;
55
- debounceRef.current = setTimeout(() => {
56
- fetchTokens(controller.signal);
57
- }, debounceMs);
58
- return () => {
59
- controller.abort();
60
- if (debounceRef.current) clearTimeout(debounceRef.current);
61
- };
62
- }, [cacheKey, debounceMs]);
63
- return useMemo(
64
- () => ({
65
- /** Current fetched data (cached when possible) */
66
- data,
67
- /** Whether a request is in progress */
68
- loading,
69
- /** Error object if a request failed */
70
- error,
71
- /** Manually refetch the token list */
72
- refetch: () => fetchTokens(),
73
- /** Clear all cached token results (shared across hook instances) */
74
- clearCache: () => tokenCache.clear()
75
- }),
76
- [data, loading, error]
77
- );
78
- }
5
+ // src/react/SwapProvider.tsx
6
+ import { createContext, useContext, useMemo } from "react";
79
7
 
80
- // src/react/useExecuteOrder.ts
81
- import { useState as useState2, useCallback, useRef as useRef2, useEffect as useEffect2 } from "react";
8
+ // src/core/getQuote.ts
9
+ import { QuoteProvider } from "@shogun-sdk/intents-sdk";
10
+ import { parseUnits } from "viem";
82
11
 
83
- // src/core/executeOrder/execute.ts
84
- import { ChainID as ChainID4, isEvmChain as isEvmChain2 } from "@shogun-sdk/intents-sdk";
85
- import { BaseError } from "viem";
12
+ // src/core/execute/normalizeNative.ts
13
+ import { isEvmChain as isEvmChain2 } from "@shogun-sdk/intents-sdk";
86
14
 
87
15
  // src/utils/address.ts
16
+ import { zeroAddress } from "viem";
88
17
  var NATIVE_TOKEN = {
89
18
  ETH: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
90
19
  SOL: "So11111111111111111111111111111111111111111",
@@ -95,13 +24,32 @@ var isNativeAddress = (tokenAddress) => {
95
24
  const normalizedTokenAddress = tokenAddress.toLowerCase();
96
25
  return !!tokenAddress && NATIVE_ADDRESSES.includes(normalizedTokenAddress);
97
26
  };
27
+ function normalizeEvmTokenAddress(address) {
28
+ const lower = address.toLowerCase();
29
+ return lower === NATIVE_TOKEN.ETH.toLowerCase() ? zeroAddress : address;
30
+ }
98
31
 
99
32
  // src/utils/chain.ts
100
- import { ChainID } from "@shogun-sdk/intents-sdk";
101
- var SOLANA_CHAIN_ID = ChainID.Solana;
102
- var SupportedChains = [
33
+ import { ChainID as BaseChainID, isEvmChain as isEvmChainIntent } from "@shogun-sdk/intents-sdk";
34
+ var SOLANA_CHAIN_ID = BaseChainID.Solana;
35
+ var CURRENT_SUPPORTED = [
36
+ BaseChainID.Solana,
37
+ BaseChainID.BSC,
38
+ BaseChainID.Base,
39
+ BaseChainID.MONAD
40
+ ];
41
+ var ChainId = Object.entries(BaseChainID).reduce(
42
+ (acc, [key, value]) => {
43
+ if (typeof value === "number" && CURRENT_SUPPORTED.includes(value)) {
44
+ acc[key] = value;
45
+ }
46
+ return acc;
47
+ },
48
+ {}
49
+ );
50
+ var SupportedChainsInternal = [
103
51
  {
104
- id: ChainID.Arbitrum,
52
+ id: BaseChainID.Arbitrum,
105
53
  name: "Arbitrum",
106
54
  isEVM: true,
107
55
  wrapped: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
@@ -110,7 +58,7 @@ var SupportedChains = [
110
58
  tokenAddress: NATIVE_TOKEN.ETH
111
59
  },
112
60
  {
113
- id: ChainID.Optimism,
61
+ id: BaseChainID.Optimism,
114
62
  name: "Optimism",
115
63
  isEVM: true,
116
64
  wrapped: "0x4200000000000000000000000000000000000006",
@@ -119,7 +67,7 @@ var SupportedChains = [
119
67
  tokenAddress: NATIVE_TOKEN.ETH
120
68
  },
121
69
  {
122
- id: ChainID.Base,
70
+ id: BaseChainID.Base,
123
71
  name: "Base",
124
72
  isEVM: true,
125
73
  wrapped: "0x4200000000000000000000000000000000000006",
@@ -128,7 +76,7 @@ var SupportedChains = [
128
76
  tokenAddress: NATIVE_TOKEN.ETH
129
77
  },
130
78
  {
131
- id: ChainID.Hyperliquid,
79
+ id: BaseChainID.Hyperliquid,
132
80
  name: "Hyperliquid",
133
81
  isEVM: true,
134
82
  wrapped: "0x5555555555555555555555555555555555555555",
@@ -137,7 +85,7 @@ var SupportedChains = [
137
85
  tokenAddress: NATIVE_TOKEN.ETH
138
86
  },
139
87
  {
140
- id: ChainID.BSC,
88
+ id: BaseChainID.BSC,
141
89
  name: "BSC",
142
90
  isEVM: true,
143
91
  wrapped: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",
@@ -153,8 +101,21 @@ var SupportedChains = [
153
101
  symbol: "SOL",
154
102
  decimals: 9,
155
103
  tokenAddress: NATIVE_TOKEN.SOL
104
+ },
105
+ {
106
+ id: BaseChainID.MONAD,
107
+ name: "Monad",
108
+ isEVM: true,
109
+ wrapped: "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
110
+ symbol: "MON",
111
+ decimals: 18,
112
+ tokenAddress: NATIVE_TOKEN.ETH
156
113
  }
157
114
  ];
115
+ var SupportedChains = SupportedChainsInternal.filter(
116
+ (c) => CURRENT_SUPPORTED.includes(c.id)
117
+ );
118
+ var isEvmChain = isEvmChainIntent;
158
119
 
159
120
  // src/utils/viem.ts
160
121
  function isViemWalletClient(wallet) {
@@ -182,11 +143,200 @@ function serializeBigIntsToStrings(obj) {
182
143
  return obj;
183
144
  }
184
145
 
146
+ // src/core/execute/normalizeNative.ts
147
+ function normalizeNative(chainId, address) {
148
+ if (isEvmChain2(chainId) && isNativeAddress(address)) {
149
+ const chain = SupportedChains.find((c) => c.id === chainId);
150
+ if (!chain?.wrapped)
151
+ throw new Error(`Wrapped token not found for chainId ${chainId}`);
152
+ return chain.wrapped;
153
+ }
154
+ return address;
155
+ }
156
+
157
+ // src/core/getQuote.ts
158
+ async function getQuote(params) {
159
+ const amount = BigInt(params.amount);
160
+ if (!params.tokenIn?.address || !params.tokenOut?.address) {
161
+ throw new Error("Both tokenIn and tokenOut must include an address.");
162
+ }
163
+ if (!params.sourceChainId || !params.destChainId) {
164
+ throw new Error("Both sourceChainId and destChainId are required.");
165
+ }
166
+ if (amount <= 0n) {
167
+ throw new Error("Amount must be greater than 0.");
168
+ }
169
+ const normalizedTokenIn = normalizeNative(params.sourceChainId, params.tokenIn.address);
170
+ const data = await QuoteProvider.getQuote({
171
+ sourceChainId: params.sourceChainId,
172
+ destChainId: params.destChainId,
173
+ tokenIn: normalizedTokenIn,
174
+ tokenOut: params.tokenOut.address,
175
+ amount
176
+ });
177
+ const slippagePercent = Math.min(Math.max(params.slippage ?? 0.5, 0), 50);
178
+ let warning;
179
+ if (slippagePercent > 10) {
180
+ warning = `\u26A0\uFE0F High slippage tolerance (${slippagePercent.toFixed(2)}%) \u2014 price may vary significantly.`;
181
+ }
182
+ const estimatedAmountOut = BigInt(data.estimatedAmountOut);
183
+ const slippageBps = BigInt(Math.round(slippagePercent * 100));
184
+ const estimatedAmountOutAfterSlippage = estimatedAmountOut * (10000n - slippageBps) / 10000n;
185
+ const pricePerTokenOutInUsd = data.estimatedAmountOutUsd / Number(data.estimatedAmountOut);
186
+ const amountOutUsdAfterSlippage = Number(estimatedAmountOutAfterSlippage) * pricePerTokenOutInUsd;
187
+ const minStablecoinsAmountValue = BigInt(data.estimatedAmountInAsMinStablecoinAmount);
188
+ const minStablecoinsAmountAfterSlippage = minStablecoinsAmountValue * (10000n - slippageBps) / 10000n;
189
+ const pricePerInputToken = estimatedAmountOut * 10n ** BigInt(params.tokenIn.decimals ?? 18) / BigInt(params.amount);
190
+ return {
191
+ amountOut: estimatedAmountOutAfterSlippage,
192
+ amountOutUsd: amountOutUsdAfterSlippage,
193
+ amountInUsd: data.amountInUsd,
194
+ // Input USD stays the same
195
+ minStablecoinsAmount: minStablecoinsAmountAfterSlippage,
196
+ tokenIn: {
197
+ address: params.tokenIn.address,
198
+ decimals: params.tokenIn.decimals ?? 18,
199
+ chainId: params.sourceChainId
200
+ },
201
+ tokenOut: {
202
+ address: params.tokenOut.address,
203
+ decimals: params.tokenOut.decimals ?? 18,
204
+ chainId: params.destChainId
205
+ },
206
+ amountIn: BigInt(params.amount),
207
+ pricePerInputToken,
208
+ slippage: slippagePercent,
209
+ internal: {
210
+ ...data,
211
+ estimatedAmountOutReduced: estimatedAmountOutAfterSlippage,
212
+ estimatedAmountOutUsdReduced: amountOutUsdAfterSlippage
213
+ },
214
+ warning
215
+ };
216
+ }
217
+ function buildQuoteParams({
218
+ tokenIn,
219
+ tokenOut,
220
+ sourceChainId,
221
+ destChainId,
222
+ amount,
223
+ slippage
224
+ }) {
225
+ return {
226
+ tokenIn,
227
+ tokenOut,
228
+ sourceChainId,
229
+ destChainId,
230
+ amount: parseUnits(amount.toString(), tokenIn.decimals ?? 18).toString(),
231
+ slippage
232
+ };
233
+ }
234
+
235
+ // src/core/getBalances.ts
236
+ import { TOKEN_SEARCH_API_BASE_URL } from "@shogun-sdk/intents-sdk";
237
+ async function getBalances(params, options) {
238
+ const { addresses, cursorEvm, cursorSvm } = params;
239
+ const { signal } = options ?? {};
240
+ if (!addresses?.evm && !addresses?.svm) {
241
+ throw new Error("At least one address (EVM or SVM) must be provided.");
242
+ }
243
+ const payload = JSON.stringify({
244
+ addresses,
245
+ cursorEvm,
246
+ cursorSvm
247
+ });
248
+ const start = performance.now();
249
+ const response = await fetch(`${TOKEN_SEARCH_API_BASE_URL}/tokens/balances`, {
250
+ method: "POST",
251
+ headers: {
252
+ accept: "application/json",
253
+ "Content-Type": "application/json"
254
+ },
255
+ body: payload,
256
+ signal
257
+ }).catch((err) => {
258
+ if (err.name === "AbortError") {
259
+ throw new Error("Balance request was cancelled.");
260
+ }
261
+ throw err;
262
+ });
263
+ if (!response.ok) {
264
+ const text = await response.text().catch(() => "");
265
+ throw new Error(`Failed to fetch balances: ${response.status} ${text}`);
266
+ }
267
+ const data = await response.json().catch(() => {
268
+ throw new Error("Invalid JSON response from balances API.");
269
+ });
270
+ const duration = (performance.now() - start).toFixed(1);
271
+ if (process.env.NODE_ENV !== "production") {
272
+ console.debug(`[Shogun SDK] Fetched balances in ${duration}ms`);
273
+ }
274
+ const evmItems = data.evm?.items ?? [];
275
+ const svmItems = data.svm?.items ?? [];
276
+ const combined = [...evmItems, ...svmItems];
277
+ const filtered = combined.filter(
278
+ (b) => CURRENT_SUPPORTED.includes(b.chainId)
279
+ );
280
+ return {
281
+ results: filtered,
282
+ nextCursorEvm: data.evm?.cursor ?? null,
283
+ nextCursorSvm: data.svm?.cursor ?? null
284
+ };
285
+ }
286
+
287
+ // src/core/token-list.ts
288
+ import { TOKEN_SEARCH_API_BASE_URL as TOKEN_SEARCH_API_BASE_URL2 } from "@shogun-sdk/intents-sdk";
289
+ async function getTokenList(params) {
290
+ const url = new URL(`${TOKEN_SEARCH_API_BASE_URL2}/tokens/search`);
291
+ if (params.q) url.searchParams.append("q", params.q);
292
+ if (params.networkId) url.searchParams.append("networkId", String(params.networkId));
293
+ if (params.page) url.searchParams.append("page", String(params.page));
294
+ if (params.limit) url.searchParams.append("limit", String(params.limit));
295
+ const res = await fetch(url.toString(), {
296
+ signal: params.signal
297
+ });
298
+ if (!res.ok) {
299
+ throw new Error(`Failed to fetch tokens: ${res.status} ${res.statusText}`);
300
+ }
301
+ const data = await res.json();
302
+ const filteredResults = data.results.filter(
303
+ (token) => CURRENT_SUPPORTED.includes(token.chainId)
304
+ );
305
+ return {
306
+ ...data,
307
+ results: filteredResults,
308
+ count: filteredResults.length
309
+ };
310
+ }
311
+
312
+ // src/core/token.ts
313
+ import { TOKEN_SEARCH_API_BASE_URL as TOKEN_SEARCH_API_BASE_URL3 } from "@shogun-sdk/intents-sdk";
314
+ async function getTokensData(addresses) {
315
+ if (!addresses?.length) return [];
316
+ const response = await fetch(`${TOKEN_SEARCH_API_BASE_URL3}/tokens/tokens`, {
317
+ method: "POST",
318
+ headers: {
319
+ "Content-Type": "application/json",
320
+ accept: "*/*"
321
+ },
322
+ body: JSON.stringify({ addresses })
323
+ });
324
+ if (!response.ok) {
325
+ throw new Error(`Failed to fetch token data: ${response.statusText}`);
326
+ }
327
+ const data = await response.json();
328
+ const filtered = data.filter((t) => CURRENT_SUPPORTED.includes(Number(t.chainId)));
329
+ return filtered;
330
+ }
331
+
332
+ // src/core/execute/execute.ts
333
+ import { ChainID as ChainID2, isEvmChain as isEvmChain3 } from "@shogun-sdk/intents-sdk";
334
+ import "viem";
335
+
185
336
  // src/wallet-adapter/evm-wallet-adapter/adapter.ts
186
- import "ethers/lib/ethers.js";
187
- import { hexValue } from "ethers/lib/utils.js";
188
337
  import {
189
- custom
338
+ custom,
339
+ publicActions
190
340
  } from "viem";
191
341
  function isEVMTransaction(tx) {
192
342
  return typeof tx.from === "string";
@@ -205,15 +355,26 @@ var adaptViemWallet = (wallet) => {
205
355
  if (!isEVMTransaction(transaction)) {
206
356
  throw new Error("Expected EVMTransaction but got SolanaTransaction");
207
357
  }
208
- const tx = await wallet.sendTransaction({
209
- from: transaction.from,
210
- to: transaction.to,
211
- data: transaction.data,
212
- value: transaction.value,
213
- account: wallet.account?.address,
214
- chain: wallet.chain
215
- });
216
- return tx;
358
+ if (wallet.transport.type === "http") {
359
+ const request = await wallet.prepareTransactionRequest({
360
+ to: transaction.to,
361
+ data: transaction.data,
362
+ value: transaction.value,
363
+ chain: wallet.chain
364
+ });
365
+ const serializedTransaction = await wallet.signTransaction(request);
366
+ const tx = await wallet.sendRawTransaction({ serializedTransaction });
367
+ return tx;
368
+ } else {
369
+ const hash = await wallet.sendTransaction({
370
+ to: transaction.to,
371
+ data: transaction.data,
372
+ value: transaction.value,
373
+ chain: wallet.chain,
374
+ account: wallet.account
375
+ });
376
+ return hash;
377
+ }
217
378
  };
218
379
  const switchChain = async (chainId) => {
219
380
  try {
@@ -236,6 +397,20 @@ var adaptViemWallet = (wallet) => {
236
397
  if (!addr) throw new Error("No address found");
237
398
  return addr;
238
399
  };
400
+ const readContract = async ({
401
+ address: address2,
402
+ abi,
403
+ functionName,
404
+ args = []
405
+ }) => {
406
+ const publicClient = wallet.extend(publicActions);
407
+ return await publicClient.readContract({
408
+ address: address2,
409
+ abi,
410
+ functionName,
411
+ args
412
+ });
413
+ };
239
414
  return {
240
415
  vmType: "EVM" /* EVM */,
241
416
  transport: custom(wallet.transport),
@@ -243,51 +418,65 @@ var adaptViemWallet = (wallet) => {
243
418
  address,
244
419
  sendTransaction,
245
420
  signTypedData,
246
- switchChain
421
+ switchChain,
422
+ readContract
247
423
  };
248
424
  };
249
425
 
250
- // src/core/executeOrder/handleEvmExecution.ts
426
+ // src/core/execute/handleEvmExecution.ts
251
427
  import {
252
428
  getEVMSingleChainOrderTypedData,
253
- getEVMCrossChainOrderTypedData,
254
- PERMIT2_ADDRESS
429
+ getEVMCrossChainOrderTypedData
255
430
  } from "@shogun-sdk/intents-sdk";
256
- import { encodeFunctionData, erc20Abi } from "viem";
257
-
258
- // src/core/executeOrder/normalizeNative.ts
259
- import { isEvmChain } from "@shogun-sdk/intents-sdk";
260
- function normalizeNative(chainId, address) {
261
- if (isEvmChain(chainId) && isNativeAddress(address)) {
262
- const chain = SupportedChains.find((c) => c.id === chainId);
263
- if (!chain?.wrapped)
264
- throw new Error(`Wrapped token not found for chainId ${chainId}`);
265
- return chain.wrapped;
266
- }
267
- return address;
268
- }
431
+ import { encodeFunctionData as encodeFunctionData2 } from "viem";
269
432
 
270
- // src/core/executeOrder/stageMessages.ts
433
+ // src/core/execute/stageMessages.ts
271
434
  var DEFAULT_STAGE_MESSAGES = {
272
435
  processing: "Preparing transaction for execution",
273
436
  approving: "Approving token allowance",
274
437
  approved: "Token approved successfully",
275
- signing: "Signing order for submission",
276
- submitting: "Submitting order to Auctioneer",
277
- success: "Order executed successfully",
278
- error: "Order execution failed"
438
+ signing: "Signing transaction for submission",
439
+ submitting: "Submitting transaction",
440
+ initiated: "Transaction initiated.",
441
+ success: "Transaction Executed successfully",
442
+ success_limit: "Limit order has been submitted successfully.",
443
+ shogun_processing: "Shogun is processing your transaction",
444
+ error: "Transaction failed during submission"
279
445
  };
280
446
 
281
- // src/core/executeOrder/buildOrder.ts
447
+ // src/core/execute/buildOrder.ts
282
448
  import { CrossChainOrder, SingleChainOrder } from "@shogun-sdk/intents-sdk";
449
+ import { formatUnits, parseUnits as parseUnits2 } from "viem";
450
+
451
+ // src/utils/order.ts
452
+ var OrderExecutionType = /* @__PURE__ */ ((OrderExecutionType2) => {
453
+ OrderExecutionType2["LIMIT"] = "limit";
454
+ OrderExecutionType2["MARKET"] = "market";
455
+ return OrderExecutionType2;
456
+ })(OrderExecutionType || {});
457
+
458
+ // src/core/execute/buildOrder.ts
283
459
  async function buildOrder({
284
460
  quote,
285
461
  accountAddress,
286
462
  destination,
287
463
  deadline,
288
- isSingleChain
464
+ isSingleChain,
465
+ orderType,
466
+ options
289
467
  }) {
290
468
  const { tokenIn, tokenOut } = quote;
469
+ let amountOutMin = BigInt(quote.internal.estimatedAmountOutReduced);
470
+ if (orderType === "limit" /* LIMIT */ && options && "executionPrice" in options) {
471
+ const executionPrice = Number(options.executionPrice);
472
+ if (Number.isFinite(executionPrice) && executionPrice > 0) {
473
+ const decimalsIn = tokenIn.decimals ?? 18;
474
+ const decimalsOut = tokenOut.decimals ?? 18;
475
+ const formattedAmountIn = Number(formatUnits(BigInt(quote.amountIn.toString()), decimalsIn));
476
+ const rawAmountOut = formattedAmountIn * executionPrice;
477
+ amountOutMin = parseUnits2(rawAmountOut.toString(), decimalsOut);
478
+ }
479
+ }
291
480
  if (isSingleChain) {
292
481
  return await SingleChainOrder.create({
293
482
  user: accountAddress,
@@ -295,7 +484,7 @@ async function buildOrder({
295
484
  tokenIn: tokenIn.address,
296
485
  tokenOut: tokenOut.address,
297
486
  amountIn: quote.amountIn,
298
- amountOutMin: quote.internal.estimatedAmountOutReduced,
487
+ amountOutMin,
299
488
  deadline,
300
489
  destinationAddress: destination
301
490
  });
@@ -309,12 +498,166 @@ async function buildOrder({
309
498
  destinationTokenAddress: tokenOut.address,
310
499
  destinationAddress: destination,
311
500
  deadline,
312
- destinationTokenMinAmount: quote.internal.estimatedAmountOutReduced,
501
+ destinationTokenMinAmount: amountOutMin,
313
502
  minStablecoinAmount: quote.minStablecoinsAmount
314
503
  });
315
504
  }
316
505
 
317
- // src/core/executeOrder/handleEvmExecution.ts
506
+ // src/utils/pollOrderStatus.ts
507
+ import { AUCTIONEER_URL } from "@shogun-sdk/intents-sdk";
508
+ async function pollOrderStatus(address, orderId, options = {}) {
509
+ const { intervalMs = 2e3, timeoutMs = 3e5, authToken } = options;
510
+ const startTime = Date.now();
511
+ const isDebug = process.env.NODE_ENV !== "production";
512
+ const isEvmAddress = /^0x[a-fA-F0-9]{40}$/.test(address);
513
+ const isSuiAddress = /^0x[a-fA-F0-9]{64}$/.test(address);
514
+ const isSolanaAddress = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address);
515
+ let queryParam;
516
+ if (isEvmAddress) queryParam = `evmWallets=${address}`;
517
+ else if (isSuiAddress) queryParam = `suiWallets=${address}`;
518
+ else if (isSolanaAddress) queryParam = `solanaWallets=${address}`;
519
+ else throw new Error(`Unrecognized wallet address format: ${address}`);
520
+ const queryUrl = `${AUCTIONEER_URL}/user_intent?${queryParam}`;
521
+ return new Promise((resolve, reject) => {
522
+ const pollInterval = setInterval(async () => {
523
+ try {
524
+ if (Date.now() - startTime > timeoutMs) {
525
+ clearInterval(pollInterval);
526
+ return resolve("Timeout");
527
+ }
528
+ const res = await fetch(queryUrl, {
529
+ method: "GET",
530
+ headers: {
531
+ "Content-Type": "application/json",
532
+ // The /user_intent status endpoint requires the SIWE JWT; without it
533
+ // the request 401s after the order has already been submitted.
534
+ ...authToken ? { Authorization: `Bearer ${authToken}` } : {}
535
+ }
536
+ });
537
+ if (!res.ok) {
538
+ clearInterval(pollInterval);
539
+ return reject(
540
+ new Error(`Failed to fetch orders: ${res.status} ${res.statusText}`)
541
+ );
542
+ }
543
+ const json = await res.json();
544
+ const data = json?.data ?? {};
545
+ const allOrders = [
546
+ ...data.crossChainDcaOrders ?? [],
547
+ ...data.crossChainLimitOrders ?? [],
548
+ ...data.singleChainDcaOrders ?? [],
549
+ ...data.singleChainLimitOrders ?? []
550
+ ];
551
+ const targetOrder = allOrders.find((o) => o.orderId === orderId);
552
+ if (!targetOrder) {
553
+ if (isDebug)
554
+ console.debug(`[pollOrderStatus] [${orderId}] Not found yet`);
555
+ return;
556
+ }
557
+ const { orderStatus } = targetOrder;
558
+ if (isDebug) {
559
+ const elapsed = ((Date.now() - startTime) / 1e3).toFixed(1);
560
+ console.debug(`targetOrder`, targetOrder);
561
+ console.debug(
562
+ `[pollOrderStatus] [${orderId}] status=${orderStatus} (elapsed ${elapsed}s)`
563
+ );
564
+ }
565
+ if (["Fulfilled", "Cancelled", "Outdated"].includes(orderStatus)) {
566
+ clearInterval(pollInterval);
567
+ return resolve(orderStatus);
568
+ }
569
+ } catch (error) {
570
+ clearInterval(pollInterval);
571
+ return reject(error);
572
+ }
573
+ }, intervalMs);
574
+ });
575
+ }
576
+
577
+ // src/core/execute/handleOrderPollingResult.ts
578
+ async function handleOrderPollingResult({
579
+ status,
580
+ orderId,
581
+ chainId,
582
+ update,
583
+ messageFor
584
+ }) {
585
+ switch (status) {
586
+ case "Fulfilled":
587
+ update("success", messageFor("success"));
588
+ return {
589
+ status: true,
590
+ orderId,
591
+ chainId,
592
+ finalStatus: status,
593
+ stage: "success"
594
+ };
595
+ case "Cancelled":
596
+ update("error", "Order was cancelled before fulfillment");
597
+ break;
598
+ case "Timeout":
599
+ update("error", "Order polling timed out");
600
+ break;
601
+ case "NotFound":
602
+ default:
603
+ update("error", "Order not found");
604
+ break;
605
+ }
606
+ return {
607
+ status: false,
608
+ orderId,
609
+ chainId,
610
+ finalStatus: status,
611
+ stage: "error"
612
+ };
613
+ }
614
+
615
+ // src/core/execute/ensurePermit2Allowance.ts
616
+ import { encodeFunctionData, erc20Abi, maxUint256 } from "viem";
617
+ import { PERMIT2_ADDRESS } from "@shogun-sdk/intents-sdk";
618
+ async function ensurePermit2Allowance({
619
+ chainId,
620
+ tokenIn,
621
+ wallet,
622
+ accountAddress,
623
+ requiredAmount,
624
+ increaseByDelta = false
625
+ }) {
626
+ const spender = PERMIT2_ADDRESS[chainId];
627
+ let currentAllowance = 0n;
628
+ try {
629
+ if (!wallet.readContract) {
630
+ throw new Error("Wallet does not implement readContract()");
631
+ }
632
+ currentAllowance = await wallet.readContract({
633
+ address: tokenIn,
634
+ abi: erc20Abi,
635
+ functionName: "allowance",
636
+ args: [accountAddress, spender]
637
+ });
638
+ } catch (error) {
639
+ console.warn(`[Permit2] Failed to read allowance for ${tokenIn}`, error);
640
+ }
641
+ const approvalAmount = increaseByDelta ? currentAllowance + requiredAmount : maxUint256;
642
+ console.debug(
643
+ `[Permit2] Approving ${approvalAmount} for ${tokenIn} (current: ${currentAllowance}, required: ${requiredAmount})`
644
+ );
645
+ await wallet.sendTransaction({
646
+ to: tokenIn,
647
+ from: accountAddress,
648
+ data: encodeFunctionData({
649
+ abi: erc20Abi,
650
+ functionName: "approve",
651
+ args: [spender, approvalAmount]
652
+ }),
653
+ value: 0n
654
+ });
655
+ console.info(
656
+ `[Permit2] Approval transaction sent for ${tokenIn} on chain ${chainId}`
657
+ );
658
+ }
659
+
660
+ // src/core/execute/handleEvmExecution.ts
318
661
  async function handleEvmExecution({
319
662
  recipientAddress,
320
663
  quote,
@@ -322,18 +665,22 @@ async function handleEvmExecution({
322
665
  accountAddress,
323
666
  wallet,
324
667
  isSingleChain,
325
- deadline,
326
- update
668
+ update,
669
+ orderType,
670
+ options
327
671
  }) {
328
- const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage];
672
+ const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage] ?? "";
673
+ const deadline = options?.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
329
674
  await wallet.switchChain(chainId);
330
675
  const tokenIn = normalizeNative(chainId, quote.tokenIn.address);
676
+ quote.tokenOut.address = normalizeEvmTokenAddress(quote.tokenOut.address);
331
677
  const shouldWrapNative = isNativeAddress(quote.tokenIn.address);
332
678
  update("processing", shouldWrapNative ? `${messageFor("processing")} (wrapping native token)` : messageFor("processing"));
333
679
  if (shouldWrapNative) {
680
+ quote.tokenIn.address === tokenIn;
334
681
  await wallet.sendTransaction({
335
682
  to: tokenIn,
336
- data: encodeFunctionData({
683
+ data: encodeFunctionData2({
337
684
  abi: [{ type: "function", name: "deposit", stateMutability: "payable", inputs: [], outputs: [] }],
338
685
  functionName: "deposit",
339
686
  args: []
@@ -342,44 +689,70 @@ async function handleEvmExecution({
342
689
  from: accountAddress
343
690
  });
344
691
  }
345
- update("approving", messageFor("approving"));
346
- await wallet.sendTransaction({
347
- to: tokenIn,
348
- data: encodeFunctionData({
349
- abi: erc20Abi,
350
- functionName: "approve",
351
- args: [PERMIT2_ADDRESS[chainId], BigInt(quote.amountIn)]
352
- }),
353
- value: 0n,
354
- from: accountAddress
692
+ update("processing", messageFor("approving"));
693
+ await ensurePermit2Allowance({
694
+ chainId,
695
+ tokenIn,
696
+ wallet,
697
+ accountAddress,
698
+ requiredAmount: BigInt(quote.amountIn)
355
699
  });
356
- update("approved", messageFor("approved"));
700
+ update("processing", messageFor("approved"));
357
701
  const destination = recipientAddress ?? accountAddress;
358
702
  const order = await buildOrder({
359
703
  quote,
360
704
  accountAddress,
361
705
  destination,
362
706
  deadline,
363
- isSingleChain
707
+ isSingleChain,
708
+ orderType,
709
+ options
364
710
  });
365
- update("signing", messageFor("signing"));
711
+ console.debug(`order`, order);
712
+ update("processing", messageFor("signing"));
366
713
  const { orderTypedData, nonce } = isSingleChain ? await getEVMSingleChainOrderTypedData(order) : await getEVMCrossChainOrderTypedData(order);
714
+ const typedData = serializeBigIntsToStrings(orderTypedData);
367
715
  if (!wallet.signTypedData) {
368
716
  throw new Error("Wallet does not support EIP-712 signing");
369
717
  }
370
- const signature = await wallet.signTypedData(serializeBigIntsToStrings(orderTypedData));
371
- update("submitting", messageFor("submitting"));
718
+ const signature = await wallet.signTypedData({
719
+ domain: typedData.domain,
720
+ types: typedData.types,
721
+ primaryType: typedData.primaryType,
722
+ value: typedData.message,
723
+ message: typedData.message
724
+ });
725
+ update("processing", messageFor("submitting"));
372
726
  const res = await order.sendToAuctioneer({ signature, nonce: nonce.toString() });
373
727
  if (!res.success) {
374
728
  throw new Error("Auctioneer submission failed");
375
729
  }
376
- update("success", messageFor("success"));
377
- return { status: true, txHash: res.data, chainId, stage: "success" };
730
+ update("initiated", messageFor("initiated"));
731
+ const { intentId: orderId } = res.data;
732
+ update("initiated", messageFor("shogun_processing"));
733
+ if (orderType === "limit" /* LIMIT */) {
734
+ update("success", messageFor("success_limit"));
735
+ return {
736
+ status: true,
737
+ orderId,
738
+ chainId,
739
+ finalStatus: "OrderPlaced",
740
+ stage: "success"
741
+ };
742
+ } else {
743
+ const status = await pollOrderStatus(accountAddress, orderId, { authToken: options?.authToken });
744
+ return await handleOrderPollingResult({
745
+ status,
746
+ orderId,
747
+ chainId,
748
+ update,
749
+ messageFor
750
+ });
751
+ }
378
752
  }
379
753
 
380
- // src/core/executeOrder/handleSolanaExecution.ts
754
+ // src/core/execute/handleSolanaExecution.ts
381
755
  import {
382
- ChainID as ChainID3,
383
756
  getSolanaSingleChainOrderInstructions,
384
757
  getSolanaCrossChainOrderInstructions
385
758
  } from "@shogun-sdk/intents-sdk";
@@ -391,12 +764,14 @@ async function handleSolanaExecution({
391
764
  isSingleChain,
392
765
  update,
393
766
  accountAddress,
394
- deadline
767
+ orderType,
768
+ options
395
769
  }) {
396
770
  if (!wallet.rpcUrl) {
397
771
  throw new Error("Solana wallet is missing rpcUrl");
398
772
  }
399
- const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage];
773
+ const deadline = options?.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
774
+ const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage] ?? "";
400
775
  update("processing", messageFor("processing"));
401
776
  const destination = recipientAddress ?? accountAddress;
402
777
  const order = await buildOrder({
@@ -404,7 +779,9 @@ async function handleSolanaExecution({
404
779
  accountAddress,
405
780
  destination,
406
781
  deadline,
407
- isSingleChain
782
+ isSingleChain,
783
+ orderType,
784
+ options
408
785
  });
409
786
  const txData = await getSolanaOrderInstructions({
410
787
  order,
@@ -412,10 +789,9 @@ async function handleSolanaExecution({
412
789
  rpcUrl: wallet.rpcUrl
413
790
  });
414
791
  const transaction = VersionedTransaction.deserialize(Uint8Array.from(txData.txBytes));
415
- update("signing", messageFor("signing"));
416
- console.log({ order });
417
- const txSignature = await wallet.sendTransaction(transaction);
418
- update("submitting", messageFor("submitting"));
792
+ update("processing", messageFor("signing"));
793
+ await wallet.sendTransaction(transaction);
794
+ update("processing", messageFor("submitting"));
419
795
  const response = await submitToAuctioneer({
420
796
  order,
421
797
  isSingleChain,
@@ -424,13 +800,28 @@ async function handleSolanaExecution({
424
800
  if (!response.success) {
425
801
  throw new Error("Auctioneer submission failed");
426
802
  }
427
- update("success", messageFor("success"));
428
- return {
429
- status: true,
430
- txHash: txSignature,
431
- chainId: ChainID3.Solana,
432
- stage: "success"
433
- };
803
+ update("initiated", messageFor("initiated"));
804
+ const { intentId: orderId } = response.data;
805
+ update("initiated", messageFor("shogun_processing"));
806
+ if (orderType === "limit" /* LIMIT */) {
807
+ update("success", messageFor("success_limit"));
808
+ return {
809
+ status: true,
810
+ orderId,
811
+ chainId: SOLANA_CHAIN_ID,
812
+ finalStatus: "OrderPlaced",
813
+ stage: "success"
814
+ };
815
+ } else {
816
+ const status = await pollOrderStatus(accountAddress, orderId, { authToken: options?.authToken });
817
+ return await handleOrderPollingResult({
818
+ status,
819
+ orderId,
820
+ chainId: SOLANA_CHAIN_ID,
821
+ update,
822
+ messageFor
823
+ });
824
+ }
434
825
  }
435
826
  async function getSolanaOrderInstructions({
436
827
  order,
@@ -463,52 +854,93 @@ async function submitToAuctioneer({
463
854
  });
464
855
  }
465
856
 
466
- // src/core/executeOrder/execute.ts
857
+ // src/core/execute/execute.ts
467
858
  async function executeOrder({
468
859
  quote,
469
860
  accountAddress,
470
861
  recipientAddress,
471
862
  wallet,
472
863
  onStatus,
864
+ orderType = "market" /* MARKET */,
473
865
  options = {}
474
866
  }) {
475
- const deadline = options.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
867
+ const isDev = process.env.NODE_ENV !== "production";
868
+ const log = (...args) => {
869
+ if (isDev) console.debug("[OneShot::executeOrder]", ...args);
870
+ };
476
871
  const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage];
477
- const update = (stage, message) => onStatus?.(stage, message ?? messageFor(stage));
872
+ const update = (stage, message) => {
873
+ log("Stage:", stage, "| Message:", message ?? messageFor(stage));
874
+ onStatus?.(stage, message ?? messageFor(stage));
875
+ };
478
876
  try {
877
+ log("Starting execution:", {
878
+ accountAddress,
879
+ recipientAddress,
880
+ tokenIn: quote?.tokenIn,
881
+ tokenOut: quote?.tokenOut
882
+ });
479
883
  const adapter = normalizeWallet(wallet);
480
884
  if (!adapter) throw new Error("No wallet provided");
481
885
  const { tokenIn, tokenOut } = quote;
886
+ const srcChain = Number(tokenIn.chainId);
887
+ const destChain = Number(tokenOut.chainId);
888
+ if (!CURRENT_SUPPORTED.includes(srcChain) || !CURRENT_SUPPORTED.includes(destChain)) {
889
+ const unsupportedChains = [
890
+ !CURRENT_SUPPORTED.includes(srcChain) ? srcChain : null,
891
+ !CURRENT_SUPPORTED.includes(destChain) ? destChain : null
892
+ ].filter(Boolean).join(", ");
893
+ const errorMsg = `Unsupported chain(s): ${unsupportedChains}`;
894
+ update("error", errorMsg);
895
+ log("Error:", errorMsg);
896
+ throw new Error(errorMsg);
897
+ }
482
898
  const isSingleChain = tokenIn.chainId === tokenOut.chainId;
483
899
  const chainId = Number(tokenIn.chainId);
484
- update("processing", messageFor("processing"));
485
- if (isEvmChain2(chainId)) {
486
- return await handleEvmExecution({
900
+ update("processing");
901
+ if (isEvmChain3(chainId)) {
902
+ log("Detected EVM chain:", chainId);
903
+ const result = await handleEvmExecution({
487
904
  recipientAddress,
488
905
  quote,
489
906
  chainId,
490
907
  accountAddress,
491
908
  wallet: adapter,
492
909
  isSingleChain,
493
- deadline,
494
- update
910
+ update,
911
+ orderType,
912
+ options
495
913
  });
914
+ log("EVM execution result:", result);
915
+ return result;
496
916
  }
497
- if (chainId === ChainID4.Solana) {
498
- return await handleSolanaExecution({
917
+ if (chainId === ChainID2.Solana) {
918
+ log("Detected Solana chain");
919
+ const result = await handleSolanaExecution({
499
920
  recipientAddress,
500
921
  quote,
501
922
  accountAddress,
502
923
  wallet: adapter,
503
924
  isSingleChain,
504
- deadline,
505
- update
925
+ update,
926
+ orderType,
927
+ options
506
928
  });
929
+ log("Solana execution result:", result);
930
+ return result;
507
931
  }
508
- update("error", "Unsupported chain");
509
- return { status: false, message: "Unsupported chain", stage: "error" };
932
+ const unsupported = `Unsupported chain: ${chainId}`;
933
+ update("error", unsupported);
934
+ log("Error:", unsupported);
935
+ return { status: false, message: unsupported, stage: "error" };
510
936
  } catch (error) {
511
- const message = error instanceof BaseError ? error.shortMessage : error instanceof Error ? error.message : String(error);
937
+ let message = "An unknown error occurred";
938
+ if (error && typeof error === "object") {
939
+ const err = error;
940
+ message = err.details ?? err.message ?? message;
941
+ } else if (typeof error === "string") {
942
+ message = error;
943
+ }
512
944
  update("error", message);
513
945
  return { status: false, message, stage: "error" };
514
946
  }
@@ -519,348 +951,998 @@ function normalizeWallet(wallet) {
519
951
  return wallet;
520
952
  }
521
953
 
522
- // src/react/useExecuteOrder.ts
523
- function useExecuteOrder() {
524
- const [status, setStatus] = useState2("processing");
525
- const [message, setMessage] = useState2(null);
526
- const [loading, setLoading] = useState2(false);
527
- const [data, setData] = useState2(null);
528
- const [error, setError] = useState2(null);
529
- const isMounted = useRef2(true);
954
+ // src/core/orders/getOrders.ts
955
+ import { fetchUserOrders } from "@shogun-sdk/intents-sdk";
956
+ async function getOrders({
957
+ evmAddress,
958
+ solAddress
959
+ }) {
960
+ const wallets = [evmAddress, solAddress].filter(
961
+ (wallet) => Boolean(wallet)
962
+ );
963
+ if (wallets.length === 0) {
964
+ throw new Error("At least one wallet address (EVM, Solana) must be provided.");
965
+ }
966
+ const results = await Promise.all(
967
+ wallets.map((wallet) => fetchUserOrders({ wallet }))
968
+ );
969
+ return results.reduce(
970
+ (merged, orders) => {
971
+ merged.singleChainLimitOrders.push(...orders.singleChainLimitOrders);
972
+ merged.crossChainLimitOrders.push(...orders.crossChainLimitOrders);
973
+ return merged;
974
+ },
975
+ { singleChainLimitOrders: [], crossChainLimitOrders: [] }
976
+ );
977
+ }
978
+
979
+ // src/core/orders/cancelOrder.ts
980
+ import {
981
+ cancelCrossChainOrderInstructionsAsBytes,
982
+ cancelSingleChainOrderInstructionsAsBytes,
983
+ ChainID as ChainID3,
984
+ CROSS_CHAIN_GUARD_ADDRESSES,
985
+ PERMIT2_ADDRESS as PERMIT2_ADDRESS2,
986
+ SINGLE_CHAIN_GUARD_ADDRESSES
987
+ } from "@shogun-sdk/intents-sdk";
988
+ import {
989
+ VersionedMessage,
990
+ VersionedTransaction as VersionedTransaction2
991
+ } from "@solana/web3.js";
992
+ import { encodeFunctionData as encodeFunctionData3 } from "viem";
993
+ var inFlightCancels = /* @__PURE__ */ new Map();
994
+ function cancelIntentsOrder(args) {
995
+ const srcChain = "srcChainId" in args.order ? args.order.srcChainId : args.order.chainId;
996
+ const key = `${srcChain}:${args.order.orderId}`;
997
+ const existing = inFlightCancels.get(key);
998
+ if (existing) return existing;
999
+ const pending = performCancel(args).finally(() => {
1000
+ inFlightCancels.delete(key);
1001
+ });
1002
+ inFlightCancels.set(key, pending);
1003
+ return pending;
1004
+ }
1005
+ async function performCancel({
1006
+ order,
1007
+ wallet,
1008
+ sol_rpc
1009
+ }) {
1010
+ const isCrossChain = "srcChainId" in order && "destChainId" in order && order.srcChainId !== order.destChainId;
1011
+ const srcChain = "srcChainId" in order ? order.srcChainId : order.chainId;
1012
+ const isSolanaOrder = srcChain === ChainID3.Solana;
1013
+ if (isSolanaOrder) {
1014
+ if (!isCrossChain) {
1015
+ const { versionedMessageBytes: versionedMessageBytes2 } = await cancelSingleChainOrderInstructionsAsBytes(
1016
+ order.orderId,
1017
+ order.user,
1018
+ { rpcUrl: sol_rpc }
1019
+ );
1020
+ const message2 = VersionedMessage.deserialize(
1021
+ versionedMessageBytes2
1022
+ );
1023
+ const tx2 = new VersionedTransaction2(message2);
1024
+ return await wallet.sendTransaction(tx2);
1025
+ }
1026
+ const { versionedMessageBytes } = await cancelCrossChainOrderInstructionsAsBytes(
1027
+ order.orderId,
1028
+ order.user,
1029
+ { rpcUrl: sol_rpc }
1030
+ );
1031
+ const message = VersionedMessage.deserialize(
1032
+ versionedMessageBytes
1033
+ );
1034
+ const tx = new VersionedTransaction2(message);
1035
+ return await wallet.sendTransaction(tx);
1036
+ }
1037
+ const chainId = srcChain;
1038
+ const { readContract } = wallet;
1039
+ if (!readContract) {
1040
+ throw new Error("Wallet does not support readContract");
1041
+ }
1042
+ const nonce = BigInt(order.nonce ?? "0");
1043
+ const nonceWordPos = nonce >> 8n;
1044
+ const nonceBitPos = nonce - nonceWordPos * 256n;
1045
+ if (isCrossChain) {
1046
+ const [orderData = [false, false], currentNonceBitmap = 0n] = await Promise.all([
1047
+ readContract({
1048
+ address: CROSS_CHAIN_GUARD_ADDRESSES[chainId],
1049
+ abi: [
1050
+ {
1051
+ inputs: [{ name: "orderId", type: "bytes32" }],
1052
+ name: "orderData",
1053
+ outputs: [
1054
+ { name: "initialized", type: "bool" },
1055
+ { name: "deactivated", type: "bool" }
1056
+ ],
1057
+ stateMutability: "view",
1058
+ type: "function"
1059
+ }
1060
+ ],
1061
+ functionName: "orderData",
1062
+ args: [order.orderId]
1063
+ }),
1064
+ readContract({
1065
+ address: PERMIT2_ADDRESS2[chainId],
1066
+ abi: [
1067
+ {
1068
+ inputs: [
1069
+ { name: "owner", type: "address" },
1070
+ { name: "wordPos", type: "uint256" }
1071
+ ],
1072
+ name: "nonceBitmap",
1073
+ outputs: [{ name: "", type: "uint256" }],
1074
+ stateMutability: "view",
1075
+ type: "function"
1076
+ }
1077
+ ],
1078
+ functionName: "nonceBitmap",
1079
+ args: [order.user, nonceWordPos]
1080
+ })
1081
+ ]);
1082
+ const [initialized, deactivated] = orderData;
1083
+ if (initialized) {
1084
+ if (deactivated) {
1085
+ throw new Error("Order is already deactivated");
1086
+ }
1087
+ return await wallet.sendTransaction({
1088
+ to: CROSS_CHAIN_GUARD_ADDRESSES[order.srcChainId],
1089
+ data: encodeFunctionData3({
1090
+ abi: [
1091
+ {
1092
+ inputs: [
1093
+ {
1094
+ components: [
1095
+ { name: "user", type: "address" },
1096
+ { name: "tokenIn", type: "address" },
1097
+ { name: "srcChainId", type: "uint256" },
1098
+ { name: "deadline", type: "uint256" },
1099
+ { name: "amountIn", type: "uint256" },
1100
+ { name: "minStablecoinsAmount", type: "uint256" },
1101
+ { name: "executionDetailsHash", type: "bytes32" },
1102
+ { name: "nonce", type: "uint256" }
1103
+ ],
1104
+ name: "orderInfo",
1105
+ type: "tuple"
1106
+ }
1107
+ ],
1108
+ name: "cancelOrder",
1109
+ outputs: [],
1110
+ stateMutability: "nonpayable",
1111
+ type: "function"
1112
+ }
1113
+ ],
1114
+ functionName: "cancelOrder",
1115
+ args: [
1116
+ {
1117
+ user: order.user,
1118
+ tokenIn: order.tokenIn,
1119
+ srcChainId: BigInt(order.srcChainId),
1120
+ deadline: BigInt(order.deadline),
1121
+ amountIn: BigInt(order.amountIn),
1122
+ minStablecoinsAmount: BigInt(order.minStablecoinsAmount),
1123
+ executionDetailsHash: order.executionDetailsHash,
1124
+ nonce
1125
+ }
1126
+ ]
1127
+ }),
1128
+ value: BigInt(0),
1129
+ from: order.user
1130
+ });
1131
+ } else {
1132
+ if ((currentNonceBitmap & 1n << nonceBitPos) !== 0n) {
1133
+ throw new Error("Nonce is already invalidated");
1134
+ }
1135
+ const mask2 = 1n << nonceBitPos;
1136
+ return await wallet.sendTransaction({
1137
+ to: PERMIT2_ADDRESS2[order.srcChainId],
1138
+ data: encodeFunctionData3({
1139
+ abi: [
1140
+ {
1141
+ inputs: [
1142
+ { name: "wordPos", type: "uint256" },
1143
+ { name: "mask", type: "uint256" }
1144
+ ],
1145
+ name: "invalidateUnorderedNonces",
1146
+ outputs: [],
1147
+ stateMutability: "nonpayable",
1148
+ type: "function"
1149
+ }
1150
+ ],
1151
+ functionName: "invalidateUnorderedNonces",
1152
+ args: [nonceWordPos, mask2]
1153
+ }),
1154
+ value: BigInt(0),
1155
+ from: order.user
1156
+ });
1157
+ }
1158
+ }
1159
+ const [wasManuallyInitialized, currentBitmap = 0n] = await Promise.all([
1160
+ readContract({
1161
+ address: SINGLE_CHAIN_GUARD_ADDRESSES[chainId],
1162
+ abi: [
1163
+ {
1164
+ inputs: [{ name: "orderHash", type: "bytes32" }],
1165
+ name: "orderManuallyInitialized",
1166
+ outputs: [{ name: "", type: "bool" }],
1167
+ stateMutability: "view",
1168
+ type: "function"
1169
+ }
1170
+ ],
1171
+ functionName: "orderManuallyInitialized",
1172
+ args: [order.orderId]
1173
+ }),
1174
+ readContract({
1175
+ address: PERMIT2_ADDRESS2[chainId],
1176
+ abi: [
1177
+ {
1178
+ inputs: [
1179
+ { name: "owner", type: "address" },
1180
+ { name: "wordPos", type: "uint256" }
1181
+ ],
1182
+ name: "nonceBitmap",
1183
+ outputs: [{ name: "", type: "uint256" }],
1184
+ stateMutability: "view",
1185
+ type: "function"
1186
+ }
1187
+ ],
1188
+ functionName: "nonceBitmap",
1189
+ args: [order.user, nonceWordPos]
1190
+ })
1191
+ ]);
1192
+ if (wasManuallyInitialized) {
1193
+ return await wallet.sendTransaction({
1194
+ to: SINGLE_CHAIN_GUARD_ADDRESSES[chainId],
1195
+ data: encodeFunctionData3({
1196
+ abi: [
1197
+ {
1198
+ inputs: [
1199
+ {
1200
+ name: "order",
1201
+ type: "tuple",
1202
+ components: [
1203
+ { name: "amountIn", type: "uint256" },
1204
+ { name: "tokenIn", type: "address" },
1205
+ { name: "deadline", type: "uint256" },
1206
+ { name: "nonce", type: "uint256" },
1207
+ { name: "encodedExternalCallData", type: "bytes" },
1208
+ {
1209
+ name: "extraTransfers",
1210
+ type: "tuple[]",
1211
+ components: [
1212
+ { name: "amount", type: "uint256" },
1213
+ { name: "receiver", type: "address" },
1214
+ { name: "token", type: "address" }
1215
+ ]
1216
+ },
1217
+ {
1218
+ name: "requestedOutput",
1219
+ type: "tuple",
1220
+ components: [
1221
+ { name: "amount", type: "uint256" },
1222
+ { name: "receiver", type: "address" },
1223
+ { name: "token", type: "address" }
1224
+ ]
1225
+ },
1226
+ { name: "user", type: "address" }
1227
+ ]
1228
+ }
1229
+ ],
1230
+ name: "cancelManuallyCreatedOrder",
1231
+ outputs: [],
1232
+ stateMutability: "nonpayable",
1233
+ type: "function"
1234
+ }
1235
+ ],
1236
+ functionName: "cancelManuallyCreatedOrder",
1237
+ args: [
1238
+ {
1239
+ amountIn: BigInt(order.amountIn),
1240
+ tokenIn: order.tokenIn,
1241
+ deadline: BigInt(order.deadline),
1242
+ nonce,
1243
+ encodedExternalCallData: "0x",
1244
+ extraTransfers: (order.extraTransfers || []).map((t) => ({
1245
+ amount: BigInt(t.amount),
1246
+ receiver: t.receiver,
1247
+ token: t.token
1248
+ })),
1249
+ requestedOutput: {
1250
+ amount: BigInt(order.amountOutMin),
1251
+ receiver: order.destinationAddress,
1252
+ token: order.tokenOut
1253
+ },
1254
+ user: order.user
1255
+ }
1256
+ ]
1257
+ }),
1258
+ value: 0n,
1259
+ from: order.user
1260
+ });
1261
+ }
1262
+ const mask = 1n << nonceBitPos;
1263
+ if ((currentBitmap & mask) !== 0n) {
1264
+ throw new Error("Nonce is already invalidated");
1265
+ }
1266
+ return await wallet.sendTransaction({
1267
+ to: PERMIT2_ADDRESS2[chainId],
1268
+ data: encodeFunctionData3({
1269
+ abi: [
1270
+ {
1271
+ inputs: [
1272
+ { name: "wordPos", type: "uint256" },
1273
+ { name: "mask", type: "uint256" }
1274
+ ],
1275
+ name: "invalidateUnorderedNonces",
1276
+ outputs: [],
1277
+ stateMutability: "nonpayable",
1278
+ type: "function"
1279
+ }
1280
+ ],
1281
+ functionName: "invalidateUnorderedNonces",
1282
+ args: [nonceWordPos, mask]
1283
+ }),
1284
+ value: 0n,
1285
+ from: order.user
1286
+ });
1287
+ }
1288
+
1289
+ // src/core/client.ts
1290
+ var SwapSDK = class {
1291
+ constructor(config) {
1292
+ __publicField(this, "apiKey");
1293
+ /**
1294
+ * Fetches metadata for one or more tokens from the Shogun Token Search API.
1295
+ *
1296
+ * ---
1297
+ * ### Overview
1298
+ * `getTokensData` retrieves normalized token information — such as symbol, name,
1299
+ * decimals, logo URI, and verified status — for a given list of token addresses.
1300
+ *
1301
+ * It supports both **EVM** and **SVM (Solana)** tokens, returning metadata from
1302
+ * Shogun’s unified token registry.
1303
+ *
1304
+ * ---
1305
+ * @example
1306
+ * ```ts
1307
+ * const tokens = await getTokensData([
1308
+ * "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC
1309
+ * "So11111111111111111111111111111111111111112", // SOL
1310
+ * ]);
1311
+ *
1312
+ * console.log(tokens);
1313
+ * [
1314
+ * { symbol: "USDC", name: "USD Coin", chainId: 1, decimals: 6, ... },
1315
+ * { symbol: "SOL", name: "Solana", chainId: 101, decimals: 9, ... }
1316
+ * ]
1317
+ * ```
1318
+ *
1319
+ * @param addresses - An array of token addresses (EVM or SVM) to fetch metadata for.
1320
+ * @returns A promise resolving to an array of {@link TokenInfo} objects.
1321
+ *
1322
+ * @throws Will throw an error if the network request fails or the API responds with a non-OK status.
1323
+ */
1324
+ __publicField(this, "getTokensData", getTokensData.bind(this));
1325
+ if (!config.apiKey) {
1326
+ throw new Error("SwapSDK: Missing API key");
1327
+ }
1328
+ this.apiKey = config.apiKey;
1329
+ if (this.apiKey) void this.apiKey;
1330
+ }
1331
+ /**
1332
+ * Retrieves a swap quote for the given input and output tokens.
1333
+ *
1334
+ * @param params - Quote parameters including source/destination tokens and amount.
1335
+ * @returns A normalized `SwapQuoteResponse` containing output amount, route, and metadata.
1336
+ */
1337
+ async getQuote(params) {
1338
+ return getQuote(params);
1339
+ }
1340
+ /**
1341
+ * Fetches token balances for the specified user wallet(s).
1342
+ *
1343
+ * Supports both EVM and SVM (Solana) wallet addresses.
1344
+ *
1345
+ * @param params - Wallet address and optional chain filters.
1346
+ * @param options - Optional abort signal for cancellation.
1347
+ * @returns A unified balance response with per-chain token details.
1348
+ */
1349
+ async getBalances(params, options) {
1350
+ return getBalances(params, options);
1351
+ }
1352
+ /**
1353
+ * Retrieves a list of verified tokens based on search query or chain filter.
1354
+ *
1355
+ * @param params - Search parameters (query, chain ID, pagination options).
1356
+ * @returns Paginated `TokenSearchResponse` containing token metadata.
1357
+ */
1358
+ async getTokenList(params) {
1359
+ return getTokenList(params);
1360
+ }
1361
+ /**
1362
+ * Executes a prepared swap quote using the provided wallet and configuration.
1363
+ *
1364
+ * Handles:
1365
+ * - Token approval (if required)
1366
+ * - Transaction signing and broadcasting
1367
+ * - Confirmation polling and stage-based status updates
1368
+ *
1369
+ * Supports both:
1370
+ * - Market orders (with optional deadline)
1371
+ * - Limit orders (requires executionPrice and deadline)
1372
+ *
1373
+ * @param quote - The swap quote to execute, containing route and metadata.
1374
+ * @param accountAddress - The user's wallet address executing the swap.
1375
+ * @param recipientAddress - Optional recipient address for the output tokens (defaults to sender).
1376
+ * @param wallet - Adapted wallet instance (EVM/Solana) or a standard Viem `WalletClient`.
1377
+ * @param onStatus - Optional callback for receiving execution stage updates and messages.
1378
+ * @param orderType - Defines whether this is a market or limit order.
1379
+ * @param options - Execution parameters (different per order type).
1380
+ *
1381
+ * @returns A finalized execution result containing transaction hash, status, and any returned data.
1382
+ *
1383
+ * @example
1384
+ * ```ts
1385
+ * * Market order
1386
+ * const result = await sdk.executeTransaction({
1387
+ * quote,
1388
+ * accountAddress: "0x123...",
1389
+ * wallet,
1390
+ * orderType: OrderExecutionType.MARKET,
1391
+ * options: { deadline: 1800 },
1392
+ * onStatus: (stage, msg) => console.log(stage, msg),
1393
+ * });
1394
+ *
1395
+ * * Limit order
1396
+ * const result = await sdk.executeTransaction({
1397
+ * quote,
1398
+ * accountAddress: "0x123...",
1399
+ * wallet,
1400
+ * orderType: OrderExecutionType.LIMIT,
1401
+ * options: { executionPrice: "0.0021", deadline: 3600 },
1402
+ * });
1403
+ * ```
1404
+ */
1405
+ async executeTransaction({
1406
+ quote,
1407
+ accountAddress,
1408
+ recipientAddress,
1409
+ wallet,
1410
+ onStatus,
1411
+ orderType,
1412
+ options
1413
+ }) {
1414
+ return executeOrder({
1415
+ quote,
1416
+ wallet,
1417
+ accountAddress,
1418
+ recipientAddress,
1419
+ onStatus,
1420
+ orderType,
1421
+ options
1422
+ });
1423
+ }
1424
+ /**
1425
+ * Fetches all user orders (Market, Limit, Cross-chain) for connected wallets.
1426
+ *
1427
+ * ---
1428
+ * ### Overview
1429
+ * Retrieves both **single-chain** and **cross-chain** orders from the Shogun Intents API.
1430
+ * Works across EVM, Solana
1431
+ *
1432
+ * ---
1433
+ * @example
1434
+ * ```ts
1435
+ * const orders = await sdk.getOrders({
1436
+ * evmAddress: "0x123...",
1437
+ * solAddress: "9d12hF...abc",
1438
+ * });
1439
+ *
1440
+ * console.log(orders.singleChainLimitOrders);
1441
+ * ```
1442
+ *
1443
+ * @param params - Wallet addresses to fetch orders for (EVM, Solana).
1444
+ * @returns A structured {@link ApiUserOrders} object containing all user orders.
1445
+ */
1446
+ async getOrders(params) {
1447
+ return getOrders(params);
1448
+ }
1449
+ /**
1450
+ * Cancels an order (single-chain or cross-chain) on EVM or Solana.
1451
+ *
1452
+ * Internally routes to the correct guard contract or Solana program to
1453
+ * deactivate the order or invalidate its nonce.
1454
+ *
1455
+ * @param params.order - Order payload returned from the Intents API.
1456
+ * @param params.wallet - Adapted wallet used to submit the cancellation transaction.
1457
+ * @param params.solRpc - Solana RPC URL used for SVM cancellations.
1458
+ *
1459
+ * @returns A transaction signature or hash from the underlying wallet.
1460
+ */
1461
+ async cancelOrder(params) {
1462
+ return cancelIntentsOrder({
1463
+ order: params.order,
1464
+ wallet: params.wallet,
1465
+ sol_rpc: params.solRpc
1466
+ });
1467
+ }
1468
+ };
1469
+
1470
+ // src/react/SwapProvider.tsx
1471
+ import { jsx } from "react/jsx-runtime";
1472
+ var SwapContext = createContext(null);
1473
+ var SwapProvider = ({ config, children }) => {
1474
+ const sdk = useMemo(() => new SwapSDK(config), [config.apiKey]);
1475
+ return /* @__PURE__ */ jsx(SwapContext.Provider, { value: sdk, children });
1476
+ };
1477
+ var useSwap = () => {
1478
+ const ctx = useContext(SwapContext);
1479
+ if (!ctx) {
1480
+ throw new Error("useSwap must be used within <SwapProvider>");
1481
+ }
1482
+ return ctx;
1483
+ };
1484
+
1485
+ // src/react/useQuote.ts
1486
+ import { useCallback, useEffect, useMemo as useMemo2, useRef } from "react";
1487
+ import useSWR, { mutate } from "swr";
1488
+ var QUOTE_KEY = "quote-global";
1489
+ function isValidQuoteParams(p) {
1490
+ if (!p) return false;
1491
+ const { tokenIn, tokenOut, amount } = p;
1492
+ if (!tokenIn || !tokenOut || !amount) return false;
1493
+ const n = Number(amount);
1494
+ return Number.isFinite(n) && n > 0;
1495
+ }
1496
+ function useQuote(initialParams) {
1497
+ const sdk = useSwap();
1498
+ const abortRef = useRef(null);
1499
+ const paramsRef = globalThis.__QUOTE_PARAMS_REF__ ?? (globalThis.__QUOTE_PARAMS_REF__ = { current: initialParams ?? null });
1500
+ useEffect(() => {
1501
+ if (initialParams && JSON.stringify(paramsRef.current) !== JSON.stringify(initialParams)) {
1502
+ paramsRef.current = initialParams;
1503
+ void mutate(QUOTE_KEY);
1504
+ }
1505
+ }, [initialParams]);
1506
+ const fetcher = useCallback(async () => {
1507
+ const activeParams = paramsRef.current;
1508
+ if (!isValidQuoteParams(activeParams)) return null;
1509
+ if (abortRef.current) abortRef.current.abort();
1510
+ const controller = new AbortController();
1511
+ abortRef.current = controller;
1512
+ try {
1513
+ return await sdk.getQuote(activeParams);
1514
+ } catch (err) {
1515
+ if (err instanceof DOMException && err.name === "AbortError") return null;
1516
+ if (err instanceof Error) throw err;
1517
+ throw new Error(String(err));
1518
+ }
1519
+ }, [sdk]);
1520
+ const {
1521
+ data,
1522
+ error,
1523
+ isValidating: loading,
1524
+ mutate: mutateQuote
1525
+ } = useSWR(QUOTE_KEY, fetcher, {
1526
+ revalidateOnFocus: false,
1527
+ shouldRetryOnError: false,
1528
+ keepPreviousData: true
1529
+ });
1530
+ const refetch = useCallback(async () => {
1531
+ await mutateQuote();
1532
+ }, [mutateQuote]);
1533
+ const setParams = useCallback(
1534
+ (next) => {
1535
+ paramsRef.current = next;
1536
+ void mutate(QUOTE_KEY);
1537
+ },
1538
+ []
1539
+ );
1540
+ return useMemo2(
1541
+ () => ({
1542
+ data,
1543
+ loading,
1544
+ error: error instanceof Error ? error.message : null,
1545
+ refetch,
1546
+ setParams,
1547
+ get activeParams() {
1548
+ return paramsRef.current;
1549
+ }
1550
+ }),
1551
+ [data, loading, error, refetch, setParams]
1552
+ );
1553
+ }
1554
+
1555
+ // src/react/useExecuteTransaction.ts
1556
+ import { useState, useCallback as useCallback3 } from "react";
1557
+
1558
+ // src/react/useBalances.ts
1559
+ import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo3, useRef as useRef2 } from "react";
1560
+ import useSWR2, { mutate as mutate2 } from "swr";
1561
+ var BALANCE_KEY = "balances-global";
1562
+ function useBalances(initialParams, options) {
1563
+ const sdk = useSwap();
1564
+ const abortRef = useRef2(null);
1565
+ const lastDataRef = useRef2(null);
1566
+ const paramsRef = globalThis.__BALANCES_PARAMS_REF__ ?? (globalThis.__BALANCES_PARAMS_REF__ = { current: initialParams ?? null });
1567
+ const fetcher = useCallback2(async () => {
1568
+ const activeParams = paramsRef.current;
1569
+ if (!activeParams) return null;
1570
+ if (abortRef.current) abortRef.current.abort();
1571
+ const controller = new AbortController();
1572
+ abortRef.current = controller;
1573
+ try {
1574
+ const balances = await sdk.getBalances(activeParams, { signal: controller.signal });
1575
+ lastDataRef.current = balances;
1576
+ return balances;
1577
+ } catch (err) {
1578
+ if (err instanceof DOMException && err.name === "AbortError") return lastDataRef.current;
1579
+ if (err instanceof Error) throw err;
1580
+ throw new Error(String(err));
1581
+ }
1582
+ }, [sdk, paramsRef]);
1583
+ const {
1584
+ data,
1585
+ error,
1586
+ // `isLoading` is only true on the initial fetch (no data yet), so background
1587
+ // refreshes on `refreshInterval` don't toggle it and flicker the UI.
1588
+ isLoading: loading,
1589
+ isValidating,
1590
+ mutate: mutateBalances
1591
+ } = useSWR2(BALANCE_KEY, fetcher, {
1592
+ revalidateOnFocus: false,
1593
+ shouldRetryOnError: false,
1594
+ keepPreviousData: true,
1595
+ // 0 (default) disables polling; a positive value re-fetches on that interval.
1596
+ refreshInterval: options?.refreshInterval ?? 0
1597
+ });
1598
+ const refetch = useCallback2(async () => {
1599
+ await mutateBalances();
1600
+ }, [mutateBalances]);
1601
+ const setParams = useCallback2((next) => {
1602
+ paramsRef.current = next;
1603
+ void mutate2(BALANCE_KEY);
1604
+ }, [paramsRef]);
530
1605
  useEffect2(() => {
531
- return () => {
532
- isMounted.current = false;
533
- };
534
- }, []);
535
- const execute = useCallback(
1606
+ if (initialParams) {
1607
+ const prevParams = paramsRef.current;
1608
+ const paramsChanged = !prevParams || prevParams.addresses.svm !== initialParams.addresses.svm || prevParams.addresses.evm !== initialParams.addresses.evm;
1609
+ if (paramsChanged) {
1610
+ paramsRef.current = initialParams;
1611
+ void mutate2(BALANCE_KEY);
1612
+ }
1613
+ }
1614
+ }, [initialParams, paramsRef]);
1615
+ return useMemo3(
1616
+ () => ({
1617
+ data,
1618
+ loading,
1619
+ // True during background revalidation (e.g. `refreshInterval` polls) while
1620
+ // previous `data` stays visible — use for a subtle refresh indicator.
1621
+ isValidating,
1622
+ error: error instanceof Error ? error : null,
1623
+ refetch,
1624
+ setParams,
1625
+ get activeParams() {
1626
+ return paramsRef.current;
1627
+ }
1628
+ }),
1629
+ [data, loading, isValidating, error, refetch, setParams, paramsRef]
1630
+ );
1631
+ }
1632
+
1633
+ // src/react/useExecuteTransaction.ts
1634
+ function useExecuteTransaction() {
1635
+ const sdk = useSwap();
1636
+ const [isLoading, setLoading] = useState(false);
1637
+ const [stage, setStage] = useState(null);
1638
+ const [message, setMessage] = useState(null);
1639
+ const [error, setError] = useState(null);
1640
+ const [result, setResult] = useState(null);
1641
+ const { refetch: refetchQuote } = useQuote();
1642
+ const { refetch: refetchBalances } = useBalances();
1643
+ const execute = useCallback3(
536
1644
  async ({
537
1645
  quote,
538
1646
  accountAddress,
539
1647
  recipientAddress,
540
1648
  wallet,
541
- deadline
1649
+ orderType,
1650
+ options
542
1651
  }) => {
543
- if (!quote || !wallet) {
544
- throw new Error("Quote and wallet are required for order execution.");
545
- }
546
1652
  setLoading(true);
547
1653
  setError(null);
548
- setData(null);
549
- setMessage(null);
1654
+ setResult(null);
1655
+ const onStatus = (s, msg) => {
1656
+ setStage(s);
1657
+ setMessage(msg ?? "");
1658
+ };
550
1659
  try {
551
- const effectiveDeadline = deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
552
- const onStatus = (stage, msg) => {
553
- if (!isMounted.current) return;
554
- setStatus(stage);
555
- if (msg) setMessage(msg);
556
- };
557
- const result = await executeOrder({
1660
+ const res = await sdk.executeTransaction({
558
1661
  quote,
1662
+ wallet,
559
1663
  accountAddress,
560
1664
  recipientAddress,
561
- wallet,
562
1665
  onStatus,
563
- options: { deadline: effectiveDeadline }
1666
+ orderType,
1667
+ options
564
1668
  });
565
- if (!isMounted.current) return result;
566
- setData(result);
567
- setStatus(result.stage);
568
- setMessage("Order executed successfully");
569
- return result;
570
- } catch (err) {
571
- const errorObj = err instanceof Error ? err : new Error(String(err));
572
- if (isMounted.current) {
573
- setError(errorObj);
574
- setStatus("error");
575
- setMessage(errorObj.message);
576
- setData({
577
- status: false,
578
- stage: "error",
579
- message: errorObj.message
1669
+ if (res && typeof res === "object" && "status" in res && "stage" in res && typeof res.stage === "string") {
1670
+ setResult({
1671
+ ...res,
1672
+ stage: res.stage
580
1673
  });
1674
+ } else {
1675
+ setResult(res);
581
1676
  }
582
- return {
583
- status: false,
584
- stage: "error",
585
- message: errorObj.message
586
- };
1677
+ return res;
1678
+ } catch (err) {
1679
+ const msg = err instanceof Error ? err.message : String(err);
1680
+ setError(msg);
1681
+ throw err;
587
1682
  } finally {
588
- if (isMounted.current) setLoading(false);
1683
+ await Promise.allSettled([refetchQuote(), refetchBalances()]);
1684
+ setLoading(false);
589
1685
  }
590
1686
  },
591
- []
1687
+ [sdk, refetchQuote, refetchBalances]
592
1688
  );
593
1689
  return {
594
- /** Executes the swap order. */
595
1690
  execute,
596
- /** Current execution stage. */
597
- status,
598
- /** Human-readable status message. */
1691
+ isLoading,
1692
+ stage,
599
1693
  message,
600
- /** Whether execution is ongoing. */
601
- loading,
602
- /** Raw SDK response data. */
603
- data,
604
- /** Captured error (if execution failed). */
605
- error
606
- };
607
- }
608
-
609
- // src/react/useQuote.ts
610
- import { useCallback as useCallback2, useEffect as useEffect3, useMemo as useMemo2, useRef as useRef3, useState as useState3 } from "react";
611
-
612
- // src/core/getQuote.ts
613
- import { QuoteProvider } from "@shogun-sdk/intents-sdk";
614
- import { parseUnits } from "viem";
615
- async function getQuote(params) {
616
- if (!params.tokenIn?.address || !params.tokenOut?.address) {
617
- throw new Error("Both tokenIn and tokenOut must include an address.");
618
- }
619
- if (!params.sourceChainId || !params.destChainId) {
620
- throw new Error("Both sourceChainId and destChainId are required.");
621
- }
622
- if (params.amount <= 0n) {
623
- throw new Error("Amount must be greater than 0.");
624
- }
625
- const normalizedTokenIn = normalizeNative(params.sourceChainId, params.tokenIn.address);
626
- const data = await QuoteProvider.getQuote({
627
- sourceChainId: params.sourceChainId,
628
- destChainId: params.destChainId,
629
- tokenIn: normalizedTokenIn,
630
- tokenOut: params.tokenOut.address,
631
- amount: params.amount
632
- });
633
- const inputSlippage = params.slippage ?? 5;
634
- const slippageDecimal = inputSlippage / 100;
635
- const slippage = Math.min(Math.max(slippageDecimal, 0), 0.5);
636
- let warning;
637
- if (slippage > 0.1) {
638
- warning = `\u26A0\uFE0F High slippage tolerance (${(slippage * 100).toFixed(2)}%) \u2014 price may vary significantly.`;
639
- }
640
- const estimatedAmountOut = BigInt(data.estimatedAmountOutReduced);
641
- const slippageBps = BigInt(Math.round(slippage * 1e4));
642
- const estimatedAmountOutAfterSlippage = estimatedAmountOut * (10000n - slippageBps) / 10000n;
643
- const pricePerInputToken = estimatedAmountOut * 10n ** BigInt(params.tokenIn.decimals ?? 18) / BigInt(params.amount);
644
- return {
645
- amountOut: estimatedAmountOut,
646
- amountOutUsd: data.estimatedAmountOutUsd,
647
- amountInUsd: data.amountInUsd,
648
- minStablecoinsAmount: data.estimatedAmountInAsMinStablecoinAmount,
649
- tokenIn: {
650
- address: params.tokenIn.address,
651
- decimals: params.tokenIn.decimals ?? 18,
652
- chainId: params.sourceChainId
653
- },
654
- tokenOut: {
655
- address: params.tokenOut.address,
656
- decimals: params.tokenOut.decimals ?? 18,
657
- chainId: params.destChainId
658
- },
659
- amountIn: params.amount,
660
- pricePerInputToken,
661
- slippage,
662
- internal: {
663
- ...data,
664
- estimatedAmountOutReduced: estimatedAmountOutAfterSlippage
665
- },
666
- warning
1694
+ error,
1695
+ result
667
1696
  };
668
1697
  }
669
1698
 
670
- // src/react/useQuote.ts
671
- function useQuote(params, options) {
672
- const [data, setData] = useState3(null);
673
- const [loading, setLoading] = useState3(false);
674
- const [error, setError] = useState3(null);
675
- const [warning, setWarning] = useState3(null);
676
- const debounceMs = options?.debounceMs ?? 250;
677
- const autoRefreshMs = options?.autoRefreshMs;
678
- const abortRef = useRef3(null);
679
- const debounceRef = useRef3(null);
680
- const mounted = useRef3(false);
681
- useEffect3(() => {
682
- mounted.current = true;
683
- return () => {
684
- mounted.current = false;
685
- abortRef.current?.abort();
686
- if (debounceRef.current) clearTimeout(debounceRef.current);
687
- };
688
- }, []);
689
- const fetchQuote = useCallback2(
690
- async () => {
691
- if (!params) return;
1699
+ // src/react/useTokenList.ts
1700
+ import { useRef as useRef3, useState as useState2, useCallback as useCallback4 } from "react";
1701
+ function useTokenList() {
1702
+ const [tokens, setTokens] = useState2([]);
1703
+ const [loading, setLoading] = useState2(false);
1704
+ const [error, setError] = useState2(null);
1705
+ const [hasMore, setHasMore] = useState2(true);
1706
+ const [page, setPage] = useState2(1);
1707
+ const sdk = useSwap();
1708
+ const pageRef = useRef3(1);
1709
+ const hasMoreRef = useRef3(true);
1710
+ const lastQuery = useRef3({});
1711
+ const cache = useRef3(/* @__PURE__ */ new Map());
1712
+ const isLoadingRef = useRef3(false);
1713
+ pageRef.current = page;
1714
+ hasMoreRef.current = hasMore;
1715
+ const loadTokens = useCallback4(
1716
+ async (params) => {
1717
+ const { q, networkId, reset } = params;
1718
+ if (isLoadingRef.current && !reset) return;
692
1719
  try {
1720
+ let currentPage = pageRef.current;
1721
+ if (reset) {
1722
+ currentPage = 1;
1723
+ setTokens([]);
1724
+ setPage(1);
1725
+ setHasMore(true);
1726
+ pageRef.current = 1;
1727
+ hasMoreRef.current = true;
1728
+ }
1729
+ if (!reset && !hasMoreRef.current) return;
1730
+ isLoadingRef.current = true;
693
1731
  setLoading(true);
694
- setWarning(null);
695
- const result = await getQuote(params);
696
- const serializeResult = serializeBigIntsToStrings(result);
697
- if (!mounted.current) return;
698
- setData((prev) => {
699
- if (JSON.stringify(prev) === JSON.stringify(serializeResult)) return prev;
700
- return serializeResult;
701
- });
702
- setWarning(result.warning ?? null);
703
1732
  setError(null);
704
- } catch (err) {
705
- if (err.name === "AbortError") return;
706
- console.error("[useQuote] fetch error:", err);
707
- if (mounted.current) setError(err instanceof Error ? err : new Error(String(err)));
1733
+ const cacheKey = JSON.stringify({
1734
+ q: q?.toLowerCase() ?? "",
1735
+ networkId: networkId ?? void 0,
1736
+ page: currentPage
1737
+ });
1738
+ if (cache.current.has(cacheKey)) {
1739
+ const cached = cache.current.get(cacheKey);
1740
+ setTokens((prev) => reset ? cached.results : [...prev, ...cached.results]);
1741
+ if (!reset && cached.results.length > 0) {
1742
+ const nextPage = currentPage + 1;
1743
+ setPage(nextPage);
1744
+ pageRef.current = nextPage;
1745
+ }
1746
+ isLoadingRef.current = false;
1747
+ setLoading(false);
1748
+ return;
1749
+ }
1750
+ const apiParams = {
1751
+ q,
1752
+ page: currentPage,
1753
+ limit: 20,
1754
+ ...networkId !== void 0 ? { networkId } : {}
1755
+ };
1756
+ const res = await sdk.getTokenList(apiParams);
1757
+ cache.current.set(cacheKey, res);
1758
+ setTokens((prev) => reset ? res.results : [...prev, ...res.results]);
1759
+ const isLastPage = res.results.length === 0 || res.results.length < 20 || res.count && currentPage * 20 >= res.count;
1760
+ setHasMore(!isLastPage);
1761
+ hasMoreRef.current = !isLastPage;
1762
+ if (!reset && !isLastPage) {
1763
+ const nextPage = currentPage + 1;
1764
+ setPage(nextPage);
1765
+ pageRef.current = nextPage;
1766
+ }
1767
+ lastQuery.current = { q, networkId };
1768
+ } catch (e) {
1769
+ console.error("useTokenList error:", e);
1770
+ setError("Failed to load tokens");
708
1771
  } finally {
709
- if (mounted.current) setLoading(false);
1772
+ setLoading(false);
1773
+ isLoadingRef.current = false;
710
1774
  }
711
1775
  },
712
- [params]
1776
+ [sdk]
713
1777
  );
1778
+ const resetTokens = useCallback4(() => {
1779
+ setTokens([]);
1780
+ setPage(1);
1781
+ setHasMore(true);
1782
+ pageRef.current = 1;
1783
+ hasMoreRef.current = true;
1784
+ cache.current.clear();
1785
+ lastQuery.current = {};
1786
+ }, []);
1787
+ return {
1788
+ tokens,
1789
+ loading,
1790
+ error,
1791
+ hasMore,
1792
+ page,
1793
+ lastQuery: lastQuery.current,
1794
+ loadTokens,
1795
+ resetTokens
1796
+ };
1797
+ }
1798
+
1799
+ // src/react/useTokensData.ts
1800
+ import { useState as useState3, useEffect as useEffect3 } from "react";
1801
+ function useTokensData(addresses) {
1802
+ const sdk = useSwap();
1803
+ const [data, setData] = useState3([]);
1804
+ const [loading, setLoading] = useState3(false);
1805
+ const [error, setError] = useState3(null);
714
1806
  useEffect3(() => {
715
- if (!params) return;
716
- if (debounceRef.current) clearTimeout(debounceRef.current);
717
- debounceRef.current = setTimeout(() => {
718
- fetchQuote();
719
- }, debounceMs);
1807
+ if (!addresses?.length) return;
1808
+ let isMounted = true;
1809
+ setLoading(true);
1810
+ setError(null);
1811
+ sdk.getTokensData(addresses).then((res) => {
1812
+ if (isMounted) setData(res);
1813
+ }).catch((e) => {
1814
+ if (isMounted) setError(e instanceof Error ? e : new Error(String(e)));
1815
+ }).finally(() => {
1816
+ if (isMounted) setLoading(false);
1817
+ });
720
1818
  return () => {
721
- if (debounceRef.current) clearTimeout(debounceRef.current);
722
- abortRef.current?.abort();
1819
+ isMounted = false;
723
1820
  };
724
- }, [params, debounceMs, fetchQuote]);
725
- useEffect3(() => {
726
- if (!autoRefreshMs || !params) return;
727
- const interval = setInterval(() => fetchQuote(), autoRefreshMs);
728
- return () => clearInterval(interval);
729
- }, [autoRefreshMs, params, fetchQuote]);
730
- return useMemo2(
731
- () => ({
732
- data,
733
- loading,
734
- error,
735
- warning,
736
- refetch: () => fetchQuote()
737
- }),
738
- [data, loading, error, warning, fetchQuote]
739
- );
1821
+ }, [sdk, JSON.stringify(addresses)]);
1822
+ return { data, loading, error };
740
1823
  }
741
1824
 
742
- // src/react/useBalances.ts
743
- import { useCallback as useCallback3, useEffect as useEffect4, useMemo as useMemo3, useRef as useRef4, useState as useState4 } from "react";
744
-
745
- // src/core/getBalances.ts
746
- import { TOKEN_SEARCH_API_BASE_URL } from "@shogun-sdk/intents-sdk";
747
- async function getBalances(params, options) {
748
- const { addresses, cursorEvm, cursorSvm } = params;
749
- const { signal } = options ?? {};
750
- if (!addresses?.evm && !addresses?.svm) {
751
- throw new Error("At least one address (EVM or SVM) must be provided.");
752
- }
753
- const payload = JSON.stringify({
754
- addresses,
755
- cursorEvm,
756
- cursorSvm
757
- });
758
- const start = performance.now();
759
- const response = await fetch(`${TOKEN_SEARCH_API_BASE_URL}/tokens/balances`, {
760
- method: "POST",
761
- headers: {
762
- accept: "application/json",
763
- "Content-Type": "application/json"
764
- },
765
- body: payload,
766
- signal
767
- }).catch((err) => {
768
- if (err.name === "AbortError") {
769
- throw new Error("Balance request was cancelled.");
770
- }
771
- throw err;
772
- });
773
- if (!response.ok) {
774
- const text = await response.text().catch(() => "");
775
- throw new Error(`Failed to fetch balances: ${response.status} ${text}`);
776
- }
777
- const data = await response.json().catch(() => {
778
- throw new Error("Invalid JSON response from balances API.");
779
- });
780
- const duration = (performance.now() - start).toFixed(1);
781
- if (process.env.NODE_ENV !== "production") {
782
- console.debug(`[Shogun SDK] Fetched balances in ${duration}ms`);
783
- }
784
- const evmItems = data.evm?.items ?? [];
785
- const svmItems = data.svm?.items ?? [];
786
- const combined = [...evmItems, ...svmItems];
787
- return {
788
- results: combined,
789
- nextCursorEvm: data.evm?.cursor ?? null,
790
- nextCursorSvm: data.svm?.cursor ?? null
791
- };
1825
+ // src/react/useOrders.ts
1826
+ import { useCallback as useCallback5, useEffect as useEffect4, useMemo as useMemo4, useRef as useRef4 } from "react";
1827
+ import useSWR3, { mutate as mutate3 } from "swr";
1828
+ var ORDERS_KEY = "orders-global";
1829
+ function hasValidAddress(addrs) {
1830
+ if (!addrs) return false;
1831
+ return Boolean(addrs.evmAddress || addrs.solAddress || addrs.suiAddress);
792
1832
  }
793
-
794
- // src/react/useBalances.ts
795
- function useBalances(params) {
796
- const [data, setData] = useState4(null);
797
- const [loading, setLoading] = useState4(false);
798
- const [error, setError] = useState4(null);
1833
+ function useOrders(initialAddresses) {
1834
+ const sdk = useSwap();
799
1835
  const abortRef = useRef4(null);
800
- const stableParams = useMemo3(() => {
801
- if (!params) return null;
802
- const { addresses, cursorEvm, cursorSvm } = params;
803
- return {
804
- addresses: {
805
- evm: addresses?.evm ?? void 0,
806
- svm: addresses?.svm ?? void 0
807
- },
808
- cursorEvm,
809
- cursorSvm
810
- };
811
- }, [params?.addresses?.evm, params?.addresses?.svm, params?.cursorEvm, params?.cursorSvm]);
812
- const fetchBalances = useCallback3(async () => {
813
- if (!stableParams) return;
1836
+ const addrRef = globalThis.__ORDERS_ADDR_REF__ ?? (globalThis.__ORDERS_ADDR_REF__ = { current: initialAddresses ?? null });
1837
+ useEffect4(() => {
1838
+ if (initialAddresses && JSON.stringify(addrRef.current) !== JSON.stringify(initialAddresses)) {
1839
+ addrRef.current = initialAddresses;
1840
+ void mutate3(ORDERS_KEY);
1841
+ }
1842
+ }, [initialAddresses]);
1843
+ const fetcher = useCallback5(async () => {
1844
+ const active = addrRef.current;
1845
+ if (!hasValidAddress(active)) return null;
814
1846
  if (abortRef.current) abortRef.current.abort();
815
1847
  const controller = new AbortController();
816
1848
  abortRef.current = controller;
817
- setLoading(true);
818
- setError(null);
819
1849
  try {
820
- const result = await getBalances(stableParams, { signal: controller.signal });
821
- setData((prev) => {
822
- if (JSON.stringify(prev) === JSON.stringify(result)) return prev;
823
- return result;
824
- });
825
- return result;
1850
+ return await sdk.getOrders(active ?? {});
826
1851
  } catch (err) {
827
- if (err.name === "AbortError") return;
828
- const e = err instanceof Error ? err : new Error(String(err));
829
- setError(e);
830
- throw e;
831
- } finally {
832
- setLoading(false);
1852
+ if (err instanceof DOMException && err.name === "AbortError") return null;
1853
+ if (err instanceof Error) throw err;
1854
+ throw new Error(String(err));
833
1855
  }
834
- }, [stableParams]);
835
- useEffect4(() => {
836
- if (stableParams) fetchBalances().catch(() => {
837
- });
838
- return () => {
839
- if (abortRef.current) abortRef.current.abort();
840
- };
841
- }, [fetchBalances]);
842
- return useMemo3(
1856
+ }, [sdk]);
1857
+ const {
1858
+ data,
1859
+ error,
1860
+ isValidating: loading,
1861
+ mutate: mutateOrders
1862
+ } = useSWR3(ORDERS_KEY, fetcher, {
1863
+ revalidateOnFocus: false,
1864
+ revalidateOnReconnect: false,
1865
+ shouldRetryOnError: false,
1866
+ keepPreviousData: true
1867
+ });
1868
+ const refetch = useCallback5(async () => {
1869
+ await mutateOrders();
1870
+ }, [mutateOrders]);
1871
+ const setAddresses = useCallback5(
1872
+ (next) => {
1873
+ if (!next) return;
1874
+ addrRef.current = next;
1875
+ void mutate3(ORDERS_KEY);
1876
+ },
1877
+ []
1878
+ );
1879
+ return useMemo4(
843
1880
  () => ({
844
- /** Latest fetched balance data */
845
1881
  data,
846
- /** Whether the hook is currently fetching */
847
1882
  loading,
848
- /** Error object if fetching failed */
849
- error,
850
- /** Manually trigger a refresh */
851
- refetch: fetchBalances
1883
+ error: error instanceof Error ? error.message : null,
1884
+ refetch,
1885
+ setAddresses,
1886
+ get activeAddresses() {
1887
+ return addrRef.current;
1888
+ }
852
1889
  }),
853
- [data, loading, error, fetchBalances]
1890
+ [data, loading, error, refetch, setAddresses]
854
1891
  );
855
1892
  }
856
1893
 
857
- // src/react/index.ts
858
- import { ChainID as ChainID5, isEvmChain as isEvmChain3 } from "@shogun-sdk/intents-sdk";
1894
+ // src/react/useCancelOrder.ts
1895
+ import { useCallback as useCallback6, useState as useState4 } from "react";
1896
+ import { mutate as mutate4 } from "swr";
1897
+ function useCancelOrder() {
1898
+ const sdk = useSwap();
1899
+ const [isLoading, setLoading] = useState4(false);
1900
+ const [error, setError] = useState4(null);
1901
+ const [result, setResult] = useState4(null);
1902
+ const cancel = useCallback6(
1903
+ async (params) => {
1904
+ setLoading(true);
1905
+ setError(null);
1906
+ setResult(null);
1907
+ try {
1908
+ const tx = await sdk.cancelOrder({
1909
+ order: params.order,
1910
+ wallet: params.wallet,
1911
+ solRpc: params.solRpc
1912
+ });
1913
+ setResult(tx);
1914
+ void mutate4("orders-global");
1915
+ return tx;
1916
+ } catch (err) {
1917
+ const msg = err instanceof Error ? err.message : String(err);
1918
+ setError(msg);
1919
+ throw err;
1920
+ } finally {
1921
+ setLoading(false);
1922
+ }
1923
+ },
1924
+ [sdk]
1925
+ );
1926
+ return {
1927
+ cancel,
1928
+ isLoading,
1929
+ error,
1930
+ result
1931
+ };
1932
+ }
859
1933
  export {
860
- ChainID5 as ChainID,
861
- isEvmChain3 as isEvmChain,
1934
+ ChainId,
1935
+ OrderExecutionType,
1936
+ SupportedChains,
1937
+ SwapProvider,
1938
+ buildQuoteParams,
1939
+ isEvmChain,
862
1940
  useBalances,
863
- useExecuteOrder,
1941
+ useCancelOrder,
1942
+ useExecuteTransaction,
1943
+ useOrders,
864
1944
  useQuote,
865
- useTokenList
1945
+ useSwap,
1946
+ useTokenList,
1947
+ useTokensData
866
1948
  };