@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/core.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,22 +271,69 @@ 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";
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
+ );
302
+ return {
303
+ ...data,
304
+ results: filteredResults,
305
+ count: filteredResults.length
306
+ };
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";
248
332
 
249
333
  // src/wallet-adapter/evm-wallet-adapter/adapter.ts
250
- import "ethers/lib/ethers.js";
251
- import { hexValue } from "ethers/lib/utils.js";
252
334
  import {
253
- custom
335
+ custom,
336
+ publicActions
254
337
  } from "viem";
255
338
  function isEVMTransaction(tx) {
256
339
  return typeof tx.from === "string";
@@ -269,15 +352,26 @@ var adaptViemWallet = (wallet) => {
269
352
  if (!isEVMTransaction(transaction)) {
270
353
  throw new Error("Expected EVMTransaction but got SolanaTransaction");
271
354
  }
272
- const tx = await wallet.sendTransaction({
273
- from: transaction.from,
274
- to: transaction.to,
275
- data: transaction.data,
276
- value: transaction.value,
277
- account: wallet.account?.address,
278
- chain: wallet.chain
279
- });
280
- 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
+ }
281
375
  };
282
376
  const switchChain = async (chainId) => {
283
377
  try {
@@ -300,6 +394,20 @@ var adaptViemWallet = (wallet) => {
300
394
  if (!addr) throw new Error("No address found");
301
395
  return addr;
302
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
+ };
303
411
  return {
304
412
  vmType: "EVM" /* EVM */,
305
413
  transport: custom(wallet.transport),
@@ -307,39 +415,65 @@ var adaptViemWallet = (wallet) => {
307
415
  address,
308
416
  sendTransaction,
309
417
  signTypedData,
310
- switchChain
418
+ switchChain,
419
+ readContract
311
420
  };
312
421
  };
313
422
 
314
- // src/core/executeOrder/handleEvmExecution.ts
423
+ // src/core/execute/handleEvmExecution.ts
315
424
  import {
316
425
  getEVMSingleChainOrderTypedData,
317
- getEVMCrossChainOrderTypedData,
318
- PERMIT2_ADDRESS
426
+ getEVMCrossChainOrderTypedData
319
427
  } from "@shogun-sdk/intents-sdk";
320
- import { encodeFunctionData, erc20Abi } from "viem";
428
+ import { encodeFunctionData as encodeFunctionData2 } from "viem";
321
429
 
322
- // src/core/executeOrder/stageMessages.ts
430
+ // src/core/execute/stageMessages.ts
323
431
  var DEFAULT_STAGE_MESSAGES = {
324
432
  processing: "Preparing transaction for execution",
325
433
  approving: "Approving token allowance",
326
434
  approved: "Token approved successfully",
327
- signing: "Signing order for submission",
328
- submitting: "Submitting order to Auctioneer",
329
- success: "Order executed successfully",
330
- 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"
331
442
  };
332
443
 
333
- // src/core/executeOrder/buildOrder.ts
444
+ // src/core/execute/buildOrder.ts
334
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
335
456
  async function buildOrder({
336
457
  quote,
337
458
  accountAddress,
338
459
  destination,
339
460
  deadline,
340
- isSingleChain
461
+ isSingleChain,
462
+ orderType,
463
+ options
341
464
  }) {
342
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
+ }
343
477
  if (isSingleChain) {
344
478
  return await SingleChainOrder.create({
345
479
  user: accountAddress,
@@ -347,7 +481,7 @@ async function buildOrder({
347
481
  tokenIn: tokenIn.address,
348
482
  tokenOut: tokenOut.address,
349
483
  amountIn: quote.amountIn,
350
- amountOutMin: quote.internal.estimatedAmountOutReduced,
484
+ amountOutMin,
351
485
  deadline,
352
486
  destinationAddress: destination
353
487
  });
@@ -361,12 +495,166 @@ async function buildOrder({
361
495
  destinationTokenAddress: tokenOut.address,
362
496
  destinationAddress: destination,
363
497
  deadline,
364
- destinationTokenMinAmount: quote.internal.estimatedAmountOutReduced,
498
+ destinationTokenMinAmount: amountOutMin,
365
499
  minStablecoinAmount: quote.minStablecoinsAmount
366
500
  });
367
501
  }
368
502
 
369
- // 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
370
658
  async function handleEvmExecution({
371
659
  recipientAddress,
372
660
  quote,
@@ -374,18 +662,22 @@ async function handleEvmExecution({
374
662
  accountAddress,
375
663
  wallet,
376
664
  isSingleChain,
377
- deadline,
378
- update
665
+ update,
666
+ orderType,
667
+ options
379
668
  }) {
380
- 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;
381
671
  await wallet.switchChain(chainId);
382
672
  const tokenIn = normalizeNative(chainId, quote.tokenIn.address);
673
+ quote.tokenOut.address = normalizeEvmTokenAddress(quote.tokenOut.address);
383
674
  const shouldWrapNative = isNativeAddress(quote.tokenIn.address);
384
675
  update("processing", shouldWrapNative ? `${messageFor("processing")} (wrapping native token)` : messageFor("processing"));
385
676
  if (shouldWrapNative) {
677
+ quote.tokenIn.address === tokenIn;
386
678
  await wallet.sendTransaction({
387
679
  to: tokenIn,
388
- data: encodeFunctionData({
680
+ data: encodeFunctionData2({
389
681
  abi: [{ type: "function", name: "deposit", stateMutability: "payable", inputs: [], outputs: [] }],
390
682
  functionName: "deposit",
391
683
  args: []
@@ -394,44 +686,70 @@ async function handleEvmExecution({
394
686
  from: accountAddress
395
687
  });
396
688
  }
397
- update("approving", messageFor("approving"));
398
- await wallet.sendTransaction({
399
- to: tokenIn,
400
- data: encodeFunctionData({
401
- abi: erc20Abi,
402
- functionName: "approve",
403
- args: [PERMIT2_ADDRESS[chainId], BigInt(quote.amountIn)]
404
- }),
405
- value: 0n,
406
- from: accountAddress
689
+ update("processing", messageFor("approving"));
690
+ await ensurePermit2Allowance({
691
+ chainId,
692
+ tokenIn,
693
+ wallet,
694
+ accountAddress,
695
+ requiredAmount: BigInt(quote.amountIn)
407
696
  });
408
- update("approved", messageFor("approved"));
697
+ update("processing", messageFor("approved"));
409
698
  const destination = recipientAddress ?? accountAddress;
410
699
  const order = await buildOrder({
411
700
  quote,
412
701
  accountAddress,
413
702
  destination,
414
703
  deadline,
415
- isSingleChain
704
+ isSingleChain,
705
+ orderType,
706
+ options
416
707
  });
417
- update("signing", messageFor("signing"));
708
+ console.debug(`order`, order);
709
+ update("processing", messageFor("signing"));
418
710
  const { orderTypedData, nonce } = isSingleChain ? await getEVMSingleChainOrderTypedData(order) : await getEVMCrossChainOrderTypedData(order);
711
+ const typedData = serializeBigIntsToStrings(orderTypedData);
419
712
  if (!wallet.signTypedData) {
420
713
  throw new Error("Wallet does not support EIP-712 signing");
421
714
  }
422
- const signature = await wallet.signTypedData(serializeBigIntsToStrings(orderTypedData));
423
- 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"));
424
723
  const res = await order.sendToAuctioneer({ signature, nonce: nonce.toString() });
425
724
  if (!res.success) {
426
725
  throw new Error("Auctioneer submission failed");
427
726
  }
428
- update("success", messageFor("success"));
429
- 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
+ }
430
749
  }
431
750
 
432
- // src/core/executeOrder/handleSolanaExecution.ts
751
+ // src/core/execute/handleSolanaExecution.ts
433
752
  import {
434
- ChainID as ChainID3,
435
753
  getSolanaSingleChainOrderInstructions,
436
754
  getSolanaCrossChainOrderInstructions
437
755
  } from "@shogun-sdk/intents-sdk";
@@ -443,12 +761,14 @@ async function handleSolanaExecution({
443
761
  isSingleChain,
444
762
  update,
445
763
  accountAddress,
446
- deadline
764
+ orderType,
765
+ options
447
766
  }) {
448
767
  if (!wallet.rpcUrl) {
449
768
  throw new Error("Solana wallet is missing rpcUrl");
450
769
  }
451
- 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] ?? "";
452
772
  update("processing", messageFor("processing"));
453
773
  const destination = recipientAddress ?? accountAddress;
454
774
  const order = await buildOrder({
@@ -456,7 +776,9 @@ async function handleSolanaExecution({
456
776
  accountAddress,
457
777
  destination,
458
778
  deadline,
459
- isSingleChain
779
+ isSingleChain,
780
+ orderType,
781
+ options
460
782
  });
461
783
  const txData = await getSolanaOrderInstructions({
462
784
  order,
@@ -464,10 +786,9 @@ async function handleSolanaExecution({
464
786
  rpcUrl: wallet.rpcUrl
465
787
  });
466
788
  const transaction = VersionedTransaction.deserialize(Uint8Array.from(txData.txBytes));
467
- update("signing", messageFor("signing"));
468
- console.log({ order });
469
- const txSignature = await wallet.sendTransaction(transaction);
470
- update("submitting", messageFor("submitting"));
789
+ update("processing", messageFor("signing"));
790
+ await wallet.sendTransaction(transaction);
791
+ update("processing", messageFor("submitting"));
471
792
  const response = await submitToAuctioneer({
472
793
  order,
473
794
  isSingleChain,
@@ -476,13 +797,28 @@ async function handleSolanaExecution({
476
797
  if (!response.success) {
477
798
  throw new Error("Auctioneer submission failed");
478
799
  }
479
- update("success", messageFor("success"));
480
- return {
481
- status: true,
482
- txHash: txSignature,
483
- chainId: ChainID3.Solana,
484
- stage: "success"
485
- };
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
+ }
486
822
  }
487
823
  async function getSolanaOrderInstructions({
488
824
  order,
@@ -515,52 +851,93 @@ async function submitToAuctioneer({
515
851
  });
516
852
  }
517
853
 
518
- // src/core/executeOrder/execute.ts
854
+ // src/core/execute/execute.ts
519
855
  async function executeOrder({
520
856
  quote,
521
857
  accountAddress,
522
858
  recipientAddress,
523
859
  wallet,
524
860
  onStatus,
861
+ orderType = "market" /* MARKET */,
525
862
  options = {}
526
863
  }) {
527
- 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
+ };
528
868
  const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage];
529
- 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
+ };
530
873
  try {
874
+ log("Starting execution:", {
875
+ accountAddress,
876
+ recipientAddress,
877
+ tokenIn: quote?.tokenIn,
878
+ tokenOut: quote?.tokenOut
879
+ });
531
880
  const adapter = normalizeWallet(wallet);
532
881
  if (!adapter) throw new Error("No wallet provided");
533
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
+ }
534
895
  const isSingleChain = tokenIn.chainId === tokenOut.chainId;
535
896
  const chainId = Number(tokenIn.chainId);
536
- update("processing", messageFor("processing"));
537
- if (isEvmChain2(chainId)) {
538
- return await handleEvmExecution({
897
+ update("processing");
898
+ if (isEvmChain3(chainId)) {
899
+ log("Detected EVM chain:", chainId);
900
+ const result = await handleEvmExecution({
539
901
  recipientAddress,
540
902
  quote,
541
903
  chainId,
542
904
  accountAddress,
543
905
  wallet: adapter,
544
906
  isSingleChain,
545
- deadline,
546
- update
907
+ update,
908
+ orderType,
909
+ options
547
910
  });
911
+ log("EVM execution result:", result);
912
+ return result;
548
913
  }
549
- if (chainId === ChainID4.Solana) {
550
- return await handleSolanaExecution({
914
+ if (chainId === ChainID2.Solana) {
915
+ log("Detected Solana chain");
916
+ const result = await handleSolanaExecution({
551
917
  recipientAddress,
552
918
  quote,
553
919
  accountAddress,
554
920
  wallet: adapter,
555
921
  isSingleChain,
556
- deadline,
557
- update
922
+ update,
923
+ orderType,
924
+ options
558
925
  });
926
+ log("Solana execution result:", result);
927
+ return result;
559
928
  }
560
- update("error", "Unsupported chain");
561
- 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" };
562
933
  } catch (error) {
563
- 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
+ }
564
941
  update("error", message);
565
942
  return { status: false, message, stage: "error" };
566
943
  }
@@ -571,20 +948,526 @@ function normalizeWallet(wallet) {
571
948
  return wallet;
572
949
  }
573
950
 
574
- // src/core/index.ts
575
- import { ChainID as ChainID5, isEvmChain as isEvmChain3 } from "@shogun-sdk/intents-sdk";
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.");
962
+ }
963
+ const results = await Promise.all(
964
+ wallets.map((wallet) => fetchUserOrders({ wallet }))
965
+ );
966
+ return results.reduce(
967
+ (merged, orders) => {
968
+ merged.singleChainLimitOrders.push(...orders.singleChainLimitOrders);
969
+ merged.crossChainLimitOrders.push(...orders.crossChainLimitOrders);
970
+ return merged;
971
+ },
972
+ { singleChainLimitOrders: [], crossChainLimitOrders: [] }
973
+ );
974
+ }
975
+
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;
1001
+ }
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
1153
+ });
1154
+ }
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
1257
+ });
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]
1280
+ }),
1281
+ value: 0n,
1282
+ from: order.user
1283
+ });
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
+ };
576
1466
  export {
577
- ChainID5 as ChainID,
578
- NATIVE_TOKEN,
579
- SOLANA_CHAIN_ID,
1467
+ ChainId,
1468
+ OrderExecutionType,
580
1469
  SupportedChains,
1470
+ SwapSDK,
581
1471
  buildQuoteParams,
582
- executeOrder,
583
- getBalances,
584
- getQuote,
585
- getTokenList,
586
- isEvmChain3 as isEvmChain,
587
- isNativeAddress,
588
- isViemWalletClient,
589
- serializeBigIntsToStrings
1472
+ isEvmChain
590
1473
  };