@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.cjs.js CHANGED
@@ -25467,6 +25467,10 @@ function maxLiquidityForAmount0Precise(sqrtRatioAX96, sqrtRatioBX96, amount0) {
25467
25467
  if (sqrtRatioAX96 > sqrtRatioBX96) {
25468
25468
  [sqrtRatioAX96, sqrtRatioBX96] = [sqrtRatioBX96, sqrtRatioAX96];
25469
25469
  }
25470
+ // Handle edge case where sqrt ratios are equal (division by zero)
25471
+ if (sqrtRatioAX96 === sqrtRatioBX96) {
25472
+ return 0n;
25473
+ }
25470
25474
  const Q96 = 2n ** 96n;
25471
25475
  const numerator = amount0 * sqrtRatioAX96 * sqrtRatioBX96;
25472
25476
  const denominator = Q96 * (sqrtRatioBX96 - sqrtRatioAX96);
@@ -25483,6 +25487,10 @@ function maxLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1) {
25483
25487
  if (sqrtRatioAX96 > sqrtRatioBX96) {
25484
25488
  [sqrtRatioAX96, sqrtRatioBX96] = [sqrtRatioBX96, sqrtRatioAX96];
25485
25489
  }
25490
+ // Handle edge case where sqrt ratios are equal (division by zero)
25491
+ if (sqrtRatioAX96 === sqrtRatioBX96) {
25492
+ return 0n;
25493
+ }
25486
25494
  const Q96 = 2n ** 96n;
25487
25495
  return (amount1 * Q96) / (sqrtRatioBX96 - sqrtRatioAX96);
25488
25496
  }
@@ -26394,7 +26402,7 @@ class ReadFlaunchSDK {
26394
26402
  * @returns Promise<number> - The current tick of the pool
26395
26403
  */
26396
26404
  async currentTick(coinAddress, version) {
26397
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26405
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26398
26406
  const poolId = await this.poolId(coinAddress, coinVersion);
26399
26407
  const poolState = await this.readStateView.poolSlot0({ poolId });
26400
26408
  return poolState.tick;
@@ -26406,7 +26414,7 @@ class ReadFlaunchSDK {
26406
26414
  * @returns Promise<string> - The price of the coin in ETH with 18 decimals precision
26407
26415
  */
26408
26416
  async coinPriceInETH(coinAddress, version) {
26409
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26417
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26410
26418
  const isFLETHZero = this.flETHIsCurrencyZero(coinAddress);
26411
26419
  const currentTick = await this.currentTick(coinAddress, coinVersion);
26412
26420
  const price = Math.pow(1.0001, currentTick);
@@ -26426,7 +26434,7 @@ class ReadFlaunchSDK {
26426
26434
  * @returns Promise<string> - The price of the coin in USD with 18 decimal precision
26427
26435
  */
26428
26436
  async coinPriceInUSD({ coinAddress, version, drift, }) {
26429
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26437
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26430
26438
  const ethPerCoin = await this.coinPriceInETH(coinAddress, coinVersion);
26431
26439
  const ethPrice = await this.getETHUSDCPrice(drift);
26432
26440
  return (parseFloat(ethPerCoin) * ethPrice).toFixed(18);
@@ -26474,7 +26482,7 @@ class ReadFlaunchSDK {
26474
26482
  * @returns Fair launch information from the appropriate contract version
26475
26483
  */
26476
26484
  async fairLaunchInfo(coinAddress, version) {
26477
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26485
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26478
26486
  const poolId = await this.poolId(coinAddress, coinVersion);
26479
26487
  return this.getFairLaunch(coinVersion).fairLaunchInfo({ poolId });
26480
26488
  }
@@ -26485,12 +26493,12 @@ class ReadFlaunchSDK {
26485
26493
  * @returns Promise<boolean> - True if fair launch is active, false otherwise
26486
26494
  */
26487
26495
  async isFairLaunchActive(coinAddress, version) {
26488
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26496
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26489
26497
  const poolId = await this.poolId(coinAddress, coinVersion);
26490
26498
  return this.getFairLaunch(coinVersion).isFairLaunchActive({ poolId });
26491
26499
  }
26492
26500
  async trustedPoolKeySignerStatus(coinAddress, version) {
26493
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26501
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26494
26502
  if (coinVersion === exports.FlaunchVersion.ANY) {
26495
26503
  throw new Error("AnyPositionManager is not supported for TrustedSigner");
26496
26504
  }
@@ -26539,7 +26547,7 @@ class ReadFlaunchSDK {
26539
26547
  * @returns Promise<number> - The duration in seconds (30 minutes for V1, variable for V1.1)
26540
26548
  */
26541
26549
  async fairLaunchDuration(coinAddress, version) {
26542
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26550
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26543
26551
  const poolId = await this.poolId(coinAddress, coinVersion);
26544
26552
  return this.getFairLaunch(coinVersion).fairLaunchDuration({ poolId });
26545
26553
  }
@@ -26550,7 +26558,7 @@ class ReadFlaunchSDK {
26550
26558
  * @returns Promise<number> - The initial tick value
26551
26559
  */
26552
26560
  async initialTick(coinAddress, version) {
26553
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26561
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26554
26562
  const poolId = await this.poolId(coinAddress, coinVersion);
26555
26563
  const fairLaunchInfo = await this.getFairLaunch(coinVersion).fairLaunchInfo({ poolId });
26556
26564
  return fairLaunchInfo.initialTick;
@@ -26562,7 +26570,7 @@ class ReadFlaunchSDK {
26562
26570
  * @returns Promise<{flETHAmount: bigint, coinAmount: bigint, tickLower: number, tickUpper: number}> - Position details
26563
26571
  */
26564
26572
  async fairLaunchETHOnlyPosition(coinAddress, version) {
26565
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26573
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26566
26574
  const poolId = await this.poolId(coinAddress, coinVersion);
26567
26575
  const initialTick = await this.initialTick(coinAddress, coinVersion);
26568
26576
  const currentTick = await this.currentTick(coinAddress, coinVersion);
@@ -26610,7 +26618,7 @@ class ReadFlaunchSDK {
26610
26618
  * @returns Promise<{flETHAmount: bigint, coinAmount: bigint, tickLower: number, tickUpper: number}> - Position details
26611
26619
  */
26612
26620
  async fairLaunchCoinOnlyPosition(coinAddress, version) {
26613
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26621
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26614
26622
  const poolId = await this.poolId(coinAddress, coinVersion);
26615
26623
  const initialTick = await this.initialTick(coinAddress, coinVersion);
26616
26624
  const currentTick = await this.currentTick(coinAddress, coinVersion);
@@ -26658,7 +26666,7 @@ class ReadFlaunchSDK {
26658
26666
  * @returns Promise<{flETHAmount: bigint, coinAmount: bigint, pendingEth: bigint, tickLower: number, tickUpper: number}> - Bid wall position details
26659
26667
  */
26660
26668
  async bidWallPosition(coinAddress, version) {
26661
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26669
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26662
26670
  const poolId = await this.poolId(coinAddress, coinVersion);
26663
26671
  const isFLETHZero = this.flETHIsCurrencyZero(coinAddress);
26664
26672
  const { amount0_: amount0, amount1_: amount1, pendingEth_: pendingEth, } = await this.getBidWall(coinVersion).position({ poolId });
@@ -26774,13 +26782,8 @@ class ReadFlaunchSDK {
26774
26782
  */
26775
26783
  async poolId(coinAddress, version) {
26776
26784
  let hookAddress;
26777
- if (version) {
26778
- hookAddress = this.getPositionManagerAddress(version);
26779
- }
26780
- else {
26781
- const coinVersion = await this.getCoinVersion(coinAddress);
26782
- hookAddress = this.getPositionManagerAddress(coinVersion);
26783
- }
26785
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26786
+ hookAddress = this.getPositionManagerAddress(coinVersion);
26784
26787
  return getPoolId(orderPoolKey({
26785
26788
  currency0: FLETHAddress[this.chainId],
26786
26789
  currency1: coinAddress,
@@ -26838,7 +26841,7 @@ class ReadFlaunchSDK {
26838
26841
  * @returns Promise<bigint> - The expected amount of ETH to receive
26839
26842
  */
26840
26843
  async getSellQuoteExactInput({ coinAddress, version, amountIn, intermediatePoolKey, }) {
26841
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26844
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26842
26845
  return this.readQuoter.getSellQuoteExactInput({
26843
26846
  coinAddress,
26844
26847
  amountIn,
@@ -26857,7 +26860,7 @@ class ReadFlaunchSDK {
26857
26860
  * @returns Promise<bigint> - The expected amount of coins to receive
26858
26861
  */
26859
26862
  async getBuyQuoteExactInput({ coinAddress, version, amountIn, intermediatePoolKey, hookData, userWallet, }) {
26860
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26863
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26861
26864
  return this.readQuoter.getBuyQuoteExactInput({
26862
26865
  coinAddress,
26863
26866
  amountIn,
@@ -26878,7 +26881,7 @@ class ReadFlaunchSDK {
26878
26881
  * @returns Promise<bigint> - The required amount of ETH or inputToken to spend
26879
26882
  */
26880
26883
  async getBuyQuoteExactOutput({ coinAddress, amountOut, version, intermediatePoolKey, hookData, userWallet, }) {
26881
- const coinVersion = version || (await this.getCoinVersion(coinAddress));
26884
+ const coinVersion = await this.determineCoinVersion(coinAddress, version);
26882
26885
  return this.readQuoter.getBuyQuoteExactOutput({
26883
26886
  coinAddress,
26884
26887
  coinOut: amountOut,
@@ -26936,7 +26939,8 @@ class ReadFlaunchSDK {
26936
26939
  memecoin.totalSupply(),
26937
26940
  memecoin.decimals(),
26938
26941
  ]);
26939
- return { totalSupply, decimals };
26942
+ const formattedTotalSupplyInDecimals = parseFloat(viem.formatUnits(totalSupply, decimals));
26943
+ return { totalSupply, decimals, formattedTotalSupplyInDecimals };
26940
26944
  }
26941
26945
  /**
26942
26946
  * Gets market context information needed for tick calculations
@@ -26958,8 +26962,8 @@ class ReadFlaunchSDK {
26958
26962
  /**
26959
26963
  * Converts market cap in USD to token price in ETH
26960
26964
  */
26961
- marketCapToTokenPriceEth(marketCapUsd, totalSupplyDecimal, ethUsdPrice) {
26962
- const tokenPriceUsd = marketCapUsd / totalSupplyDecimal;
26965
+ marketCapToTokenPriceEth(marketCapUsd, formattedTotalSupplyInDecimals, ethUsdPrice) {
26966
+ const tokenPriceUsd = marketCapUsd / formattedTotalSupplyInDecimals;
26963
26967
  return tokenPriceUsd / ethUsdPrice;
26964
26968
  }
26965
26969
  /**
@@ -26977,24 +26981,22 @@ class ReadFlaunchSDK {
26977
26981
  /**
26978
26982
  * Calculates current tick from market cap if provided
26979
26983
  */
26980
- calculateCurrentTickFromMarketCap(currentMarketCap, totalSupplyDecimal, marketContext) {
26984
+ calculateCurrentTickFromMarketCap(currentMarketCap, formattedTotalSupplyInDecimals, marketContext) {
26981
26985
  if (!currentMarketCap) {
26982
26986
  return undefined;
26983
26987
  }
26984
26988
  const currentMarketCapNum = parseFloat(currentMarketCap);
26985
- const currentTokenPriceEth = this.marketCapToTokenPriceEth(currentMarketCapNum, totalSupplyDecimal, marketContext.ethUsdPrice);
26989
+ const currentTokenPriceEth = this.marketCapToTokenPriceEth(currentMarketCapNum, formattedTotalSupplyInDecimals, marketContext.ethUsdPrice);
26986
26990
  return this.convertPriceToTick(currentTokenPriceEth, marketContext.isFlethZero, marketContext.decimals0, marketContext.decimals1);
26987
26991
  }
26988
26992
  async calculateAddLiquidityTicks({ coinAddress, liquidityMode, minMarketCap, maxMarketCap, currentMarketCap, }) {
26989
26993
  // Get coin information
26990
- const { totalSupply: coinTotalSupply, decimals: coinDecimals } = await this.getCoinInfo(coinAddress);
26991
- // Convert total supply to decimal format
26992
- const totalSupplyDecimal = parseFloat(viem.formatEther(coinTotalSupply));
26994
+ const { totalSupply: coinTotalSupply, decimals: coinDecimals, formattedTotalSupplyInDecimals, } = await this.getCoinInfo(coinAddress);
26993
26995
  if (liquidityMode === exports.LiquidityMode.FULL_RANGE) {
26994
26996
  let currentTick;
26995
26997
  if (currentMarketCap) {
26996
26998
  const marketContext = await this.getMarketContext(coinAddress, coinDecimals);
26997
- currentTick = this.calculateCurrentTickFromMarketCap(currentMarketCap, totalSupplyDecimal, marketContext);
26999
+ currentTick = this.calculateCurrentTickFromMarketCap(currentMarketCap, formattedTotalSupplyInDecimals, marketContext);
26998
27000
  }
26999
27001
  return {
27000
27002
  tickLower: getNearestUsableTick({
@@ -27021,13 +27023,13 @@ class ReadFlaunchSDK {
27021
27023
  throw new Error("[ReadFlaunchSDK.addLiquidityCalculateTicks]: Invalid market cap range");
27022
27024
  }
27023
27025
  // Convert market caps to token prices in ETH
27024
- const minTokenPriceEth = this.marketCapToTokenPriceEth(minMarketCapNum, totalSupplyDecimal, marketContext.ethUsdPrice);
27025
- const maxTokenPriceEth = this.marketCapToTokenPriceEth(maxMarketCapNum, totalSupplyDecimal, marketContext.ethUsdPrice);
27026
+ const minTokenPriceEth = this.marketCapToTokenPriceEth(minMarketCapNum, formattedTotalSupplyInDecimals, marketContext.ethUsdPrice);
27027
+ const maxTokenPriceEth = this.marketCapToTokenPriceEth(maxMarketCapNum, formattedTotalSupplyInDecimals, marketContext.ethUsdPrice);
27026
27028
  // Convert to ticks
27027
27029
  const minTick = this.convertPriceToTick(minTokenPriceEth, marketContext.isFlethZero, marketContext.decimals0, marketContext.decimals1);
27028
27030
  const maxTick = this.convertPriceToTick(maxTokenPriceEth, marketContext.isFlethZero, marketContext.decimals0, marketContext.decimals1);
27029
27031
  // Calculate current tick if provided
27030
- const currentTick = this.calculateCurrentTickFromMarketCap(currentMarketCap, totalSupplyDecimal, marketContext);
27032
+ const currentTick = this.calculateCurrentTickFromMarketCap(currentMarketCap, formattedTotalSupplyInDecimals, marketContext);
27031
27033
  return {
27032
27034
  tickLower: Math.min(minTick, maxTick),
27033
27035
  tickUpper: Math.max(minTick, maxTick),
@@ -27048,12 +27050,11 @@ class ReadFlaunchSDK {
27048
27050
  currentMarketCap = params.currentMarketCap;
27049
27051
  }
27050
27052
  else {
27051
- const { totalSupply, decimals } = await this.getCoinInfo(coinAddress);
27052
- const formattedTotalSupply = parseFloat(viem.formatUnits(totalSupply, decimals));
27053
- minMarketCap = (parseFloat(params.minPriceUSD) * formattedTotalSupply).toString();
27054
- maxMarketCap = (parseFloat(params.maxPriceUSD) * formattedTotalSupply).toString();
27053
+ const { formattedTotalSupplyInDecimals } = await this.getCoinInfo(coinAddress);
27054
+ minMarketCap = (parseFloat(params.minPriceUSD) * formattedTotalSupplyInDecimals).toString();
27055
+ maxMarketCap = (parseFloat(params.maxPriceUSD) * formattedTotalSupplyInDecimals).toString();
27055
27056
  if (params.currentPriceUSD) {
27056
- currentMarketCap = (params.currentPriceUSD * formattedTotalSupply).toString();
27057
+ currentMarketCap = (params.currentPriceUSD * formattedTotalSupplyInDecimals).toString();
27057
27058
  }
27058
27059
  }
27059
27060
  let { tickLower, tickUpper, currentTick } = await this.calculateAddLiquidityTicks({
@@ -27065,24 +27066,9 @@ class ReadFlaunchSDK {
27065
27066
  });
27066
27067
  // If no current tick is provided from the above calculation, get it from the pool state
27067
27068
  if (!currentTick) {
27068
- let version = params.version;
27069
- // if version is not provided, check on existing managers, else default to ANY
27070
- if (!version) {
27071
- try {
27072
- version = await this.getCoinVersion(coinAddress);
27073
- }
27074
- catch {
27075
- version = exports.FlaunchVersion.ANY;
27076
- }
27077
- }
27069
+ const version = await this.determineCoinVersion(coinAddress, params.version);
27078
27070
  const poolState = await this.readStateView.poolSlot0({
27079
- poolId: getPoolId(orderPoolKey({
27080
- currency0: coinAddress,
27081
- currency1: FLETHAddress[this.chainId],
27082
- fee: 0,
27083
- tickSpacing: TICK_SPACING,
27084
- hooks: this.getPositionManagerAddress(version),
27085
- })),
27071
+ poolId: getPoolId(this.createPoolKey(coinAddress, version)),
27086
27072
  });
27087
27073
  currentTick = poolState.tick;
27088
27074
  }
@@ -27139,12 +27125,11 @@ class ReadFlaunchSDK {
27139
27125
  currentMarketCap = params.currentMarketCap;
27140
27126
  }
27141
27127
  else {
27142
- const { totalSupply, decimals } = await this.getCoinInfo(coinAddress);
27143
- const formattedTotalSupply = parseFloat(viem.formatUnits(totalSupply, decimals));
27144
- minMarketCap = (parseFloat(params.minPriceUSD) * formattedTotalSupply).toString();
27145
- maxMarketCap = (parseFloat(params.maxPriceUSD) * formattedTotalSupply).toString();
27128
+ const { formattedTotalSupplyInDecimals } = await this.getCoinInfo(coinAddress);
27129
+ minMarketCap = (parseFloat(params.minPriceUSD) * formattedTotalSupplyInDecimals).toString();
27130
+ maxMarketCap = (parseFloat(params.maxPriceUSD) * formattedTotalSupplyInDecimals).toString();
27146
27131
  if (params.currentPriceUSD) {
27147
- currentMarketCap = (params.currentPriceUSD * formattedTotalSupply).toString();
27132
+ currentMarketCap = (params.currentPriceUSD * formattedTotalSupplyInDecimals).toString();
27148
27133
  }
27149
27134
  }
27150
27135
  let { tickLower, tickUpper, currentTick } = await this.calculateAddLiquidityTicks({
@@ -27156,24 +27141,9 @@ class ReadFlaunchSDK {
27156
27141
  });
27157
27142
  // get the current pool state for the coin
27158
27143
  if (!currentTick) {
27159
- let version = params.version;
27160
- // if version is not provided, check on existing managers, else default to ANY
27161
- if (!version) {
27162
- try {
27163
- version = await this.getCoinVersion(coinAddress);
27164
- }
27165
- catch {
27166
- version = exports.FlaunchVersion.ANY;
27167
- }
27168
- }
27144
+ const version = await this.determineCoinVersion(coinAddress, params.version);
27169
27145
  const poolState = await this.readStateView.poolSlot0({
27170
- poolId: getPoolId(orderPoolKey({
27171
- currency0: coinAddress,
27172
- currency1: FLETHAddress[this.chainId],
27173
- fee: 0,
27174
- tickSpacing: TICK_SPACING,
27175
- hooks: this.getPositionManagerAddress(version),
27176
- })),
27146
+ poolId: getPoolId(this.createPoolKey(coinAddress, version)),
27177
27147
  });
27178
27148
  currentTick = poolState.tick;
27179
27149
  }
@@ -27328,6 +27298,39 @@ class ReadFlaunchSDK {
27328
27298
  args: { owner, operator },
27329
27299
  });
27330
27300
  }
27301
+ /**
27302
+ * Determines the version for a coin, using provided version or fetching it
27303
+ * @param coinAddress - The coin address
27304
+ * @param version - Optional version, if not provided will be fetched
27305
+ * @returns The determined version
27306
+ */
27307
+ async determineCoinVersion(coinAddress, version) {
27308
+ if (!version) {
27309
+ try {
27310
+ version = await this.getCoinVersion(coinAddress);
27311
+ }
27312
+ catch {
27313
+ version = exports.FlaunchVersion.ANY;
27314
+ }
27315
+ }
27316
+ return version;
27317
+ }
27318
+ /**
27319
+ * Creates a pool key for the given coin and version
27320
+ * @param coinAddress - The coin address
27321
+ * @param version - The version to use for position manager
27322
+ * @returns The ordered pool key
27323
+ */
27324
+ createPoolKey(coinAddress, version) {
27325
+ const flethAddress = FLETHAddress[this.chainId];
27326
+ return orderPoolKey({
27327
+ currency0: coinAddress,
27328
+ currency1: flethAddress,
27329
+ fee: 0,
27330
+ tickSpacing: this.TICK_SPACING,
27331
+ hooks: this.getPositionManagerAddress(version),
27332
+ });
27333
+ }
27331
27334
  }
27332
27335
  class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
27333
27336
  constructor(chainId, drift$1 = drift.createDrift(), publicClient) {
@@ -27452,7 +27455,7 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
27452
27455
  * @returns Transaction response for the buy operation
27453
27456
  */
27454
27457
  async buyCoin(params, version) {
27455
- const coinVersion = version || (await this.getCoinVersion(params.coinAddress));
27458
+ const coinVersion = await this.determineCoinVersion(params.coinAddress, version);
27456
27459
  const sender = await this.drift.getSignerAddress();
27457
27460
  let amountIn;
27458
27461
  let amountOutMin;
@@ -27537,7 +27540,7 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
27537
27540
  * @returns Transaction response for the sell operation
27538
27541
  */
27539
27542
  async sellCoin(params, version) {
27540
- const coinVersion = version || (await this.getCoinVersion(params.coinAddress));
27543
+ const coinVersion = await this.determineCoinVersion(params.coinAddress, version);
27541
27544
  let amountOutMin;
27542
27545
  await this.readQuoter.contract.cache.clear();
27543
27546
  if (params.amountOutMin === undefined) {
@@ -27760,22 +27763,8 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
27760
27763
  let tickLower;
27761
27764
  let tickUpper;
27762
27765
  let currentTick;
27763
- let version = params.version;
27764
- if (!version) {
27765
- try {
27766
- version = await this.getCoinVersion(coinAddress);
27767
- }
27768
- catch {
27769
- version = exports.FlaunchVersion.ANY;
27770
- }
27771
- }
27772
- const poolKey = orderPoolKey({
27773
- currency0: coinAddress,
27774
- currency1: flethAddress,
27775
- fee: 0,
27776
- tickSpacing: this.TICK_SPACING,
27777
- hooks: this.getPositionManagerAddress(version),
27778
- });
27766
+ const version = await this.determineCoinVersion(coinAddress, params.version);
27767
+ const poolKey = this.createPoolKey(coinAddress, version);
27779
27768
  // Check if we need to calculate values or use direct values
27780
27769
  if ("tickLower" in params) {
27781
27770
  // Use the directly provided values
@@ -27804,12 +27793,12 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
27804
27793
  initialMarketCapUSD = params.initialMarketCapUSD;
27805
27794
  }
27806
27795
  else {
27807
- const { totalSupply, decimals } = await this.getCoinInfo(coinAddress);
27808
- const formattedTotalSupply = parseFloat(viem.formatUnits(totalSupply, decimals));
27809
- minMarketCap = (parseFloat(params.minPriceUSD) * formattedTotalSupply).toString();
27810
- maxMarketCap = (parseFloat(params.maxPriceUSD) * formattedTotalSupply).toString();
27796
+ const { formattedTotalSupplyInDecimals } = await this.getCoinInfo(coinAddress);
27797
+ minMarketCap = (parseFloat(params.minPriceUSD) * formattedTotalSupplyInDecimals).toString();
27798
+ maxMarketCap = (parseFloat(params.maxPriceUSD) * formattedTotalSupplyInDecimals).toString();
27811
27799
  if (params.initialPriceUSD) {
27812
- initialMarketCapUSD = params.initialPriceUSD * formattedTotalSupply;
27800
+ initialMarketCapUSD =
27801
+ params.initialPriceUSD * formattedTotalSupplyInDecimals;
27813
27802
  }
27814
27803
  }
27815
27804
  const calculated = await this.calculateAddLiquidityAmounts({
@@ -27973,6 +27962,246 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
27973
27962
  // Determine amounts for each currency based on pool key ordering
27974
27963
  const amount0 = poolKey.currency0 === coinAddress ? coinAmount : flethAmount;
27975
27964
  const amount1 = poolKey.currency0 === coinAddress ? flethAmount : coinAmount;
27965
+ // Calculate and constrain liquidity using shared method
27966
+ const { finalLiquidity, finalAmount0, finalAmount1 } = this.calculateConstrainedLiquidity(currentTick, tickLower, tickUpper, amount0, amount1);
27967
+ // 6. Add liquidity
27968
+ calls.push(this.createLiquidityCall(poolKey, tickLower, tickUpper, finalLiquidity, finalAmount0, finalAmount1, userAddress));
27969
+ return calls;
27970
+ }
27971
+ // Implementation with union type for internal use
27972
+ async getImportAndAddLiquidityCalls(params) {
27973
+ let importParams;
27974
+ if ("initialMarketCapUSD" in params) {
27975
+ const paramsWithMarketCap = params;
27976
+ importParams = await this.readWriteTokenImporter.getInitializeParams({
27977
+ coinAddress: paramsWithMarketCap.coinAddress,
27978
+ creatorFeeAllocationPercent: paramsWithMarketCap.creatorFeeAllocationPercent,
27979
+ initialMarketCapUSD: paramsWithMarketCap.initialMarketCapUSD,
27980
+ verifier: paramsWithMarketCap.verifier,
27981
+ });
27982
+ }
27983
+ else {
27984
+ const paramsWithPrice = params;
27985
+ importParams = await this.readWriteTokenImporter.getInitializeParams({
27986
+ coinAddress: paramsWithPrice.coinAddress,
27987
+ creatorFeeAllocationPercent: paramsWithPrice.creatorFeeAllocationPercent,
27988
+ initialPriceUSD: paramsWithPrice.initialPriceUSD,
27989
+ verifier: paramsWithPrice.verifier,
27990
+ });
27991
+ }
27992
+ const addLiquidityCalls = await this.getAddLiquidityCalls({
27993
+ ...params,
27994
+ version: exports.FlaunchVersion.ANY, // optimize to avoid fetching if not passed
27995
+ });
27996
+ return [
27997
+ {
27998
+ to: this.readWriteTokenImporter.contract.address,
27999
+ data: this.readWriteTokenImporter.contract.encodeFunctionData("initialize", importParams),
28000
+ description: "Import Memecoin to Flaunch",
28001
+ },
28002
+ ...addLiquidityCalls,
28003
+ ];
28004
+ }
28005
+ /**
28006
+ * Gets the calls needed to add single-sided liquidity in coin from current tick to infinity
28007
+ * @param params - Parameters for adding single-sided liquidity
28008
+ * @returns Array of calls with descriptions
28009
+ */
28010
+ async getSingleSidedCoinAddLiquidityCalls(params) {
28011
+ const { coinAddress, coinAmount } = params;
28012
+ const version = await this.determineCoinVersion(coinAddress, params.version);
28013
+ const poolKey = this.createPoolKey(coinAddress, version);
28014
+ let currentTick;
28015
+ // if initial marketcap or price is provided, it means that the pool is not initialized yet
28016
+ // so determining the currentTick
28017
+ if (("initialMarketCapUSD" in params && params.initialMarketCapUSD) ||
28018
+ ("initialPriceUSD" in params && params.initialPriceUSD)) {
28019
+ const { decimals: coinDecimals, formattedTotalSupplyInDecimals } = await this.getCoinInfo(coinAddress);
28020
+ // Determine market cap based on provided parameter
28021
+ let initialMarketCapUSD;
28022
+ if ("initialMarketCapUSD" in params && params.initialMarketCapUSD) {
28023
+ initialMarketCapUSD = params.initialMarketCapUSD;
28024
+ }
28025
+ else if ("initialPriceUSD" in params && params.initialPriceUSD) {
28026
+ initialMarketCapUSD =
28027
+ params.initialPriceUSD * formattedTotalSupplyInDecimals;
28028
+ }
28029
+ else {
28030
+ throw new Error("Either initialMarketCapUSD or initialPriceUSD must be provided");
28031
+ }
28032
+ const marketContext = await this.getMarketContext(coinAddress, coinDecimals);
28033
+ const calculatedTick = this.calculateCurrentTickFromMarketCap(initialMarketCapUSD.toString(), formattedTotalSupplyInDecimals, marketContext);
28034
+ if (calculatedTick === undefined) {
28035
+ throw new Error("Failed to calculate current tick from market cap");
28036
+ }
28037
+ currentTick = calculatedTick;
28038
+ }
28039
+ else {
28040
+ // the pool is already initialized, get the current tick from the pool
28041
+ const poolState = await this.readStateView.poolSlot0({
28042
+ poolId: getPoolId(poolKey),
28043
+ });
28044
+ currentTick = poolState.tick;
28045
+ }
28046
+ // We want to add liquidity from current price to infinity (as coin appreciates vs flETH)
28047
+ // This means providing single-sided coin liquidity that becomes active as coin price increases
28048
+ const isFLETHZero = this.flETHIsCurrencyZero(coinAddress);
28049
+ let tickLower;
28050
+ let tickUpper;
28051
+ if (isFLETHZero) {
28052
+ // flETH is currency0, coin is currency1
28053
+ // Price = coin/flETH. As coin appreciates, price and tick increase.
28054
+ // For single-sided coin position, we need the range to end at current tick
28055
+ // so as price increases beyond current, position becomes coin-only
28056
+ tickLower = TickFinder.MIN_TICK;
28057
+ tickUpper = getValidTick({
28058
+ tick: currentTick,
28059
+ tickSpacing: this.TICK_SPACING,
28060
+ roundDown: true,
28061
+ });
28062
+ }
28063
+ else {
28064
+ // coin is currency0, flETH is currency1
28065
+ // Price = flETH/coin. As coin appreciates, price decreases and tick decreases.
28066
+ // For single-sided coin position, we need the range to start at current tick
28067
+ // so as price decreases below current, position becomes coin-only
28068
+ tickLower = getValidTick({
28069
+ tick: currentTick,
28070
+ tickSpacing: this.TICK_SPACING,
28071
+ roundDown: false,
28072
+ });
28073
+ tickUpper = TickFinder.MAX_TICK;
28074
+ }
28075
+ // Fetch approvals via multicall
28076
+ const userAddress = await this.drift.getSignerAddress();
28077
+ const permit2Address = Permit2Address[this.chainId];
28078
+ const results = await this.drift.multicall({
28079
+ calls: [
28080
+ // coin -> permit2
28081
+ {
28082
+ address: coinAddress,
28083
+ abi: viem.erc20Abi,
28084
+ fn: "allowance",
28085
+ args: {
28086
+ owner: userAddress,
28087
+ spender: permit2Address,
28088
+ },
28089
+ },
28090
+ // coin --permit2--> uni position manager
28091
+ {
28092
+ address: permit2Address,
28093
+ abi: Permit2Abi,
28094
+ fn: "allowance",
28095
+ args: {
28096
+ 0: userAddress,
28097
+ 1: coinAddress,
28098
+ 2: UniV4PositionManagerAddress[this.chainId],
28099
+ },
28100
+ },
28101
+ // coin symbol
28102
+ {
28103
+ address: coinAddress,
28104
+ abi: viem.erc20Abi,
28105
+ fn: "symbol",
28106
+ },
28107
+ ],
28108
+ });
28109
+ const coinToPermit2 = results[0].value;
28110
+ const permit2ToUniPosManagerCoinAllowance = results[1].value;
28111
+ const coinSymbol = results[2].value;
28112
+ const needsCoinApproval = coinToPermit2 < coinAmount;
28113
+ const currentTime = Math.floor(Date.now() / 1000);
28114
+ const needsCoinPermit2Approval = permit2ToUniPosManagerCoinAllowance.amount < coinAmount ||
28115
+ permit2ToUniPosManagerCoinAllowance.expiration <= currentTime;
28116
+ const calls = [];
28117
+ // 1. Coin approval to Permit2
28118
+ if (needsCoinApproval) {
28119
+ calls.push({
28120
+ to: coinAddress,
28121
+ description: `Approve ${coinSymbol} for Permit2`,
28122
+ data: viem.encodeFunctionData({
28123
+ abi: viem.erc20Abi,
28124
+ functionName: "approve",
28125
+ args: [permit2Address, coinAmount],
28126
+ }),
28127
+ });
28128
+ }
28129
+ // 2. Permit2 approval for coin to uni position manager
28130
+ const expiration = Math.floor(Date.now() / 1000) + 3600; // 1 hour from now
28131
+ if (needsCoinPermit2Approval) {
28132
+ calls.push({
28133
+ to: permit2Address,
28134
+ description: `Permit2 approval for ${coinSymbol} to UniV4PositionManager`,
28135
+ data: viem.encodeFunctionData({
28136
+ abi: Permit2Abi,
28137
+ functionName: "approve",
28138
+ args: [
28139
+ coinAddress,
28140
+ UniV4PositionManagerAddress[this.chainId],
28141
+ coinAmount,
28142
+ expiration,
28143
+ ],
28144
+ }),
28145
+ });
28146
+ }
28147
+ // === generate add liquidity call ===
28148
+ // Determine amounts for each currency based on pool key ordering
28149
+ const flethAmount = 0n;
28150
+ const amount0 = poolKey.currency0 === coinAddress ? coinAmount : flethAmount;
28151
+ const amount1 = poolKey.currency0 === coinAddress ? flethAmount : coinAmount;
28152
+ // Calculate and constrain liquidity using shared method
28153
+ const { finalLiquidity, finalAmount0, finalAmount1 } = this.calculateConstrainedLiquidity(currentTick, tickLower, tickUpper, amount0, amount1);
28154
+ // 3. Add liquidity
28155
+ calls.push(this.createLiquidityCall(poolKey, tickLower, tickUpper, finalLiquidity, finalAmount0, finalAmount1, userAddress));
28156
+ return calls;
28157
+ }
28158
+ // Implementation with union type for internal use
28159
+ async getImportAndSingleSidedCoinAddLiquidityCalls(params) {
28160
+ let importParams;
28161
+ if ("initialMarketCapUSD" in params) {
28162
+ const paramsWithMarketCap = params;
28163
+ importParams = await this.readWriteTokenImporter.getInitializeParams({
28164
+ coinAddress: paramsWithMarketCap.coinAddress,
28165
+ creatorFeeAllocationPercent: paramsWithMarketCap.creatorFeeAllocationPercent,
28166
+ initialMarketCapUSD: paramsWithMarketCap.initialMarketCapUSD,
28167
+ verifier: paramsWithMarketCap.verifier,
28168
+ });
28169
+ }
28170
+ else {
28171
+ const paramsWithPrice = params;
28172
+ importParams = await this.readWriteTokenImporter.getInitializeParams({
28173
+ coinAddress: paramsWithPrice.coinAddress,
28174
+ creatorFeeAllocationPercent: paramsWithPrice.creatorFeeAllocationPercent,
28175
+ initialPriceUSD: paramsWithPrice.initialPriceUSD,
28176
+ verifier: paramsWithPrice.verifier,
28177
+ });
28178
+ }
28179
+ const addLiquidityCalls = await this.getSingleSidedCoinAddLiquidityCalls({
28180
+ ...params,
28181
+ version: exports.FlaunchVersion.ANY, // optimize to avoid fetching if not passed
28182
+ });
28183
+ return [
28184
+ {
28185
+ to: this.readWriteTokenImporter.contract.address,
28186
+ data: this.readWriteTokenImporter.contract.encodeFunctionData("initialize", importParams),
28187
+ description: "Import Memecoin to Flaunch",
28188
+ },
28189
+ ...addLiquidityCalls,
28190
+ ];
28191
+ }
28192
+ /**
28193
+ * === Private helper functions ===
28194
+ */
28195
+ /**
28196
+ * Calculates and constrains liquidity amounts for a position
28197
+ * @param currentTick - Current pool tick
28198
+ * @param tickLower - Lower tick of the position
28199
+ * @param tickUpper - Upper tick of the position
28200
+ * @param amount0 - Amount of currency0
28201
+ * @param amount1 - Amount of currency1
28202
+ * @returns Final liquidity and amounts
28203
+ */
28204
+ calculateConstrainedLiquidity(currentTick, tickLower, tickUpper, amount0, amount1) {
27976
28205
  // Calculate liquidity first using user's input amounts
27977
28206
  const initialLiquidity = getLiquidityFromAmounts({
27978
28207
  currentTick,
@@ -28038,7 +28267,25 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
28038
28267
  }
28039
28268
  finalAmount0 = amount0; // Use user's full amount as maximum
28040
28269
  finalAmount1 = amount1; // Use user's full amount as maximum
28041
- // Prepare mint position parameters (following swiss-knife pattern)
28270
+ return {
28271
+ finalLiquidity,
28272
+ finalAmount0,
28273
+ finalAmount1,
28274
+ };
28275
+ }
28276
+ /**
28277
+ * Creates the UniV4 Position Manager liquidity call
28278
+ * @param poolKey - The pool key
28279
+ * @param tickLower - Lower tick of the position
28280
+ * @param tickUpper - Upper tick of the position
28281
+ * @param finalLiquidity - Final liquidity amount
28282
+ * @param finalAmount0 - Final amount of currency0
28283
+ * @param finalAmount1 - Final amount of currency1
28284
+ * @param userAddress - User's address
28285
+ * @returns CallWithDescription for adding liquidity
28286
+ */
28287
+ createLiquidityCall(poolKey, tickLower, tickUpper, finalLiquidity, finalAmount0, finalAmount1, userAddress) {
28288
+ // Prepare mint position parameters
28042
28289
  const V4PMActions = {
28043
28290
  MINT_POSITION: "02",
28044
28291
  SETTLE_PAIR: "0d",
@@ -28092,8 +28339,7 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
28092
28339
  currency1: poolKey.currency1,
28093
28340
  },
28094
28341
  ]);
28095
- // 6. Add liquidity
28096
- calls.push({
28342
+ return {
28097
28343
  to: UniV4PositionManagerAddress[this.chainId],
28098
28344
  data: viem.encodeFunctionData({
28099
28345
  abi: [
@@ -28119,33 +28365,7 @@ class ReadWriteFlaunchSDK extends ReadFlaunchSDK {
28119
28365
  }),
28120
28366
  value: 0n,
28121
28367
  description: "Add Liquidity",
28122
- });
28123
- return calls;
28124
- }
28125
- /**
28126
- * Gets the calls needed to import a memecoin to Flaunch and add liquidity to AnyPositionManager as a batch
28127
- * @param params - Parameters for importing and adding liquidity
28128
- * @returns Array of calls with descriptions
28129
- */
28130
- async getImportAndAddLiquidityCalls(params) {
28131
- const importParams = await this.readWriteTokenImporter.getInitializeParams({
28132
- coinAddress: params.coinAddress,
28133
- creatorFeeAllocationPercent: params.creatorFeeAllocationPercent,
28134
- initialMarketCapUSD: params.initialMarketCapUSD,
28135
- verifier: params.verifier,
28136
- });
28137
- const addLiquidityCalls = await this.getAddLiquidityCalls({
28138
- ...params,
28139
- version: exports.FlaunchVersion.ANY, // optimize to avoid fetching if not passed
28140
- });
28141
- return [
28142
- {
28143
- to: this.readWriteTokenImporter.contract.address,
28144
- data: this.readWriteTokenImporter.contract.encodeFunctionData("initialize", importParams),
28145
- description: "Import Memecoin to Flaunch",
28146
- },
28147
- ...addLiquidityCalls,
28148
- ];
28368
+ };
28149
28369
  }
28150
28370
  }
28151
28371