@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.cjs CHANGED
@@ -20,7 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/core/index.ts
21
21
  var core_exports = {};
22
22
  __export(core_exports, {
23
- ChainID: () => import_intents_sdk10.ChainID,
23
+ ChainID: () => import_intents_sdk11.ChainID,
24
24
  NATIVE_TOKEN: () => NATIVE_TOKEN,
25
25
  SOLANA_CHAIN_ID: () => SOLANA_CHAIN_ID,
26
26
  SupportedChains: () => SupportedChains,
@@ -29,7 +29,7 @@ __export(core_exports, {
29
29
  getBalances: () => getBalances,
30
30
  getQuote: () => getQuote,
31
31
  getTokenList: () => getTokenList,
32
- isEvmChain: () => import_intents_sdk10.isEvmChain,
32
+ isEvmChain: () => import_intents_sdk11.isEvmChain,
33
33
  isNativeAddress: () => isNativeAddress,
34
34
  isViemWalletClient: () => isViemWalletClient,
35
35
  serializeBigIntsToStrings: () => serializeBigIntsToStrings
@@ -177,22 +177,26 @@ async function getQuote(params) {
177
177
  tokenOut: params.tokenOut.address,
178
178
  amount: params.amount
179
179
  });
180
- const inputSlippage = params.slippage ?? 5;
181
- const slippageDecimal = inputSlippage / 100;
182
- const slippage = Math.min(Math.max(slippageDecimal, 0), 0.5);
180
+ console.log({ data });
181
+ const slippagePercent = Math.min(Math.max(params.slippage ?? 0.5, 0), 50);
183
182
  let warning;
184
- if (slippage > 0.1) {
185
- warning = `\u26A0\uFE0F High slippage tolerance (${(slippage * 100).toFixed(2)}%) \u2014 price may vary significantly.`;
183
+ if (slippagePercent > 10) {
184
+ warning = `\u26A0\uFE0F High slippage tolerance (${slippagePercent.toFixed(2)}%) \u2014 price may vary significantly.`;
186
185
  }
187
- const estimatedAmountOut = BigInt(data.estimatedAmountOutReduced);
188
- const slippageBps = BigInt(Math.round(slippage * 1e4));
186
+ const estimatedAmountOut = BigInt(data.estimatedAmountOut);
187
+ const slippageBps = BigInt(Math.round(slippagePercent * 100));
189
188
  const estimatedAmountOutAfterSlippage = estimatedAmountOut * (10000n - slippageBps) / 10000n;
189
+ const pricePerTokenOutInUsd = data.estimatedAmountOutUsd / Number(data.estimatedAmountOut);
190
+ const amountOutUsdAfterSlippage = Number(estimatedAmountOutAfterSlippage) * pricePerTokenOutInUsd;
191
+ const minStablecoinsAmountValue = BigInt(data.estimatedAmountInAsMinStablecoinAmount);
192
+ const minStablecoinsAmountAfterSlippage = minStablecoinsAmountValue * (10000n - slippageBps) / 10000n;
190
193
  const pricePerInputToken = estimatedAmountOut * 10n ** BigInt(params.tokenIn.decimals ?? 18) / BigInt(params.amount);
191
194
  return {
192
- amountOut: estimatedAmountOut,
193
- amountOutUsd: data.estimatedAmountOutUsd,
195
+ amountOut: estimatedAmountOutAfterSlippage,
196
+ amountOutUsd: amountOutUsdAfterSlippage,
194
197
  amountInUsd: data.amountInUsd,
195
- minStablecoinsAmount: data.estimatedAmountInAsMinStablecoinAmount,
198
+ // Input USD stays the same
199
+ minStablecoinsAmount: minStablecoinsAmountAfterSlippage,
196
200
  tokenIn: {
197
201
  address: params.tokenIn.address,
198
202
  decimals: params.tokenIn.decimals ?? 18,
@@ -205,10 +209,11 @@ async function getQuote(params) {
205
209
  },
206
210
  amountIn: params.amount,
207
211
  pricePerInputToken,
208
- slippage,
212
+ slippage: slippagePercent,
209
213
  internal: {
210
214
  ...data,
211
- estimatedAmountOutReduced: estimatedAmountOutAfterSlippage
215
+ estimatedAmountOutReduced: estimatedAmountOutAfterSlippage,
216
+ estimatedAmountOutUsdReduced: amountOutUsdAfterSlippage
212
217
  },
213
218
  warning
214
219
  };
@@ -281,7 +286,7 @@ async function getBalances(params, options) {
281
286
  }
282
287
 
283
288
  // src/core/executeOrder/execute.ts
284
- var import_intents_sdk9 = require("@shogun-sdk/intents-sdk");
289
+ var import_intents_sdk10 = require("@shogun-sdk/intents-sdk");
285
290
  var import_viem4 = require("viem");
286
291
 
287
292
  // src/wallet-adapter/evm-wallet-adapter/adapter.ts
@@ -348,7 +353,7 @@ var adaptViemWallet = (wallet) => {
348
353
  };
349
354
 
350
355
  // src/core/executeOrder/handleEvmExecution.ts
351
- var import_intents_sdk7 = require("@shogun-sdk/intents-sdk");
356
+ var import_intents_sdk8 = require("@shogun-sdk/intents-sdk");
352
357
  var import_viem3 = require("viem");
353
358
 
354
359
  // src/core/executeOrder/stageMessages.ts
@@ -356,10 +361,12 @@ var DEFAULT_STAGE_MESSAGES = {
356
361
  processing: "Preparing transaction for execution",
357
362
  approving: "Approving token allowance",
358
363
  approved: "Token approved successfully",
359
- signing: "Signing order for submission",
360
- submitting: "Submitting order to Auctioneer",
361
- success: "Order executed successfully",
362
- error: "Order execution failed"
364
+ signing: "Signing transaction for submission",
365
+ submitting: "Submitting transaction",
366
+ initiated: "Transaction initiated.",
367
+ success: "Transaction Executed successfully",
368
+ shogun_processing: "Shogun is processing your transaction",
369
+ error: "Transaction failed during submission"
363
370
  };
364
371
 
365
372
  // src/core/executeOrder/buildOrder.ts
@@ -398,6 +405,95 @@ async function buildOrder({
398
405
  });
399
406
  }
400
407
 
408
+ // src/utils/pollOrderStatus.ts
409
+ var import_intents_sdk7 = require("@shogun-sdk/intents-sdk");
410
+ async function pollOrderStatus(jwt, orderId, options = {}) {
411
+ const { intervalMs = 2e3, timeoutMs = 3e5 } = options;
412
+ const startTime = Date.now();
413
+ return new Promise((resolve, reject) => {
414
+ const pollInterval = setInterval(async () => {
415
+ try {
416
+ if (Date.now() - startTime > timeoutMs) {
417
+ clearInterval(pollInterval);
418
+ return resolve("Timeout");
419
+ }
420
+ const res = await fetch(`${import_intents_sdk7.AUCTIONEER_URL}/user_intent`, {
421
+ method: "GET",
422
+ headers: {
423
+ Authorization: `Bearer ${jwt}`,
424
+ "Content-Type": "application/json"
425
+ }
426
+ });
427
+ if (!res.ok) {
428
+ clearInterval(pollInterval);
429
+ return reject(
430
+ new Error(`Failed to fetch orders: ${res.status} ${res.statusText}`)
431
+ );
432
+ }
433
+ const json = await res.json();
434
+ const data = json?.data ?? {};
435
+ const allOrders = [
436
+ ...data.crossChainDcaOrders ?? [],
437
+ ...data.crossChainLimitOrders ?? [],
438
+ ...data.singleChainDcaOrders ?? [],
439
+ ...data.singleChainLimitOrders ?? []
440
+ ];
441
+ const targetOrder = allOrders.find((o) => o.orderId === orderId);
442
+ if (!targetOrder) {
443
+ clearInterval(pollInterval);
444
+ return resolve("NotFound");
445
+ }
446
+ const { orderStatus } = targetOrder;
447
+ if (orderStatus === "Fulfilled" || orderStatus === "Cancelled" || orderStatus === "Outdated") {
448
+ clearInterval(pollInterval);
449
+ return resolve(orderStatus);
450
+ }
451
+ } catch (error) {
452
+ clearInterval(pollInterval);
453
+ return reject(error);
454
+ }
455
+ }, intervalMs);
456
+ });
457
+ }
458
+
459
+ // src/core/executeOrder/handleOrderPollingResult.ts
460
+ async function handleOrderPollingResult({
461
+ status,
462
+ orderId,
463
+ chainId,
464
+ update,
465
+ messageFor
466
+ }) {
467
+ switch (status) {
468
+ case "Fulfilled":
469
+ update("success", messageFor("success"));
470
+ return {
471
+ status: true,
472
+ orderId,
473
+ chainId,
474
+ finalStatus: status,
475
+ stage: "success"
476
+ };
477
+ case "Cancelled":
478
+ update("error", "Order was cancelled before fulfillment");
479
+ break;
480
+ case "Timeout":
481
+ update("error", "Order polling timed out");
482
+ break;
483
+ case "NotFound":
484
+ default:
485
+ update("error", "Order not found");
486
+ break;
487
+ }
488
+ return {
489
+ status: false,
490
+ orderId,
491
+ chainId,
492
+ finalStatus: status,
493
+ stage: "error"
494
+ };
495
+ }
496
+
401
497
  // src/core/executeOrder/handleEvmExecution.ts
402
498
  async function handleEvmExecution({
403
499
  recipientAddress,
@@ -426,18 +522,18 @@ async function handleEvmExecution({
426
522
  from: accountAddress
427
523
  });
428
524
  }
429
- update("approving", messageFor("approving"));
525
+ update("processing", messageFor("approving"));
430
526
  await wallet.sendTransaction({
431
527
  to: tokenIn,
432
528
  data: (0, import_viem3.encodeFunctionData)({
433
529
  abi: import_viem3.erc20Abi,
434
530
  functionName: "approve",
435
- args: [import_intents_sdk7.PERMIT2_ADDRESS[chainId], BigInt(quote.amountIn)]
531
+ args: [import_intents_sdk8.PERMIT2_ADDRESS[chainId], BigInt(quote.amountIn)]
436
532
  }),
437
533
  value: 0n,
438
534
  from: accountAddress
439
535
  });
440
- update("approved", messageFor("approved"));
536
+ update("processing", messageFor("approved"));
441
537
  const destination = recipientAddress ?? accountAddress;
442
538
  const order = await buildOrder({
443
539
  quote,
@@ -446,23 +542,32 @@ async function handleEvmExecution({
446
542
  deadline,
447
543
  isSingleChain
448
544
  });
449
- update("signing", messageFor("signing"));
450
- const { orderTypedData, nonce } = isSingleChain ? await (0, import_intents_sdk7.getEVMSingleChainOrderTypedData)(order) : await (0, import_intents_sdk7.getEVMCrossChainOrderTypedData)(order);
545
+ update("processing", messageFor("signing"));
546
+ const { orderTypedData, nonce } = isSingleChain ? await (0, import_intents_sdk8.getEVMSingleChainOrderTypedData)(order) : await (0, import_intents_sdk8.getEVMCrossChainOrderTypedData)(order);
451
547
  if (!wallet.signTypedData) {
452
548
  throw new Error("Wallet does not support EIP-712 signing");
453
549
  }
454
550
  const signature = await wallet.signTypedData(serializeBigIntsToStrings(orderTypedData));
455
- update("submitting", messageFor("submitting"));
551
+ update("processing", messageFor("submitting"));
456
552
  const res = await order.sendToAuctioneer({ signature, nonce: nonce.toString() });
457
553
  if (!res.success) {
458
554
  throw new Error("Auctioneer submission failed");
459
555
  }
460
- update("success", messageFor("success"));
461
- return { status: true, txHash: res.data, chainId, stage: "success" };
556
+ update("initiated", messageFor("initiated"));
557
+ const { jwt, intentId: orderId } = res.data;
558
+ update("initiated", messageFor("shogun_processing"));
559
+ const status = await pollOrderStatus(jwt, orderId);
560
+ return await handleOrderPollingResult({
561
+ status,
562
+ orderId,
563
+ chainId,
564
+ update,
565
+ messageFor
566
+ });
462
567
  }
463
568
 
464
569
  // src/core/executeOrder/handleSolanaExecution.ts
465
- var import_intents_sdk8 = require("@shogun-sdk/intents-sdk");
570
+ var import_intents_sdk9 = require("@shogun-sdk/intents-sdk");
466
571
  var import_web3 = require("@solana/web3.js");
467
572
  async function handleSolanaExecution({
468
573
  recipientAddress,
@@ -492,10 +597,9 @@ async function handleSolanaExecution({
492
597
  rpcUrl: wallet.rpcUrl
493
598
  });
494
599
  const transaction = import_web3.VersionedTransaction.deserialize(Uint8Array.from(txData.txBytes));
495
- update("signing", messageFor("signing"));
496
- console.log({ order });
497
- const txSignature = await wallet.sendTransaction(transaction);
498
- update("submitting", messageFor("submitting"));
600
+ update("processing", messageFor("signing"));
601
+ await wallet.sendTransaction(transaction);
602
+ update("processing", messageFor("submitting"));
499
603
  const response = await submitToAuctioneer({
500
604
  order,
501
605
  isSingleChain,
@@ -504,13 +608,17 @@ async function handleSolanaExecution({
504
608
  if (!response.success) {
505
609
  throw new Error("Auctioneer submission failed");
506
610
  }
507
- update("success", messageFor("success"));
508
- return {
509
- status: true,
510
- txHash: txSignature,
511
- chainId: import_intents_sdk8.ChainID.Solana,
512
- stage: "success"
513
- };
611
+ update("initiated", messageFor("initiated"));
612
+ const { jwt, intentId: orderId } = response.data;
613
+ update("initiated", messageFor("shogun_processing"));
614
+ const status = await pollOrderStatus(jwt, orderId);
615
+ return await handleOrderPollingResult({
616
+ status,
617
+ orderId,
618
+ chainId: SOLANA_CHAIN_ID,
619
+ update,
620
+ messageFor
621
+ });
514
622
  }
515
623
  async function getSolanaOrderInstructions({
516
624
  order,
@@ -518,11 +626,11 @@ async function getSolanaOrderInstructions({
518
626
  rpcUrl
519
627
  }) {
520
628
  if (isSingleChain) {
521
- return await (0, import_intents_sdk8.getSolanaSingleChainOrderInstructions)(order, {
629
+ return await (0, import_intents_sdk9.getSolanaSingleChainOrderInstructions)(order, {
522
630
  rpcUrl
523
631
  });
524
632
  }
525
- return await (0, import_intents_sdk8.getSolanaCrossChainOrderInstructions)(order, {
633
+ return await (0, import_intents_sdk9.getSolanaCrossChainOrderInstructions)(order, {
526
634
  rpcUrl
527
635
  });
528
636
  }
@@ -552,18 +660,33 @@ async function executeOrder({
552
660
  onStatus,
553
661
  options = {}
554
662
  }) {
555
- const deadline = options.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
663
+ const isDev = process.env.NODE_ENV !== "production";
664
+ const log = (...args) => {
665
+ if (isDev) console.log("[OneShot::executeOrder]", ...args);
666
+ };
556
667
  const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage];
557
- const update = (stage, message) => onStatus?.(stage, message ?? messageFor(stage));
668
+ const update = (stage, message) => {
669
+ log("Stage:", stage, "| Message:", message ?? messageFor(stage));
670
+ onStatus?.(stage, message ?? messageFor(stage));
671
+ };
558
672
  try {
673
+ const deadline = options.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
674
+ log("Starting execution:", {
675
+ accountAddress,
676
+ recipientAddress,
677
+ deadline,
678
+ tokenIn: quote?.tokenIn?.symbol,
679
+ tokenOut: quote?.tokenOut?.symbol
680
+ });
559
681
  const adapter = normalizeWallet(wallet);
560
682
  if (!adapter) throw new Error("No wallet provided");
561
683
  const { tokenIn, tokenOut } = quote;
562
684
  const isSingleChain = tokenIn.chainId === tokenOut.chainId;
563
685
  const chainId = Number(tokenIn.chainId);
564
- update("processing", messageFor("processing"));
565
- if ((0, import_intents_sdk9.isEvmChain)(chainId)) {
566
- return await handleEvmExecution({
686
+ update("processing");
687
+ if ((0, import_intents_sdk10.isEvmChain)(chainId)) {
688
+ log("Detected EVM chain:", chainId);
689
+ const result = await handleEvmExecution({
567
690
  recipientAddress,
568
691
  quote,
569
692
  chainId,
@@ -573,9 +696,12 @@ async function executeOrder({
573
696
  deadline,
574
697
  update
575
698
  });
699
+ log("EVM execution result:", result);
700
+ return result;
576
701
  }
577
- if (chainId === import_intents_sdk9.ChainID.Solana) {
578
- return await handleSolanaExecution({
702
+ if (chainId === import_intents_sdk10.ChainID.Solana) {
703
+ log("Detected Solana chain");
704
+ const result = await handleSolanaExecution({
579
705
  recipientAddress,
580
706
  quote,
581
707
  accountAddress,
@@ -584,11 +710,16 @@ async function executeOrder({
584
710
  deadline,
585
711
  update
586
712
  });
713
+ log("Solana execution result:", result);
714
+ return result;
587
715
  }
588
- update("error", "Unsupported chain");
589
- return { status: false, message: "Unsupported chain", stage: "error" };
716
+ const unsupported = `Unsupported chain: ${chainId}`;
717
+ update("error", unsupported);
718
+ log("Error:", unsupported);
719
+ return { status: false, message: unsupported, stage: "error" };
590
720
  } catch (error) {
591
721
  const message = error instanceof import_viem4.BaseError ? error.shortMessage : error instanceof Error ? error.message : String(error);
722
+ log("Execution failed:", { message, error });
592
723
  update("error", message);
593
724
  return { status: false, message, stage: "error" };
594
725
  }
@@ -600,7 +731,7 @@ function normalizeWallet(wallet) {
600
731
  }
601
732
 
602
733
  // src/core/index.ts
603
- var import_intents_sdk10 = require("@shogun-sdk/intents-sdk");
734
+ var import_intents_sdk11 = require("@shogun-sdk/intents-sdk");
604
735
  // Annotate the CommonJS export names for ESM import in node:
605
736
  0 && (module.exports = {
606
737
  ChainID,
package/dist/core.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { TokenSearchParams, TokenSearchResponse, ChainID } from '@shogun-sdk/intents-sdk';
2
2
  export { ChainID, isEvmChain } from '@shogun-sdk/intents-sdk';
3
- import { S as SwapQuoteParams, a as SwapQuoteResponse, Q as QuoteTokenInfo, B as BalanceRequestParams, c as BalanceResponse } from './execute-FaLLPp1i.cjs';
4
- export { P as PlaceOrderResult, b as Stage, T as TokenBalance, f as TokenInfo, d as TokenSearchResponse, e as executeOrder } from './execute-FaLLPp1i.cjs';
3
+ import { S as SwapQuoteParams, a as SwapQuoteResponse, Q as QuoteTokenInfo, B as BalanceRequestParams, c as BalanceResponse } from './execute-DOv1i2Su.cjs';
4
+ export { P as PlaceOrderResult, b as Stage, T as TokenBalance, f as TokenInfo, d as TokenSearchResponse, e as executeOrder } from './execute-DOv1i2Su.cjs';
5
5
  import { WalletClient } from 'viem';
6
6
  import { A as AdaptedWallet } from './wallet-MmUIz8GE.cjs';
7
7
  import '@mysten/sui/transactions';
package/dist/core.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { TokenSearchParams, TokenSearchResponse, ChainID } from '@shogun-sdk/intents-sdk';
2
2
  export { ChainID, isEvmChain } from '@shogun-sdk/intents-sdk';
3
- import { S as SwapQuoteParams, a as SwapQuoteResponse, Q as QuoteTokenInfo, B as BalanceRequestParams, c as BalanceResponse } from './execute-HX1fQ7wG.js';
4
- export { P as PlaceOrderResult, b as Stage, T as TokenBalance, f as TokenInfo, d as TokenSearchResponse, e as executeOrder } from './execute-HX1fQ7wG.js';
3
+ import { S as SwapQuoteParams, a as SwapQuoteResponse, Q as QuoteTokenInfo, B as BalanceRequestParams, c as BalanceResponse } from './execute-CKTsf_tD.js';
4
+ export { P as PlaceOrderResult, b as Stage, T as TokenBalance, f as TokenInfo, d as TokenSearchResponse, e as executeOrder } from './execute-CKTsf_tD.js';
5
5
  import { WalletClient } from 'viem';
6
6
  import { A as AdaptedWallet } from './wallet-MmUIz8GE.js';
7
7
  import '@mysten/sui/transactions';