@shogun-sdk/swap 0.0.2-test.1 → 0.0.2-test.11

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
@@ -139,22 +139,26 @@ async function getQuote(params) {
139
139
  tokenOut: params.tokenOut.address,
140
140
  amount: params.amount
141
141
  });
142
- const inputSlippage = params.slippage ?? 5;
143
- const slippageDecimal = inputSlippage / 100;
144
- const slippage = Math.min(Math.max(slippageDecimal, 0), 0.5);
142
+ console.log({ data });
143
+ const slippagePercent = Math.min(Math.max(params.slippage ?? 0.5, 0), 50);
145
144
  let warning;
146
- if (slippage > 0.1) {
147
- warning = `\u26A0\uFE0F High slippage tolerance (${(slippage * 100).toFixed(2)}%) \u2014 price may vary significantly.`;
145
+ if (slippagePercent > 10) {
146
+ warning = `\u26A0\uFE0F High slippage tolerance (${slippagePercent.toFixed(2)}%) \u2014 price may vary significantly.`;
148
147
  }
149
- const estimatedAmountOut = BigInt(data.estimatedAmountOutReduced);
150
- const slippageBps = BigInt(Math.round(slippage * 1e4));
148
+ const estimatedAmountOut = BigInt(data.estimatedAmountOut);
149
+ const slippageBps = BigInt(Math.round(slippagePercent * 100));
151
150
  const estimatedAmountOutAfterSlippage = estimatedAmountOut * (10000n - slippageBps) / 10000n;
151
+ const pricePerTokenOutInUsd = data.estimatedAmountOutUsd / Number(data.estimatedAmountOut);
152
+ const amountOutUsdAfterSlippage = Number(estimatedAmountOutAfterSlippage) * pricePerTokenOutInUsd;
153
+ const minStablecoinsAmountValue = BigInt(data.estimatedAmountInAsMinStablecoinAmount);
154
+ const minStablecoinsAmountAfterSlippage = minStablecoinsAmountValue * (10000n - slippageBps) / 10000n;
152
155
  const pricePerInputToken = estimatedAmountOut * 10n ** BigInt(params.tokenIn.decimals ?? 18) / BigInt(params.amount);
153
156
  return {
154
- amountOut: estimatedAmountOut,
155
- amountOutUsd: data.estimatedAmountOutUsd,
157
+ amountOut: estimatedAmountOutAfterSlippage,
158
+ amountOutUsd: amountOutUsdAfterSlippage,
156
159
  amountInUsd: data.amountInUsd,
157
- minStablecoinsAmount: data.estimatedAmountInAsMinStablecoinAmount,
160
+ // Input USD stays the same
161
+ minStablecoinsAmount: minStablecoinsAmountAfterSlippage,
158
162
  tokenIn: {
159
163
  address: params.tokenIn.address,
160
164
  decimals: params.tokenIn.decimals ?? 18,
@@ -167,10 +171,11 @@ async function getQuote(params) {
167
171
  },
168
172
  amountIn: params.amount,
169
173
  pricePerInputToken,
170
- slippage,
174
+ slippage: slippagePercent,
171
175
  internal: {
172
176
  ...data,
173
- estimatedAmountOutReduced: estimatedAmountOutAfterSlippage
177
+ estimatedAmountOutReduced: estimatedAmountOutAfterSlippage,
178
+ estimatedAmountOutUsdReduced: amountOutUsdAfterSlippage
174
179
  },
175
180
  warning
176
181
  };
@@ -243,7 +248,7 @@ async function getBalances(params, options) {
243
248
  }
244
249
 
245
250
  // src/core/executeOrder/execute.ts
246
- import { ChainID as ChainID4, isEvmChain as isEvmChain2 } from "@shogun-sdk/intents-sdk";
251
+ import { ChainID as ChainID3, isEvmChain as isEvmChain2 } from "@shogun-sdk/intents-sdk";
247
252
  import { BaseError } from "viem";
248
253
 
249
254
  // src/wallet-adapter/evm-wallet-adapter/adapter.ts
@@ -324,10 +329,12 @@ var DEFAULT_STAGE_MESSAGES = {
324
329
  processing: "Preparing transaction for execution",
325
330
  approving: "Approving token allowance",
326
331
  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"
332
+ signing: "Signing transaction for submission",
333
+ submitting: "Submitting transaction",
334
+ initiated: "Transaction initiated.",
335
+ success: "Transaction Executed successfully",
336
+ shogun_processing: "Shogun is processing your transaction",
337
+ error: "Transaction failed during submission"
331
338
  };
332
339
 
333
340
  // src/core/executeOrder/buildOrder.ts
@@ -366,6 +373,95 @@ async function buildOrder({
366
373
  });
367
374
  }
368
375
 
376
+ // src/utils/pollOrderStatus.ts
377
+ import { AUCTIONEER_URL } from "@shogun-sdk/intents-sdk";
378
+ async function pollOrderStatus(jwt, orderId, options = {}) {
379
+ const { intervalMs = 2e3, timeoutMs = 3e5 } = options;
380
+ const startTime = Date.now();
381
+ return new Promise((resolve, reject) => {
382
+ const pollInterval = setInterval(async () => {
383
+ try {
384
+ if (Date.now() - startTime > timeoutMs) {
385
+ clearInterval(pollInterval);
386
+ return resolve("Timeout");
387
+ }
388
+ const res = await fetch(`${AUCTIONEER_URL}/user_intent`, {
389
+ method: "GET",
390
+ headers: {
391
+ Authorization: `Bearer ${jwt}`,
392
+ "Content-Type": "application/json"
393
+ }
394
+ });
395
+ if (!res.ok) {
396
+ clearInterval(pollInterval);
397
+ return reject(
398
+ new Error(`Failed to fetch orders: ${res.status} ${res.statusText}`)
399
+ );
400
+ }
401
+ const json = await res.json();
402
+ const data = json?.data ?? {};
403
+ const allOrders = [
404
+ ...data.crossChainDcaOrders ?? [],
405
+ ...data.crossChainLimitOrders ?? [],
406
+ ...data.singleChainDcaOrders ?? [],
407
+ ...data.singleChainLimitOrders ?? []
408
+ ];
409
+ const targetOrder = allOrders.find((o) => o.orderId === orderId);
410
+ if (!targetOrder) {
411
+ clearInterval(pollInterval);
412
+ return resolve("NotFound");
413
+ }
414
+ const { orderStatus } = targetOrder;
415
+ if (orderStatus === "Fulfilled" || orderStatus === "Cancelled" || orderStatus === "Outdated") {
416
+ clearInterval(pollInterval);
417
+ return resolve(orderStatus);
418
+ }
419
+ } catch (error) {
420
+ clearInterval(pollInterval);
421
+ return reject(error);
422
+ }
423
+ }, intervalMs);
424
+ });
425
+ }
426
+
427
+ // src/core/executeOrder/handleOrderPollingResult.ts
428
+ async function handleOrderPollingResult({
429
+ status,
430
+ orderId,
431
+ chainId,
432
+ update,
433
+ messageFor
434
+ }) {
435
+ switch (status) {
436
+ case "Fulfilled":
437
+ update("success", messageFor("success"));
438
+ return {
439
+ status: true,
440
+ orderId,
441
+ chainId,
442
+ finalStatus: status,
443
+ stage: "success"
444
+ };
445
+ case "Cancelled":
446
+ update("error", "Order was cancelled before fulfillment");
447
+ break;
448
+ case "Timeout":
449
+ update("error", "Order polling timed out");
450
+ break;
451
+ case "NotFound":
452
+ default:
453
+ update("error", "Order not found");
454
+ break;
455
+ }
456
+ return {
457
+ status: false,
458
+ orderId,
459
+ chainId,
460
+ finalStatus: status,
461
+ stage: "error"
462
+ };
463
+ }
464
+
369
465
  // src/core/executeOrder/handleEvmExecution.ts
370
466
  async function handleEvmExecution({
371
467
  recipientAddress,
@@ -394,7 +490,7 @@ async function handleEvmExecution({
394
490
  from: accountAddress
395
491
  });
396
492
  }
397
- update("approving", messageFor("approving"));
493
+ update("processing", messageFor("approving"));
398
494
  await wallet.sendTransaction({
399
495
  to: tokenIn,
400
496
  data: encodeFunctionData({
@@ -405,7 +501,7 @@ async function handleEvmExecution({
405
501
  value: 0n,
406
502
  from: accountAddress
407
503
  });
408
- update("approved", messageFor("approved"));
504
+ update("processing", messageFor("approved"));
409
505
  const destination = recipientAddress ?? accountAddress;
410
506
  const order = await buildOrder({
411
507
  quote,
@@ -414,24 +510,32 @@ async function handleEvmExecution({
414
510
  deadline,
415
511
  isSingleChain
416
512
  });
417
- update("signing", messageFor("signing"));
513
+ update("processing", messageFor("signing"));
418
514
  const { orderTypedData, nonce } = isSingleChain ? await getEVMSingleChainOrderTypedData(order) : await getEVMCrossChainOrderTypedData(order);
419
515
  if (!wallet.signTypedData) {
420
516
  throw new Error("Wallet does not support EIP-712 signing");
421
517
  }
422
518
  const signature = await wallet.signTypedData(serializeBigIntsToStrings(orderTypedData));
423
- update("submitting", messageFor("submitting"));
519
+ update("processing", messageFor("submitting"));
424
520
  const res = await order.sendToAuctioneer({ signature, nonce: nonce.toString() });
425
521
  if (!res.success) {
426
522
  throw new Error("Auctioneer submission failed");
427
523
  }
428
- update("success", messageFor("success"));
429
- return { status: true, txHash: res.data, chainId, stage: "success" };
524
+ update("initiated", messageFor("initiated"));
525
+ const { jwt, intentId: orderId } = res.data;
526
+ update("initiated", messageFor("shogun_processing"));
527
+ const status = await pollOrderStatus(jwt, orderId);
528
+ return await handleOrderPollingResult({
529
+ status,
530
+ orderId,
531
+ chainId,
532
+ update,
533
+ messageFor
534
+ });
430
535
  }
431
536
 
432
537
  // src/core/executeOrder/handleSolanaExecution.ts
433
538
  import {
434
- ChainID as ChainID3,
435
539
  getSolanaSingleChainOrderInstructions,
436
540
  getSolanaCrossChainOrderInstructions
437
541
  } from "@shogun-sdk/intents-sdk";
@@ -464,10 +568,9 @@ async function handleSolanaExecution({
464
568
  rpcUrl: wallet.rpcUrl
465
569
  });
466
570
  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"));
571
+ update("processing", messageFor("signing"));
572
+ await wallet.sendTransaction(transaction);
573
+ update("processing", messageFor("submitting"));
471
574
  const response = await submitToAuctioneer({
472
575
  order,
473
576
  isSingleChain,
@@ -476,13 +579,17 @@ async function handleSolanaExecution({
476
579
  if (!response.success) {
477
580
  throw new Error("Auctioneer submission failed");
478
581
  }
479
- update("success", messageFor("success"));
480
- return {
481
- status: true,
482
- txHash: txSignature,
483
- chainId: ChainID3.Solana,
484
- stage: "success"
485
- };
582
+ update("initiated", messageFor("initiated"));
583
+ const { jwt, intentId: orderId } = response.data;
584
+ update("initiated", messageFor("shogun_processing"));
585
+ const status = await pollOrderStatus(jwt, orderId);
586
+ return await handleOrderPollingResult({
587
+ status,
588
+ orderId,
589
+ chainId: SOLANA_CHAIN_ID,
590
+ update,
591
+ messageFor
592
+ });
486
593
  }
487
594
  async function getSolanaOrderInstructions({
488
595
  order,
@@ -524,18 +631,33 @@ async function executeOrder({
524
631
  onStatus,
525
632
  options = {}
526
633
  }) {
527
- const deadline = options.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
634
+ const isDev = process.env.NODE_ENV !== "production";
635
+ const log = (...args) => {
636
+ if (isDev) console.log("[OneShot::executeOrder]", ...args);
637
+ };
528
638
  const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage];
529
- const update = (stage, message) => onStatus?.(stage, message ?? messageFor(stage));
639
+ const update = (stage, message) => {
640
+ log("Stage:", stage, "| Message:", message ?? messageFor(stage));
641
+ onStatus?.(stage, message ?? messageFor(stage));
642
+ };
530
643
  try {
644
+ const deadline = options.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
645
+ log("Starting execution:", {
646
+ accountAddress,
647
+ recipientAddress,
648
+ deadline,
649
+ tokenIn: quote?.tokenIn?.symbol,
650
+ tokenOut: quote?.tokenOut?.symbol
651
+ });
531
652
  const adapter = normalizeWallet(wallet);
532
653
  if (!adapter) throw new Error("No wallet provided");
533
654
  const { tokenIn, tokenOut } = quote;
534
655
  const isSingleChain = tokenIn.chainId === tokenOut.chainId;
535
656
  const chainId = Number(tokenIn.chainId);
536
- update("processing", messageFor("processing"));
657
+ update("processing");
537
658
  if (isEvmChain2(chainId)) {
538
- return await handleEvmExecution({
659
+ log("Detected EVM chain:", chainId);
660
+ const result = await handleEvmExecution({
539
661
  recipientAddress,
540
662
  quote,
541
663
  chainId,
@@ -545,9 +667,12 @@ async function executeOrder({
545
667
  deadline,
546
668
  update
547
669
  });
670
+ log("EVM execution result:", result);
671
+ return result;
548
672
  }
549
- if (chainId === ChainID4.Solana) {
550
- return await handleSolanaExecution({
673
+ if (chainId === ChainID3.Solana) {
674
+ log("Detected Solana chain");
675
+ const result = await handleSolanaExecution({
551
676
  recipientAddress,
552
677
  quote,
553
678
  accountAddress,
@@ -556,11 +681,16 @@ async function executeOrder({
556
681
  deadline,
557
682
  update
558
683
  });
684
+ log("Solana execution result:", result);
685
+ return result;
559
686
  }
560
- update("error", "Unsupported chain");
561
- return { status: false, message: "Unsupported chain", stage: "error" };
687
+ const unsupported = `Unsupported chain: ${chainId}`;
688
+ update("error", unsupported);
689
+ log("Error:", unsupported);
690
+ return { status: false, message: unsupported, stage: "error" };
562
691
  } catch (error) {
563
692
  const message = error instanceof BaseError ? error.shortMessage : error instanceof Error ? error.message : String(error);
693
+ log("Execution failed:", { message, error });
564
694
  update("error", message);
565
695
  return { status: false, message, stage: "error" };
566
696
  }
@@ -572,9 +702,9 @@ function normalizeWallet(wallet) {
572
702
  }
573
703
 
574
704
  // src/core/index.ts
575
- import { ChainID as ChainID5, isEvmChain as isEvmChain3 } from "@shogun-sdk/intents-sdk";
705
+ import { ChainID as ChainID4, isEvmChain as isEvmChain3 } from "@shogun-sdk/intents-sdk";
576
706
  export {
577
- ChainID5 as ChainID,
707
+ ChainID4 as ChainID,
578
708
  NATIVE_TOKEN,
579
709
  SOLANA_CHAIN_ID,
580
710
  SupportedChains,
@@ -1,4 +1,4 @@
1
- import { ChainID, QuoteResponse, TokenSearchResponse as TokenSearchResponse$1, TokenInfo as TokenInfo$1 } from '@shogun-sdk/intents-sdk';
1
+ import { ChainID, QuoteResponse, TokenSearchResponse as TokenSearchResponse$1, TokenInfo as TokenInfo$1, ChainOrderStatus } from '@shogun-sdk/intents-sdk';
2
2
  import { WalletClient } from 'viem';
3
3
  import { A as AdaptedWallet } from './wallet-MmUIz8GE.js';
4
4
 
@@ -65,7 +65,7 @@ type SwapQuoteResponse = {
65
65
  warning?: string;
66
66
  };
67
67
 
68
- type Stage = 'processing' | 'approving' | 'approved' | 'signing' | 'submitting' | 'success' | 'error';
68
+ type Stage = 'processing' | 'approving' | 'approved' | 'signing' | 'submitting' | 'initiated' | 'shogun_processing' | 'success' | 'error';
69
69
  type PlaceOrderResult = {
70
70
  status: boolean;
71
71
  txHash?: string;
@@ -109,19 +109,17 @@ interface BalanceResponse {
109
109
  type TokenSearchResponse = TokenSearchResponse$1;
110
110
  type TokenInfo = TokenInfo$1;
111
111
 
112
+ /**
113
+ * Types representing the structure of user orders and polling results.
114
+ */
115
+
116
+ type OrderStatus = ChainOrderStatus | "Timeout" | "NotFound";
117
+ type PollResult = OrderStatus;
118
+
112
119
  /**
113
120
  * Executes a swap order on the correct chain (EVM or Solana).
114
121
  *
115
- * @param quote - The quote object returned from the quote API.
116
- * @param accountAddress - The wallet address initiating the swap.
117
- * @param recipientAddress - recipient for output tokens.
118
- * @param wallet - Adapted wallet (EVM or Solana).
119
- * @param onStatus - Optional callback for UI updates.
120
- * @param options - Optional execution settings.
121
- * - deadline: UNIX timestamp (seconds)
122
- * Default = now + 20 minutes
123
- *
124
- * @returns Execution result { status, message, stage }
122
+ * Provides detailed logs for debugging when NODE_ENV !== 'production'.
125
123
  */
126
124
  declare function executeOrder({ quote, accountAddress, recipientAddress, wallet, onStatus, options, }: {
127
125
  quote: SwapQuoteResponse;
@@ -130,18 +128,18 @@ declare function executeOrder({ quote, accountAddress, recipientAddress, wallet,
130
128
  wallet: AdaptedWallet | WalletClient;
131
129
  onStatus?: (stage: Stage, message?: string) => void;
132
130
  options?: {
133
- /** Optional swap deadline (UNIX seconds). Default: now + 20 minutes */
134
131
  deadline?: number;
135
132
  };
136
133
  }): Promise<{
137
134
  status: boolean;
138
- txHash: string;
135
+ orderId: string;
139
136
  chainId: number;
140
- stage: string;
137
+ finalStatus: PollResult;
138
+ stage: Stage;
141
139
  } | {
142
140
  status: boolean;
143
141
  message: string;
144
142
  stage: string;
145
143
  }>;
146
144
 
147
- export { type BalanceRequestParams as B, type PlaceOrderResult as P, type QuoteTokenInfo as Q, type SwapQuoteParams as S, type TokenBalance as T, type SwapQuoteResponse as a, type Stage as b, type BalanceResponse as c, type TokenSearchResponse as d, executeOrder as e, type TokenInfo as f };
145
+ export { type BalanceRequestParams as B, type PlaceOrderResult as P, type QuoteTokenInfo as Q, type SwapQuoteParams as S, type TokenBalance as T, type SwapQuoteResponse as a, type Stage as b, type BalanceResponse as c, type TokenSearchResponse as d, executeOrder as e, type TokenInfo as f, type PollResult as g };
@@ -1,4 +1,4 @@
1
- import { ChainID, QuoteResponse, TokenSearchResponse as TokenSearchResponse$1, TokenInfo as TokenInfo$1 } from '@shogun-sdk/intents-sdk';
1
+ import { ChainID, QuoteResponse, TokenSearchResponse as TokenSearchResponse$1, TokenInfo as TokenInfo$1, ChainOrderStatus } from '@shogun-sdk/intents-sdk';
2
2
  import { WalletClient } from 'viem';
3
3
  import { A as AdaptedWallet } from './wallet-MmUIz8GE.cjs';
4
4
 
@@ -65,7 +65,7 @@ type SwapQuoteResponse = {
65
65
  warning?: string;
66
66
  };
67
67
 
68
- type Stage = 'processing' | 'approving' | 'approved' | 'signing' | 'submitting' | 'success' | 'error';
68
+ type Stage = 'processing' | 'approving' | 'approved' | 'signing' | 'submitting' | 'initiated' | 'shogun_processing' | 'success' | 'error';
69
69
  type PlaceOrderResult = {
70
70
  status: boolean;
71
71
  txHash?: string;
@@ -109,19 +109,17 @@ interface BalanceResponse {
109
109
  type TokenSearchResponse = TokenSearchResponse$1;
110
110
  type TokenInfo = TokenInfo$1;
111
111
 
112
+ /**
113
+ * Types representing the structure of user orders and polling results.
114
+ */
115
+
116
+ type OrderStatus = ChainOrderStatus | "Timeout" | "NotFound";
117
+ type PollResult = OrderStatus;
118
+
112
119
  /**
113
120
  * Executes a swap order on the correct chain (EVM or Solana).
114
121
  *
115
- * @param quote - The quote object returned from the quote API.
116
- * @param accountAddress - The wallet address initiating the swap.
117
- * @param recipientAddress - recipient for output tokens.
118
- * @param wallet - Adapted wallet (EVM or Solana).
119
- * @param onStatus - Optional callback for UI updates.
120
- * @param options - Optional execution settings.
121
- * - deadline: UNIX timestamp (seconds)
122
- * Default = now + 20 minutes
123
- *
124
- * @returns Execution result { status, message, stage }
122
+ * Provides detailed logs for debugging when NODE_ENV !== 'production'.
125
123
  */
126
124
  declare function executeOrder({ quote, accountAddress, recipientAddress, wallet, onStatus, options, }: {
127
125
  quote: SwapQuoteResponse;
@@ -130,18 +128,18 @@ declare function executeOrder({ quote, accountAddress, recipientAddress, wallet,
130
128
  wallet: AdaptedWallet | WalletClient;
131
129
  onStatus?: (stage: Stage, message?: string) => void;
132
130
  options?: {
133
- /** Optional swap deadline (UNIX seconds). Default: now + 20 minutes */
134
131
  deadline?: number;
135
132
  };
136
133
  }): Promise<{
137
134
  status: boolean;
138
- txHash: string;
135
+ orderId: string;
139
136
  chainId: number;
140
- stage: string;
137
+ finalStatus: PollResult;
138
+ stage: Stage;
141
139
  } | {
142
140
  status: boolean;
143
141
  message: string;
144
142
  stage: string;
145
143
  }>;
146
144
 
147
- export { type BalanceRequestParams as B, type PlaceOrderResult as P, type QuoteTokenInfo as Q, type SwapQuoteParams as S, type TokenBalance as T, type SwapQuoteResponse as a, type Stage as b, type BalanceResponse as c, type TokenSearchResponse as d, executeOrder as e, type TokenInfo as f };
145
+ export { type BalanceRequestParams as B, type PlaceOrderResult as P, type QuoteTokenInfo as Q, type SwapQuoteParams as S, type TokenBalance as T, type SwapQuoteResponse as a, type Stage as b, type BalanceResponse as c, type TokenSearchResponse as d, executeOrder as e, type TokenInfo as f, type PollResult as g };