@flaunch/sdk 0.9.6 → 0.9.8

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/index.esm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createDrift as createDrift$1 } from '@delvtech/drift';
2
- import { zeroAddress, parseEther, encodeAbiParameters as encodeAbiParameters$1, maxUint256 as maxUint256$1, encodeFunctionData, maxUint160, maxUint48, parseUnits, hexToBigInt as hexToBigInt$1, pad as pad$1, keccak256 as keccak256$1, encodePacked, stringToHex as stringToHex$1, zeroHash, formatUnits as formatUnits$1, parseEventLogs, concat as concat$1, toHex as toHex$1, formatEther, erc721Abi, erc20Abi, parseAbi, createWalletClient, http, decodeFunctionData } from 'viem';
2
+ import { zeroAddress, parseEther, encodeAbiParameters as encodeAbiParameters$1, maxUint256 as maxUint256$1, encodeFunctionData, maxUint160, maxUint48, parseUnits, hexToBigInt as hexToBigInt$1, pad as pad$1, keccak256 as keccak256$1, encodePacked, stringToHex as stringToHex$1, zeroHash, formatUnits as formatUnits$1, parseEventLogs, concat as concat$1, toHex as toHex$1, erc721Abi, erc20Abi, parseAbi, createWalletClient, http, decodeFunctionData } from 'viem';
3
3
  import axios from 'axios';
4
4
  import { viemAdapter } from '@delvtech/drift-viem';
5
5
 
@@ -25459,6 +25459,10 @@ function maxLiquidityForAmount0Precise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
25459
25459
  if (sqrtRatioAX96 > sqrtRatioBX96) {
25460
25460
  [sqrtRatioAX96, sqrtRatioBX96] = [sqrtRatioBX96, sqrtRatioAX96];
25461
25461
  }
25462
+ // Handle edge case where sqrt ratios are equal (division by zero)
25463
+ if (sqrtRatioAX96 === sqrtRatioBX96) {
25464
+ return 0n;
25465
+ }
25462
25466
  const Q96 = 2n ** 96n;
25463
25467
  const numerator = amount0 * sqrtRatioAX96 * sqrtRatioBX96;
25464
25468
  const denominator = Q96 * (sqrtRatioBX96 - sqrtRatioAX96);
@@ -25475,6 +25479,10 @@ function maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1) {
25475
25479
  if (sqrtRatioAX96 > sqrtRatioBX96) {
25476
25480
  [sqrtRatioAX96, sqrtRatioBX96] = [sqrtRatioBX96, sqrtRatioAX96];
25477
25481
  }
25482
+ // Handle edge case where sqrt ratios are equal (division by zero)
25483
+ if (sqrtRatioAX96 === sqrtRatioBX96) {
25484
+ return 0n;
25485
+ }
25478
25486
  const Q96 = 2n ** 96n;
25479
25487
  return (amount1 * Q96) / (sqrtRatioBX96 - sqrtRatioAX96);
25480
25488
  }
@@ -26386,7 +26394,7 @@ class ReadFlaunchSDK {
26386
26394
  * @returns Promise<number> - The current tick of the pool
26387
26395
  */
26388
26396
  async currentTick(coinAddress, version) {
26389
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26397
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26390
26398
  const poolId = await this.poolId(coinAddress, coinVersion);
26391
26399
  const poolState = await this.readStateView.poolSlot0({ poolId });
26392
26400
  return poolState.tick;
@@ -26398,7 +26406,7 @@ class ReadFlaunchSDK {
26398
26406
  * @returns Promise<string> - The price of the coin in ETH with 18 decimals precision
26399
26407
  */
26400
26408
  async coinPriceInETH(coinAddress, version) {
26401
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26409
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26402
26410
  const isFLETHZero = this.flETHIsCurrencyZero(coinAddress);
26403
26411
  const currentTick = await this.currentTick(coinAddress, coinVersion);
26404
26412
  const price = Math.pow(1.0001, currentTick);
@@ -26418,7 +26426,7 @@ class ReadFlaunchSDK {
26418
26426
  * @returns Promise<string> - The price of the coin in USD with 18 decimal precision
26419
26427
  */
26420
26428
  async coinPriceInUSD({ coinAddress, version, drift, }) {
26421
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26429
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26422
26430
  const ethPerCoin = await this.coinPriceInETH(coinAddress, coinVersion);
26423
26431
  const ethPrice = await this.getETHUSDCPrice(drift);
26424
26432
  return (parseFloat(ethPerCoin) * ethPrice).toFixed(18);
@@ -26466,7 +26474,7 @@ class ReadFlaunchSDK {
26466
26474
  * @returns Fair launch information from the appropriate contract version
26467
26475
  */
26468
26476
  async fairLaunchInfo(coinAddress, version) {
26469
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26477
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26470
26478
  const poolId = await this.poolId(coinAddress, coinVersion);
26471
26479
  return this.getFairLaunch(coinVersion).fairLaunchInfo({ poolId });
26472
26480
  }
@@ -26477,12 +26485,12 @@ class ReadFlaunchSDK {
26477
26485
  * @returns Promise<boolean> - True if fair launch is active, false otherwise
26478
26486
  */
26479
26487
  async isFairLaunchActive(coinAddress, version) {
26480
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26488
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26481
26489
  const poolId = await this.poolId(coinAddress, coinVersion);
26482
26490
  return this.getFairLaunch(coinVersion).isFairLaunchActive({ poolId });
26483
26491
  }
26484
26492
  async trustedPoolKeySignerStatus(coinAddress, version) {
26485
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26493
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26486
26494
  if (coinVersion === FlaunchVersion.ANY) {
26487
26495
  throw new Error("AnyPositionManager is not supported for TrustedSigner");
26488
26496
  }
@@ -26531,7 +26539,7 @@ class ReadFlaunchSDK {
26531
26539
  * @returns Promise<number> - The duration in seconds (30 minutes for V1, variable for V1.1)
26532
26540
  */
26533
26541
  async fairLaunchDuration(coinAddress, version) {
26534
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26542
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26535
26543
  const poolId = await this.poolId(coinAddress, coinVersion);
26536
26544
  return this.getFairLaunch(coinVersion).fairLaunchDuration({ poolId });
26537
26545
  }
@@ -26542,7 +26550,7 @@ class ReadFlaunchSDK {
26542
26550
  * @returns Promise<number> - The initial tick value
26543
26551
  */
26544
26552
  async initialTick(coinAddress, version) {
26545
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26553
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26546
26554
  const poolId = await this.poolId(coinAddress, coinVersion);
26547
26555
  const fairLaunchInfo = await this.getFairLaunch(coinVersion).fairLaunchInfo({ poolId });
26548
26556
  return fairLaunchInfo.initialTick;
@@ -26554,7 +26562,7 @@ class ReadFlaunchSDK {
26554
26562
  * @returns Promise<{flETHAmount: bigint, coinAmount: bigint, tickLower: number, tickUpper: number}> - Position details
26555
26563
  */
26556
26564
  async fairLaunchETHOnlyPosition(coinAddress, version) {
26557
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26565
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26558
26566
  const poolId = await this.poolId(coinAddress, coinVersion);
26559
26567
  const initialTick = await this.initialTick(coinAddress, coinVersion);
26560
26568
  const currentTick = await this.currentTick(coinAddress, coinVersion);
@@ -26602,7 +26610,7 @@ class ReadFlaunchSDK {
26602
26610
  * @returns Promise<{flETHAmount: bigint, coinAmount: bigint, tickLower: number, tickUpper: number}> - Position details
26603
26611
  */
26604
26612
  async fairLaunchCoinOnlyPosition(coinAddress, version) {
26605
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26613
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26606
26614
  const poolId = await this.poolId(coinAddress, coinVersion);
26607
26615
  const initialTick = await this.initialTick(coinAddress, coinVersion);
26608
26616
  const currentTick = await this.currentTick(coinAddress, coinVersion);
@@ -26650,7 +26658,7 @@ class ReadFlaunchSDK {
26650
26658
  * @returns Promise<{flETHAmount: bigint, coinAmount: bigint, pendingEth: bigint, tickLower: number, tickUpper: number}> - Bid wall position details
26651
26659
  */
26652
26660
  async bidWallPosition(coinAddress, version) {
26653
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26661
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26654
26662
  const poolId = await this.poolId(coinAddress, coinVersion);
26655
26663
  const isFLETHZero = this.flETHIsCurrencyZero(coinAddress);
26656
26664
  const { amount0_: amount0, amount1_: amount1, pendingEth_: pendingEth, } = await this.getBidWall(coinVersion).position({ poolId });
@@ -26766,13 +26774,8 @@ class ReadFlaunchSDK {
26766
26774
  */
26767
26775
  async poolId(coinAddress, version) {
26768
26776
  let hookAddress;
26769
- if (version) {
26770
- hookAddress = this.getPositionManagerAddress(version);
26771
- }
26772
- else {
26773
- const coinVersion = await this.getCoinVersion(coinAddress);
26774
- hookAddress = this.getPositionManagerAddress(coinVersion);
26775
- }
26777
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26778
+ hookAddress = this.getPositionManagerAddress(coinVersion);
26776
26779
  return getPoolId(orderPoolKey({
26777
26780
  currency0: FLETHAddress[this.chainId],
26778
26781
  currency1: coinAddress,
@@ -26830,7 +26833,7 @@ class ReadFlaunchSDK {
26830
26833
  * @returns Promise<bigint> - The expected amount of ETH to receive
26831
26834
  */
26832
26835
  async getSellQuoteExactInput({ coinAddress, version, amountIn, intermediatePoolKey, }) {
26833
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26836
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26834
26837
  return this.readQuoter.getSellQuoteExactInput({
26835
26838
  coinAddress,
26836
26839
  amountIn,
@@ -26849,7 +26852,7 @@ class ReadFlaunchSDK {
26849
26852
  * @returns Promise<bigint> - The expected amount of coins to receive
26850
26853
  */
26851
26854
  async getBuyQuoteExactInput({ coinAddress, version, amountIn, intermediatePoolKey, hookData, userWallet, }) {
26852
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26855
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26853
26856
  return this.readQuoter.getBuyQuoteExactInput({
26854
26857
  coinAddress,
26855
26858
  amountIn,
@@ -26870,7 +26873,7 @@ class ReadFlaunchSDK {
26870
26873
  * @returns Promise<bigint> - The required amount of ETH or inputToken to spend
26871
26874
  */
26872
26875
  async getBuyQuoteExactOutput({ coinAddress, amountOut, version, intermediatePoolKey, hookData, userWallet, }) {
26873
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26876
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26874
26877
  return this.readQuoter.getBuyQuoteExactOutput({
26875
26878
  coinAddress,
26876
26879
  coinOut: amountOut,
@@ -26928,7 +26931,8 @@ class ReadFlaunchSDK {
26928
26931
  memecoin.totalSupply(),
26929
26932
  memecoin.decimals(),
26930
26933
  ]);
26931
- return { totalSupply, decimals };
26934
+ const formattedTotalSupplyInDecimals = parseFloat(formatUnits$1(totalSupply, decimals));
26935
+ return { totalSupply, decimals, formattedTotalSupplyInDecimals };
26932
26936
  }
26933
26937
  /**
26934
26938
  * Gets market context information needed for tick calculations
@@ -26950,8 +26954,8 @@ class ReadFlaunchSDK {
26950
26954
  /**
26951
26955
  * Converts market cap in USD to token price in ETH
26952
26956
  */
26953
- marketCapToTokenPriceEth(marketCapUsd, totalSupplyDecimal, ethUsdPrice) {
26954
- const tokenPriceUsd = marketCapUsd / totalSupplyDecimal;
26957
+ marketCapToTokenPriceEth(marketCapUsd, formattedTotalSupplyInDecimals, ethUsdPrice) {
26958
+ const tokenPriceUsd = marketCapUsd / formattedTotalSupplyInDecimals;
26955
26959
  return tokenPriceUsd / ethUsdPrice;
26956
26960
  }
26957
26961
  /**
@@ -26969,24 +26973,22 @@ class ReadFlaunchSDK {
26969
26973
  /**
26970
26974
  * Calculates current tick from market cap if provided
26971
26975
  */
26972
- calculateCurrentTickFromMarketCap(currentMarketCap, totalSupplyDecimal, marketContext) {
26976
+ calculateCurrentTickFromMarketCap(currentMarketCap, formattedTotalSupplyInDecimals, marketContext) {
26973
26977
  if (!currentMarketCap) {
26974
26978
  return undefined;
26975
26979
  }
26976
26980
  const currentMarketCapNum = parseFloat(currentMarketCap);
26977
- const currentTokenPriceEth = this.marketCapToTokenPriceEth(currentMarketCapNum, totalSupplyDecimal, marketContext.ethUsdPrice);
26981
+ const currentTokenPriceEth = this.marketCapToTokenPriceEth(currentMarketCapNum, formattedTotalSupplyInDecimals, marketContext.ethUsdPrice);
26978
26982
  return this.convertPriceToTick(currentTokenPriceEth, marketContext.isFlethZero, marketContext.decimals0, marketContext.decimals1);
26979
26983
  }
26980
26984
  async calculateAddLiquidityTicks({ coinAddress, liquidityMode, minMarketCap, maxMarketCap, currentMarketCap, }) {
26981
26985
  // Get coin information
26982
- const { totalSupply: coinTotalSupply, decimals: coinDecimals } = await this.getCoinInfo(coinAddress);
26983
- // Convert total supply to decimal format
26984
- const totalSupplyDecimal = parseFloat(formatEther(coinTotalSupply));
26986
+ const { totalSupply: coinTotalSupply, decimals: coinDecimals, formattedTotalSupplyInDecimals, } = await this.getCoinInfo(coinAddress);
26985
26987
  if (liquidityMode === LiquidityMode.FULL_RANGE) {
26986
26988
  let currentTick;
26987
26989
  if (currentMarketCap) {
26988
26990
  const marketContext = await this.getMarketContext(coinAddress, coinDecimals);
26989
- currentTick = this.calculateCurrentTickFromMarketCap(currentMarketCap, totalSupplyDecimal, marketContext);
26991
+ currentTick = this.calculateCurrentTickFromMarketCap(currentMarketCap, formattedTotalSupplyInDecimals, marketContext);
26990
26992
  }
26991
26993
  return {
26992
26994
  tickLower: getNearestUsableTick({
@@ -27013,13 +27015,13 @@ class ReadFlaunchSDK {
27013
27015
  throw new Error("[ReadFlaunchSDK.addLiquidityCalculateTicks]: Invalid market cap range");
27014
27016
  }
27015
27017
  // Convert market caps to token prices in ETH
27016
- const minTokenPriceEth = this.marketCapToTokenPriceEth(minMarketCapNum, totalSupplyDecimal, marketContext.ethUsdPrice);
27017
- const maxTokenPriceEth = this.marketCapToTokenPriceEth(maxMarketCapNum, totalSupplyDecimal, marketContext.ethUsdPrice);
27018
+ const minTokenPriceEth = this.marketCapToTokenPriceEth(minMarketCapNum, formattedTotalSupplyInDecimals, marketContext.ethUsdPrice);
27019
+ const maxTokenPriceEth = this.marketCapToTokenPriceEth(maxMarketCapNum, formattedTotalSupplyInDecimals, marketContext.ethUsdPrice);
27018
27020
  // Convert to ticks
27019
27021
  const minTick = this.convertPriceToTick(minTokenPriceEth, marketContext.isFlethZero, marketContext.decimals0, marketContext.decimals1);
27020
27022
  const maxTick = this.convertPriceToTick(maxTokenPriceEth, marketContext.isFlethZero, marketContext.decimals0, marketContext.decimals1);
27021
27023
  // Calculate current tick if provided
27022
- const currentTick = this.calculateCurrentTickFromMarketCap(currentMarketCap, totalSupplyDecimal, marketContext);
27024
+ const currentTick = this.calculateCurrentTickFromMarketCap(currentMarketCap, formattedTotalSupplyInDecimals, marketContext);
27023
27025
  return {
27024
27026
  tickLower: Math.min(minTick, maxTick),
27025
27027
  tickUpper: Math.max(minTick, maxTick),
@@ -27040,12 +27042,11 @@ class ReadFlaunchSDK {
27040
27042
  currentMarketCap = params.currentMarketCap;
27041
27043
  }
27042
27044
  else {
27043
- const { totalSupply, decimals } = await this.getCoinInfo(coinAddress);
27044
- const formattedTotalSupply = parseFloat(formatUnits$1(totalSupply, decimals));
27045
- minMarketCap = (parseFloat(params.minPriceUSD) * formattedTotalSupply).toString();
27046
- maxMarketCap = (parseFloat(params.maxPriceUSD) * formattedTotalSupply).toString();
27045
+ const { formattedTotalSupplyInDecimals } = await this.getCoinInfo(coinAddress);
27046
+ minMarketCap = (parseFloat(params.minPriceUSD) * formattedTotalSupplyInDecimals).toString();
27047
+ maxMarketCap = (parseFloat(params.maxPriceUSD) * formattedTotalSupplyInDecimals).toString();
27047
27048
  if (params.currentPriceUSD) {
27048
- currentMarketCap = (params.currentPriceUSD * formattedTotalSupply).toString();
27049
+ currentMarketCap = (params.currentPriceUSD * formattedTotalSupplyInDecimals).toString();
27049
27050
  }
27050
27051
  }
27051
27052
  let { tickLower, tickUpper, currentTick } = await this.calculateAddLiquidityTicks({
@@ -27057,24 +27058,9 @@ class ReadFlaunchSDK {
27057
27058
  });
27058
27059
  // If no current tick is provided from the above calculation, get it from the pool state
27059
27060
  if (!currentTick) {
27060
- let version = params.version;
27061
- // if version is not provided, check on existing managers, else default to ANY
27062
- if (!version) {
27063
- try {
27064
- version = await this.getCoinVersion(coinAddress);
27065
- }
27066
- catch {
27067
- version = FlaunchVersion.ANY;
27068
- }
27069
- }
27061
+ const version = await this.determineCoinVersion(coinAddress, params.version);
27070
27062
  const poolState = await this.readStateView.poolSlot0({
27071
- poolId: getPoolId(orderPoolKey({
27072
- currency0: coinAddress,
27073
- currency1: FLETHAddress[this.chainId],
27074
- fee: 0,
27075
- tickSpacing: TICK_SPACING,
27076
- hooks: this.getPositionManagerAddress(version),
27077
- })),
27063
+ poolId: getPoolId(this.createPoolKey(coinAddress, version)),
27078
27064
  });
27079
27065
  currentTick = poolState.tick;
27080
27066
  }
@@ -27131,12 +27117,11 @@ class ReadFlaunchSDK {
27131
27117
  currentMarketCap = params.currentMarketCap;
27132
27118
  }
27133
27119
  else {
27134
- const { totalSupply, decimals } = await this.getCoinInfo(coinAddress);
27135
- const formattedTotalSupply = parseFloat(formatUnits$1(totalSupply, decimals));
27136
- minMarketCap = (parseFloat(params.minPriceUSD) * formattedTotalSupply).toString();
27137
- maxMarketCap = (parseFloat(params.maxPriceUSD) * formattedTotalSupply).toString();
27120
+ const { formattedTotalSupplyInDecimals } = await this.getCoinInfo(coinAddress);
27121
+ minMarketCap = (parseFloat(params.minPriceUSD) * formattedTotalSupplyInDecimals).toString();
27122
+ maxMarketCap = (parseFloat(params.maxPriceUSD) * formattedTotalSupplyInDecimals).toString();
27138
27123
  if (params.currentPriceUSD) {
27139
- currentMarketCap = (params.currentPriceUSD * formattedTotalSupply).toString();
27124
+ currentMarketCap = (params.currentPriceUSD * formattedTotalSupplyInDecimals).toString();
27140
27125
  }
27141
27126
  }
27142
27127
  let { tickLower, tickUpper, currentTick } = await this.calculateAddLiquidityTicks({
@@ -27148,24 +27133,9 @@ class ReadFlaunchSDK {
27148
27133
  });
27149
27134
  // get the current pool state for the coin
27150
27135
  if (!currentTick) {
27151
- let version = params.version;
27152
- // if version is not provided, check on existing managers, else default to ANY
27153
- if (!version) {
27154
- try {
27155
- version = await this.getCoinVersion(coinAddress);
27156
- }
27157
- catch {
27158
- version = FlaunchVersion.ANY;
27159
- }
27160
- }
27136
+ const version = await this.determineCoinVersion(coinAddress, params.version);
27161
27137
  const poolState = await this.readStateView.poolSlot0({
27162
- poolId: getPoolId(orderPoolKey({
27163
- currency0: coinAddress,
27164
- currency1: FLETHAddress[this.chainId],
27165
- fee: 0,
27166
- tickSpacing: TICK_SPACING,
27167
- hooks: this.getPositionManagerAddress(version),
27168
- })),
27138
+ poolId: getPoolId(this.createPoolKey(coinAddress, version)),
27169
27139
  });
27170
27140
  currentTick = poolState.tick;
27171
27141
  }
@@ -27320,6 +27290,39 @@ class ReadFlaunchSDK {
27320
27290
  args: { owner, operator },
27321
27291
  });
27322
27292
  }
27293
+ /**
27294
+ * Determines the version for a coin, using provided version or fetching it
27295
+ * @param coinAddress - The coin address
27296
+ * @param version - Optional version, if not provided will be fetched
27297
+ * @returns The determined version
27298
+ */
27299
+ async determineCoinVersion(coinAddress, version) {
27300
+ if (!version) {
27301
+ try {
27302
+ version = await this.getCoinVersion(coinAddress);
27303
+ }
27304
+ catch {
27305
+ version = FlaunchVersion.ANY;
27306
+ }
27307
+ }
27308
+ return version;
27309
+ }
27310
+ /**
27311
+ * Creates a pool key for the given coin and version
27312
+ * @param coinAddress - The coin address
27313
+ * @param version - The version to use for position manager
27314
+ * @returns The ordered pool key
27315
+ */
27316
+ createPoolKey(coinAddress, version) {
27317
+ const flethAddress = FLETHAddress[this.chainId];
27318
+ return orderPoolKey({
27319
+ currency0: coinAddress,
27320
+ currency1: flethAddress,
27321
+ fee: 0,
27322
+ tickSpacing: this.TICK_SPACING,
27323
+ hooks: this.getPositionManagerAddress(version),
27324
+ });
27325
+ }
27323
27326
  }
27324
27327
  class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
27325
27328
  constructor(chainId, drift = createDrift$1(), publicClient) {
@@ -27444,7 +27447,7 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
27444
27447
  * @returns Transaction response for the buy operation
27445
27448
  */
27446
27449
  async buyCoin(params, version) {
27447
- const coinVersion = version || (await this.getCoinVersion(params.coinAddress));
27450
+ const coinVersion = await this.determineCoinVersion(params.coinAddress, version);
27448
27451
  const sender = await this.drift.getSignerAddress();
27449
27452
  let amountIn;
27450
27453
  let amountOutMin;
@@ -27529,7 +27532,7 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
27529
27532
  * @returns Transaction response for the sell operation
27530
27533
  */
27531
27534
  async sellCoin(params, version) {
27532
- const coinVersion = version || (await this.getCoinVersion(params.coinAddress));
27535
+ const coinVersion = await this.determineCoinVersion(params.coinAddress, version);
27533
27536
  let amountOutMin;
27534
27537
  await this.readQuoter.contract.cache.clear();
27535
27538
  if (params.amountOutMin === undefined) {
@@ -27752,22 +27755,8 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
27752
27755
  let tickLower;
27753
27756
  let tickUpper;
27754
27757
  let currentTick;
27755
- let version = params.version;
27756
- if (!version) {
27757
- try {
27758
- version = await this.getCoinVersion(coinAddress);
27759
- }
27760
- catch {
27761
- version = FlaunchVersion.ANY;
27762
- }
27763
- }
27764
- const poolKey = orderPoolKey({
27765
- currency0: coinAddress,
27766
- currency1: flethAddress,
27767
- fee: 0,
27768
- tickSpacing: this.TICK_SPACING,
27769
- hooks: this.getPositionManagerAddress(version),
27770
- });
27758
+ const version = await this.determineCoinVersion(coinAddress, params.version);
27759
+ const poolKey = this.createPoolKey(coinAddress, version);
27771
27760
  // Check if we need to calculate values or use direct values
27772
27761
  if ("tickLower" in params) {
27773
27762
  // Use the directly provided values
@@ -27796,12 +27785,12 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
27796
27785
  initialMarketCapUSD = params.initialMarketCapUSD;
27797
27786
  }
27798
27787
  else {
27799
- const { totalSupply, decimals } = await this.getCoinInfo(coinAddress);
27800
- const formattedTotalSupply = parseFloat(formatUnits$1(totalSupply, decimals));
27801
- minMarketCap = (parseFloat(params.minPriceUSD) * formattedTotalSupply).toString();
27802
- maxMarketCap = (parseFloat(params.maxPriceUSD) * formattedTotalSupply).toString();
27788
+ const { formattedTotalSupplyInDecimals } = await this.getCoinInfo(coinAddress);
27789
+ minMarketCap = (parseFloat(params.minPriceUSD) * formattedTotalSupplyInDecimals).toString();
27790
+ maxMarketCap = (parseFloat(params.maxPriceUSD) * formattedTotalSupplyInDecimals).toString();
27803
27791
  if (params.initialPriceUSD) {
27804
- initialMarketCapUSD = params.initialPriceUSD * formattedTotalSupply;
27792
+ initialMarketCapUSD =
27793
+ params.initialPriceUSD * formattedTotalSupplyInDecimals;
27805
27794
  }
27806
27795
  }
27807
27796
  const calculated = await this.calculateAddLiquidityAmounts({
@@ -27965,6 +27954,246 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
27965
27954
  // Determine amounts for each currency based on pool key ordering
27966
27955
  const amount0 = poolKey.currency0 === coinAddress ? coinAmount : flethAmount;
27967
27956
  const amount1 = poolKey.currency0 === coinAddress ? flethAmount : coinAmount;
27957
+ // Calculate and constrain liquidity using shared method
27958
+ const { finalLiquidity, finalAmount0, finalAmount1 } = this.calculateConstrainedLiquidity(currentTick, tickLower, tickUpper, amount0, amount1);
27959
+ // 6. Add liquidity
27960
+ calls.push(this.createLiquidityCall(poolKey, tickLower, tickUpper, finalLiquidity, finalAmount0, finalAmount1, userAddress));
27961
+ return calls;
27962
+ }
27963
+ // Implementation with union type for internal use
27964
+ async getImportAndAddLiquidityCalls(params) {
27965
+ let importParams;
27966
+ if ("initialMarketCapUSD" in params) {
27967
+ const paramsWithMarketCap = params;
27968
+ importParams = await this.readWriteTokenImporter.getInitializeParams({
27969
+ coinAddress: paramsWithMarketCap.coinAddress,
27970
+ creatorFeeAllocationPercent: paramsWithMarketCap.creatorFeeAllocationPercent,
27971
+ initialMarketCapUSD: paramsWithMarketCap.initialMarketCapUSD,
27972
+ verifier: paramsWithMarketCap.verifier,
27973
+ });
27974
+ }
27975
+ else {
27976
+ const paramsWithPrice = params;
27977
+ importParams = await this.readWriteTokenImporter.getInitializeParams({
27978
+ coinAddress: paramsWithPrice.coinAddress,
27979
+ creatorFeeAllocationPercent: paramsWithPrice.creatorFeeAllocationPercent,
27980
+ initialPriceUSD: paramsWithPrice.initialPriceUSD,
27981
+ verifier: paramsWithPrice.verifier,
27982
+ });
27983
+ }
27984
+ const addLiquidityCalls = await this.getAddLiquidityCalls({
27985
+ ...params,
27986
+ version: FlaunchVersion.ANY, // optimize to avoid fetching if not passed
27987
+ });
27988
+ return [
27989
+ {
27990
+ to: this.readWriteTokenImporter.contract.address,
27991
+ data: this.readWriteTokenImporter.contract.encodeFunctionData("initialize", importParams),
27992
+ description: "Import Memecoin to Flaunch",
27993
+ },
27994
+ ...addLiquidityCalls,
27995
+ ];
27996
+ }
27997
+ /**
27998
+ * Gets the calls needed to add single-sided liquidity in coin from current tick to infinity
27999
+ * @param params - Parameters for adding single-sided liquidity
28000
+ * @returns Array of calls with descriptions
28001
+ */
28002
+ async getSingleSidedCoinAddLiquidityCalls(params) {
28003
+ const { coinAddress, coinAmount } = params;
28004
+ const version = await this.determineCoinVersion(coinAddress, params.version);
28005
+ const poolKey = this.createPoolKey(coinAddress, version);
28006
+ let currentTick;
28007
+ // if initial marketcap or price is provided, it means that the pool is not initialized yet
28008
+ // so determining the currentTick
28009
+ if (("initialMarketCapUSD" in params && params.initialMarketCapUSD) ||
28010
+ ("initialPriceUSD" in params && params.initialPriceUSD)) {
28011
+ const { decimals: coinDecimals, formattedTotalSupplyInDecimals } = await this.getCoinInfo(coinAddress);
28012
+ // Determine market cap based on provided parameter
28013
+ let initialMarketCapUSD;
28014
+ if ("initialMarketCapUSD" in params && params.initialMarketCapUSD) {
28015
+ initialMarketCapUSD = params.initialMarketCapUSD;
28016
+ }
28017
+ else if ("initialPriceUSD" in params && params.initialPriceUSD) {
28018
+ initialMarketCapUSD =
28019
+ params.initialPriceUSD * formattedTotalSupplyInDecimals;
28020
+ }
28021
+ else {
28022
+ throw new Error("Either initialMarketCapUSD or initialPriceUSD must be provided");
28023
+ }
28024
+ const marketContext = await this.getMarketContext(coinAddress, coinDecimals);
28025
+ const calculatedTick = this.calculateCurrentTickFromMarketCap(initialMarketCapUSD.toString(), formattedTotalSupplyInDecimals, marketContext);
28026
+ if (calculatedTick === undefined) {
28027
+ throw new Error("Failed to calculate current tick from market cap");
28028
+ }
28029
+ currentTick = calculatedTick;
28030
+ }
28031
+ else {
28032
+ // the pool is already initialized, get the current tick from the pool
28033
+ const poolState = await this.readStateView.poolSlot0({
28034
+ poolId: getPoolId(poolKey),
28035
+ });
28036
+ currentTick = poolState.tick;
28037
+ }
28038
+ // We want to add liquidity from current price to infinity (as coin appreciates vs flETH)
28039
+ // This means providing single-sided coin liquidity that becomes active as coin price increases
28040
+ const isFLETHZero = this.flETHIsCurrencyZero(coinAddress);
28041
+ let tickLower;
28042
+ let tickUpper;
28043
+ if (isFLETHZero) {
28044
+ // flETH is currency0, coin is currency1
28045
+ // Price = coin/flETH. As coin appreciates, price and tick increase.
28046
+ // For single-sided coin position, we need the range to end at current tick
28047
+ // so as price increases beyond current, position becomes coin-only
28048
+ tickLower = TickFinder.MIN_TICK;
28049
+ tickUpper = getValidTick({
28050
+ tick: currentTick,
28051
+ tickSpacing: this.TICK_SPACING,
28052
+ roundDown: true,
28053
+ });
28054
+ }
28055
+ else {
28056
+ // coin is currency0, flETH is currency1
28057
+ // Price = flETH/coin. As coin appreciates, price decreases and tick decreases.
28058
+ // For single-sided coin position, we need the range to start at current tick
28059
+ // so as price decreases below current, position becomes coin-only
28060
+ tickLower = getValidTick({
28061
+ tick: currentTick,
28062
+ tickSpacing: this.TICK_SPACING,
28063
+ roundDown: false,
28064
+ });
28065
+ tickUpper = TickFinder.MAX_TICK;
28066
+ }
28067
+ // Fetch approvals via multicall
28068
+ const userAddress = await this.drift.getSignerAddress();
28069
+ const permit2Address = Permit2Address[this.chainId];
28070
+ const results = await this.drift.multicall({
28071
+ calls: [
28072
+ // coin -> permit2
28073
+ {
28074
+ address: coinAddress,
28075
+ abi: erc20Abi,
28076
+ fn: "allowance",
28077
+ args: {
28078
+ owner: userAddress,
28079
+ spender: permit2Address,
28080
+ },
28081
+ },
28082
+ // coin --permit2--> uni position manager
28083
+ {
28084
+ address: permit2Address,
28085
+ abi: Permit2Abi,
28086
+ fn: "allowance",
28087
+ args: {
28088
+ 0: userAddress,
28089
+ 1: coinAddress,
28090
+ 2: UniV4PositionManagerAddress[this.chainId],
28091
+ },
28092
+ },
28093
+ // coin symbol
28094
+ {
28095
+ address: coinAddress,
28096
+ abi: erc20Abi,
28097
+ fn: "symbol",
28098
+ },
28099
+ ],
28100
+ });
28101
+ const coinToPermit2 = results[0].value;
28102
+ const permit2ToUniPosManagerCoinAllowance = results[1].value;
28103
+ const coinSymbol = results[2].value;
28104
+ const needsCoinApproval = coinToPermit2 < coinAmount;
28105
+ const currentTime = Math.floor(Date.now() / 1000);
28106
+ const needsCoinPermit2Approval = permit2ToUniPosManagerCoinAllowance.amount < coinAmount ||
28107
+ permit2ToUniPosManagerCoinAllowance.expiration <= currentTime;
28108
+ const calls = [];
28109
+ // 1. Coin approval to Permit2
28110
+ if (needsCoinApproval) {
28111
+ calls.push({
28112
+ to: coinAddress,
28113
+ description: `Approve ${coinSymbol} for Permit2`,
28114
+ data: encodeFunctionData({
28115
+ abi: erc20Abi,
28116
+ functionName: "approve",
28117
+ args: [permit2Address, coinAmount],
28118
+ }),
28119
+ });
28120
+ }
28121
+ // 2. Permit2 approval for coin to uni position manager
28122
+ const expiration = Math.floor(Date.now() / 1000) + 3600; // 1 hour from now
28123
+ if (needsCoinPermit2Approval) {
28124
+ calls.push({
28125
+ to: permit2Address,
28126
+ description: `Permit2 approval for ${coinSymbol} to UniV4PositionManager`,
28127
+ data: encodeFunctionData({
28128
+ abi: Permit2Abi,
28129
+ functionName: "approve",
28130
+ args: [
28131
+ coinAddress,
28132
+ UniV4PositionManagerAddress[this.chainId],
28133
+ coinAmount,
28134
+ expiration,
28135
+ ],
28136
+ }),
28137
+ });
28138
+ }
28139
+ // === generate add liquidity call ===
28140
+ // Determine amounts for each currency based on pool key ordering
28141
+ const flethAmount = 0n;
28142
+ const amount0 = poolKey.currency0 === coinAddress ? coinAmount : flethAmount;
28143
+ const amount1 = poolKey.currency0 === coinAddress ? flethAmount : coinAmount;
28144
+ // Calculate and constrain liquidity using shared method
28145
+ const { finalLiquidity, finalAmount0, finalAmount1 } = this.calculateConstrainedLiquidity(currentTick, tickLower, tickUpper, amount0, amount1);
28146
+ // 3. Add liquidity
28147
+ calls.push(this.createLiquidityCall(poolKey, tickLower, tickUpper, finalLiquidity, finalAmount0, finalAmount1, userAddress));
28148
+ return calls;
28149
+ }
28150
+ // Implementation with union type for internal use
28151
+ async getImportAndSingleSidedCoinAddLiquidityCalls(params) {
28152
+ let importParams;
28153
+ if ("initialMarketCapUSD" in params) {
28154
+ const paramsWithMarketCap = params;
28155
+ importParams = await this.readWriteTokenImporter.getInitializeParams({
28156
+ coinAddress: paramsWithMarketCap.coinAddress,
28157
+ creatorFeeAllocationPercent: paramsWithMarketCap.creatorFeeAllocationPercent,
28158
+ initialMarketCapUSD: paramsWithMarketCap.initialMarketCapUSD,
28159
+ verifier: paramsWithMarketCap.verifier,
28160
+ });
28161
+ }
28162
+ else {
28163
+ const paramsWithPrice = params;
28164
+ importParams = await this.readWriteTokenImporter.getInitializeParams({
28165
+ coinAddress: paramsWithPrice.coinAddress,
28166
+ creatorFeeAllocationPercent: paramsWithPrice.creatorFeeAllocationPercent,
28167
+ initialPriceUSD: paramsWithPrice.initialPriceUSD,
28168
+ verifier: paramsWithPrice.verifier,
28169
+ });
28170
+ }
28171
+ const addLiquidityCalls = await this.getSingleSidedCoinAddLiquidityCalls({
28172
+ ...params,
28173
+ version: FlaunchVersion.ANY, // optimize to avoid fetching if not passed
28174
+ });
28175
+ return [
28176
+ {
28177
+ to: this.readWriteTokenImporter.contract.address,
28178
+ data: this.readWriteTokenImporter.contract.encodeFunctionData("initialize", importParams),
28179
+ description: "Import Memecoin to Flaunch",
28180
+ },
28181
+ ...addLiquidityCalls,
28182
+ ];
28183
+ }
28184
+ /**
28185
+ * === Private helper functions ===
28186
+ */
28187
+ /**
28188
+ * Calculates and constrains liquidity amounts for a position
28189
+ * @param currentTick - Current pool tick
28190
+ * @param tickLower - Lower tick of the position
28191
+ * @param tickUpper - Upper tick of the position
28192
+ * @param amount0 - Amount of currency0
28193
+ * @param amount1 - Amount of currency1
28194
+ * @returns Final liquidity and amounts
28195
+ */
28196
+ calculateConstrainedLiquidity(currentTick, tickLower, tickUpper, amount0, amount1) {
27968
28197
  // Calculate liquidity first using user's input amounts
27969
28198
  const initialLiquidity = getLiquidityFromAmounts({
27970
28199
  currentTick,
@@ -28030,7 +28259,25 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
28030
28259
  }
28031
28260
  finalAmount0 = amount0; // Use user's full amount as maximum
28032
28261
  finalAmount1 = amount1; // Use user's full amount as maximum
28033
- // Prepare mint position parameters (following swiss-knife pattern)
28262
+ return {
28263
+ finalLiquidity,
28264
+ finalAmount0,
28265
+ finalAmount1,
28266
+ };
28267
+ }
28268
+ /**
28269
+ * Creates the UniV4 Position Manager liquidity call
28270
+ * @param poolKey - The pool key
28271
+ * @param tickLower - Lower tick of the position
28272
+ * @param tickUpper - Upper tick of the position
28273
+ * @param finalLiquidity - Final liquidity amount
28274
+ * @param finalAmount0 - Final amount of currency0
28275
+ * @param finalAmount1 - Final amount of currency1
28276
+ * @param userAddress - User's address
28277
+ * @returns CallWithDescription for adding liquidity
28278
+ */
28279
+ createLiquidityCall(poolKey, tickLower, tickUpper, finalLiquidity, finalAmount0, finalAmount1, userAddress) {
28280
+ // Prepare mint position parameters
28034
28281
  const V4PMActions = {
28035
28282
  MINT_POSITION: "02",
28036
28283
  SETTLE_PAIR: "0d",
@@ -28084,8 +28331,7 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
28084
28331
  currency1: poolKey.currency1,
28085
28332
  },
28086
28333
  ]);
28087
- // 6. Add liquidity
28088
- calls.push({
28334
+ return {
28089
28335
  to: UniV4PositionManagerAddress[this.chainId],
28090
28336
  data: encodeFunctionData({
28091
28337
  abi: [
@@ -28111,33 +28357,7 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
28111
28357
  }),
28112
28358
  value: 0n,
28113
28359
  description: "Add Liquidity",
28114
- });
28115
- return calls;
28116
- }
28117
- /**
28118
- * Gets the calls needed to import a memecoin to Flaunch and add liquidity to AnyPositionManager as a batch
28119
- * @param params - Parameters for importing and adding liquidity
28120
- * @returns Array of calls with descriptions
28121
- */
28122
- async getImportAndAddLiquidityCalls(params) {
28123
- const importParams = await this.readWriteTokenImporter.getInitializeParams({
28124
- coinAddress: params.coinAddress,
28125
- creatorFeeAllocationPercent: params.creatorFeeAllocationPercent,
28126
- initialMarketCapUSD: params.initialMarketCapUSD,
28127
- verifier: params.verifier,
28128
- });
28129
- const addLiquidityCalls = await this.getAddLiquidityCalls({
28130
- ...params,
28131
- version: FlaunchVersion.ANY, // optimize to avoid fetching if not passed
28132
- });
28133
- return [
28134
- {
28135
- to: this.readWriteTokenImporter.contract.address,
28136
- data: this.readWriteTokenImporter.contract.encodeFunctionData("initialize", importParams),
28137
- description: "Import Memecoin to Flaunch",
28138
- },
28139
- ...addLiquidityCalls,
28140
- ];
28360
+ };
28141
28361
  }
28142
28362
  }
28143
28363