@shogun-sdk/swap 0.0.2-test.2 → 0.0.2-test.21

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,25 @@ 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
+ const slippagePercent = Math.min(Math.max(params.slippage ?? 0.5, 0), 50);
183
181
  let warning;
184
- if (slippage > 0.1) {
185
- warning = `\u26A0\uFE0F High slippage tolerance (${(slippage * 100).toFixed(2)}%) \u2014 price may vary significantly.`;
182
+ if (slippagePercent > 10) {
183
+ warning = `\u26A0\uFE0F High slippage tolerance (${slippagePercent.toFixed(2)}%) \u2014 price may vary significantly.`;
186
184
  }
187
- const estimatedAmountOut = BigInt(data.estimatedAmountOutReduced);
188
- const slippageBps = BigInt(Math.round(slippage * 1e4));
185
+ const estimatedAmountOut = BigInt(data.estimatedAmountOut);
186
+ const slippageBps = BigInt(Math.round(slippagePercent * 100));
189
187
  const estimatedAmountOutAfterSlippage = estimatedAmountOut * (10000n - slippageBps) / 10000n;
188
+ const pricePerTokenOutInUsd = data.estimatedAmountOutUsd / Number(data.estimatedAmountOut);
189
+ const amountOutUsdAfterSlippage = Number(estimatedAmountOutAfterSlippage) * pricePerTokenOutInUsd;
190
+ const minStablecoinsAmountValue = BigInt(data.estimatedAmountInAsMinStablecoinAmount);
191
+ const minStablecoinsAmountAfterSlippage = minStablecoinsAmountValue * (10000n - slippageBps) / 10000n;
190
192
  const pricePerInputToken = estimatedAmountOut * 10n ** BigInt(params.tokenIn.decimals ?? 18) / BigInt(params.amount);
191
193
  return {
192
- amountOut: estimatedAmountOut,
193
- amountOutUsd: data.estimatedAmountOutUsd,
194
+ amountOut: estimatedAmountOutAfterSlippage,
195
+ amountOutUsd: amountOutUsdAfterSlippage,
194
196
  amountInUsd: data.amountInUsd,
195
- minStablecoinsAmount: data.estimatedAmountInAsMinStablecoinAmount,
197
+ // Input USD stays the same
198
+ minStablecoinsAmount: minStablecoinsAmountAfterSlippage,
196
199
  tokenIn: {
197
200
  address: params.tokenIn.address,
198
201
  decimals: params.tokenIn.decimals ?? 18,
@@ -205,10 +208,11 @@ async function getQuote(params) {
205
208
  },
206
209
  amountIn: params.amount,
207
210
  pricePerInputToken,
208
- slippage,
211
+ slippage: slippagePercent,
209
212
  internal: {
210
213
  ...data,
211
- estimatedAmountOutReduced: estimatedAmountOutAfterSlippage
214
+ estimatedAmountOutReduced: estimatedAmountOutAfterSlippage,
215
+ estimatedAmountOutUsdReduced: amountOutUsdAfterSlippage
212
216
  },
213
217
  warning
214
218
  };
@@ -281,7 +285,7 @@ async function getBalances(params, options) {
281
285
  }
282
286
 
283
287
  // src/core/executeOrder/execute.ts
284
- var import_intents_sdk9 = require("@shogun-sdk/intents-sdk");
288
+ var import_intents_sdk10 = require("@shogun-sdk/intents-sdk");
285
289
  var import_viem4 = require("viem");
286
290
 
287
291
  // src/wallet-adapter/evm-wallet-adapter/adapter.ts
@@ -305,15 +309,26 @@ var adaptViemWallet = (wallet) => {
305
309
  if (!isEVMTransaction(transaction)) {
306
310
  throw new Error("Expected EVMTransaction but got SolanaTransaction");
307
311
  }
308
- const tx = await wallet.sendTransaction({
309
- from: transaction.from,
310
- to: transaction.to,
311
- data: transaction.data,
312
- value: transaction.value,
313
- account: wallet.account?.address,
314
- chain: wallet.chain
315
- });
316
- return tx;
312
+ if (wallet.transport.type === "http") {
313
+ const request = await wallet.prepareTransactionRequest({
314
+ to: transaction.to,
315
+ data: transaction.data,
316
+ value: transaction.value,
317
+ chain: wallet.chain
318
+ });
319
+ const serializedTransaction = await wallet.signTransaction(request);
320
+ const tx = await wallet.sendRawTransaction({ serializedTransaction });
321
+ return tx;
322
+ } else {
323
+ const hash = await wallet.sendTransaction({
324
+ to: transaction.to,
325
+ data: transaction.data,
326
+ value: transaction.value,
327
+ chain: wallet.chain,
328
+ account: wallet.account
329
+ });
330
+ return hash;
331
+ }
317
332
  };
318
333
  const switchChain = async (chainId) => {
319
334
  try {
@@ -348,7 +363,7 @@ var adaptViemWallet = (wallet) => {
348
363
  };
349
364
 
350
365
  // src/core/executeOrder/handleEvmExecution.ts
351
- var import_intents_sdk7 = require("@shogun-sdk/intents-sdk");
366
+ var import_intents_sdk8 = require("@shogun-sdk/intents-sdk");
352
367
  var import_viem3 = require("viem");
353
368
 
354
369
  // src/core/executeOrder/stageMessages.ts
@@ -356,10 +371,12 @@ var DEFAULT_STAGE_MESSAGES = {
356
371
  processing: "Preparing transaction for execution",
357
372
  approving: "Approving token allowance",
358
373
  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"
374
+ signing: "Signing transaction for submission",
375
+ submitting: "Submitting transaction",
376
+ initiated: "Transaction initiated.",
377
+ success: "Transaction Executed successfully",
378
+ shogun_processing: "Shogun is processing your transaction",
379
+ error: "Transaction failed during submission"
363
380
  };
364
381
 
365
382
  // src/core/executeOrder/buildOrder.ts
@@ -398,6 +415,110 @@ async function buildOrder({
398
415
  });
399
416
  }
400
417
 
418
+ // src/utils/pollOrderStatus.ts
419
+ var import_intents_sdk7 = require("@shogun-sdk/intents-sdk");
420
+ async function pollOrderStatus(address, orderId, options = {}) {
421
+ const { intervalMs = 2e3, timeoutMs = 3e5 } = options;
422
+ const startTime = Date.now();
423
+ const isDebug = process.env.NODE_ENV !== "production";
424
+ const isEvmAddress = /^0x[a-fA-F0-9]{40}$/.test(address);
425
+ const isSuiAddress = /^0x[a-fA-F0-9]{64}$/.test(address);
426
+ const isSolanaAddress = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address);
427
+ let queryParam;
428
+ if (isEvmAddress) queryParam = `evmWallets=${address}`;
429
+ else if (isSuiAddress) queryParam = `suiWallets=${address}`;
430
+ else if (isSolanaAddress) queryParam = `solanaWallets=${address}`;
431
+ else throw new Error(`Unrecognized wallet address format: ${address}`);
432
+ const queryUrl = `${import_intents_sdk7.AUCTIONEER_URL}/user_intent?${queryParam}`;
433
+ return new Promise((resolve, reject) => {
434
+ const pollInterval = setInterval(async () => {
435
+ try {
436
+ if (Date.now() - startTime > timeoutMs) {
437
+ clearInterval(pollInterval);
438
+ return resolve("Timeout");
439
+ }
440
+ const res = await fetch(queryUrl, {
441
+ method: "GET",
442
+ headers: { "Content-Type": "application/json" }
443
+ });
444
+ if (!res.ok) {
445
+ clearInterval(pollInterval);
446
+ return reject(
447
+ new Error(`Failed to fetch orders: ${res.status} ${res.statusText}`)
448
+ );
449
+ }
450
+ const json = await res.json();
451
+ const data = json?.data ?? {};
452
+ const allOrders = [
453
+ ...data.crossChainDcaOrders ?? [],
454
+ ...data.crossChainLimitOrders ?? [],
455
+ ...data.singleChainDcaOrders ?? [],
456
+ ...data.singleChainLimitOrders ?? []
457
+ ];
458
+ const targetOrder = allOrders.find((o) => o.orderId === orderId);
459
+ if (!targetOrder) {
460
+ if (isDebug)
461
+ console.debug(`[pollOrderStatus] [${orderId}] Not found yet`);
462
+ return;
463
+ }
464
+ const { orderStatus } = targetOrder;
465
+ if (isDebug) {
466
+ const elapsed = ((Date.now() - startTime) / 1e3).toFixed(1);
467
+ console.debug(`targetOrder`, targetOrder);
468
+ console.debug(
469
+ `[pollOrderStatus] [${orderId}] status=${orderStatus} (elapsed ${elapsed}s)`
470
+ );
471
+ }
472
+ if (["Fulfilled", "Cancelled", "Outdated"].includes(orderStatus)) {
473
+ clearInterval(pollInterval);
474
+ return resolve(orderStatus);
475
+ }
476
+ } catch (error) {
477
+ clearInterval(pollInterval);
478
+ return reject(error);
479
+ }
480
+ }, intervalMs);
481
+ });
482
+ }
483
+
484
+ // src/core/executeOrder/handleOrderPollingResult.ts
485
+ async function handleOrderPollingResult({
486
+ status,
487
+ orderId,
488
+ chainId,
489
+ update,
490
+ messageFor
491
+ }) {
492
+ switch (status) {
493
+ case "Fulfilled":
494
+ update("success", messageFor("success"));
495
+ return {
496
+ status: true,
497
+ orderId,
498
+ chainId,
499
+ finalStatus: status,
500
+ stage: "success"
501
+ };
502
+ case "Cancelled":
503
+ update("error", "Order was cancelled before fulfillment");
504
+ break;
505
+ case "Timeout":
506
+ update("error", "Order polling timed out");
507
+ break;
508
+ case "NotFound":
509
+ default:
510
+ update("error", "Order not found");
511
+ break;
512
+ }
513
+ return {
514
+ status: false,
515
+ orderId,
516
+ chainId,
517
+ finalStatus: status,
518
+ stage: "error"
519
+ };
520
+ }
521
+
401
522
  // src/core/executeOrder/handleEvmExecution.ts
402
523
  async function handleEvmExecution({
403
524
  recipientAddress,
@@ -426,18 +547,18 @@ async function handleEvmExecution({
426
547
  from: accountAddress
427
548
  });
428
549
  }
429
- update("approving", messageFor("approving"));
550
+ update("processing", messageFor("approving"));
430
551
  await wallet.sendTransaction({
431
552
  to: tokenIn,
432
553
  data: (0, import_viem3.encodeFunctionData)({
433
554
  abi: import_viem3.erc20Abi,
434
555
  functionName: "approve",
435
- args: [import_intents_sdk7.PERMIT2_ADDRESS[chainId], BigInt(quote.amountIn)]
556
+ args: [import_intents_sdk8.PERMIT2_ADDRESS[chainId], quote.amountIn]
436
557
  }),
437
558
  value: 0n,
438
559
  from: accountAddress
439
560
  });
440
- update("approved", messageFor("approved"));
561
+ update("processing", messageFor("approved"));
441
562
  const destination = recipientAddress ?? accountAddress;
442
563
  const order = await buildOrder({
443
564
  quote,
@@ -446,23 +567,40 @@ async function handleEvmExecution({
446
567
  deadline,
447
568
  isSingleChain
448
569
  });
449
- update("signing", messageFor("signing"));
450
- const { orderTypedData, nonce } = isSingleChain ? await (0, import_intents_sdk7.getEVMSingleChainOrderTypedData)(order) : await (0, import_intents_sdk7.getEVMCrossChainOrderTypedData)(order);
570
+ console.debug(`order`, order);
571
+ update("processing", messageFor("signing"));
572
+ const { orderTypedData, nonce } = isSingleChain ? await (0, import_intents_sdk8.getEVMSingleChainOrderTypedData)(order) : await (0, import_intents_sdk8.getEVMCrossChainOrderTypedData)(order);
573
+ const typedData = serializeBigIntsToStrings(orderTypedData);
451
574
  if (!wallet.signTypedData) {
452
575
  throw new Error("Wallet does not support EIP-712 signing");
453
576
  }
454
- const signature = await wallet.signTypedData(serializeBigIntsToStrings(orderTypedData));
455
- update("submitting", messageFor("submitting"));
577
+ const signature = await wallet.signTypedData({
578
+ domain: typedData.domain,
579
+ types: typedData.types,
580
+ primaryType: typedData.primaryType,
581
+ value: typedData.message,
582
+ message: typedData.message
583
+ });
584
+ update("processing", messageFor("submitting"));
456
585
  const res = await order.sendToAuctioneer({ signature, nonce: nonce.toString() });
457
586
  if (!res.success) {
458
587
  throw new Error("Auctioneer submission failed");
459
588
  }
460
- update("success", messageFor("success"));
461
- return { status: true, txHash: res.data, chainId, stage: "success" };
589
+ update("initiated", messageFor("initiated"));
590
+ const { intentId: orderId } = res.data;
591
+ update("initiated", messageFor("shogun_processing"));
592
+ const status = await pollOrderStatus(accountAddress, orderId);
593
+ return await handleOrderPollingResult({
594
+ status,
595
+ orderId,
596
+ chainId,
597
+ update,
598
+ messageFor
599
+ });
462
600
  }
463
601
 
464
602
  // src/core/executeOrder/handleSolanaExecution.ts
465
- var import_intents_sdk8 = require("@shogun-sdk/intents-sdk");
603
+ var import_intents_sdk9 = require("@shogun-sdk/intents-sdk");
466
604
  var import_web3 = require("@solana/web3.js");
467
605
  async function handleSolanaExecution({
468
606
  recipientAddress,
@@ -492,10 +630,9 @@ async function handleSolanaExecution({
492
630
  rpcUrl: wallet.rpcUrl
493
631
  });
494
632
  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"));
633
+ update("processing", messageFor("signing"));
634
+ await wallet.sendTransaction(transaction);
635
+ update("processing", messageFor("submitting"));
499
636
  const response = await submitToAuctioneer({
500
637
  order,
501
638
  isSingleChain,
@@ -504,13 +641,17 @@ async function handleSolanaExecution({
504
641
  if (!response.success) {
505
642
  throw new Error("Auctioneer submission failed");
506
643
  }
507
- update("success", messageFor("success"));
508
- return {
509
- status: true,
510
- txHash: txSignature,
511
- chainId: import_intents_sdk8.ChainID.Solana,
512
- stage: "success"
513
- };
644
+ update("initiated", messageFor("initiated"));
645
+ const { jwt, intentId: orderId } = response.data;
646
+ update("initiated", messageFor("shogun_processing"));
647
+ const status = await pollOrderStatus(jwt, orderId);
648
+ return await handleOrderPollingResult({
649
+ status,
650
+ orderId,
651
+ chainId: SOLANA_CHAIN_ID,
652
+ update,
653
+ messageFor
654
+ });
514
655
  }
515
656
  async function getSolanaOrderInstructions({
516
657
  order,
@@ -518,11 +659,11 @@ async function getSolanaOrderInstructions({
518
659
  rpcUrl
519
660
  }) {
520
661
  if (isSingleChain) {
521
- return await (0, import_intents_sdk8.getSolanaSingleChainOrderInstructions)(order, {
662
+ return await (0, import_intents_sdk9.getSolanaSingleChainOrderInstructions)(order, {
522
663
  rpcUrl
523
664
  });
524
665
  }
525
- return await (0, import_intents_sdk8.getSolanaCrossChainOrderInstructions)(order, {
666
+ return await (0, import_intents_sdk9.getSolanaCrossChainOrderInstructions)(order, {
526
667
  rpcUrl
527
668
  });
528
669
  }
@@ -552,18 +693,33 @@ async function executeOrder({
552
693
  onStatus,
553
694
  options = {}
554
695
  }) {
555
- const deadline = options.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
696
+ const isDev = process.env.NODE_ENV !== "production";
697
+ const log = (...args) => {
698
+ if (isDev) console.debug("[OneShot::executeOrder]", ...args);
699
+ };
556
700
  const messageFor = (stage) => DEFAULT_STAGE_MESSAGES[stage];
557
- const update = (stage, message) => onStatus?.(stage, message ?? messageFor(stage));
701
+ const update = (stage, message) => {
702
+ log("Stage:", stage, "| Message:", message ?? messageFor(stage));
703
+ onStatus?.(stage, message ?? messageFor(stage));
704
+ };
558
705
  try {
706
+ const deadline = options.deadline ?? Math.floor(Date.now() / 1e3) + 20 * 60;
707
+ log("Starting execution:", {
708
+ accountAddress,
709
+ recipientAddress,
710
+ deadline,
711
+ tokenIn: quote?.tokenIn,
712
+ tokenOut: quote?.tokenOut
713
+ });
559
714
  const adapter = normalizeWallet(wallet);
560
715
  if (!adapter) throw new Error("No wallet provided");
561
716
  const { tokenIn, tokenOut } = quote;
562
717
  const isSingleChain = tokenIn.chainId === tokenOut.chainId;
563
718
  const chainId = Number(tokenIn.chainId);
564
- update("processing", messageFor("processing"));
565
- if ((0, import_intents_sdk9.isEvmChain)(chainId)) {
566
- return await handleEvmExecution({
719
+ update("processing");
720
+ if ((0, import_intents_sdk10.isEvmChain)(chainId)) {
721
+ log("Detected EVM chain:", chainId);
722
+ const result = await handleEvmExecution({
567
723
  recipientAddress,
568
724
  quote,
569
725
  chainId,
@@ -573,9 +729,12 @@ async function executeOrder({
573
729
  deadline,
574
730
  update
575
731
  });
732
+ log("EVM execution result:", result);
733
+ return result;
576
734
  }
577
- if (chainId === import_intents_sdk9.ChainID.Solana) {
578
- return await handleSolanaExecution({
735
+ if (chainId === import_intents_sdk10.ChainID.Solana) {
736
+ log("Detected Solana chain");
737
+ const result = await handleSolanaExecution({
579
738
  recipientAddress,
580
739
  quote,
581
740
  accountAddress,
@@ -584,11 +743,16 @@ async function executeOrder({
584
743
  deadline,
585
744
  update
586
745
  });
746
+ log("Solana execution result:", result);
747
+ return result;
587
748
  }
588
- update("error", "Unsupported chain");
589
- return { status: false, message: "Unsupported chain", stage: "error" };
749
+ const unsupported = `Unsupported chain: ${chainId}`;
750
+ update("error", unsupported);
751
+ log("Error:", unsupported);
752
+ return { status: false, message: unsupported, stage: "error" };
590
753
  } catch (error) {
591
754
  const message = error instanceof import_viem4.BaseError ? error.shortMessage : error instanceof Error ? error.message : String(error);
755
+ log("Execution failed:", { message, error });
592
756
  update("error", message);
593
757
  return { status: false, message, stage: "error" };
594
758
  }
@@ -600,7 +764,7 @@ function normalizeWallet(wallet) {
600
764
  }
601
765
 
602
766
  // src/core/index.ts
603
- var import_intents_sdk10 = require("@shogun-sdk/intents-sdk");
767
+ var import_intents_sdk11 = require("@shogun-sdk/intents-sdk");
604
768
  // Annotate the CommonJS export names for ESM import in node:
605
769
  0 && (module.exports = {
606
770
  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';