@kaspacom/swap-sdk 1.1.5 → 1.1.7

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.
@@ -29640,6 +29640,12 @@ var KaspaComSwapSdk = (() => {
29640
29640
  getProvider() {
29641
29641
  return this.walletProvider || this.networkProvider;
29642
29642
  }
29643
+ destroy() {
29644
+ if (this.walletProvider) {
29645
+ this.networkProvider.destroy();
29646
+ this.disconnect();
29647
+ }
29648
+ }
29643
29649
  getSigner() {
29644
29650
  return this.signer;
29645
29651
  }
@@ -29675,11 +29681,6 @@ var KaspaComSwapSdk = (() => {
29675
29681
  throw new Error("No Ethereum wallet detected. Please connect a wallet provider.");
29676
29682
  }
29677
29683
  }
29678
- // Disconnect wallet and emit event
29679
- disconnectWallet() {
29680
- this.address = null;
29681
- this.signer = null;
29682
- }
29683
29684
  };
29684
29685
 
29685
29686
  // node_modules/@uniswap/sdk-core/dist/sdk-core.esm.js
@@ -32214,12 +32215,30 @@ var KaspaComSwapSdk = (() => {
32214
32215
  this.signer = null;
32215
32216
  this.pairs = [];
32216
32217
  this.resolvePairsLoaded = null;
32218
+ this.rejectPairsLoaded = null;
32217
32219
  this.resolvePartnerFeeLoaded = null;
32220
+ this.rejectPartnerFeeLoaded = null;
32218
32221
  this.partnerFee = 0n;
32219
32222
  this.provider = provider;
32220
- this.wethAddress = config.wrappedToken.address;
32221
32223
  this.chainId = config.chainId;
32222
- const routerAbi = [
32224
+ this.routerContract = new Contract(config.routerAddress, this.routerAbi, provider);
32225
+ this.factoryContract = new Contract(config.factoryAddress, this.factoryAbi, provider);
32226
+ if (config.proxyAddress) {
32227
+ this.proxyContract = new Contract(config.proxyAddress, this.proxyAbi, provider);
32228
+ }
32229
+ this.pairsLoadedPromise = new Promise((resolve, reject) => {
32230
+ this.resolvePairsLoaded = resolve;
32231
+ this.rejectPairsLoaded = reject;
32232
+ });
32233
+ this.partnerFeeLoadedPromise = new Promise((resolve, reject) => {
32234
+ this.resolvePartnerFeeLoaded = resolve;
32235
+ this.rejectPartnerFeeLoaded = reject;
32236
+ });
32237
+ this.loadAllPairs();
32238
+ this.loadPartnerFee();
32239
+ }
32240
+ get routerAbi() {
32241
+ return [
32223
32242
  // Swaps (ERC20 <-> ERC20)
32224
32243
  "function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)",
32225
32244
  "function swapTokensForExactTokens(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)",
@@ -32232,47 +32251,49 @@ var KaspaComSwapSdk = (() => {
32232
32251
  "function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts)",
32233
32252
  "function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut)",
32234
32253
  "function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn)",
32235
- "function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts)",
32254
+ "function getAmountsIn(uint amountOut, address[] memory path) internal view returns (uint[] memory amounts)",
32236
32255
  // Get WETH
32237
32256
  "function WETH() external pure returns (address)"
32238
32257
  ];
32239
- const factoryAbi = [
32258
+ }
32259
+ get factoryAbi() {
32260
+ return [
32240
32261
  "function getPair(address tokenA, address tokenB) external view returns (address pair)",
32241
32262
  "function allPairs(uint) external view returns (address pair)",
32242
32263
  "function allPairsLength() external view returns (uint)"
32243
32264
  ];
32244
- const proxyAbi = [
32245
- ...routerAbi,
32265
+ }
32266
+ get proxyAbi() {
32267
+ return [
32268
+ ...this.routerAbi,
32246
32269
  "function partners(bytes32) external view returns (address feeRecipient, uint16 feeBps)"
32247
32270
  ];
32248
- this.routerContract = new Contract(config.routerAddress, routerAbi, provider);
32249
- this.factoryContract = new Contract(config.factoryAddress, factoryAbi, provider);
32250
- if (config.proxyAddress) {
32251
- this.proxyContract = new Contract(config.proxyAddress, proxyAbi, provider);
32252
- }
32253
- this.pairsLoadedPromise = new Promise((resolve) => {
32254
- this.resolvePairsLoaded = resolve;
32255
- });
32256
- this.partnerFeeLoadedPromise = new Promise((resolve) => {
32257
- this.resolvePartnerFeeLoaded = resolve;
32258
- });
32259
- this.loadAllPairsFromGraph();
32260
- this.loadPartnerFee();
32261
32271
  }
32262
32272
  // parnter fee is BPS_DIVISOR = 10_000n;
32263
32273
  async loadPartnerFee() {
32264
32274
  if (!this.resolvePairsLoaded) {
32265
32275
  return this.partnerFee;
32266
32276
  }
32267
- if (this.swapOptions.partnerKey && this.proxyContract) {
32268
- const [, fee] = await this.proxyContract?.partners(this.swapOptions.partnerKey);
32269
- this.partnerFee = fee;
32270
- }
32271
- if (this.resolvePartnerFeeLoaded) {
32272
- this.resolvePartnerFeeLoaded();
32273
- this.resolvePartnerFeeLoaded = null;
32277
+ try {
32278
+ if (this.swapOptions.partnerKey && this.proxyContract) {
32279
+ const [, fee] = await this.proxyContract?.partners(this.swapOptions.partnerKey);
32280
+ this.partnerFee = fee;
32281
+ }
32282
+ if (this.resolvePartnerFeeLoaded) {
32283
+ this.resolvePartnerFeeLoaded();
32284
+ this.resolvePartnerFeeLoaded = null;
32285
+ }
32286
+ return this.partnerFee;
32287
+ } catch (error) {
32288
+ if (this.rejectPartnerFeeLoaded) {
32289
+ this.rejectPartnerFeeLoaded(error);
32290
+ this.partnerFeeLoadedPromise = new Promise((resolve, reject) => {
32291
+ this.resolvePartnerFeeLoaded = resolve;
32292
+ this.rejectPartnerFeeLoaded = reject;
32293
+ });
32294
+ }
32295
+ throw error;
32274
32296
  }
32275
- return this.partnerFee;
32276
32297
  }
32277
32298
  setSigner(signer) {
32278
32299
  this.signer = signer;
@@ -32292,11 +32313,7 @@ var KaspaComSwapSdk = (() => {
32292
32313
  }
32293
32314
  return num.toFixed(decimals);
32294
32315
  }
32295
- /**
32296
- * Loads all pairs from The Graph and caches them as Uniswap SDK Pair instances.
32297
- * @param graphEndpoint The GraphQL endpoint URL
32298
- */
32299
- async loadAllPairsFromGraph() {
32316
+ async refreshPairsFromGraph() {
32300
32317
  const query = `{
32301
32318
  pairs(first: 1000) {
32302
32319
  id
@@ -32306,46 +32323,47 @@ var KaspaComSwapSdk = (() => {
32306
32323
  token1 { id symbol name decimals }
32307
32324
  }
32308
32325
  }`;
32309
- try {
32310
- const response = await fetch(this.config.graphEndpoint, {
32311
- method: "POST",
32312
- headers: { "Content-Type": "application/json" },
32313
- body: JSON.stringify({ query })
32314
- });
32315
- if (!response.ok) throw new Error(`Network error: ${response.status}`);
32316
- const { data } = await response.json();
32317
- if (!data || !data.pairs) return;
32318
- const pairs = [];
32319
- for (const pair of data.pairs) {
32320
- pairs.push(
32321
- this.createSDKPair(pair)
32322
- );
32323
- }
32324
- this.pairs = pairs;
32325
- const wethPair = data.pairs.find(
32326
- (pair) => pair.token0.id.toLowerCase() === this.wethAddress.toLowerCase() || pair.token1.id.toLowerCase() === this.wethAddress.toLowerCase()
32326
+ const response = await fetch(this.config.graphEndpoint, {
32327
+ method: "POST",
32328
+ headers: { "Content-Type": "application/json" },
32329
+ body: JSON.stringify({ query })
32330
+ });
32331
+ if (!response.ok) throw new Error(`Network error: ${response.status}`);
32332
+ const { data } = await response.json();
32333
+ if (!data || !data.pairs) throw new Error(`No pairs found: ${data}`);
32334
+ return data.pairs;
32335
+ }
32336
+ async refreshPairs() {
32337
+ const pairsResult = this.swapOptions.getPairsData ? await this.swapOptions.getPairsData() : await this.refreshPairsFromGraph();
32338
+ const pairs = [];
32339
+ for (const pair of pairsResult) {
32340
+ pairs.push(
32341
+ this.createSDKPair(pair)
32327
32342
  );
32328
- if (wethPair) {
32329
- const tokenData = wethPair.token0.id.toLowerCase() === this.wethAddress.toLowerCase() ? wethPair.token0 : wethPair.token1;
32330
- this.wethToken = {
32331
- address: tokenData.id,
32332
- symbol: tokenData.symbol,
32333
- name: tokenData.name,
32334
- decimals: Number(tokenData.decimals)
32335
- };
32336
- } else {
32337
- throw new Error("No weth token found");
32338
- }
32343
+ }
32344
+ this.pairs = pairs;
32345
+ }
32346
+ /**
32347
+ * Loads all pairs from The Graph and caches them as Uniswap SDK Pair instances.
32348
+ * @param graphEndpoint The GraphQL endpoint URL
32349
+ */
32350
+ async loadAllPairs() {
32351
+ try {
32352
+ await this.refreshPairs();
32339
32353
  if (this.resolvePairsLoaded) {
32340
32354
  this.resolvePairsLoaded();
32341
32355
  this.resolvePairsLoaded = null;
32342
32356
  }
32343
32357
  } catch (error) {
32344
32358
  console.error("Error loading pairs from graph:", error);
32345
- if (this.resolvePairsLoaded) {
32346
- this.resolvePairsLoaded();
32347
- this.resolvePairsLoaded = null;
32359
+ if (this.rejectPairsLoaded) {
32360
+ this.rejectPairsLoaded(error);
32348
32361
  }
32362
+ this.pairsLoadedPromise = new Promise((resolve, reject) => {
32363
+ this.resolvePairsLoaded = resolve;
32364
+ this.rejectPairsLoaded = reject;
32365
+ });
32366
+ setTimeout(this.loadAllPairs.bind(this), 1e3);
32349
32367
  }
32350
32368
  }
32351
32369
  async waitForPairsLoaded() {
@@ -32355,7 +32373,7 @@ var KaspaComSwapSdk = (() => {
32355
32373
  return await this.partnerFeeLoadedPromise;
32356
32374
  }
32357
32375
  createSDKPair(pair) {
32358
- const { token0, token1, id: id2, reserve0, reserve1 } = pair;
32376
+ const { token0, token1, reserve0, reserve1 } = pair;
32359
32377
  const sdkToken0 = new Token(
32360
32378
  this.chainId,
32361
32379
  token0.id,
@@ -32418,8 +32436,6 @@ var KaspaComSwapSdk = (() => {
32418
32436
  isOutputAmount ? sdkToToken : sdkFromToken,
32419
32437
  amountInWei
32420
32438
  );
32421
- await this.waitForPairsLoaded();
32422
- await this.waitForPartnerFeeLoaded();
32423
32439
  const pairs = this.getPairs();
32424
32440
  if (!pairs || pairs.length === 0) {
32425
32441
  throw new Error("Pairs not loaded yet. Please wait for initialization.");
@@ -32445,6 +32461,14 @@ var KaspaComSwapSdk = (() => {
32445
32461
  value = value.replace(/\.?0+$/, "");
32446
32462
  return value;
32447
32463
  }
32464
+ async getAmountsIn(sellAmountWei, pathAddresses) {
32465
+ const [aIn] = await this.routerContract.getAmountsIn(sellAmountWei, pathAddresses);
32466
+ return aIn;
32467
+ }
32468
+ async getAmountsOut(buyAmountWei, pathAddresses) {
32469
+ const [, aOut] = await this.routerContract.getAmountsOut(buyAmountWei, pathAddresses);
32470
+ return aOut;
32471
+ }
32448
32472
  /**
32449
32473
  *
32450
32474
  * @param sellToken
@@ -32456,6 +32480,8 @@ var KaspaComSwapSdk = (() => {
32456
32480
  */
32457
32481
  async calculateTrade(sellToken, buyToken, targetAmount, isOutputAmount, slippage) {
32458
32482
  try {
32483
+ await this.waitForPairsLoaded();
32484
+ await this.waitForPartnerFeeLoaded();
32459
32485
  const roundedAmountIn = this.roundToDecimals(targetAmount, isOutputAmount ? buyToken.decimals : sellToken.decimals);
32460
32486
  let sellAmountWei = parseUnits(
32461
32487
  roundedAmountIn,
@@ -32466,8 +32492,8 @@ var KaspaComSwapSdk = (() => {
32466
32492
  const denominator = PARTNER_FEE_BPS_DIVISOR - this.partnerFee;
32467
32493
  sellAmountWei = (numerator + denominator - 1n) / denominator;
32468
32494
  }
32469
- const sellTokenForContracts = sellToken.address == ethers_exports.ZeroAddress ? this.wethToken : sellToken;
32470
- const buyTokenForContracts = buyToken.address == ethers_exports.ZeroAddress ? this.wethToken : buyToken;
32495
+ const sellTokenForContracts = sellToken.address == ethers_exports.ZeroAddress ? this.config.wrappedToken : sellToken;
32496
+ const buyTokenForContracts = buyToken.address == ethers_exports.ZeroAddress ? this.config.wrappedToken : buyToken;
32471
32497
  const trade = await this.getBestTrade(
32472
32498
  sellTokenForContracts,
32473
32499
  buyTokenForContracts,
@@ -32477,8 +32503,16 @@ var KaspaComSwapSdk = (() => {
32477
32503
  if (!trade) {
32478
32504
  throw new Error("No trade path found for the given tokens and amount.");
32479
32505
  }
32480
- const amountIn = trade.inputAmount.quotient.toString();
32481
- const amountOut = trade.outputAmount.quotient.toString();
32506
+ const pathAddresses = trade.route.path.map((token) => token.address);
32507
+ let amountIn = "0";
32508
+ let amountOut = "0";
32509
+ if (isOutputAmount) {
32510
+ amountIn = String(await this.getAmountsIn(sellAmountWei, pathAddresses));
32511
+ amountOut = String(parseUnits(targetAmount, buyToken.decimals));
32512
+ } else {
32513
+ amountOut = String(await this.getAmountsOut(sellAmountWei, pathAddresses));
32514
+ amountIn = String(parseUnits(targetAmount, sellToken.decimals));
32515
+ }
32482
32516
  let amounts = {
32483
32517
  amountIn: formatUnits(amountIn, sellToken.decimals),
32484
32518
  amountOut: isOutputAmount ? this.trimTrailingZeros(roundedAmountIn) : formatUnits(amountOut, buyToken.decimals),
@@ -32488,18 +32522,23 @@ var KaspaComSwapSdk = (() => {
32488
32522
  const slippagePercent = new Percent(Math.round(parseFloat(slippage) * 100), 1e4);
32489
32523
  let maxAmountIn, minAmountOut;
32490
32524
  if (isOutputAmount) {
32491
- maxAmountIn = trade.maximumAmountIn(slippagePercent).quotient.toString();
32525
+ const slippageAmount = BigInt(amountIn) * BigInt(slippagePercent.numerator.toString()) / BigInt(slippagePercent.denominator.toString());
32526
+ const maxAmountInBigInt = BigInt(amountIn) + slippageAmount;
32527
+ maxAmountIn = maxAmountInBigInt.toString();
32492
32528
  amounts.maxAmountInRaw = maxAmountIn;
32493
32529
  amounts.maxAmountIn = formatUnits(maxAmountIn, sellToken.decimals);
32494
32530
  } else {
32495
- minAmountOut = trade.minimumAmountOut(slippagePercent).quotient.toString();
32531
+ const amountOutBigInt = BigInt(amountOut);
32532
+ const slippageAmount = amountOutBigInt * BigInt(slippagePercent.numerator.toString()) / BigInt(slippagePercent.denominator.toString());
32533
+ const minAmountOutBigInt = amountOutBigInt - slippageAmount;
32534
+ minAmountOut = minAmountOutBigInt.toString();
32496
32535
  amounts.minAmountOutRaw = minAmountOut;
32497
32536
  amounts.minAmountOut = formatUnits(minAmountOut, buyToken.decimals);
32498
32537
  }
32499
32538
  if (this.partnerFee && this.partnerFee > 0n) {
32500
32539
  if (!isOutputAmount) {
32501
- const amountOut2 = BigInt(trade.outputAmount.quotient.toString());
32502
- const amountOutMinusFee = amountOut2 * (PARTNER_FEE_BPS_DIVISOR - this.partnerFee) / PARTNER_FEE_BPS_DIVISOR;
32540
+ const amountOutBigInt = BigInt(amountOut);
32541
+ const amountOutMinusFee = amountOutBigInt * (PARTNER_FEE_BPS_DIVISOR - this.partnerFee) / PARTNER_FEE_BPS_DIVISOR;
32503
32542
  amounts.amountOutRaw = amountOutMinusFee.toString();
32504
32543
  amounts.amountOut = formatUnits(amountOutMinusFee, buyToken.decimals);
32505
32544
  if (minAmountOut) {
@@ -32793,6 +32832,7 @@ var KaspaComSwapSdk = (() => {
32793
32832
  };
32794
32833
  var SwapSdkController = class {
32795
32834
  constructor(options) {
32835
+ this.refreshPairsTimeout = null;
32796
32836
  this.state = {
32797
32837
  loader: null
32798
32838
  };
@@ -32811,11 +32851,16 @@ var KaspaComSwapSdk = (() => {
32811
32851
  this.options.networkConfig,
32812
32852
  this.options.walletProvider
32813
32853
  );
32814
- this.swapService = new SwapService(
32854
+ this.swapService = new (this.options.swapServiceClass || SwapService)(
32815
32855
  this.walletService.getProvider(),
32816
32856
  this.options.networkConfig,
32817
32857
  this.options
32818
32858
  );
32859
+ if (this.options.refreshPairsInterval) {
32860
+ this.swapService.waitForPairsLoaded().finally(() => {
32861
+ this.refreshPairsTimeout = setTimeout(this.refreshTokensAndUpdateQuoteAndSetTimeout.bind(this), this.options.refreshPairsInterval);
32862
+ });
32863
+ }
32819
32864
  }
32820
32865
  async setChange(patch) {
32821
32866
  const next = {
@@ -32864,6 +32909,7 @@ var KaspaComSwapSdk = (() => {
32864
32909
  await this.setChange({
32865
32910
  computed: tradeResult.computed,
32866
32911
  tradeInfo: tradeResult.trade,
32912
+ path: tradeResult.trade.route.path,
32867
32913
  loader: null
32868
32914
  });
32869
32915
  } catch (error) {
@@ -32921,9 +32967,8 @@ var KaspaComSwapSdk = (() => {
32921
32967
  if (!fromToken || !toToken || amount === void 0) throw new Error("Tokens or amount not set");
32922
32968
  await this.approveIfNeeded();
32923
32969
  await this.setChange({ loader: 3 /* SWAPPING */ });
32924
- const trade = this.state.tradeInfo;
32925
- if (!trade) throw new Error("Trade info missing - calculate quote first");
32926
- const path = trade.route.path.map((token) => token.address);
32970
+ if (!this.state.path) throw new Error("Trade info missing - calculate quote first");
32971
+ const path = this.state.path.map((token) => token.address);
32927
32972
  if (path.length === 0) throw new Error("Trade path missing");
32928
32973
  const computed = this.state.computed;
32929
32974
  if (!computed) throw new Error("Computed amounts missing");
@@ -32965,6 +33010,29 @@ var KaspaComSwapSdk = (() => {
32965
33010
  get currentNetworkConfig() {
32966
33011
  return this.options.networkConfig;
32967
33012
  }
33013
+ async destroy() {
33014
+ if (this.walletService) {
33015
+ this.walletService.destroy();
33016
+ }
33017
+ if (this.refreshPairsTimeout) {
33018
+ clearTimeout(this.refreshPairsTimeout);
33019
+ this.refreshPairsTimeout = null;
33020
+ }
33021
+ }
33022
+ async refreshTokensAndUpdateQuote(forceQuoteUpdate = false) {
33023
+ await this.swapService?.refreshPairsFromGraph();
33024
+ if ((this.options.updateQuoteAfterRefreshPairs || forceQuoteUpdate) && !this.state.loader) {
33025
+ await this.calculateQuoteIfNeeded();
33026
+ }
33027
+ }
33028
+ async refreshTokensAndUpdateQuoteAndSetTimeout() {
33029
+ try {
33030
+ await this.refreshTokensAndUpdateQuote();
33031
+ } catch (error) {
33032
+ console.error(error);
33033
+ }
33034
+ this.refreshPairsTimeout = setTimeout(this.refreshTokensAndUpdateQuoteAndSetTimeout.bind(this), this.options.refreshPairsInterval);
33035
+ }
32968
33036
  };
32969
33037
 
32970
33038
  // src/config/networks.ts
@@ -32995,6 +33063,33 @@ var KaspaComSwapSdk = (() => {
32995
33063
  name: "Kasplex Kaspa",
32996
33064
  symbol: "KAS"
32997
33065
  }
33066
+ },
33067
+ "kasplex": {
33068
+ name: "Kasplex",
33069
+ chainId: 202555,
33070
+ rpcUrl: "https://evmrpc.kasplex.org",
33071
+ routerAddress: "0x3a1f0bD164fe9D8fa18Da5abAB352dC634CA5F10",
33072
+ factoryAddress: "0xa9CBa43A407c9Eb30933EA21f7b9D74A128D613c",
33073
+ proxyAddress: "0x4c5BEaAE83577E3a117ce2F477fC42a1EA39A8a3",
33074
+ graphEndpoint: "https://graph-kasplex.kaspa.com/subgraphs/name/kasplex-v2-core",
33075
+ blockExplorerUrl: "https://explorer.kasplex.org",
33076
+ additionalJsonRpcApiProviderOptionsOptions: {
33077
+ batchMaxCount: 1,
33078
+ batchMaxSize: 1,
33079
+ batchStallTime: 0
33080
+ },
33081
+ wrappedToken: {
33082
+ address: "0x2c2Ae87Ba178F48637acAe54B87c3924F544a83e",
33083
+ decimals: 18,
33084
+ name: "Wrapped KAS",
33085
+ symbol: "WKAS"
33086
+ },
33087
+ nativeToken: {
33088
+ address: ethers_exports.ZeroAddress,
33089
+ decimals: 18,
33090
+ name: "Kasplex Kaspa",
33091
+ symbol: "KAS"
33092
+ }
32998
33093
  }
32999
33094
  // Add more networks as needed
33000
33095
  };