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