@meteora-ag/dlmm 1.3.3 → 1.3.5

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.mjs CHANGED
@@ -1,11 +1,27 @@
1
1
  // src/dlmm/index.ts
2
+ import { AnchorProvider as AnchorProvider2, BN as BN10, Program as Program3 } from "@coral-xyz/anchor";
3
+ import { bs58 } from "@coral-xyz/anchor/dist/cjs/utils/bytes";
2
4
  import {
5
+ AccountLayout,
6
+ MintLayout,
7
+ NATIVE_MINT as NATIVE_MINT2,
8
+ TOKEN_PROGRAM_ID as TOKEN_PROGRAM_ID2,
9
+ createAssociatedTokenAccountInstruction as createAssociatedTokenAccountInstruction2,
10
+ createTransferInstruction,
11
+ getAssociatedTokenAddressSync as getAssociatedTokenAddressSync2
12
+ } from "@solana/spl-token";
13
+ import {
14
+ ComputeBudgetProgram as ComputeBudgetProgram2,
3
15
  PublicKey as PublicKey6,
4
- Transaction,
16
+ SYSVAR_CLOCK_PUBKEY,
5
17
  SYSVAR_RENT_PUBKEY,
6
18
  SystemProgram as SystemProgram2,
7
- SYSVAR_CLOCK_PUBKEY
19
+ Transaction
8
20
  } from "@solana/web3.js";
21
+ import Decimal5 from "decimal.js";
22
+
23
+ // src/dlmm/constants/index.ts
24
+ import { PublicKey } from "@solana/web3.js";
9
25
 
10
26
  // src/dlmm/idl.ts
11
27
  var IDL = {
@@ -5259,7 +5275,6 @@ var IDL = {
5259
5275
  };
5260
5276
 
5261
5277
  // src/dlmm/constants/index.ts
5262
- import { PublicKey } from "@solana/web3.js";
5263
5278
  import { BN } from "@coral-xyz/anchor";
5264
5279
  var LBCLMM_PROGRAM_IDS = {
5265
5280
  devnet: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo",
@@ -5309,66 +5324,48 @@ var ILM_BASE = new PublicKey(
5309
5324
  "MFGQxwAmB91SwuYX36okv2Qmdc9aMuHTwWGUrp4AtB1"
5310
5325
  );
5311
5326
 
5312
- // src/dlmm/types/index.ts
5313
- import { u64, i64, struct } from "@coral-xyz/borsh";
5314
- var PositionVersion = /* @__PURE__ */ ((PositionVersion2) => {
5315
- PositionVersion2[PositionVersion2["V1"] = 0] = "V1";
5316
- PositionVersion2[PositionVersion2["V2"] = 1] = "V2";
5317
- return PositionVersion2;
5318
- })(PositionVersion || {});
5319
- var PairType = /* @__PURE__ */ ((PairType2) => {
5320
- PairType2[PairType2["Permissionless"] = 0] = "Permissionless";
5321
- PairType2[PairType2["Permissioned"] = 1] = "Permissioned";
5322
- return PairType2;
5323
- })(PairType || {});
5324
- var Strategy = {
5325
- SpotOneSide: { spotOneSide: {} },
5326
- CurveOneSide: { curveOneSide: {} },
5327
- BidAskOneSide: { bidAskOneSide: {} },
5328
- SpotBalanced: { spotBalanced: {} },
5329
- CurveBalanced: { curveBalanced: {} },
5330
- BidAskBalanced: { bidAskBalanced: {} },
5331
- SpotImBalanced: { spotImBalanced: {} },
5332
- CurveImBalanced: { curveImBalanced: {} },
5333
- BidAskImBalanced: { bidAskImBalanced: {} }
5327
+ // src/dlmm/error.ts
5328
+ import { AnchorError } from "@coral-xyz/anchor";
5329
+ var DLMMError = class extends Error {
5330
+ errorCode;
5331
+ errorName;
5332
+ errorMessage;
5333
+ constructor(error) {
5334
+ let _errorCode = 0;
5335
+ let _errorName = "Something went wrong";
5336
+ let _errorMessage = "Something went wrong";
5337
+ if (error instanceof Error) {
5338
+ const anchorError = AnchorError.parse(
5339
+ JSON.parse(JSON.stringify(error)).logs
5340
+ );
5341
+ if (anchorError?.program.toBase58() === LBCLMM_PROGRAM_IDS["mainnet-beta"]) {
5342
+ _errorCode = anchorError.error.errorCode.number;
5343
+ _errorName = anchorError.error.errorCode.code;
5344
+ _errorMessage = anchorError.error.errorMessage;
5345
+ }
5346
+ } else {
5347
+ const idlError = IDL.errors.find((err) => err.code === error);
5348
+ if (idlError) {
5349
+ _errorCode = idlError.code;
5350
+ _errorName = idlError.name;
5351
+ _errorMessage = idlError.msg;
5352
+ }
5353
+ }
5354
+ super(_errorMessage);
5355
+ this.errorCode = _errorCode;
5356
+ this.errorName = _errorName;
5357
+ this.errorMessage = _errorMessage;
5358
+ }
5359
+ };
5360
+ var DlmmSdkError = class extends Error {
5361
+ name;
5362
+ message;
5363
+ constructor(name, message) {
5364
+ super();
5365
+ this.name = name;
5366
+ this.message = message;
5367
+ }
5334
5368
  };
5335
- var StrategyType = /* @__PURE__ */ ((StrategyType2) => {
5336
- StrategyType2[StrategyType2["SpotOneSide"] = 0] = "SpotOneSide";
5337
- StrategyType2[StrategyType2["CurveOneSide"] = 1] = "CurveOneSide";
5338
- StrategyType2[StrategyType2["BidAskOneSide"] = 2] = "BidAskOneSide";
5339
- StrategyType2[StrategyType2["SpotImBalanced"] = 3] = "SpotImBalanced";
5340
- StrategyType2[StrategyType2["CurveImBalanced"] = 4] = "CurveImBalanced";
5341
- StrategyType2[StrategyType2["BidAskImBalanced"] = 5] = "BidAskImBalanced";
5342
- StrategyType2[StrategyType2["SpotBalanced"] = 6] = "SpotBalanced";
5343
- StrategyType2[StrategyType2["CurveBalanced"] = 7] = "CurveBalanced";
5344
- StrategyType2[StrategyType2["BidAskBalanced"] = 8] = "BidAskBalanced";
5345
- return StrategyType2;
5346
- })(StrategyType || {});
5347
- var ActivationType = /* @__PURE__ */ ((ActivationType2) => {
5348
- ActivationType2[ActivationType2["Slot"] = 0] = "Slot";
5349
- ActivationType2[ActivationType2["Timestamp"] = 1] = "Timestamp";
5350
- return ActivationType2;
5351
- })(ActivationType || {});
5352
- var BitmapType = /* @__PURE__ */ ((BitmapType2) => {
5353
- BitmapType2[BitmapType2["U1024"] = 0] = "U1024";
5354
- BitmapType2[BitmapType2["U512"] = 1] = "U512";
5355
- return BitmapType2;
5356
- })(BitmapType || {});
5357
- var ClockLayout = struct([
5358
- u64("slot"),
5359
- i64("epochStartTimestamp"),
5360
- u64("epoch"),
5361
- u64("leaderScheduleEpoch"),
5362
- i64("unixTimestamp")
5363
- ]);
5364
- var PairStatus = /* @__PURE__ */ ((PairStatus2) => {
5365
- PairStatus2[PairStatus2["Enabled"] = 0] = "Enabled";
5366
- PairStatus2[PairStatus2["Disabled"] = 1] = "Disabled";
5367
- return PairStatus2;
5368
- })(PairStatus || {});
5369
-
5370
- // src/dlmm/index.ts
5371
- import { AnchorProvider as AnchorProvider2, BN as BN9, Program as Program2 } from "@coral-xyz/anchor";
5372
5369
 
5373
5370
  // src/dlmm/helpers/index.ts
5374
5371
  import {
@@ -6344,6 +6341,14 @@ function generateBinAmount(amount, binStep, binId, tokenXDecimal, tokenYDecimal,
6344
6341
  return new BN5(c1.sub(c0).floor().toString());
6345
6342
  }
6346
6343
 
6344
+ // src/dlmm/helpers/index.ts
6345
+ import { getSimulationComputeUnits } from "@solana-developers/helpers";
6346
+
6347
+ // src/dlmm/helpers/computeUnit.ts
6348
+ var DEFAULT_ADD_LIQUIDITY_CU = 8e5;
6349
+ var MIN_CU_BUFFER = 5e4;
6350
+ var MAX_CU_BUFFER = 2e5;
6351
+
6347
6352
  // src/dlmm/helpers/derive.ts
6348
6353
  import { PublicKey as PublicKey2 } from "@solana/web3.js";
6349
6354
  function sortTokenMints(tokenX, tokenY) {
@@ -6459,11 +6464,110 @@ function deriveReserve(token, lbPair, programId) {
6459
6464
  }
6460
6465
 
6461
6466
  // src/dlmm/helpers/binArray.ts
6462
- import { BN as BN6 } from "@coral-xyz/anchor";
6467
+ import { BN as BN7 } from "@coral-xyz/anchor";
6463
6468
  import { PublicKey as PublicKey3 } from "@solana/web3.js";
6469
+
6470
+ // src/dlmm/types/index.ts
6471
+ import {
6472
+ BN as BN6
6473
+ } from "@coral-xyz/anchor";
6474
+ import Decimal4 from "decimal.js";
6475
+ import { u64, i64, struct } from "@coral-xyz/borsh";
6476
+ var PositionVersion = /* @__PURE__ */ ((PositionVersion2) => {
6477
+ PositionVersion2[PositionVersion2["V1"] = 0] = "V1";
6478
+ PositionVersion2[PositionVersion2["V2"] = 1] = "V2";
6479
+ return PositionVersion2;
6480
+ })(PositionVersion || {});
6481
+ var PairType = /* @__PURE__ */ ((PairType2) => {
6482
+ PairType2[PairType2["Permissionless"] = 0] = "Permissionless";
6483
+ PairType2[PairType2["Permissioned"] = 1] = "Permissioned";
6484
+ return PairType2;
6485
+ })(PairType || {});
6486
+ var Strategy = {
6487
+ SpotOneSide: { spotOneSide: {} },
6488
+ CurveOneSide: { curveOneSide: {} },
6489
+ BidAskOneSide: { bidAskOneSide: {} },
6490
+ SpotBalanced: { spotBalanced: {} },
6491
+ CurveBalanced: { curveBalanced: {} },
6492
+ BidAskBalanced: { bidAskBalanced: {} },
6493
+ SpotImBalanced: { spotImBalanced: {} },
6494
+ CurveImBalanced: { curveImBalanced: {} },
6495
+ BidAskImBalanced: { bidAskImBalanced: {} }
6496
+ };
6497
+ var StrategyType = /* @__PURE__ */ ((StrategyType2) => {
6498
+ StrategyType2[StrategyType2["SpotOneSide"] = 0] = "SpotOneSide";
6499
+ StrategyType2[StrategyType2["CurveOneSide"] = 1] = "CurveOneSide";
6500
+ StrategyType2[StrategyType2["BidAskOneSide"] = 2] = "BidAskOneSide";
6501
+ StrategyType2[StrategyType2["SpotImBalanced"] = 3] = "SpotImBalanced";
6502
+ StrategyType2[StrategyType2["CurveImBalanced"] = 4] = "CurveImBalanced";
6503
+ StrategyType2[StrategyType2["BidAskImBalanced"] = 5] = "BidAskImBalanced";
6504
+ StrategyType2[StrategyType2["SpotBalanced"] = 6] = "SpotBalanced";
6505
+ StrategyType2[StrategyType2["CurveBalanced"] = 7] = "CurveBalanced";
6506
+ StrategyType2[StrategyType2["BidAskBalanced"] = 8] = "BidAskBalanced";
6507
+ return StrategyType2;
6508
+ })(StrategyType || {});
6509
+ var ActivationType = /* @__PURE__ */ ((ActivationType2) => {
6510
+ ActivationType2[ActivationType2["Slot"] = 0] = "Slot";
6511
+ ActivationType2[ActivationType2["Timestamp"] = 1] = "Timestamp";
6512
+ return ActivationType2;
6513
+ })(ActivationType || {});
6514
+ var BinLiquidity;
6515
+ ((BinLiquidity3) => {
6516
+ function fromBin(bin, binId, binStep, baseTokenDecimal, quoteTokenDecimal, version) {
6517
+ const pricePerLamport = getPriceOfBinByBinId(
6518
+ binId,
6519
+ binStep
6520
+ ).toString();
6521
+ return {
6522
+ binId,
6523
+ xAmount: bin.amountX,
6524
+ yAmount: bin.amountY,
6525
+ supply: bin.liquiditySupply,
6526
+ price: pricePerLamport,
6527
+ version,
6528
+ pricePerToken: new Decimal4(pricePerLamport).mul(new Decimal4(10 ** (baseTokenDecimal - quoteTokenDecimal))).toString()
6529
+ };
6530
+ }
6531
+ BinLiquidity3.fromBin = fromBin;
6532
+ function empty(binId, binStep, baseTokenDecimal, quoteTokenDecimal, version) {
6533
+ const pricePerLamport = getPriceOfBinByBinId(
6534
+ binId,
6535
+ binStep
6536
+ ).toString();
6537
+ return {
6538
+ binId,
6539
+ xAmount: new BN6(0),
6540
+ yAmount: new BN6(0),
6541
+ supply: new BN6(0),
6542
+ price: pricePerLamport,
6543
+ version,
6544
+ pricePerToken: new Decimal4(pricePerLamport).mul(new Decimal4(10 ** (baseTokenDecimal - quoteTokenDecimal))).toString()
6545
+ };
6546
+ }
6547
+ BinLiquidity3.empty = empty;
6548
+ })(BinLiquidity || (BinLiquidity = {}));
6549
+ var BitmapType = /* @__PURE__ */ ((BitmapType2) => {
6550
+ BitmapType2[BitmapType2["U1024"] = 0] = "U1024";
6551
+ BitmapType2[BitmapType2["U512"] = 1] = "U512";
6552
+ return BitmapType2;
6553
+ })(BitmapType || {});
6554
+ var ClockLayout = struct([
6555
+ u64("slot"),
6556
+ i64("epochStartTimestamp"),
6557
+ u64("epoch"),
6558
+ u64("leaderScheduleEpoch"),
6559
+ i64("unixTimestamp")
6560
+ ]);
6561
+ var PairStatus = /* @__PURE__ */ ((PairStatus2) => {
6562
+ PairStatus2[PairStatus2["Enabled"] = 0] = "Enabled";
6563
+ PairStatus2[PairStatus2["Disabled"] = 1] = "Disabled";
6564
+ return PairStatus2;
6565
+ })(PairStatus || {});
6566
+
6567
+ // src/dlmm/helpers/binArray.ts
6464
6568
  function internalBitmapRange() {
6465
6569
  const lowerBinArrayIndex = BIN_ARRAY_BITMAP_SIZE.neg();
6466
- const upperBinArrayIndex = BIN_ARRAY_BITMAP_SIZE.sub(new BN6(1));
6570
+ const upperBinArrayIndex = BIN_ARRAY_BITMAP_SIZE.sub(new BN7(1));
6467
6571
  return [lowerBinArrayIndex, upperBinArrayIndex];
6468
6572
  }
6469
6573
  function buildBitmapFromU64Arrays(u64Arrays, type) {
@@ -6472,7 +6576,7 @@ function buildBitmapFromU64Arrays(u64Arrays, type) {
6472
6576
  return b.toArrayLike(Buffer, "le", 8);
6473
6577
  })
6474
6578
  );
6475
- return new BN6(buffer, "le");
6579
+ return new BN7(buffer, "le");
6476
6580
  }
6477
6581
  function bitmapTypeDetail(type) {
6478
6582
  if (type == 0 /* U1024 */) {
@@ -6513,24 +6617,24 @@ function leastSignificantBit(number, bitLength) {
6513
6617
  function extensionBitmapRange() {
6514
6618
  return [
6515
6619
  BIN_ARRAY_BITMAP_SIZE.neg().mul(
6516
- EXTENSION_BINARRAY_BITMAP_SIZE.add(new BN6(1))
6620
+ EXTENSION_BINARRAY_BITMAP_SIZE.add(new BN7(1))
6517
6621
  ),
6518
6622
  BIN_ARRAY_BITMAP_SIZE.mul(
6519
- EXTENSION_BINARRAY_BITMAP_SIZE.add(new BN6(1))
6520
- ).sub(new BN6(1))
6623
+ EXTENSION_BINARRAY_BITMAP_SIZE.add(new BN7(1))
6624
+ ).sub(new BN7(1))
6521
6625
  ];
6522
6626
  }
6523
6627
  function findSetBit(startIndex, endIndex, binArrayBitmapExtension) {
6524
6628
  const getBinArrayOffset = (binArrayIndex) => {
6525
- return binArrayIndex.gt(new BN6(0)) ? binArrayIndex.mod(BIN_ARRAY_BITMAP_SIZE) : binArrayIndex.add(new BN6(1)).neg().mod(BIN_ARRAY_BITMAP_SIZE);
6629
+ return binArrayIndex.gt(new BN7(0)) ? binArrayIndex.mod(BIN_ARRAY_BITMAP_SIZE) : binArrayIndex.add(new BN7(1)).neg().mod(BIN_ARRAY_BITMAP_SIZE);
6526
6630
  };
6527
6631
  const getBitmapOffset = (binArrayIndex) => {
6528
- return binArrayIndex.gt(new BN6(0)) ? binArrayIndex.div(BIN_ARRAY_BITMAP_SIZE).sub(new BN6(1)) : binArrayIndex.add(new BN6(1)).neg().div(BIN_ARRAY_BITMAP_SIZE).sub(new BN6(1));
6632
+ return binArrayIndex.gt(new BN7(0)) ? binArrayIndex.div(BIN_ARRAY_BITMAP_SIZE).sub(new BN7(1)) : binArrayIndex.add(new BN7(1)).neg().div(BIN_ARRAY_BITMAP_SIZE).sub(new BN7(1));
6529
6633
  };
6530
6634
  if (startIndex <= endIndex) {
6531
6635
  for (let i = startIndex; i <= endIndex; i++) {
6532
- const binArrayOffset = getBinArrayOffset(new BN6(i)).toNumber();
6533
- const bitmapOffset = getBitmapOffset(new BN6(i)).toNumber();
6636
+ const binArrayOffset = getBinArrayOffset(new BN7(i)).toNumber();
6637
+ const bitmapOffset = getBitmapOffset(new BN7(i)).toNumber();
6534
6638
  const bitmapChunks = i > 0 ? binArrayBitmapExtension.positiveBinArrayBitmap[bitmapOffset] : binArrayBitmapExtension.negativeBinArrayBitmap[bitmapOffset];
6535
6639
  const bitmap = buildBitmapFromU64Arrays(bitmapChunks, 1 /* U512 */);
6536
6640
  if (bitmap.testn(binArrayOffset)) {
@@ -6539,8 +6643,8 @@ function findSetBit(startIndex, endIndex, binArrayBitmapExtension) {
6539
6643
  }
6540
6644
  } else {
6541
6645
  for (let i = startIndex; i >= endIndex; i--) {
6542
- const binArrayOffset = getBinArrayOffset(new BN6(i)).toNumber();
6543
- const bitmapOffset = getBitmapOffset(new BN6(i)).toNumber();
6646
+ const binArrayOffset = getBinArrayOffset(new BN7(i)).toNumber();
6647
+ const bitmapOffset = getBitmapOffset(new BN7(i)).toNumber();
6544
6648
  const bitmapChunks = i > 0 ? binArrayBitmapExtension.positiveBinArrayBitmap[bitmapOffset] : binArrayBitmapExtension.negativeBinArrayBitmap[bitmapOffset];
6545
6649
  const bitmap = buildBitmapFromU64Arrays(bitmapChunks, 1 /* U512 */);
6546
6650
  if (bitmap.testn(binArrayOffset)) {
@@ -6562,11 +6666,11 @@ function deriveBinArrayBitmapExtension(lbPair, programId) {
6562
6666
  }
6563
6667
  function binIdToBinArrayIndex(binId) {
6564
6668
  const { div: idx, mod } = binId.divmod(MAX_BIN_ARRAY_SIZE);
6565
- return binId.isNeg() && !mod.isZero() ? idx.sub(new BN6(1)) : idx;
6669
+ return binId.isNeg() && !mod.isZero() ? idx.sub(new BN7(1)) : idx;
6566
6670
  }
6567
6671
  function getBinArrayLowerUpperBinId(binArrayIndex) {
6568
6672
  const lowerBinId = binArrayIndex.mul(MAX_BIN_ARRAY_SIZE);
6569
- const upperBinId = lowerBinId.add(MAX_BIN_ARRAY_SIZE).sub(new BN6(1));
6673
+ const upperBinId = lowerBinId.add(MAX_BIN_ARRAY_SIZE).sub(new BN7(1));
6570
6674
  return [lowerBinId, upperBinId];
6571
6675
  }
6572
6676
  function isBinIdWithinBinArray(activeId, binArrayIndex) {
@@ -6601,18 +6705,18 @@ function findNextBinArrayIndexWithLiquidity(swapForY, activeId, lbPairState, bin
6601
6705
  binArrayBitmapExtension
6602
6706
  );
6603
6707
  if (binArrayIndex !== null) {
6604
- return new BN6(binArrayIndex);
6708
+ return new BN7(binArrayIndex);
6605
6709
  } else {
6606
6710
  return null;
6607
6711
  }
6608
6712
  } else {
6609
6713
  const binArrayIndex = findSetBit(
6610
6714
  startBinArrayIndex.toNumber(),
6611
- BIN_ARRAY_BITMAP_SIZE.neg().sub(new BN6(1)).toNumber(),
6715
+ BIN_ARRAY_BITMAP_SIZE.neg().sub(new BN7(1)).toNumber(),
6612
6716
  binArrayBitmapExtension
6613
6717
  );
6614
6718
  if (binArrayIndex !== null) {
6615
- return new BN6(binArrayIndex);
6719
+ return new BN7(binArrayIndex);
6616
6720
  } else {
6617
6721
  startBinArrayIndex = BIN_ARRAY_BITMAP_SIZE.neg();
6618
6722
  }
@@ -6625,9 +6729,9 @@ function findNextBinArrayIndexWithLiquidity(swapForY, activeId, lbPairState, bin
6625
6729
  binArrayBitmapExtension
6626
6730
  );
6627
6731
  if (binArrayIndex !== null) {
6628
- return new BN6(binArrayIndex);
6732
+ return new BN7(binArrayIndex);
6629
6733
  } else {
6630
- startBinArrayIndex = BIN_ARRAY_BITMAP_SIZE.sub(new BN6(1));
6734
+ startBinArrayIndex = BIN_ARRAY_BITMAP_SIZE.sub(new BN7(1));
6631
6735
  }
6632
6736
  } else {
6633
6737
  const binArrayIndex = findSetBit(
@@ -6636,7 +6740,7 @@ function findNextBinArrayIndexWithLiquidity(swapForY, activeId, lbPairState, bin
6636
6740
  binArrayBitmapExtension
6637
6741
  );
6638
6742
  if (binArrayIndex !== null) {
6639
- return new BN6(binArrayIndex);
6743
+ return new BN7(binArrayIndex);
6640
6744
  } else {
6641
6745
  return null;
6642
6746
  }
@@ -6651,22 +6755,22 @@ function findNextBinArrayIndexWithLiquidity(swapForY, activeId, lbPairState, bin
6651
6755
  bitmapType
6652
6756
  );
6653
6757
  if (swapForY) {
6654
- const upperBitRange = new BN6(bitmapDetail.bits - 1).sub(offset);
6758
+ const upperBitRange = new BN7(bitmapDetail.bits - 1).sub(offset);
6655
6759
  const croppedBitmap = bitmap.shln(upperBitRange.toNumber());
6656
6760
  const msb = mostSignificantBit(croppedBitmap, bitmapDetail.bits);
6657
6761
  if (msb !== null) {
6658
- return startBinArrayIndex.sub(new BN6(msb));
6762
+ return startBinArrayIndex.sub(new BN7(msb));
6659
6763
  } else {
6660
- startBinArrayIndex = lowerBinArrayIndex.sub(new BN6(1));
6764
+ startBinArrayIndex = lowerBinArrayIndex.sub(new BN7(1));
6661
6765
  }
6662
6766
  } else {
6663
6767
  const lowerBitRange = offset;
6664
6768
  const croppedBitmap = bitmap.shrn(lowerBitRange.toNumber());
6665
6769
  const lsb = leastSignificantBit(croppedBitmap, bitmapDetail.bits);
6666
6770
  if (lsb !== null) {
6667
- return startBinArrayIndex.add(new BN6(lsb));
6771
+ return startBinArrayIndex.add(new BN7(lsb));
6668
6772
  } else {
6669
- startBinArrayIndex = upperBinArrayIndex.add(new BN6(1));
6773
+ startBinArrayIndex = upperBinArrayIndex.add(new BN7(1));
6670
6774
  }
6671
6775
  }
6672
6776
  }
@@ -6695,9 +6799,9 @@ function getBinArraysRequiredByPositionRange(pair, fromBinId, toBinId, programId
6695
6799
  const positionCount = getPositionCount(minBinId, maxBinId);
6696
6800
  const binArrays = /* @__PURE__ */ new Map();
6697
6801
  for (let i = 0; i < positionCount.toNumber(); i++) {
6698
- const lowerBinId = minBinId.add(MAX_BIN_PER_POSITION.mul(new BN6(i)));
6802
+ const lowerBinId = minBinId.add(MAX_BIN_PER_POSITION.mul(new BN7(i)));
6699
6803
  const lowerBinArrayIndex = binIdToBinArrayIndex(lowerBinId);
6700
- const upperBinArrayIndex = lowerBinArrayIndex.add(new BN6(1));
6804
+ const upperBinArrayIndex = lowerBinArrayIndex.add(new BN7(1));
6701
6805
  const [lowerBinArray] = deriveBinArray(pair, lowerBinArrayIndex, programId);
6702
6806
  const [upperBinArray] = deriveBinArray(pair, upperBinArrayIndex, programId);
6703
6807
  binArrays.set(lowerBinArray.toBase58(), lowerBinArrayIndex);
@@ -6708,19 +6812,29 @@ function getBinArraysRequiredByPositionRange(pair, fromBinId, toBinId, programId
6708
6812
  index
6709
6813
  }));
6710
6814
  }
6815
+ function* enumerateBins(binsById, lowerBinId, upperBinId, binStep, baseTokenDecimal, quoteTokenDecimal, version) {
6816
+ for (let currentBinId = lowerBinId; currentBinId <= upperBinId; currentBinId++) {
6817
+ const bin = binsById.get(currentBinId);
6818
+ if (bin != null) {
6819
+ yield BinLiquidity.fromBin(bin, currentBinId, binStep, baseTokenDecimal, quoteTokenDecimal, version);
6820
+ } else {
6821
+ yield BinLiquidity.empty(currentBinId, binStep, baseTokenDecimal, quoteTokenDecimal, version);
6822
+ }
6823
+ }
6824
+ }
6711
6825
 
6712
6826
  // src/dlmm/helpers/fee.ts
6713
- import { BN as BN7 } from "@coral-xyz/anchor";
6827
+ import { BN as BN8 } from "@coral-xyz/anchor";
6714
6828
  function getBaseFee(binStep, sParameter) {
6715
- return new BN7(sParameter.baseFactor).mul(new BN7(binStep)).mul(new BN7(10));
6829
+ return new BN8(sParameter.baseFactor).mul(new BN8(binStep)).mul(new BN8(10));
6716
6830
  }
6717
6831
  function getVariableFee(binStep, sParameter, vParameter) {
6718
6832
  if (sParameter.variableFeeControl > 0) {
6719
- const square_vfa_bin = new BN7(vParameter.volatilityAccumulator).mul(new BN7(binStep)).pow(new BN7(2));
6720
- const v_fee = new BN7(sParameter.variableFeeControl).mul(square_vfa_bin);
6721
- return v_fee.add(new BN7(99999999999)).div(new BN7(1e11));
6833
+ const square_vfa_bin = new BN8(vParameter.volatilityAccumulator).mul(new BN8(binStep)).pow(new BN8(2));
6834
+ const v_fee = new BN8(sParameter.variableFeeControl).mul(square_vfa_bin);
6835
+ return v_fee.add(new BN8(99999999999)).div(new BN8(1e11));
6722
6836
  }
6723
- return new BN7(0);
6837
+ return new BN8(0);
6724
6838
  }
6725
6839
  function getTotalFee(binStep, sParameter, vParameter) {
6726
6840
  const totalFee = getBaseFee(binStep, sParameter).add(
@@ -6731,30 +6845,30 @@ function getTotalFee(binStep, sParameter, vParameter) {
6731
6845
  function computeFee(binStep, sParameter, vParameter, inAmount) {
6732
6846
  const totalFee = getTotalFee(binStep, sParameter, vParameter);
6733
6847
  const denominator = FEE_PRECISION.sub(totalFee);
6734
- return inAmount.mul(totalFee).add(denominator).sub(new BN7(1)).div(denominator);
6848
+ return inAmount.mul(totalFee).add(denominator).sub(new BN8(1)).div(denominator);
6735
6849
  }
6736
6850
  function computeFeeFromAmount(binStep, sParameter, vParameter, inAmountWithFees) {
6737
6851
  const totalFee = getTotalFee(binStep, sParameter, vParameter);
6738
- return inAmountWithFees.mul(totalFee).add(FEE_PRECISION.sub(new BN7(1))).div(FEE_PRECISION);
6852
+ return inAmountWithFees.mul(totalFee).add(FEE_PRECISION.sub(new BN8(1))).div(FEE_PRECISION);
6739
6853
  }
6740
6854
  function computeProtocolFee(feeAmount, sParameter) {
6741
- return feeAmount.mul(new BN7(sParameter.protocolShare)).div(new BN7(BASIS_POINT_MAX));
6855
+ return feeAmount.mul(new BN8(sParameter.protocolShare)).div(new BN8(BASIS_POINT_MAX));
6742
6856
  }
6743
6857
  function swapExactOutQuoteAtBin(bin, binStep, sParameter, vParameter, outAmount, swapForY) {
6744
6858
  if (swapForY && bin.amountY.isZero()) {
6745
6859
  return {
6746
- amountIn: new BN7(0),
6747
- amountOut: new BN7(0),
6748
- fee: new BN7(0),
6749
- protocolFee: new BN7(0)
6860
+ amountIn: new BN8(0),
6861
+ amountOut: new BN8(0),
6862
+ fee: new BN8(0),
6863
+ protocolFee: new BN8(0)
6750
6864
  };
6751
6865
  }
6752
6866
  if (!swapForY && bin.amountX.isZero()) {
6753
6867
  return {
6754
- amountIn: new BN7(0),
6755
- amountOut: new BN7(0),
6756
- fee: new BN7(0),
6757
- protocolFee: new BN7(0)
6868
+ amountIn: new BN8(0),
6869
+ amountOut: new BN8(0),
6870
+ fee: new BN8(0),
6871
+ protocolFee: new BN8(0)
6758
6872
  };
6759
6873
  }
6760
6874
  let maxAmountOut;
@@ -6790,18 +6904,18 @@ function swapExactOutQuoteAtBin(bin, binStep, sParameter, vParameter, outAmount,
6790
6904
  function swapExactInQuoteAtBin(bin, binStep, sParameter, vParameter, inAmount, swapForY) {
6791
6905
  if (swapForY && bin.amountY.isZero()) {
6792
6906
  return {
6793
- amountIn: new BN7(0),
6794
- amountOut: new BN7(0),
6795
- fee: new BN7(0),
6796
- protocolFee: new BN7(0)
6907
+ amountIn: new BN8(0),
6908
+ amountOut: new BN8(0),
6909
+ fee: new BN8(0),
6910
+ protocolFee: new BN8(0)
6797
6911
  };
6798
6912
  }
6799
6913
  if (!swapForY && bin.amountX.isZero()) {
6800
6914
  return {
6801
- amountIn: new BN7(0),
6802
- amountOut: new BN7(0),
6803
- fee: new BN7(0),
6804
- protocolFee: new BN7(0)
6915
+ amountIn: new BN8(0),
6916
+ amountOut: new BN8(0),
6917
+ fee: new BN8(0),
6918
+ protocolFee: new BN8(0)
6805
6919
  };
6806
6920
  }
6807
6921
  let maxAmountOut;
@@ -6848,7 +6962,7 @@ function getAmountIn(amountOut, price, swapForY) {
6848
6962
  }
6849
6963
 
6850
6964
  // src/dlmm/helpers/strategy.ts
6851
- import { BN as BN8 } from "@coral-xyz/anchor";
6965
+ import { BN as BN9 } from "@coral-xyz/anchor";
6852
6966
  var DEFAULT_MAX_WEIGHT = 2e3;
6853
6967
  var DEFAULT_MIN_WEIGHT = 200;
6854
6968
  function toWeightSpotBalanced(minBinId, maxBinId) {
@@ -7008,7 +7122,7 @@ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amou
7008
7122
  for (let bin of amounts) {
7009
7123
  amountsInBin.push({
7010
7124
  binId: bin.binId,
7011
- amountX: new BN8(0),
7125
+ amountX: new BN9(0),
7012
7126
  amountY: bin.amount
7013
7127
  });
7014
7128
  }
@@ -7020,7 +7134,7 @@ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amou
7020
7134
  amountsInBin.push({
7021
7135
  binId: bin.binId,
7022
7136
  amountX: bin.amount,
7023
- amountY: new BN8(0)
7137
+ amountY: new BN9(0)
7024
7138
  });
7025
7139
  }
7026
7140
  }
@@ -7035,7 +7149,7 @@ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amou
7035
7149
  for (let bin of amountsIntoBidSide) {
7036
7150
  amountsInBin.push({
7037
7151
  binId: bin.binId,
7038
- amountX: new BN8(0),
7152
+ amountX: new BN9(0),
7039
7153
  amountY: bin.amount
7040
7154
  });
7041
7155
  }
@@ -7052,7 +7166,7 @@ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amou
7052
7166
  amountsInBin.push({
7053
7167
  binId: bin.binId,
7054
7168
  amountX: bin.amount,
7055
- amountY: new BN8(0)
7169
+ amountY: new BN9(0)
7056
7170
  });
7057
7171
  }
7058
7172
  }
@@ -7092,7 +7206,7 @@ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amou
7092
7206
  for (let bin of amounts) {
7093
7207
  amountsInBin.push({
7094
7208
  binId: bin.binId,
7095
- amountX: new BN8(0),
7209
+ amountX: new BN9(0),
7096
7210
  amountY: bin.amount
7097
7211
  });
7098
7212
  }
@@ -7104,7 +7218,7 @@ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amou
7104
7218
  amountsInBin.push({
7105
7219
  binId: bin.binId,
7106
7220
  amountX: bin.amount,
7107
- amountY: new BN8(0)
7221
+ amountY: new BN9(0)
7108
7222
  });
7109
7223
  }
7110
7224
  }
@@ -7119,7 +7233,7 @@ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amou
7119
7233
  for (let bin of amountsIntoBidSide) {
7120
7234
  amountsInBin.push({
7121
7235
  binId: bin.binId,
7122
- amountX: new BN8(0),
7236
+ amountX: new BN9(0),
7123
7237
  amountY: bin.amount
7124
7238
  });
7125
7239
  }
@@ -7136,7 +7250,7 @@ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amou
7136
7250
  amountsInBin.push({
7137
7251
  binId: bin.binId,
7138
7252
  amountX: bin.amount,
7139
- amountY: new BN8(0)
7253
+ amountY: new BN9(0)
7140
7254
  });
7141
7255
  }
7142
7256
  }
@@ -7176,7 +7290,7 @@ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amou
7176
7290
  for (let bin of amounts) {
7177
7291
  amountsInBin.push({
7178
7292
  binId: bin.binId,
7179
- amountX: new BN8(0),
7293
+ amountX: new BN9(0),
7180
7294
  amountY: bin.amount
7181
7295
  });
7182
7296
  }
@@ -7188,7 +7302,7 @@ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amou
7188
7302
  amountsInBin.push({
7189
7303
  binId: bin.binId,
7190
7304
  amountX: bin.amount,
7191
- amountY: new BN8(0)
7305
+ amountY: new BN9(0)
7192
7306
  });
7193
7307
  }
7194
7308
  }
@@ -7203,7 +7317,7 @@ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amou
7203
7317
  for (let bin of amountsIntoBidSide) {
7204
7318
  amountsInBin.push({
7205
7319
  binId: bin.binId,
7206
- amountX: new BN8(0),
7320
+ amountX: new BN9(0),
7207
7321
  amountY: bin.amount
7208
7322
  });
7209
7323
  }
@@ -7220,7 +7334,7 @@ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amou
7220
7334
  amountsInBin.push({
7221
7335
  binId: bin.binId,
7222
7336
  amountX: bin.amount,
7223
- amountY: new BN8(0)
7337
+ amountY: new BN9(0)
7224
7338
  });
7225
7339
  }
7226
7340
  }
@@ -7439,7 +7553,7 @@ function toStrategyParameters({
7439
7553
  }
7440
7554
 
7441
7555
  // src/dlmm/helpers/lbPair.ts
7442
- import { AnchorProvider, Program } from "@coral-xyz/anchor";
7556
+ import { AnchorProvider, Program as Program2 } from "@coral-xyz/anchor";
7443
7557
  import { PublicKey as PublicKey4 } from "@solana/web3.js";
7444
7558
  async function getTokensMintFromPoolAddress(connection, poolAddress, opt) {
7445
7559
  const provider = new AnchorProvider(
@@ -7447,7 +7561,7 @@ async function getTokensMintFromPoolAddress(connection, poolAddress, opt) {
7447
7561
  {},
7448
7562
  AnchorProvider.defaultOptions()
7449
7563
  );
7450
- const program = new Program(
7564
+ const program = new Program2(
7451
7565
  IDL,
7452
7566
  LBCLMM_PROGRAM_IDS[opt?.cluster ?? "mainnet-beta"],
7453
7567
  provider
@@ -7469,6 +7583,10 @@ function chunks(array, size) {
7469
7583
  (_, index) => array.slice(index * size, (index + 1) * size)
7470
7584
  );
7471
7585
  }
7586
+ function range(min, max, mapfn) {
7587
+ const length = max - min + 1;
7588
+ return Array.from({ length }, (_, i) => mapfn(min + i));
7589
+ }
7472
7590
  async function chunkedFetchMultiplePoolAccount(program, pks, chunkSize = 100) {
7473
7591
  const accounts = (await Promise.all(
7474
7592
  chunks(pks, chunkSize).map(
@@ -7574,66 +7692,37 @@ async function chunkedGetMultipleAccountInfos(connection, pks, chunkSize = 100)
7574
7692
  )).flat();
7575
7693
  return accountInfos;
7576
7694
  }
7577
- var computeBudgetIx = () => {
7578
- return ComputeBudgetProgram.setComputeUnitLimit({
7579
- units: 14e5
7580
- });
7581
- };
7582
-
7583
- // src/dlmm/index.ts
7584
- import { bs58 } from "@coral-xyz/anchor/dist/cjs/utils/bytes";
7585
- import Decimal4 from "decimal.js";
7586
- import {
7587
- AccountLayout,
7588
- MintLayout,
7589
- NATIVE_MINT as NATIVE_MINT2,
7590
- TOKEN_PROGRAM_ID as TOKEN_PROGRAM_ID2,
7591
- createAssociatedTokenAccountInstruction as createAssociatedTokenAccountInstruction2,
7592
- createTransferInstruction,
7593
- getAssociatedTokenAddressSync as getAssociatedTokenAddressSync2
7594
- } from "@solana/spl-token";
7595
-
7596
- // src/dlmm/error.ts
7597
- import { AnchorError } from "@coral-xyz/anchor";
7598
- var DLMMError = class extends Error {
7599
- errorCode;
7600
- errorName;
7601
- errorMessage;
7602
- constructor(error) {
7603
- let _errorCode = 0;
7604
- let _errorName = "Something went wrong";
7605
- let _errorMessage = "Something went wrong";
7606
- if (error instanceof Error) {
7607
- const anchorError = AnchorError.parse(
7608
- JSON.parse(JSON.stringify(error)).logs
7609
- );
7610
- if (anchorError?.program.toBase58() === LBCLMM_PROGRAM_IDS["mainnet-beta"]) {
7611
- _errorCode = anchorError.error.errorCode.number;
7612
- _errorName = anchorError.error.errorCode.code;
7613
- _errorMessage = anchorError.error.errorMessage;
7614
- }
7615
- } else {
7616
- const idlError = IDL.errors.find((err) => err.code === error);
7617
- if (idlError) {
7618
- _errorCode = idlError.code;
7619
- _errorName = idlError.name;
7620
- _errorMessage = idlError.msg;
7621
- }
7622
- }
7623
- super(_errorMessage);
7624
- this.errorCode = _errorCode;
7625
- this.errorName = _errorName;
7626
- this.errorMessage = _errorMessage;
7695
+ var getEstimatedComputeUnitUsageWithBuffer = async (connection, instructions, feePayer, buffer) => {
7696
+ if (!buffer) {
7697
+ buffer = 0.1;
7627
7698
  }
7628
- };
7629
- var DlmmSdkError = class extends Error {
7630
- name;
7631
- message;
7632
- constructor(name, message) {
7633
- super();
7634
- this.name = name;
7635
- this.message = message;
7699
+ buffer = Math.max(0, buffer);
7700
+ buffer = Math.min(1, buffer);
7701
+ const estimatedComputeUnitUsage = await getSimulationComputeUnits(
7702
+ connection,
7703
+ instructions,
7704
+ feePayer,
7705
+ []
7706
+ );
7707
+ let extraComputeUnitBuffer = estimatedComputeUnitUsage * buffer;
7708
+ if (extraComputeUnitBuffer > MAX_CU_BUFFER) {
7709
+ extraComputeUnitBuffer = MAX_CU_BUFFER;
7710
+ } else if (extraComputeUnitBuffer < MIN_CU_BUFFER) {
7711
+ extraComputeUnitBuffer = MIN_CU_BUFFER;
7636
7712
  }
7713
+ return estimatedComputeUnitUsage + extraComputeUnitBuffer;
7714
+ };
7715
+ var getEstimatedComputeUnitIxWithBuffer = async (connection, instructions, feePayer, buffer) => {
7716
+ const units = await getEstimatedComputeUnitUsageWithBuffer(
7717
+ connection,
7718
+ instructions,
7719
+ feePayer,
7720
+ buffer
7721
+ ).catch((error) => {
7722
+ console.error("Error::getEstimatedComputeUnitUsageWithBuffer", error);
7723
+ return 14e5;
7724
+ });
7725
+ return ComputeBudgetProgram.setComputeUnitLimit({ units });
7637
7726
  };
7638
7727
 
7639
7728
  // src/dlmm/index.ts
@@ -7665,7 +7754,7 @@ var DLMM = class {
7665
7754
  {},
7666
7755
  AnchorProvider2.defaultOptions()
7667
7756
  );
7668
- const program = new Program2(
7757
+ const program = new Program3(
7669
7758
  IDL,
7670
7759
  opt?.programId ?? LBCLMM_PROGRAM_IDS[opt?.cluster ?? "mainnet-beta"],
7671
7760
  provider
@@ -7679,7 +7768,7 @@ var DLMM = class {
7679
7768
  {},
7680
7769
  AnchorProvider2.defaultOptions()
7681
7770
  );
7682
- const program = new Program2(
7771
+ const program = new Program3(
7683
7772
  IDL,
7684
7773
  opt?.programId ?? LBCLMM_PROGRAM_IDS[cluster],
7685
7774
  provider
@@ -7726,7 +7815,7 @@ var DLMM = class {
7726
7815
  {},
7727
7816
  AnchorProvider2.defaultOptions()
7728
7817
  );
7729
- const program = new Program2(
7818
+ const program = new Program3(
7730
7819
  IDL,
7731
7820
  opt?.programId ?? LBCLMM_PROGRAM_IDS[cluster],
7732
7821
  provider
@@ -7826,7 +7915,7 @@ var DLMM = class {
7826
7915
  {},
7827
7916
  AnchorProvider2.defaultOptions()
7828
7917
  );
7829
- const program = new Program2(
7918
+ const program = new Program3(
7830
7919
  IDL,
7831
7920
  opt?.programId ?? LBCLMM_PROGRAM_IDS[cluster],
7832
7921
  provider
@@ -7946,7 +8035,7 @@ var DLMM = class {
7946
8035
  {},
7947
8036
  AnchorProvider2.defaultOptions()
7948
8037
  );
7949
- const program = new Program2(
8038
+ const program = new Program3(
7950
8039
  IDL,
7951
8040
  opt?.programId ?? LBCLMM_PROGRAM_IDS[opt?.cluster ?? "mainnet-beta"],
7952
8041
  provider
@@ -7972,7 +8061,7 @@ var DLMM = class {
7972
8061
  {},
7973
8062
  AnchorProvider2.defaultOptions()
7974
8063
  );
7975
- const program = new Program2(
8064
+ const program = new Program3(
7976
8065
  IDL,
7977
8066
  opt?.programId ?? LBCLMM_PROGRAM_IDS[cluster],
7978
8067
  provider
@@ -7998,8 +8087,8 @@ var DLMM = class {
7998
8087
  const binArrayPubkeySet = /* @__PURE__ */ new Set();
7999
8088
  const lbPairSet = /* @__PURE__ */ new Set();
8000
8089
  positions.forEach(({ account: { upperBinId, lowerBinId, lbPair } }) => {
8001
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
8002
- const upperBinArrayIndex = binIdToBinArrayIndex(new BN9(upperBinId));
8090
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
8091
+ const upperBinArrayIndex = binIdToBinArrayIndex(new BN10(upperBinId));
8003
8092
  const [lowerBinArrayPubKey] = deriveBinArray(
8004
8093
  lbPair,
8005
8094
  lowerBinArrayIndex,
@@ -8023,8 +8112,8 @@ var DLMM = class {
8023
8112
  const binArrayPubkeySetV2 = /* @__PURE__ */ new Set();
8024
8113
  const lbPairSetV2 = /* @__PURE__ */ new Set();
8025
8114
  positionsV2.forEach(({ account: { upperBinId, lowerBinId, lbPair } }) => {
8026
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
8027
- const upperBinArrayIndex = binIdToBinArrayIndex(new BN9(upperBinId));
8115
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
8116
+ const upperBinArrayIndex = binIdToBinArrayIndex(new BN10(upperBinId));
8028
8117
  const [lowerBinArrayPubKey] = deriveBinArray(
8029
8118
  lbPair,
8030
8119
  lowerBinArrayIndex,
@@ -8178,15 +8267,15 @@ var DLMM = class {
8178
8267
  mintYDecimal: mintY.decimals
8179
8268
  });
8180
8269
  });
8181
- const onChainTimestamp = new BN9(
8270
+ const onChainTimestamp = new BN10(
8182
8271
  clockAccInfo.data.readBigInt64LE(32).toString()
8183
8272
  ).toNumber();
8184
8273
  const positionsMap = /* @__PURE__ */ new Map();
8185
8274
  for (let position of positions) {
8186
8275
  const { account, publicKey: positionPubKey } = position;
8187
8276
  const { upperBinId, lowerBinId, lbPair } = account;
8188
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
8189
- const upperBinArrayIndex = binIdToBinArrayIndex(new BN9(upperBinId));
8277
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
8278
+ const upperBinArrayIndex = binIdToBinArrayIndex(new BN10(upperBinId));
8190
8279
  const [lowerBinArrayPubKey] = deriveBinArray(
8191
8280
  lbPair,
8192
8281
  lowerBinArrayIndex,
@@ -8253,8 +8342,8 @@ var DLMM = class {
8253
8342
  for (let position of positionsV2) {
8254
8343
  const { account, publicKey: positionPubKey } = position;
8255
8344
  const { upperBinId, lowerBinId, lbPair, feeOwner } = account;
8256
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
8257
- const upperBinArrayIndex = binIdToBinArrayIndex(new BN9(upperBinId));
8345
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
8346
+ const upperBinArrayIndex = binIdToBinArrayIndex(new BN10(upperBinId));
8258
8347
  const [lowerBinArrayPubKey] = deriveBinArray(
8259
8348
  lbPair,
8260
8349
  lowerBinArrayIndex,
@@ -8328,7 +8417,7 @@ var DLMM = class {
8328
8417
  {},
8329
8418
  AnchorProvider2.defaultOptions()
8330
8419
  );
8331
- const program = new Program2(
8420
+ const program = new Program3(
8332
8421
  IDL,
8333
8422
  opt?.programId ?? LBCLMM_PROGRAM_IDS[cluster],
8334
8423
  provider
@@ -8340,8 +8429,8 @@ var DLMM = class {
8340
8429
  return Promise.all(
8341
8430
  positionsState.map(async ({ lbPair, lowerBinId }, idx) => {
8342
8431
  const position = positions[idx];
8343
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
8344
- const upperBinArrayIndex = lowerBinArrayIndex.add(new BN9(1));
8432
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
8433
+ const upperBinArrayIndex = lowerBinArrayIndex.add(new BN10(1));
8345
8434
  const [lowerBinArrayPubKey] = deriveBinArray(
8346
8435
  lbPair,
8347
8436
  lowerBinArrayIndex,
@@ -8372,11 +8461,11 @@ var DLMM = class {
8372
8461
  );
8373
8462
  }
8374
8463
  static getPricePerLamport(tokenXDecimal, tokenYDecimal, price) {
8375
- return new Decimal4(price).mul(new Decimal4(10 ** (tokenYDecimal - tokenXDecimal))).toString();
8464
+ return new Decimal5(price).mul(new Decimal5(10 ** (tokenYDecimal - tokenXDecimal))).toString();
8376
8465
  }
8377
8466
  static getBinIdFromPrice(price, binStep, min) {
8378
- const binStepNum = new Decimal4(binStep).div(new Decimal4(BASIS_POINT_MAX));
8379
- const binId = new Decimal4(price).log().dividedBy(new Decimal4(1).add(binStepNum).log());
8467
+ const binStepNum = new Decimal5(binStep).div(new Decimal5(BASIS_POINT_MAX));
8468
+ const binId = new Decimal5(price).log().dividedBy(new Decimal5(1).add(binStepNum).log());
8380
8469
  return (min ? binId.floor() : binId.ceil()).toNumber();
8381
8470
  }
8382
8471
  /** Public methods */
@@ -8386,7 +8475,7 @@ var DLMM = class {
8386
8475
  {},
8387
8476
  AnchorProvider2.defaultOptions()
8388
8477
  );
8389
- const program = new Program2(
8478
+ const program = new Program3(
8390
8479
  IDL,
8391
8480
  opt?.programId ?? LBCLMM_PROGRAM_IDS[opt.cluster],
8392
8481
  provider
@@ -8435,7 +8524,7 @@ var DLMM = class {
8435
8524
  {},
8436
8525
  AnchorProvider2.defaultOptions()
8437
8526
  );
8438
- const program = new Program2(
8527
+ const program = new Program3(
8439
8528
  IDL,
8440
8529
  opt?.programId ?? LBCLMM_PROGRAM_IDS[opt.cluster],
8441
8530
  provider
@@ -8483,7 +8572,7 @@ var DLMM = class {
8483
8572
  {},
8484
8573
  AnchorProvider2.defaultOptions()
8485
8574
  );
8486
- const program = new Program2(
8575
+ const program = new Program3(
8487
8576
  IDL,
8488
8577
  opt?.programId ?? LBCLMM_PROGRAM_IDS[opt.cluster],
8489
8578
  provider
@@ -8619,7 +8708,7 @@ var DLMM = class {
8619
8708
  while (!shouldStop) {
8620
8709
  const binArrayIndex = findNextBinArrayIndexWithLiquidity(
8621
8710
  swapForY,
8622
- new BN9(activeIdToLoop),
8711
+ new BN10(activeIdToLoop),
8623
8712
  this.lbPair,
8624
8713
  this.binArrayBitmapExtension?.account ?? null
8625
8714
  );
@@ -8661,9 +8750,9 @@ var DLMM = class {
8661
8750
  return binArrays;
8662
8751
  }
8663
8752
  static calculateFeeInfo(baseFactor, binStep) {
8664
- const baseFeeRate = new BN9(baseFactor).mul(new BN9(binStep)).mul(new BN9(10));
8665
- const baseFeeRatePercentage = new Decimal4(baseFeeRate.toString()).mul(new Decimal4(100)).div(new Decimal4(FEE_PRECISION.toString()));
8666
- const maxFeeRatePercentage = new Decimal4(MAX_FEE_RATE.toString()).mul(new Decimal4(100)).div(new Decimal4(FEE_PRECISION.toString()));
8753
+ const baseFeeRate = new BN10(baseFactor).mul(new BN10(binStep)).mul(new BN10(10));
8754
+ const baseFeeRatePercentage = new Decimal5(baseFeeRate.toString()).mul(new Decimal5(100)).div(new Decimal5(FEE_PRECISION.toString()));
8755
+ const maxFeeRatePercentage = new Decimal5(MAX_FEE_RATE.toString()).mul(new Decimal5(100)).div(new Decimal5(FEE_PRECISION.toString()));
8667
8756
  return {
8668
8757
  baseFeeRatePercentage,
8669
8758
  maxFeeRatePercentage
@@ -8677,7 +8766,7 @@ var DLMM = class {
8677
8766
  getFeeInfo() {
8678
8767
  const { baseFactor, protocolShare } = this.lbPair.parameters;
8679
8768
  const { baseFeeRatePercentage, maxFeeRatePercentage } = DLMM.calculateFeeInfo(baseFactor, this.lbPair.binStep);
8680
- const protocolFeePercentage = new Decimal4(protocolShare.toString()).mul(new Decimal4(100)).div(new Decimal4(BASIS_POINT_MAX));
8769
+ const protocolFeePercentage = new Decimal5(protocolShare.toString()).mul(new Decimal5(100)).div(new Decimal5(BASIS_POINT_MAX));
8681
8770
  return {
8682
8771
  baseFeeRatePercentage,
8683
8772
  maxFeeRatePercentage,
@@ -8690,7 +8779,7 @@ var DLMM = class {
8690
8779
  */
8691
8780
  getDynamicFee() {
8692
8781
  let vParameterClone = Object.assign({}, this.lbPair.vParameters);
8693
- let activeId = new BN9(this.lbPair.activeId);
8782
+ let activeId = new BN10(this.lbPair.activeId);
8694
8783
  const sParameters2 = this.lbPair.parameters;
8695
8784
  const currentTimestamp = Date.now() / 1e3;
8696
8785
  this.updateReference(
@@ -8709,7 +8798,7 @@ var DLMM = class {
8709
8798
  sParameters2,
8710
8799
  vParameterClone
8711
8800
  );
8712
- return new Decimal4(totalFee.toString()).div(new Decimal4(FEE_PRECISION.toString())).mul(100);
8801
+ return new Decimal5(totalFee.toString()).div(new Decimal5(FEE_PRECISION.toString())).mul(100);
8713
8802
  }
8714
8803
  /**
8715
8804
  * The function `getEmissionRate` returns the emission rates for two rewards.
@@ -8722,8 +8811,8 @@ var DLMM = class {
8722
8811
  ({ rewardRate, rewardDurationEnd }) => now > rewardDurationEnd.toNumber() ? void 0 : rewardRate
8723
8812
  );
8724
8813
  return {
8725
- rewardOne: rewardOneEmissionRate ? new Decimal4(rewardOneEmissionRate.toString()).div(PRECISION) : void 0,
8726
- rewardTwo: rewardTwoEmissionRate ? new Decimal4(rewardTwoEmissionRate.toString()).div(PRECISION) : void 0
8814
+ rewardOne: rewardOneEmissionRate ? new Decimal5(rewardOneEmissionRate.toString()).div(PRECISION) : void 0,
8815
+ rewardTwo: rewardTwoEmissionRate ? new Decimal5(rewardTwoEmissionRate.toString()).div(PRECISION) : void 0
8727
8816
  };
8728
8817
  }
8729
8818
  /**
@@ -8785,15 +8874,15 @@ var DLMM = class {
8785
8874
  * @returns an object with two properties: "activeBin" and "bins". The value of "activeBin" is the
8786
8875
  * active bin ID of the lbPair, and the value of "bins" is an array of BinLiquidity objects.
8787
8876
  */
8788
- async getBinsBetweenLowerAndUpperBound(lowerBinId, upperBinId, lowerBinArrays, upperBinArrays) {
8877
+ async getBinsBetweenLowerAndUpperBound(lowerBinId, upperBinId, lowerBinArray, upperBinArray) {
8789
8878
  const bins = await this.getBins(
8790
8879
  this.pubkey,
8791
8880
  lowerBinId,
8792
8881
  upperBinId,
8793
8882
  this.tokenX.decimal,
8794
8883
  this.tokenY.decimal,
8795
- lowerBinArrays,
8796
- upperBinArrays
8884
+ lowerBinArray,
8885
+ upperBinArray
8797
8886
  );
8798
8887
  return { activeBin: this.lbPair.activeId, bins };
8799
8888
  }
@@ -8816,7 +8905,7 @@ var DLMM = class {
8816
8905
  * @returns {string} real price of bin
8817
8906
  */
8818
8907
  fromPricePerLamport(pricePerLamport) {
8819
- return new Decimal4(pricePerLamport).div(new Decimal4(10 ** (this.tokenY.decimal - this.tokenX.decimal))).toString();
8908
+ return new Decimal5(pricePerLamport).div(new Decimal5(10 ** (this.tokenY.decimal - this.tokenX.decimal))).toString();
8820
8909
  }
8821
8910
  /**
8822
8911
  * The function retrieves the active bin ID and its corresponding price.
@@ -8906,8 +8995,8 @@ var DLMM = class {
8906
8995
  }
8907
8996
  const binArrayPubkeySet = /* @__PURE__ */ new Set();
8908
8997
  positions.forEach(({ account: { upperBinId, lowerBinId } }) => {
8909
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
8910
- const upperBinArrayIndex = binIdToBinArrayIndex(new BN9(upperBinId));
8998
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
8999
+ const upperBinArrayIndex = binIdToBinArrayIndex(new BN10(upperBinId));
8911
9000
  const [lowerBinArrayPubKey] = deriveBinArray(
8912
9001
  this.pubkey,
8913
9002
  lowerBinArrayIndex,
@@ -8926,8 +9015,8 @@ var DLMM = class {
8926
9015
  );
8927
9016
  const binArrayPubkeySetV2 = /* @__PURE__ */ new Set();
8928
9017
  positionsV2.forEach(({ account: { upperBinId, lowerBinId, lbPair } }) => {
8929
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
8930
- const upperBinArrayIndex = binIdToBinArrayIndex(new BN9(upperBinId));
9018
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
9019
+ const upperBinArrayIndex = binIdToBinArrayIndex(new BN10(upperBinId));
8931
9020
  const [lowerBinArrayPubKey] = deriveBinArray(
8932
9021
  this.pubkey,
8933
9022
  lowerBinArrayIndex,
@@ -8984,14 +9073,14 @@ var DLMM = class {
8984
9073
  }
8985
9074
  if (!lbPairAccInfo)
8986
9075
  throw new Error(`LB Pair account ${this.pubkey.toBase58()} not found`);
8987
- const onChainTimestamp = new BN9(
9076
+ const onChainTimestamp = new BN10(
8988
9077
  clockAccInfo.data.readBigInt64LE(32).toString()
8989
9078
  ).toNumber();
8990
9079
  const userPositions = await Promise.all(
8991
9080
  positions.map(async ({ publicKey, account }) => {
8992
9081
  const { lowerBinId, upperBinId } = account;
8993
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
8994
- const upperBinArrayIndex = binIdToBinArrayIndex(new BN9(upperBinId));
9082
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
9083
+ const upperBinArrayIndex = binIdToBinArrayIndex(new BN10(upperBinId));
8995
9084
  const [lowerBinArrayPubKey] = deriveBinArray(
8996
9085
  this.pubkey,
8997
9086
  lowerBinArrayIndex,
@@ -9029,8 +9118,8 @@ var DLMM = class {
9029
9118
  const userPositionsV2 = await Promise.all(
9030
9119
  positionsV2.map(async ({ publicKey, account }) => {
9031
9120
  const { lowerBinId, upperBinId, feeOwner } = account;
9032
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
9033
- const upperBinArrayIndex = binIdToBinArrayIndex(new BN9(upperBinId));
9121
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
9122
+ const upperBinArrayIndex = binIdToBinArrayIndex(new BN10(upperBinId));
9034
9123
  const [lowerBinArrayPubKey] = deriveBinArray(
9035
9124
  this.pubkey,
9036
9125
  lowerBinArrayIndex,
@@ -9072,10 +9161,10 @@ var DLMM = class {
9072
9161
  }
9073
9162
  async quoteCreatePosition({ strategy }) {
9074
9163
  const { minBinId, maxBinId } = strategy;
9075
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(minBinId));
9076
- const upperBinArrayIndex = BN9.max(
9077
- binIdToBinArrayIndex(new BN9(maxBinId)),
9078
- lowerBinArrayIndex.add(new BN9(1))
9164
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(minBinId));
9165
+ const upperBinArrayIndex = BN10.max(
9166
+ binIdToBinArrayIndex(new BN10(maxBinId)),
9167
+ lowerBinArrayIndex.add(new BN10(1))
9079
9168
  );
9080
9169
  const binArraysCount = (await this.binArraysToBeCreate(lowerBinArrayIndex, upperBinArrayIndex)).length;
9081
9170
  const positionCount = Math.ceil((maxBinId - minBinId + 1) / MAX_BIN_PER_TX);
@@ -9099,29 +9188,34 @@ var DLMM = class {
9099
9188
  maxBinId,
9100
9189
  user
9101
9190
  }) {
9102
- const setComputeUnitLimitIx = computeBudgetIx();
9103
9191
  const createPositionIx = await this.program.methods.initializePosition(minBinId, maxBinId - minBinId + 1).accounts({
9104
9192
  payer: user,
9105
9193
  position: positionPubKey,
9106
9194
  lbPair: this.pubkey,
9107
9195
  owner: user
9108
9196
  }).instruction();
9109
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(minBinId));
9110
- const upperBinArrayIndex = BN9.max(
9111
- lowerBinArrayIndex.add(new BN9(1)),
9112
- binIdToBinArrayIndex(new BN9(maxBinId))
9197
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(minBinId));
9198
+ const upperBinArrayIndex = BN10.max(
9199
+ lowerBinArrayIndex.add(new BN10(1)),
9200
+ binIdToBinArrayIndex(new BN10(maxBinId))
9113
9201
  );
9114
9202
  const createBinArrayIxs = await this.createBinArraysIfNeeded(
9115
9203
  upperBinArrayIndex,
9116
9204
  lowerBinArrayIndex,
9117
9205
  user
9118
9206
  );
9207
+ const instructions = [createPositionIx, ...createBinArrayIxs];
9208
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
9209
+ this.program.provider.connection,
9210
+ instructions,
9211
+ user
9212
+ );
9119
9213
  const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
9120
9214
  return new Transaction({
9121
9215
  blockhash,
9122
9216
  lastValidBlockHeight,
9123
9217
  feePayer: user
9124
- }).add(setComputeUnitLimitIx, createPositionIx, ...createBinArrayIxs);
9218
+ }).add(setCUIx, ...instructions);
9125
9219
  }
9126
9220
  /**
9127
9221
  * The function `initializePositionAndAddLiquidityByStrategy` function is used to initializes a position and adds liquidity
@@ -9145,8 +9239,7 @@ var DLMM = class {
9145
9239
  }) {
9146
9240
  const { maxBinId, minBinId } = strategy;
9147
9241
  const maxActiveBinSlippage = slippage ? Math.ceil(slippage / (this.lbPair.binStep / 100)) : MAX_ACTIVE_BIN_SLIPPAGE;
9148
- const setComputeUnitLimitIx = computeBudgetIx();
9149
- const preInstructions = [setComputeUnitLimitIx];
9242
+ const preInstructions = [];
9150
9243
  const initializePositionIx = await this.program.methods.initializePosition(minBinId, maxBinId - minBinId + 1).accounts({
9151
9244
  payer: user,
9152
9245
  position: positionPubKey,
@@ -9154,15 +9247,15 @@ var DLMM = class {
9154
9247
  owner: user
9155
9248
  }).instruction();
9156
9249
  preInstructions.push(initializePositionIx);
9157
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(minBinId));
9250
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(minBinId));
9158
9251
  const [binArrayLower] = deriveBinArray(
9159
9252
  this.pubkey,
9160
9253
  lowerBinArrayIndex,
9161
9254
  this.program.programId
9162
9255
  );
9163
- const upperBinArrayIndex = BN9.max(
9164
- lowerBinArrayIndex.add(new BN9(1)),
9165
- binIdToBinArrayIndex(new BN9(maxBinId))
9256
+ const upperBinArrayIndex = BN10.max(
9257
+ lowerBinArrayIndex.add(new BN10(1)),
9258
+ binIdToBinArrayIndex(new BN10(maxBinId))
9166
9259
  );
9167
9260
  const [binArrayUpper] = deriveBinArray(
9168
9261
  this.pubkey,
@@ -9216,8 +9309,8 @@ var DLMM = class {
9216
9309
  const closeWrappedSOLIx = await unwrapSOLInstruction(user);
9217
9310
  closeWrappedSOLIx && postInstructions.push(closeWrappedSOLIx);
9218
9311
  }
9219
- const minBinArrayIndex = binIdToBinArrayIndex(new BN9(minBinId));
9220
- const maxBinArrayIndex = binIdToBinArrayIndex(new BN9(maxBinId));
9312
+ const minBinArrayIndex = binIdToBinArrayIndex(new BN10(minBinId));
9313
+ const maxBinArrayIndex = binIdToBinArrayIndex(new BN10(maxBinId));
9221
9314
  const useExtension = isOverflowDefaultBinArrayBitmap(minBinArrayIndex) || isOverflowDefaultBinArrayBitmap(maxBinArrayIndex);
9222
9315
  const binArrayBitmapExtension = useExtension ? deriveBinArrayBitmapExtension(this.pubkey, this.program.programId)[0] : null;
9223
9316
  const activeId = this.lbPair.activeId;
@@ -9246,13 +9339,24 @@ var DLMM = class {
9246
9339
  tokenYProgram: TOKEN_PROGRAM_ID2
9247
9340
  };
9248
9341
  const programMethod = this.program.methods.addLiquidityByStrategy(liquidityParams);
9249
- const createPositionTx = await programMethod.accounts(addLiquidityAccounts).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
9342
+ const addLiquidityIx = await programMethod.accounts(addLiquidityAccounts).instruction();
9343
+ const instructions = [
9344
+ ...preInstructions,
9345
+ addLiquidityIx,
9346
+ ...postInstructions
9347
+ ];
9348
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
9349
+ this.program.provider.connection,
9350
+ instructions,
9351
+ user
9352
+ );
9353
+ instructions.unshift(setCUIx);
9250
9354
  const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
9251
9355
  return new Transaction({
9252
9356
  blockhash,
9253
9357
  lastValidBlockHeight,
9254
9358
  feePayer: user
9255
- }).add(createPositionTx);
9359
+ }).add(...instructions);
9256
9360
  }
9257
9361
  /**
9258
9362
  * The function `initializePositionAndAddLiquidityByWeight` function is used to initializes a position and adds liquidity
@@ -9289,15 +9393,15 @@ var DLMM = class {
9289
9393
  owner: user
9290
9394
  }).instruction();
9291
9395
  preInstructions.push(initializePositionIx);
9292
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
9396
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
9293
9397
  const [binArrayLower] = deriveBinArray(
9294
9398
  this.pubkey,
9295
9399
  lowerBinArrayIndex,
9296
9400
  this.program.programId
9297
9401
  );
9298
- const upperBinArrayIndex = BN9.max(
9299
- lowerBinArrayIndex.add(new BN9(1)),
9300
- binIdToBinArrayIndex(new BN9(upperBinId))
9402
+ const upperBinArrayIndex = BN10.max(
9403
+ lowerBinArrayIndex.add(new BN10(1)),
9404
+ binIdToBinArrayIndex(new BN10(upperBinId))
9301
9405
  );
9302
9406
  const [binArrayUpper] = deriveBinArray(
9303
9407
  this.pubkey,
@@ -9351,11 +9455,10 @@ var DLMM = class {
9351
9455
  const closeWrappedSOLIx = await unwrapSOLInstruction(user);
9352
9456
  closeWrappedSOLIx && postInstructions.push(closeWrappedSOLIx);
9353
9457
  }
9354
- const setComputeUnitLimitIx = computeBudgetIx();
9355
9458
  const minBinId = Math.min(...binIds);
9356
9459
  const maxBinId = Math.max(...binIds);
9357
- const minBinArrayIndex = binIdToBinArrayIndex(new BN9(minBinId));
9358
- const maxBinArrayIndex = binIdToBinArrayIndex(new BN9(maxBinId));
9460
+ const minBinArrayIndex = binIdToBinArrayIndex(new BN10(minBinId));
9461
+ const maxBinArrayIndex = binIdToBinArrayIndex(new BN10(maxBinId));
9359
9462
  const useExtension = isOverflowDefaultBinArrayBitmap(minBinArrayIndex) || isOverflowDefaultBinArrayBitmap(maxBinArrayIndex);
9360
9463
  const binArrayBitmapExtension = useExtension ? deriveBinArrayBitmapExtension(this.pubkey, this.program.programId)[0] : null;
9361
9464
  const activeId = this.lbPair.activeId;
@@ -9416,19 +9519,34 @@ var DLMM = class {
9416
9519
  const isOneSideDeposit = totalXAmount.isZero() || totalYAmount.isZero();
9417
9520
  const programMethod = isOneSideDeposit ? this.program.methods.addLiquidityOneSide(oneSideLiquidityParams) : this.program.methods.addLiquidityByWeight(liquidityParams);
9418
9521
  if (xYAmountDistribution.length < MAX_BIN_LENGTH_ALLOWED_IN_ONE_TX) {
9419
- const addLiqTx2 = await programMethod.accounts(
9522
+ const addLiqIx2 = await programMethod.accounts(
9420
9523
  isOneSideDeposit ? oneSideAddLiquidityAccounts : addLiquidityAccounts
9421
- ).preInstructions([setComputeUnitLimitIx, ...preInstructions]).postInstructions(postInstructions).transaction();
9524
+ ).instruction();
9525
+ const instructions = [...preInstructions, addLiqIx2, ...postInstructions];
9526
+ const setCUIx2 = await getEstimatedComputeUnitIxWithBuffer(
9527
+ this.program.provider.connection,
9528
+ instructions,
9529
+ user
9530
+ );
9531
+ instructions.unshift(setCUIx2);
9422
9532
  const { blockhash: blockhash2, lastValidBlockHeight: lastValidBlockHeight2 } = await this.program.provider.connection.getLatestBlockhash("confirmed");
9423
9533
  return new Transaction({
9424
9534
  blockhash: blockhash2,
9425
9535
  lastValidBlockHeight: lastValidBlockHeight2,
9426
9536
  feePayer: user
9427
- }).add(addLiqTx2);
9537
+ }).add(...instructions);
9428
9538
  }
9429
- const addLiqTx = await programMethod.accounts(
9539
+ const addLiqIx = await programMethod.accounts(
9430
9540
  isOneSideDeposit ? oneSideAddLiquidityAccounts : addLiquidityAccounts
9431
- ).preInstructions([setComputeUnitLimitIx]).transaction();
9541
+ ).instruction();
9542
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
9543
+ this.program.provider.connection,
9544
+ [addLiqIx],
9545
+ user,
9546
+ DEFAULT_ADD_LIQUIDITY_CU
9547
+ // The function return multiple transactions that dependent on each other, simulation will fail
9548
+ );
9549
+ const mainInstructions = [setCUIx, addLiqIx];
9432
9550
  const transactions = [];
9433
9551
  const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
9434
9552
  if (preInstructions.length) {
@@ -9443,7 +9561,7 @@ var DLMM = class {
9443
9561
  blockhash,
9444
9562
  lastValidBlockHeight,
9445
9563
  feePayer: user
9446
- }).add(addLiqTx);
9564
+ }).add(...mainInstructions);
9447
9565
  transactions.push(mainTx);
9448
9566
  if (postInstructions.length) {
9449
9567
  const postInstructionsTx = new Transaction({
@@ -9478,10 +9596,8 @@ var DLMM = class {
9478
9596
  const { maxBinId, minBinId } = strategy;
9479
9597
  const maxActiveBinSlippage = slippage ? Math.ceil(slippage / (this.lbPair.binStep / 100)) : MAX_ACTIVE_BIN_SLIPPAGE;
9480
9598
  const preInstructions = [];
9481
- const setComputeUnitLimitIx = computeBudgetIx();
9482
- preInstructions.push(setComputeUnitLimitIx);
9483
- const minBinArrayIndex = binIdToBinArrayIndex(new BN9(minBinId));
9484
- const maxBinArrayIndex = binIdToBinArrayIndex(new BN9(maxBinId));
9599
+ const minBinArrayIndex = binIdToBinArrayIndex(new BN10(minBinId));
9600
+ const maxBinArrayIndex = binIdToBinArrayIndex(new BN10(maxBinId));
9485
9601
  const useExtension = isOverflowDefaultBinArrayBitmap(minBinArrayIndex) || isOverflowDefaultBinArrayBitmap(maxBinArrayIndex);
9486
9602
  const binArrayBitmapExtension = useExtension ? deriveBinArrayBitmapExtension(this.pubkey, this.program.programId)[0] : null;
9487
9603
  const strategyParameters = toStrategyParameters(strategy);
@@ -9489,9 +9605,9 @@ var DLMM = class {
9489
9605
  positionPubKey
9490
9606
  );
9491
9607
  const lowerBinArrayIndex = binIdToBinArrayIndex(
9492
- new BN9(positionAccount.lowerBinId)
9608
+ new BN10(positionAccount.lowerBinId)
9493
9609
  );
9494
- const upperBinArrayIndex = lowerBinArrayIndex.add(new BN9(1));
9610
+ const upperBinArrayIndex = lowerBinArrayIndex.add(new BN10(1));
9495
9611
  const [binArrayLower] = deriveBinArray(
9496
9612
  this.pubkey,
9497
9613
  lowerBinArrayIndex,
@@ -9573,13 +9689,24 @@ var DLMM = class {
9573
9689
  tokenYProgram: TOKEN_PROGRAM_ID2
9574
9690
  };
9575
9691
  const programMethod = this.program.methods.addLiquidityByStrategy(liquidityParams);
9576
- const createPositionTx = await programMethod.accounts(addLiquidityAccounts).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
9692
+ const addLiquidityIx = await programMethod.accounts(addLiquidityAccounts).instruction();
9693
+ const instructions = [
9694
+ ...preInstructions,
9695
+ addLiquidityIx,
9696
+ ...postInstructions
9697
+ ];
9698
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
9699
+ this.program.provider.connection,
9700
+ instructions,
9701
+ user
9702
+ );
9703
+ instructions.unshift(setCUIx);
9577
9704
  const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
9578
9705
  return new Transaction({
9579
9706
  blockhash,
9580
9707
  lastValidBlockHeight,
9581
9708
  feePayer: user
9582
- }).add(createPositionTx);
9709
+ }).add(...instructions);
9583
9710
  }
9584
9711
  /**
9585
9712
  * The `addLiquidityByWeight` function is used to add liquidity to existing position
@@ -9616,8 +9743,8 @@ var DLMM = class {
9616
9743
  );
9617
9744
  const minBinId = Math.min(...binIds);
9618
9745
  const maxBinId = Math.max(...binIds);
9619
- const minBinArrayIndex = binIdToBinArrayIndex(new BN9(minBinId));
9620
- const maxBinArrayIndex = binIdToBinArrayIndex(new BN9(maxBinId));
9746
+ const minBinArrayIndex = binIdToBinArrayIndex(new BN10(minBinId));
9747
+ const maxBinArrayIndex = binIdToBinArrayIndex(new BN10(maxBinId));
9621
9748
  const useExtension = isOverflowDefaultBinArrayBitmap(minBinArrayIndex) || isOverflowDefaultBinArrayBitmap(maxBinArrayIndex);
9622
9749
  const binArrayBitmapExtension = useExtension ? deriveBinArrayBitmapExtension(this.pubkey, this.program.programId)[0] : null;
9623
9750
  const activeId = this.lbPair.activeId;
@@ -9635,16 +9762,16 @@ var DLMM = class {
9635
9762
  throw new Error("No liquidity to add");
9636
9763
  }
9637
9764
  const lowerBinArrayIndex = binIdToBinArrayIndex(
9638
- new BN9(positionAccount.lowerBinId)
9765
+ new BN10(positionAccount.lowerBinId)
9639
9766
  );
9640
9767
  const [binArrayLower] = deriveBinArray(
9641
9768
  this.pubkey,
9642
9769
  lowerBinArrayIndex,
9643
9770
  this.program.programId
9644
9771
  );
9645
- const upperBinArrayIndex = BN9.max(
9646
- lowerBinArrayIndex.add(new BN9(1)),
9647
- binIdToBinArrayIndex(new BN9(positionAccount.upperBinId))
9772
+ const upperBinArrayIndex = BN10.max(
9773
+ lowerBinArrayIndex.add(new BN10(1)),
9774
+ binIdToBinArrayIndex(new BN10(positionAccount.upperBinId))
9648
9775
  );
9649
9776
  const [binArrayUpper] = deriveBinArray(
9650
9777
  this.pubkey,
@@ -9699,7 +9826,6 @@ var DLMM = class {
9699
9826
  const closeWrappedSOLIx = await unwrapSOLInstruction(user);
9700
9827
  closeWrappedSOLIx && postInstructions.push(closeWrappedSOLIx);
9701
9828
  }
9702
- const setComputeUnitLimitIx = computeBudgetIx();
9703
9829
  const liquidityParams = {
9704
9830
  amountX: totalXAmount,
9705
9831
  amountY: totalYAmount,
@@ -9744,19 +9870,32 @@ var DLMM = class {
9744
9870
  const isOneSideDeposit = totalXAmount.isZero() || totalYAmount.isZero();
9745
9871
  const programMethod = isOneSideDeposit ? this.program.methods.addLiquidityOneSide(oneSideLiquidityParams) : this.program.methods.addLiquidityByWeight(liquidityParams);
9746
9872
  if (xYAmountDistribution.length < MAX_BIN_LENGTH_ALLOWED_IN_ONE_TX) {
9747
- const addLiqTx2 = await programMethod.accounts(
9873
+ const addLiqIx2 = await programMethod.accounts(
9748
9874
  isOneSideDeposit ? oneSideAddLiquidityAccounts : addLiquidityAccounts
9749
- ).preInstructions([setComputeUnitLimitIx, ...preInstructions]).postInstructions(postInstructions).transaction();
9875
+ ).instruction();
9876
+ const instructions = [...preInstructions, addLiqIx2, ...postInstructions];
9877
+ const setCUIx2 = await getEstimatedComputeUnitIxWithBuffer(
9878
+ this.program.provider.connection,
9879
+ instructions,
9880
+ user
9881
+ );
9882
+ instructions.unshift(setCUIx2);
9750
9883
  const { blockhash: blockhash2, lastValidBlockHeight: lastValidBlockHeight2 } = await this.program.provider.connection.getLatestBlockhash("confirmed");
9751
9884
  return new Transaction({
9752
9885
  blockhash: blockhash2,
9753
9886
  lastValidBlockHeight: lastValidBlockHeight2,
9754
9887
  feePayer: user
9755
- }).add(addLiqTx2);
9888
+ }).add(...instructions);
9756
9889
  }
9757
- const addLiqTx = await programMethod.accounts(
9890
+ const addLiqIx = await programMethod.accounts(
9758
9891
  isOneSideDeposit ? oneSideAddLiquidityAccounts : addLiquidityAccounts
9759
- ).preInstructions([setComputeUnitLimitIx]).transaction();
9892
+ ).instruction();
9893
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
9894
+ this.program.provider.connection,
9895
+ [addLiqIx],
9896
+ user
9897
+ );
9898
+ const mainInstructions = [setCUIx, addLiqIx];
9760
9899
  const transactions = [];
9761
9900
  const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
9762
9901
  if (preInstructions.length) {
@@ -9771,7 +9910,7 @@ var DLMM = class {
9771
9910
  blockhash,
9772
9911
  lastValidBlockHeight,
9773
9912
  feePayer: user
9774
- }).add(addLiqTx);
9913
+ }).add(...mainInstructions);
9775
9914
  transactions.push(mainTx);
9776
9915
  if (postInstructions.length) {
9777
9916
  const postInstructionsTx = new Transaction({
@@ -9803,8 +9942,8 @@ var DLMM = class {
9803
9942
  }) {
9804
9943
  const { lbPair, lowerBinId, owner, feeOwner } = await this.program.account.positionV2.fetch(position);
9805
9944
  const { reserveX, reserveY, tokenXMint, tokenYMint } = await this.program.account.lbPair.fetch(lbPair);
9806
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
9807
- const upperBinArrayIndex = lowerBinArrayIndex.add(new BN9(1));
9945
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
9946
+ const upperBinArrayIndex = lowerBinArrayIndex.add(new BN10(1));
9808
9947
  const [binArrayLower] = deriveBinArray(
9809
9948
  lbPair,
9810
9949
  lowerBinArrayIndex,
@@ -9816,8 +9955,6 @@ var DLMM = class {
9816
9955
  this.program.programId
9817
9956
  );
9818
9957
  const preInstructions = [];
9819
- const setComputeUnitLimitIx = computeBudgetIx();
9820
- preInstructions.push(setComputeUnitLimitIx);
9821
9958
  const walletToReceiveFee = feeOwner.equals(PublicKey6.default) ? user : feeOwner;
9822
9959
  const [
9823
9960
  { ataPubKey: userTokenX, ix: createPayerTokenXIx },
@@ -9884,7 +10021,7 @@ var DLMM = class {
9884
10021
  user
9885
10022
  );
9886
10023
  rewardAtaIx && preInstructions.push(rewardAtaIx);
9887
- const claimRewardIx = await this.program.methods.claimReward(new BN9(i)).accounts({
10024
+ const claimRewardIx = await this.program.methods.claimReward(new BN10(i)).accounts({
9888
10025
  lbPair: this.pubkey,
9889
10026
  sender: user,
9890
10027
  position,
@@ -9921,11 +10058,11 @@ var DLMM = class {
9921
10058
  }
9922
10059
  const minBinId = Math.min(...binIds);
9923
10060
  const maxBinId = Math.max(...binIds);
9924
- const minBinArrayIndex = binIdToBinArrayIndex(new BN9(minBinId));
9925
- const maxBinArrayIndex = binIdToBinArrayIndex(new BN9(maxBinId));
10061
+ const minBinArrayIndex = binIdToBinArrayIndex(new BN10(minBinId));
10062
+ const maxBinArrayIndex = binIdToBinArrayIndex(new BN10(maxBinId));
9926
10063
  const useExtension = isOverflowDefaultBinArrayBitmap(minBinArrayIndex) || isOverflowDefaultBinArrayBitmap(maxBinArrayIndex);
9927
10064
  const binArrayBitmapExtension = useExtension ? deriveBinArrayBitmapExtension(this.pubkey, this.program.programId)[0] : null;
9928
- const removeLiquidityTx = await this.program.methods.removeLiquidityByRange(minBinId, maxBinId, bps.toNumber()).accounts({
10065
+ const removeLiquidityIx = await this.program.methods.removeLiquidityByRange(minBinId, maxBinId, bps.toNumber()).accounts({
9929
10066
  position,
9930
10067
  lbPair,
9931
10068
  userTokenX,
@@ -9940,26 +10077,43 @@ var DLMM = class {
9940
10077
  tokenXProgram: TOKEN_PROGRAM_ID2,
9941
10078
  tokenYProgram: TOKEN_PROGRAM_ID2,
9942
10079
  sender: user
9943
- }).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
9944
- const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
10080
+ }).instruction();
10081
+ const instructions = [
10082
+ ...preInstructions,
10083
+ removeLiquidityIx,
10084
+ ...postInstructions
10085
+ ];
10086
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
10087
+ this.program.provider.connection,
10088
+ instructions,
10089
+ user
10090
+ );
10091
+ instructions.unshift(setCUIx);
9945
10092
  if (secondTransactionsIx.length) {
10093
+ const setCUIx2 = await getEstimatedComputeUnitIxWithBuffer(
10094
+ this.program.provider.connection,
10095
+ secondTransactionsIx,
10096
+ user
10097
+ );
10098
+ const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
9946
10099
  const claimRewardsTx = new Transaction({
9947
10100
  blockhash,
9948
10101
  lastValidBlockHeight,
9949
10102
  feePayer: user
9950
- }).add(...secondTransactionsIx);
10103
+ }).add(setCUIx2, ...secondTransactionsIx);
9951
10104
  const mainTx = new Transaction({
9952
10105
  blockhash,
9953
10106
  lastValidBlockHeight,
9954
10107
  feePayer: user
9955
- }).add(removeLiquidityTx);
10108
+ }).add(...instructions);
9956
10109
  return [mainTx, claimRewardsTx];
9957
10110
  } else {
10111
+ const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
9958
10112
  return new Transaction({
9959
10113
  blockhash,
9960
10114
  lastValidBlockHeight,
9961
10115
  feePayer: user
9962
- }).add(removeLiquidityTx);
10116
+ }).add(...instructions);
9963
10117
  }
9964
10118
  }
9965
10119
  /**
@@ -9976,13 +10130,13 @@ var DLMM = class {
9976
10130
  const { lowerBinId } = await this.program.account.positionV2.fetch(
9977
10131
  position.publicKey
9978
10132
  );
9979
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
10133
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
9980
10134
  const [binArrayLower] = deriveBinArray(
9981
10135
  this.pubkey,
9982
10136
  lowerBinArrayIndex,
9983
10137
  this.program.programId
9984
10138
  );
9985
- const upperBinArrayIndex = lowerBinArrayIndex.add(new BN9(1));
10139
+ const upperBinArrayIndex = lowerBinArrayIndex.add(new BN10(1));
9986
10140
  const [binArrayUpper] = deriveBinArray(
9987
10141
  this.pubkey,
9988
10142
  upperBinArrayIndex,
@@ -10023,7 +10177,7 @@ var DLMM = class {
10023
10177
  const currentTimestamp = Date.now() / 1e3;
10024
10178
  let outAmountLeft = outAmount;
10025
10179
  let vParameterClone = Object.assign({}, this.lbPair.vParameters);
10026
- let activeId = new BN9(this.lbPair.activeId);
10180
+ let activeId = new BN10(this.lbPair.activeId);
10027
10181
  const binStep = this.lbPair.binStep;
10028
10182
  const sParameters2 = this.lbPair.parameters;
10029
10183
  this.updateReference(
@@ -10034,9 +10188,9 @@ var DLMM = class {
10034
10188
  );
10035
10189
  let startBinId = activeId;
10036
10190
  let binArraysForSwap = /* @__PURE__ */ new Map();
10037
- let actualInAmount = new BN9(0);
10038
- let feeAmount = new BN9(0);
10039
- let protocolFeeAmount = new BN9(0);
10191
+ let actualInAmount = new BN10(0);
10192
+ let feeAmount = new BN10(0);
10193
+ let protocolFeeAmount = new BN10(0);
10040
10194
  while (!outAmountLeft.isZero()) {
10041
10195
  let binArrayAccountToSwap = findNextBinArrayWithLiquidity(
10042
10196
  swapForY,
@@ -10079,9 +10233,9 @@ var DLMM = class {
10079
10233
  }
10080
10234
  if (!outAmountLeft.isZero()) {
10081
10235
  if (swapForY) {
10082
- activeId = activeId.sub(new BN9(1));
10236
+ activeId = activeId.sub(new BN10(1));
10083
10237
  } else {
10084
- activeId = activeId.add(new BN9(1));
10238
+ activeId = activeId.add(new BN10(1));
10085
10239
  }
10086
10240
  }
10087
10241
  }
@@ -10093,8 +10247,8 @@ var DLMM = class {
10093
10247
  activeId.toNumber(),
10094
10248
  this.lbPair.binStep
10095
10249
  );
10096
- const priceImpact = startPrice.sub(endPrice).abs().div(startPrice).mul(new Decimal4(100));
10097
- const maxInAmount = actualInAmount.mul(new BN9(BASIS_POINT_MAX).add(allowedSlippage)).div(new BN9(BASIS_POINT_MAX));
10250
+ const priceImpact = startPrice.sub(endPrice).abs().div(startPrice).mul(new Decimal5(100));
10251
+ const maxInAmount = actualInAmount.mul(new BN10(BASIS_POINT_MAX).add(allowedSlippage)).div(new BN10(BASIS_POINT_MAX));
10098
10252
  return {
10099
10253
  inAmount: actualInAmount,
10100
10254
  maxInAmount,
@@ -10127,7 +10281,7 @@ var DLMM = class {
10127
10281
  const currentTimestamp = Date.now() / 1e3;
10128
10282
  let inAmountLeft = inAmount;
10129
10283
  let vParameterClone = Object.assign({}, this.lbPair.vParameters);
10130
- let activeId = new BN9(this.lbPair.activeId);
10284
+ let activeId = new BN10(this.lbPair.activeId);
10131
10285
  const binStep = this.lbPair.binStep;
10132
10286
  const sParameters2 = this.lbPair.parameters;
10133
10287
  this.updateReference(
@@ -10138,9 +10292,9 @@ var DLMM = class {
10138
10292
  );
10139
10293
  let startBin = null;
10140
10294
  let binArraysForSwap = /* @__PURE__ */ new Map();
10141
- let actualOutAmount = new BN9(0);
10142
- let feeAmount = new BN9(0);
10143
- let protocolFeeAmount = new BN9(0);
10295
+ let actualOutAmount = new BN10(0);
10296
+ let feeAmount = new BN10(0);
10297
+ let protocolFeeAmount = new BN10(0);
10144
10298
  while (!inAmountLeft.isZero()) {
10145
10299
  let binArrayAccountToSwap = findNextBinArrayWithLiquidity(
10146
10300
  swapForY,
@@ -10190,9 +10344,9 @@ var DLMM = class {
10190
10344
  }
10191
10345
  if (!inAmountLeft.isZero()) {
10192
10346
  if (swapForY) {
10193
- activeId = activeId.sub(new BN9(1));
10347
+ activeId = activeId.sub(new BN10(1));
10194
10348
  } else {
10195
- activeId = activeId.add(new BN9(1));
10349
+ activeId = activeId.add(new BN10(1));
10196
10350
  }
10197
10351
  }
10198
10352
  }
@@ -10210,8 +10364,8 @@ var DLMM = class {
10210
10364
  ),
10211
10365
  swapForY
10212
10366
  );
10213
- const priceImpact = new Decimal4(actualOutAmount.toString()).sub(new Decimal4(outAmountWithoutSlippage.toString())).div(new Decimal4(outAmountWithoutSlippage.toString())).mul(new Decimal4(100));
10214
- const minOutAmount = actualOutAmount.mul(new BN9(BASIS_POINT_MAX).sub(allowedSlippage)).div(new BN9(BASIS_POINT_MAX));
10367
+ const priceImpact = new Decimal5(actualOutAmount.toString()).sub(new Decimal5(outAmountWithoutSlippage.toString())).div(new Decimal5(outAmountWithoutSlippage.toString())).mul(new Decimal5(100));
10368
+ const minOutAmount = actualOutAmount.mul(new BN10(BASIS_POINT_MAX).sub(allowedSlippage)).div(new BN10(BASIS_POINT_MAX));
10215
10369
  const endPrice = getPriceOfBinByBinId(
10216
10370
  activeId.toNumber(),
10217
10371
  this.lbPair.binStep
@@ -10237,7 +10391,7 @@ var DLMM = class {
10237
10391
  binArraysPubkey
10238
10392
  }) {
10239
10393
  const { tokenXMint, tokenYMint, reserveX, reserveY, activeId, oracle } = await this.program.account.lbPair.fetch(lbPair);
10240
- const preInstructions = [computeBudgetIx()];
10394
+ const preInstructions = [];
10241
10395
  const postInstructions = [];
10242
10396
  const [
10243
10397
  { ataPubKey: userTokenIn, ix: createInTokenAccountIx },
@@ -10280,7 +10434,7 @@ var DLMM = class {
10280
10434
  pubkey
10281
10435
  };
10282
10436
  });
10283
- const swapTx = await this.program.methods.swapExactOut(maxInAmount, outAmount).accounts({
10437
+ const swapIx = await this.program.methods.swapExactOut(maxInAmount, outAmount).accounts({
10284
10438
  lbPair,
10285
10439
  reserveX,
10286
10440
  reserveY,
@@ -10294,13 +10448,20 @@ var DLMM = class {
10294
10448
  binArrayBitmapExtension: this.binArrayBitmapExtension ? this.binArrayBitmapExtension.publicKey : null,
10295
10449
  oracle,
10296
10450
  hostFeeIn: null
10297
- }).remainingAccounts(binArrays).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
10451
+ }).remainingAccounts(binArrays).instruction();
10452
+ const instructions = [...preInstructions, swapIx, ...postInstructions];
10453
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
10454
+ this.program.provider.connection,
10455
+ instructions,
10456
+ user
10457
+ );
10458
+ instructions.unshift(setCUIx);
10298
10459
  const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
10299
10460
  return new Transaction({
10300
10461
  blockhash,
10301
10462
  lastValidBlockHeight,
10302
10463
  feePayer: user
10303
- }).add(swapTx);
10464
+ }).add(...instructions);
10304
10465
  }
10305
10466
  /**
10306
10467
  * Returns a transaction to be signed and sent by user performing swap.
@@ -10324,7 +10485,7 @@ var DLMM = class {
10324
10485
  binArraysPubkey
10325
10486
  }) {
10326
10487
  const { tokenXMint, tokenYMint, reserveX, reserveY, activeId, oracle } = await this.program.account.lbPair.fetch(lbPair);
10327
- const preInstructions = [computeBudgetIx()];
10488
+ const preInstructions = [];
10328
10489
  const postInstructions = [];
10329
10490
  const [
10330
10491
  { ataPubKey: userTokenIn, ix: createInTokenAccountIx },
@@ -10367,7 +10528,7 @@ var DLMM = class {
10367
10528
  pubkey
10368
10529
  };
10369
10530
  });
10370
- const swapTx = await this.program.methods.swapWithPriceImpact(
10531
+ const swapIx = await this.program.methods.swapWithPriceImpact(
10371
10532
  inAmount,
10372
10533
  this.lbPair.activeId,
10373
10534
  priceImpact.toNumber()
@@ -10385,13 +10546,20 @@ var DLMM = class {
10385
10546
  binArrayBitmapExtension: this.binArrayBitmapExtension ? this.binArrayBitmapExtension.publicKey : null,
10386
10547
  oracle,
10387
10548
  hostFeeIn: null
10388
- }).remainingAccounts(binArrays).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
10549
+ }).remainingAccounts(binArrays).instruction();
10550
+ const instructions = [...preInstructions, swapIx, ...postInstructions];
10551
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
10552
+ this.program.provider.connection,
10553
+ instructions,
10554
+ user
10555
+ );
10556
+ instructions.unshift(setCUIx);
10389
10557
  const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
10390
10558
  return new Transaction({
10391
10559
  blockhash,
10392
10560
  lastValidBlockHeight,
10393
10561
  feePayer: user
10394
- }).add(swapTx);
10562
+ }).add(...instructions);
10395
10563
  }
10396
10564
  /**
10397
10565
  * Returns a transaction to be signed and sent by user performing swap.
@@ -10415,7 +10583,7 @@ var DLMM = class {
10415
10583
  binArraysPubkey
10416
10584
  }) {
10417
10585
  const { tokenXMint, tokenYMint, reserveX, reserveY, activeId, oracle } = await this.program.account.lbPair.fetch(lbPair);
10418
- const preInstructions = [computeBudgetIx()];
10586
+ const preInstructions = [];
10419
10587
  const postInstructions = [];
10420
10588
  const [
10421
10589
  { ataPubKey: userTokenIn, ix: createInTokenAccountIx },
@@ -10458,7 +10626,7 @@ var DLMM = class {
10458
10626
  pubkey
10459
10627
  };
10460
10628
  });
10461
- const swapTx = await this.program.methods.swap(inAmount, minOutAmount).accounts({
10629
+ const swapIx = await this.program.methods.swap(inAmount, minOutAmount).accounts({
10462
10630
  lbPair,
10463
10631
  reserveX,
10464
10632
  reserveY,
@@ -10474,13 +10642,20 @@ var DLMM = class {
10474
10642
  binArrayBitmapExtension: this.binArrayBitmapExtension ? this.binArrayBitmapExtension.publicKey : null,
10475
10643
  oracle,
10476
10644
  hostFeeIn: null
10477
- }).remainingAccounts(binArrays).preInstructions(preInstructions).postInstructions(postInstructions).transaction();
10645
+ }).remainingAccounts(binArrays).instruction();
10646
+ const instructions = [...preInstructions, swapIx, ...postInstructions];
10647
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
10648
+ this.program.provider.connection,
10649
+ instructions,
10650
+ user
10651
+ );
10652
+ instructions.unshift(setCUIx);
10478
10653
  const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
10479
10654
  return new Transaction({
10480
10655
  blockhash,
10481
10656
  lastValidBlockHeight,
10482
10657
  feePayer: user
10483
- }).add(swapTx);
10658
+ }).add(...instructions);
10484
10659
  }
10485
10660
  /**
10486
10661
  * The claimLMReward function is used to claim rewards for a specific position owned by a specific owner.
@@ -10499,12 +10674,18 @@ var DLMM = class {
10499
10674
  });
10500
10675
  if (!claimTransactions.length)
10501
10676
  return;
10677
+ const instructions = claimTransactions.map((t) => t.instructions).flat();
10678
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
10679
+ this.program.provider.connection,
10680
+ instructions,
10681
+ owner
10682
+ );
10502
10683
  const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
10503
10684
  return new Transaction({
10504
10685
  blockhash,
10505
10686
  lastValidBlockHeight,
10506
10687
  feePayer: owner
10507
- }).add(...claimTransactions);
10688
+ }).add(setCUIx, ...claimTransactions);
10508
10689
  }
10509
10690
  /**
10510
10691
  * The `claimAllLMRewards` function is used to claim all liquidity mining rewards for a given owner
@@ -10530,6 +10711,14 @@ var DLMM = class {
10530
10711
  })
10531
10712
  )).flat();
10532
10713
  const chunkedClaimAllTx = chunks(claimAllTxs, MAX_CLAIM_ALL_ALLOWED);
10714
+ if (chunkedClaimAllTx.length === 0)
10715
+ return [];
10716
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
10717
+ this.program.provider.connection,
10718
+ // First tx simulation will success because it will create all the ATA. Then, we use the simulated CU as references for the rest
10719
+ chunkedClaimAllTx[0].map((t) => t.instructions).flat(),
10720
+ owner
10721
+ );
10533
10722
  const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
10534
10723
  return Promise.all(
10535
10724
  chunkedClaimAllTx.map(async (claimAllTx) => {
@@ -10537,7 +10726,7 @@ var DLMM = class {
10537
10726
  feePayer: owner,
10538
10727
  blockhash,
10539
10728
  lastValidBlockHeight
10540
- }).add(computeBudgetIx()).add(...claimAllTx);
10729
+ }).add(setCUIx).add(...claimAllTx);
10541
10730
  })
10542
10731
  );
10543
10732
  }
@@ -10596,14 +10785,22 @@ var DLMM = class {
10596
10785
  })
10597
10786
  )).flat();
10598
10787
  const chunkedClaimAllTx = chunks(claimAllTxs, MAX_CLAIM_ALL_ALLOWED);
10788
+ if (chunkedClaimAllTx.length === 0)
10789
+ return [];
10790
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
10791
+ this.program.provider.connection,
10792
+ // First tx simulation will success because it will create all the ATA. Then, we use the simulated CU as references for the rest
10793
+ chunkedClaimAllTx[0].map((t) => t.instructions).flat(),
10794
+ owner
10795
+ );
10796
+ const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
10599
10797
  return Promise.all(
10600
10798
  chunkedClaimAllTx.map(async (claimAllTx) => {
10601
- const { recentBlockhash, lastValidBlockHeight } = claimAllTx[0];
10602
10799
  return new Transaction({
10603
10800
  feePayer: owner,
10604
- blockhash: recentBlockhash,
10801
+ blockhash,
10605
10802
  lastValidBlockHeight
10606
- }).add(computeBudgetIx()).add(...claimAllTx);
10803
+ }).add(setCUIx).add(...claimAllTx);
10607
10804
  })
10608
10805
  );
10609
10806
  }
@@ -10670,11 +10867,22 @@ var DLMM = class {
10670
10867
  const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
10671
10868
  return Promise.all(
10672
10869
  claimAllTxs.map(async (claimAllTx) => {
10870
+ const mainInstructions = claimAllTx.map((t) => t.instructions).flat();
10871
+ const instructions = [
10872
+ ...preInstructions,
10873
+ ...mainInstructions,
10874
+ ...postInstructions
10875
+ ];
10876
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
10877
+ this.program.provider.connection,
10878
+ instructions,
10879
+ owner
10880
+ );
10673
10881
  const tx = new Transaction({
10674
10882
  feePayer: owner,
10675
10883
  blockhash,
10676
10884
  lastValidBlockHeight
10677
- }).add(computeBudgetIx());
10885
+ }).add(setCUIx);
10678
10886
  if (preInstructions.length)
10679
10887
  tx.add(...preInstructions);
10680
10888
  tx.add(...claimAllTx);
@@ -10695,15 +10903,15 @@ var DLMM = class {
10695
10903
  * @returns {Promise<SeedLiquidityResponse>}
10696
10904
  */
10697
10905
  async seedLiquidity(owner, seedAmount, curvature, minPrice, maxPrice, base) {
10698
- const toLamportMultiplier = new Decimal4(
10906
+ const toLamportMultiplier = new Decimal5(
10699
10907
  10 ** (this.tokenY.decimal - this.tokenX.decimal)
10700
10908
  );
10701
- const minPricePerLamport = new Decimal4(minPrice).mul(toLamportMultiplier);
10702
- const maxPricePerLamport = new Decimal4(maxPrice).mul(toLamportMultiplier);
10703
- const minBinId = new BN9(
10909
+ const minPricePerLamport = new Decimal5(minPrice).mul(toLamportMultiplier);
10910
+ const maxPricePerLamport = new Decimal5(maxPrice).mul(toLamportMultiplier);
10911
+ const minBinId = new BN10(
10704
10912
  DLMM.getBinIdFromPrice(minPricePerLamport, this.lbPair.binStep, false)
10705
10913
  );
10706
- const maxBinId = new BN9(
10914
+ const maxBinId = new BN10(
10707
10915
  DLMM.getBinIdFromPrice(maxPricePerLamport, this.lbPair.binStep, true)
10708
10916
  );
10709
10917
  if (minBinId.toNumber() < this.lbPair.activeId) {
@@ -10722,7 +10930,7 @@ var DLMM = class {
10722
10930
  maxBinId,
10723
10931
  k
10724
10932
  );
10725
- const decompressMultiplier = new BN9(10 ** this.tokenX.decimal);
10933
+ const decompressMultiplier = new BN10(10 ** this.tokenX.decimal);
10726
10934
  let { compressedBinAmount, compressionLoss } = compressBinAmount(
10727
10935
  binDepositAmount,
10728
10936
  decompressMultiplier
@@ -10734,10 +10942,10 @@ var DLMM = class {
10734
10942
  compressedBinAmount,
10735
10943
  compressionLoss,
10736
10944
  decompressMultiplier,
10737
- new BN9(2 ** 32 - 1)
10945
+ new BN10(2 ** 32 - 1)
10738
10946
  // u32
10739
10947
  );
10740
- const positionCount = getPositionCount(minBinId, maxBinId.sub(new BN9(1)));
10948
+ const positionCount = getPositionCount(minBinId, maxBinId.sub(new BN10(1)));
10741
10949
  const seederTokenX = getAssociatedTokenAddressSync2(
10742
10950
  this.lbPair.tokenXMint,
10743
10951
  owner,
@@ -10747,8 +10955,8 @@ var DLMM = class {
10747
10955
  const addLiquidityIxs = [];
10748
10956
  const appendedInitBinArrayIx = /* @__PURE__ */ new Set();
10749
10957
  for (let i = 0; i < positionCount.toNumber(); i++) {
10750
- const lowerBinId = minBinId.add(MAX_BIN_PER_POSITION.mul(new BN9(i)));
10751
- const upperBinId = lowerBinId.add(MAX_BIN_PER_POSITION).sub(new BN9(1));
10958
+ const lowerBinId = minBinId.add(MAX_BIN_PER_POSITION.mul(new BN10(i)));
10959
+ const upperBinId = lowerBinId.add(MAX_BIN_PER_POSITION).sub(new BN10(1));
10752
10960
  const lowerBinArrayIndex = binIdToBinArrayIndex(lowerBinId);
10753
10961
  const upperBinArrayIndex = binIdToBinArrayIndex(upperBinId);
10754
10962
  const [positionPda, _bump] = derivePosition(
@@ -10773,7 +10981,7 @@ var DLMM = class {
10773
10981
  upperBinArray,
10774
10982
  positionPda
10775
10983
  ]);
10776
- let instructions = [computeBudgetIx()];
10984
+ let instructions = [];
10777
10985
  const lowerBinArrayAccount = accounts[0];
10778
10986
  if (!lowerBinArrayAccount && !appendedInitBinArrayIx.has(lowerBinArray.toBase58())) {
10779
10987
  instructions.push(
@@ -10812,10 +11020,17 @@ var DLMM = class {
10812
11020
  );
10813
11021
  }
10814
11022
  if (instructions.length > 1) {
11023
+ instructions.push(
11024
+ await getEstimatedComputeUnitIxWithBuffer(
11025
+ this.program.provider.connection,
11026
+ instructions,
11027
+ owner
11028
+ )
11029
+ );
10815
11030
  initializeBinArraysAndPositionIxs.push(instructions);
10816
- instructions = [computeBudgetIx()];
11031
+ instructions = [];
10817
11032
  }
10818
- const positionDeposited = positionAccount && this.program.coder.accounts.decode("positionV2", positionAccount.data).liquidityShares.reduce((total, cur) => total.add(cur), new BN9(0)).gt(new BN9(0));
11033
+ const positionDeposited = positionAccount && this.program.coder.accounts.decode("positionV2", positionAccount.data).liquidityShares.reduce((total, cur) => total.add(cur), new BN10(0)).gt(new BN10(0));
10819
11034
  if (!positionDeposited) {
10820
11035
  const cappedUpperBinId = Math.min(
10821
11036
  upperBinId.toNumber(),
@@ -10869,7 +11084,12 @@ var DLMM = class {
10869
11084
  }).instruction()
10870
11085
  );
10871
11086
  }
10872
- addLiquidityIxs.push(instructions);
11087
+ addLiquidityIxs.push([
11088
+ ComputeBudgetProgram2.setComputeUnitLimit({
11089
+ units: DEFAULT_ADD_LIQUIDITY_CU
11090
+ }),
11091
+ ...instructions
11092
+ ]);
10873
11093
  }
10874
11094
  }
10875
11095
  return {
@@ -10905,12 +11125,12 @@ var DLMM = class {
10905
11125
  this.lbPair.binStep,
10906
11126
  !roundingUp
10907
11127
  );
10908
- const binId = new BN9(binIdNumber);
11128
+ const binId = new BN10(binIdNumber);
10909
11129
  const lowerBinArrayIndex = binIdToBinArrayIndex(binId);
10910
- const upperBinArrayIndex = lowerBinArrayIndex.add(new BN9(1));
11130
+ const upperBinArrayIndex = lowerBinArrayIndex.add(new BN10(1));
10911
11131
  const [lowerBinArray] = deriveBinArray(this.pubkey, lowerBinArrayIndex, this.program.programId);
10912
11132
  const [upperBinArray] = deriveBinArray(this.pubkey, upperBinArrayIndex, this.program.programId);
10913
- const [positionPda] = derivePosition(this.pubkey, base, binId, new BN9(1), this.program.programId);
11133
+ const [positionPda] = derivePosition(this.pubkey, base, binId, new BN10(1), this.program.programId);
10914
11134
  const preInstructions = [];
10915
11135
  const [
10916
11136
  { ataPubKey: userTokenX, ix: createPayerTokenXIx },
@@ -11025,7 +11245,7 @@ var DLMM = class {
11025
11245
  };
11026
11246
  const addLiquidityParams = {
11027
11247
  amountX: seedAmount,
11028
- amountY: new BN9(0),
11248
+ amountY: new BN10(0),
11029
11249
  binLiquidityDist: [binLiquidityDist]
11030
11250
  };
11031
11251
  const depositLiquidityIx = await this.program.methods.addLiquidity(addLiquidityParams).accounts({
@@ -11114,7 +11334,7 @@ var DLMM = class {
11114
11334
  owner,
11115
11335
  true
11116
11336
  );
11117
- let initializePositionByOperatorTx = await this.program.methods.initializePositionByOperator(
11337
+ const initializePositionByOperatorTx = await this.program.methods.initializePositionByOperator(
11118
11338
  lowerBinId.toNumber(),
11119
11339
  MAX_BIN_PER_POSITION.toNumber(),
11120
11340
  feeOwner,
@@ -11222,11 +11442,22 @@ var DLMM = class {
11222
11442
  const { blockhash, lastValidBlockHeight } = await this.program.provider.connection.getLatestBlockhash("confirmed");
11223
11443
  return Promise.all(
11224
11444
  chunkedClaimAllTx.map(async (claimAllTx) => {
11445
+ const mainIxs = claimAllTx.map((t) => t.instructions).flat();
11446
+ const instructions = [
11447
+ ...preInstructions,
11448
+ ...mainIxs,
11449
+ ...postInstructions
11450
+ ];
11451
+ const setCUIx = await getEstimatedComputeUnitIxWithBuffer(
11452
+ this.program.provider.connection,
11453
+ instructions,
11454
+ owner
11455
+ );
11225
11456
  const tx = new Transaction({
11226
11457
  feePayer: owner,
11227
11458
  blockhash,
11228
11459
  lastValidBlockHeight
11229
- }).add(computeBudgetIx());
11460
+ }).add(setCUIx);
11230
11461
  if (preInstructions.length)
11231
11462
  tx.add(...preInstructions);
11232
11463
  tx.add(...claimAllTx);
@@ -11248,12 +11479,12 @@ var DLMM = class {
11248
11479
  false
11249
11480
  );
11250
11481
  const marketPriceBinArrayIndex = binIdToBinArrayIndex(
11251
- new BN9(marketPriceBinId)
11482
+ new BN10(marketPriceBinId)
11252
11483
  );
11253
11484
  const swapForY = marketPriceBinId < activeBinId;
11254
11485
  const toBinArrayIndex = findNextBinArrayIndexWithLiquidity(
11255
11486
  swapForY,
11256
- new BN9(activeBinId),
11487
+ new BN10(activeBinId),
11257
11488
  this.lbPair,
11258
11489
  this.binArrayBitmapExtension?.account ?? null
11259
11490
  );
@@ -11286,11 +11517,11 @@ var DLMM = class {
11286
11517
  "Unable to sync with market price due to bin with liquidity between current and market price bin"
11287
11518
  );
11288
11519
  }
11289
- const fromBinArrayIndex = binIdToBinArrayIndex(new BN9(activeBinId));
11520
+ const fromBinArrayIndex = binIdToBinArrayIndex(new BN10(activeBinId));
11290
11521
  const swapForY = marketPriceBinId < activeBinId;
11291
11522
  const toBinArrayIndex = findNextBinArrayIndexWithLiquidity(
11292
11523
  swapForY,
11293
- new BN9(activeBinId),
11524
+ new BN10(activeBinId),
11294
11525
  this.lbPair,
11295
11526
  this.binArrayBitmapExtension?.account ?? null
11296
11527
  );
@@ -11387,7 +11618,7 @@ var DLMM = class {
11387
11618
  const amount1 = isWithdrawForY ? amountY : amountX;
11388
11619
  const remainAmountX = bin.amountX.sub(amountX);
11389
11620
  const remainAmountY = bin.amountY.sub(amountY);
11390
- if (amount0.eq(new BN9(0))) {
11621
+ if (amount0.eq(new BN10(0))) {
11391
11622
  return {
11392
11623
  withdrawAmount: amount1
11393
11624
  };
@@ -11419,19 +11650,19 @@ var DLMM = class {
11419
11650
  };
11420
11651
  }
11421
11652
  async getWithdrawSingleSideAmount(positionPubkey, isWithdrawForY) {
11422
- let totalWithdrawAmount = new BN9(0);
11653
+ let totalWithdrawAmount = new BN10(0);
11423
11654
  let lowerBinArray;
11424
11655
  let upperBinArray;
11425
11656
  const position = await this.program.account.positionV2.fetch(
11426
11657
  positionPubkey
11427
11658
  );
11428
- const lowerBinArrayIdx = binIdToBinArrayIndex(new BN9(position.lowerBinId));
11659
+ const lowerBinArrayIdx = binIdToBinArrayIndex(new BN10(position.lowerBinId));
11429
11660
  const [lowerBinArrayPubKey] = deriveBinArray(
11430
11661
  position.lbPair,
11431
11662
  lowerBinArrayIdx,
11432
11663
  this.program.programId
11433
11664
  );
11434
- const upperBinArrayIdx = lowerBinArrayIdx.add(new BN9(1));
11665
+ const upperBinArrayIdx = lowerBinArrayIdx.add(new BN10(1));
11435
11666
  const [upperBinArrayPubKey] = deriveBinArray(
11436
11667
  position.lbPair,
11437
11668
  upperBinArrayIdx,
@@ -11443,10 +11674,10 @@ var DLMM = class {
11443
11674
  ]);
11444
11675
  for (let idx = 0; idx < position.liquidityShares.length; idx++) {
11445
11676
  const shareToRemove = position.liquidityShares[idx];
11446
- if (shareToRemove.eq(new BN9(0))) {
11677
+ if (shareToRemove.eq(new BN10(0))) {
11447
11678
  continue;
11448
11679
  }
11449
- const binId = new BN9(position.lowerBinId).add(new BN9(idx));
11680
+ const binId = new BN10(position.lowerBinId).add(new BN10(idx));
11450
11681
  const binArrayIndex = binIdToBinArrayIndex(binId);
11451
11682
  const binArray = binArrayIndex.eq(lowerBinArrayIdx) ? lowerBinArray : upperBinArray;
11452
11683
  if (!binArray) {
@@ -11454,15 +11685,15 @@ var DLMM = class {
11454
11685
  }
11455
11686
  const bin = getBinFromBinArray(binId.toNumber(), binArray);
11456
11687
  if (isWithdrawForY) {
11457
- if (binId.gt(new BN9(this.lbPair.activeId))) {
11688
+ if (binId.gt(new BN10(this.lbPair.activeId))) {
11458
11689
  break;
11459
11690
  }
11460
11691
  } else {
11461
- if (binId.lt(new BN9(this.lbPair.activeId))) {
11692
+ if (binId.lt(new BN10(this.lbPair.activeId))) {
11462
11693
  continue;
11463
11694
  }
11464
11695
  }
11465
- const price = getQPriceFromId(binId, new BN9(this.lbPair.binStep));
11696
+ const price = getQPriceFromId(binId, new BN10(this.lbPair.binStep));
11466
11697
  const { withdrawAmount } = this.getAmountOutWithdrawSingleSide(
11467
11698
  shareToRemove,
11468
11699
  price,
@@ -11506,20 +11737,20 @@ var DLMM = class {
11506
11737
  ]);
11507
11738
  }
11508
11739
  static async getClaimableLMReward(program, positionVersion, lbPair, onChainTimestamp, position, lowerBinArray, upperBinArray) {
11509
- const lowerBinArrayIdx = binIdToBinArrayIndex(new BN9(position.lowerBinId));
11510
- let rewards = [new BN9(0), new BN9(0)];
11740
+ const lowerBinArrayIdx = binIdToBinArrayIndex(new BN10(position.lowerBinId));
11741
+ let rewards = [new BN10(0), new BN10(0)];
11511
11742
  let _lowerBinArray = lowerBinArray;
11512
11743
  let _upperBinArray = upperBinArray;
11513
11744
  if (!lowerBinArray || !upperBinArray) {
11514
11745
  const lowerBinArrayIdx2 = binIdToBinArrayIndex(
11515
- new BN9(position.lowerBinId)
11746
+ new BN10(position.lowerBinId)
11516
11747
  );
11517
11748
  const [lowerBinArray2] = deriveBinArray(
11518
11749
  position.lbPair,
11519
11750
  lowerBinArrayIdx2,
11520
11751
  program.programId
11521
11752
  );
11522
- const upperBinArrayIdx = lowerBinArrayIdx2.add(new BN9(1));
11753
+ const upperBinArrayIdx = lowerBinArrayIdx2.add(new BN10(1));
11523
11754
  const [upperBinArray2] = deriveBinArray(
11524
11755
  position.lbPair,
11525
11756
  upperBinArrayIdx,
@@ -11533,7 +11764,7 @@ var DLMM = class {
11533
11764
  if (!_lowerBinArray || !_upperBinArray)
11534
11765
  throw new Error("BinArray not found");
11535
11766
  for (let i = position.lowerBinId; i <= position.upperBinId; i++) {
11536
- const binArrayIdx = binIdToBinArrayIndex(new BN9(i));
11767
+ const binArrayIdx = binIdToBinArrayIndex(new BN10(i));
11537
11768
  const binArray = binArrayIdx.eq(lowerBinArrayIdx) ? _lowerBinArray : _upperBinArray;
11538
11769
  const binState = getBinFromBinArray(i, binArray);
11539
11770
  const binIdxInPosition = i - position.lowerBinId;
@@ -11544,7 +11775,7 @@ var DLMM = class {
11544
11775
  if (!pairRewardInfo.mint.equals(PublicKey6.default)) {
11545
11776
  let rewardPerTokenStored = binState.rewardPerTokenStored[j];
11546
11777
  if (i == lbPair.activeId && !binState.liquiditySupply.isZero()) {
11547
- const currentTime = new BN9(
11778
+ const currentTime = new BN10(
11548
11779
  Math.min(
11549
11780
  onChainTimestamp,
11550
11781
  pairRewardInfo.rewardDurationEnd.toNumber()
@@ -11552,7 +11783,7 @@ var DLMM = class {
11552
11783
  );
11553
11784
  const delta2 = currentTime.sub(pairRewardInfo.lastUpdateTime);
11554
11785
  const liquiditySupply = binArray.version == 0 ? binState.liquiditySupply : binState.liquiditySupply.shrn(64);
11555
- const rewardPerTokenStoredDelta = pairRewardInfo.rewardRate.mul(delta2).div(new BN9(15)).div(liquiditySupply);
11786
+ const rewardPerTokenStoredDelta = pairRewardInfo.rewardRate.mul(delta2).div(new BN10(15)).div(liquiditySupply);
11556
11787
  rewardPerTokenStored = rewardPerTokenStored.add(
11557
11788
  rewardPerTokenStoredDelta
11558
11789
  );
@@ -11576,21 +11807,21 @@ var DLMM = class {
11576
11807
  };
11577
11808
  }
11578
11809
  static async getClaimableSwapFee(program, positionVersion, position, lowerBinArray, upperBinArray) {
11579
- const lowerBinArrayIdx = binIdToBinArrayIndex(new BN9(position.lowerBinId));
11580
- let feeX = new BN9(0);
11581
- let feeY = new BN9(0);
11810
+ const lowerBinArrayIdx = binIdToBinArrayIndex(new BN10(position.lowerBinId));
11811
+ let feeX = new BN10(0);
11812
+ let feeY = new BN10(0);
11582
11813
  let _lowerBinArray = lowerBinArray;
11583
11814
  let _upperBinArray = upperBinArray;
11584
11815
  if (!lowerBinArray || !upperBinArray) {
11585
11816
  const lowerBinArrayIdx2 = binIdToBinArrayIndex(
11586
- new BN9(position.lowerBinId)
11817
+ new BN10(position.lowerBinId)
11587
11818
  );
11588
11819
  const [lowerBinArray2] = deriveBinArray(
11589
11820
  position.lbPair,
11590
11821
  lowerBinArrayIdx2,
11591
11822
  program.programId
11592
11823
  );
11593
- const upperBinArrayIdx = lowerBinArrayIdx2.add(new BN9(1));
11824
+ const upperBinArrayIdx = lowerBinArrayIdx2.add(new BN10(1));
11594
11825
  const [upperBinArray2] = deriveBinArray(
11595
11826
  position.lbPair,
11596
11827
  upperBinArrayIdx,
@@ -11604,7 +11835,7 @@ var DLMM = class {
11604
11835
  if (!_lowerBinArray || !_upperBinArray)
11605
11836
  throw new Error("BinArray not found");
11606
11837
  for (let i = position.lowerBinId; i <= position.upperBinId; i++) {
11607
- const binArrayIdx = binIdToBinArrayIndex(new BN9(i));
11838
+ const binArrayIdx = binIdToBinArrayIndex(new BN10(i));
11608
11839
  const binArray = binArrayIdx.eq(lowerBinArrayIdx) ? _lowerBinArray : _upperBinArray;
11609
11840
  const binState = getBinFromBinArray(i, binArray);
11610
11841
  const binIdxInPosition = i - position.lowerBinId;
@@ -11650,18 +11881,18 @@ var DLMM = class {
11650
11881
  if (bins[0].binId !== lowerBinId || bins[bins.length - 1].binId !== upperBinId)
11651
11882
  throw new Error("Bin ID mismatch");
11652
11883
  const positionData = [];
11653
- let totalXAmount = new Decimal4(0);
11654
- let totalYAmount = new Decimal4(0);
11884
+ let totalXAmount = new Decimal5(0);
11885
+ let totalYAmount = new Decimal5(0);
11655
11886
  bins.forEach((bin, idx) => {
11656
- const binSupply = new Decimal4(bin.supply.toString());
11887
+ const binSupply = new Decimal5(bin.supply.toString());
11657
11888
  let posShare;
11658
11889
  if (bin.version === 1 && version === 0 /* V1 */) {
11659
- posShare = new Decimal4(posShares[idx].shln(64).toString());
11890
+ posShare = new Decimal5(posShares[idx].shln(64).toString());
11660
11891
  } else {
11661
- posShare = new Decimal4(posShares[idx].toString());
11892
+ posShare = new Decimal5(posShares[idx].toString());
11662
11893
  }
11663
- const positionXAmount = binSupply.eq(new Decimal4("0")) ? new Decimal4("0") : posShare.mul(bin.xAmount.toString()).div(binSupply);
11664
- const positionYAmount = binSupply.eq(new Decimal4("0")) ? new Decimal4("0") : posShare.mul(bin.yAmount.toString()).div(binSupply);
11894
+ const positionXAmount = binSupply.eq(new Decimal5("0")) ? new Decimal5("0") : posShare.mul(bin.xAmount.toString()).div(binSupply);
11895
+ const positionYAmount = binSupply.eq(new Decimal5("0")) ? new Decimal5("0") : posShare.mul(bin.yAmount.toString()).div(binSupply);
11665
11896
  totalXAmount = totalXAmount.add(positionXAmount);
11666
11897
  totalYAmount = totalYAmount.add(positionYAmount);
11667
11898
  positionData.push({
@@ -11709,8 +11940,8 @@ var DLMM = class {
11709
11940
  };
11710
11941
  }
11711
11942
  static getBinsBetweenLowerAndUpperBound(lbPair, lowerBinId, upperBinId, baseTokenDecimal, quoteTokenDecimal, lowerBinArrays, upperBinArrays) {
11712
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
11713
- const upperBinArrayIndex = binIdToBinArrayIndex(new BN9(upperBinId));
11943
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
11944
+ const upperBinArrayIndex = binIdToBinArrayIndex(new BN10(upperBinId));
11714
11945
  let bins = [];
11715
11946
  if (lowerBinArrayIndex.eq(upperBinArrayIndex)) {
11716
11947
  const binArray = lowerBinArrays;
@@ -11731,7 +11962,7 @@ var DLMM = class {
11731
11962
  supply: bin.liquiditySupply,
11732
11963
  price: pricePerLamport,
11733
11964
  version: binArray.version,
11734
- pricePerToken: new Decimal4(pricePerLamport).mul(new Decimal4(10 ** (baseTokenDecimal - quoteTokenDecimal))).toString()
11965
+ pricePerToken: new Decimal5(pricePerLamport).mul(new Decimal5(10 ** (baseTokenDecimal - quoteTokenDecimal))).toString()
11735
11966
  });
11736
11967
  }
11737
11968
  });
@@ -11755,7 +11986,7 @@ var DLMM = class {
11755
11986
  supply: bin.liquiditySupply,
11756
11987
  price: pricePerLamport,
11757
11988
  version: binArray.version,
11758
- pricePerToken: new Decimal4(pricePerLamport).mul(new Decimal4(10 ** (baseTokenDecimal - quoteTokenDecimal))).toString()
11989
+ pricePerToken: new Decimal5(pricePerLamport).mul(new Decimal5(10 ** (baseTokenDecimal - quoteTokenDecimal))).toString()
11759
11990
  });
11760
11991
  }
11761
11992
  });
@@ -11787,112 +12018,45 @@ var DLMM = class {
11787
12018
  binIds
11788
12019
  };
11789
12020
  }
11790
- async getBins(lbPairPubKey, lowerBinId, upperBinId, baseTokenDecimal, quoteTokenDecimal, lowerBinArrays, upperBinArrays) {
11791
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
11792
- const upperBinArrayIndex = binIdToBinArrayIndex(new BN9(upperBinId));
11793
- let bins = [];
11794
- if (lowerBinArrayIndex.eq(upperBinArrayIndex)) {
11795
- const [binArrayPubKey] = deriveBinArray(
11796
- lbPairPubKey,
11797
- lowerBinArrayIndex,
11798
- this.program.programId
11799
- );
11800
- const binArray = lowerBinArrays ?? await this.program.account.binArray.fetch(binArrayPubKey).catch(() => {
11801
- const [lowerBinId2, upperBinId2] = getBinArrayLowerUpperBinId(lowerBinArrayIndex);
11802
- const binArrayBins = [];
11803
- for (let i = lowerBinId2.toNumber(); i <= upperBinId2.toNumber(); i++) {
11804
- binArrayBins.push({
11805
- amountX: new BN9(0),
11806
- amountY: new BN9(0),
11807
- liquiditySupply: new BN9(0),
11808
- rewardPerTokenStored: [new BN9(0), new BN9(0)],
11809
- amountXIn: new BN9(0),
11810
- amountYIn: new BN9(0),
11811
- feeAmountXPerTokenStored: new BN9(0),
11812
- feeAmountYPerTokenStored: new BN9(0),
11813
- price: new BN9(0)
11814
- });
11815
- }
11816
- return {
11817
- bins: binArrayBins,
11818
- index: lowerBinArrayIndex,
11819
- version: 1
11820
- };
11821
- });
11822
- const [lowerBinIdForBinArray] = getBinArrayLowerUpperBinId(
11823
- binArray.index
11824
- );
11825
- binArray.bins.forEach((bin, idx) => {
11826
- const binId = lowerBinIdForBinArray.toNumber() + idx;
11827
- if (binId >= lowerBinId && binId <= upperBinId) {
11828
- const pricePerLamport = getPriceOfBinByBinId(
11829
- binId,
11830
- this.lbPair.binStep
11831
- ).toString();
11832
- bins.push({
11833
- binId,
11834
- xAmount: bin.amountX,
11835
- yAmount: bin.amountY,
11836
- supply: bin.liquiditySupply,
11837
- price: pricePerLamport,
11838
- version: binArray.version,
11839
- pricePerToken: new Decimal4(pricePerLamport).mul(new Decimal4(10 ** (baseTokenDecimal - quoteTokenDecimal))).toString()
11840
- });
11841
- }
11842
- });
11843
- } else {
11844
- const [lowerBinArrayPubKey] = deriveBinArray(
11845
- lbPairPubKey,
11846
- lowerBinArrayIndex,
11847
- this.program.programId
11848
- );
11849
- const [upperBinArrayPubKey] = deriveBinArray(
11850
- lbPairPubKey,
11851
- upperBinArrayIndex,
11852
- this.program.programId
11853
- );
11854
- const binArrays = await (async () => {
11855
- if (!lowerBinArrays || !upperBinArrays) {
11856
- return (await this.program.account.binArray.fetchMultiple([
11857
- lowerBinArrayPubKey,
11858
- upperBinArrayPubKey
11859
- ])).filter((binArray) => binArray !== null);
11860
- }
11861
- return [lowerBinArrays, upperBinArrays];
11862
- })();
11863
- binArrays.forEach((binArray) => {
11864
- if (!binArray)
11865
- return;
11866
- const [lowerBinIdForBinArray] = getBinArrayLowerUpperBinId(
11867
- binArray.index
11868
- );
11869
- binArray.bins.forEach((bin, idx) => {
11870
- const binId = lowerBinIdForBinArray.toNumber() + idx;
11871
- if (binId >= lowerBinId && binId <= upperBinId) {
11872
- const pricePerLamport = getPriceOfBinByBinId(
11873
- binId,
11874
- this.lbPair.binStep
11875
- ).toString();
11876
- bins.push({
11877
- binId,
11878
- xAmount: bin.amountX,
11879
- yAmount: bin.amountY,
11880
- supply: bin.liquiditySupply,
11881
- price: pricePerLamport,
11882
- version: binArray.version,
11883
- pricePerToken: new Decimal4(pricePerLamport).mul(new Decimal4(10 ** (baseTokenDecimal - quoteTokenDecimal))).toString()
11884
- });
11885
- }
11886
- });
11887
- });
11888
- }
11889
- return bins;
12021
+ async getBins(lbPairPubKey, lowerBinId, upperBinId, baseTokenDecimal, quoteTokenDecimal, lowerBinArray, upperBinArray) {
12022
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
12023
+ const upperBinArrayIndex = binIdToBinArrayIndex(new BN10(upperBinId));
12024
+ const hasCachedLowerBinArray = lowerBinArray != null;
12025
+ const hasCachedUpperBinArray = upperBinArray != null;
12026
+ const isSingleBinArray = lowerBinArrayIndex.eq(upperBinArrayIndex);
12027
+ const lowerBinArrayIndexOffset = hasCachedLowerBinArray ? 1 : 0;
12028
+ const upperBinArrayIndexOffset = hasCachedUpperBinArray ? -1 : 0;
12029
+ const binArrayPubkeys = range(
12030
+ lowerBinArrayIndex.toNumber() + lowerBinArrayIndexOffset,
12031
+ upperBinArrayIndex.toNumber() + upperBinArrayIndexOffset,
12032
+ (i) => deriveBinArray(lbPairPubKey, new BN10(i), this.program.programId)[0]
12033
+ );
12034
+ const fetchedBinArrays = binArrayPubkeys.length !== 0 ? await this.program.account.binArray.fetchMultiple(binArrayPubkeys) : [];
12035
+ const binArrays = [
12036
+ ...hasCachedLowerBinArray ? [lowerBinArray] : [],
12037
+ ...fetchedBinArrays,
12038
+ ...hasCachedUpperBinArray && !isSingleBinArray ? [upperBinArray] : []
12039
+ ];
12040
+ const binsById = new Map(binArrays.filter((x) => x != null).flatMap(({ bins, index }) => {
12041
+ const [lowerBinId2] = getBinArrayLowerUpperBinId(index);
12042
+ return bins.map((b, i) => [lowerBinId2.toNumber() + i, b]);
12043
+ }));
12044
+ const version = binArrays.find((binArray) => binArray != null)?.version ?? 1;
12045
+ return Array.from(enumerateBins(
12046
+ binsById,
12047
+ lowerBinId,
12048
+ upperBinId,
12049
+ this.lbPair.binStep,
12050
+ baseTokenDecimal,
12051
+ quoteTokenDecimal,
12052
+ version
12053
+ ));
11890
12054
  }
11891
12055
  async binArraysToBeCreate(lowerBinArrayIndex, upperBinArrayIndex) {
11892
12056
  const binArrayIndexes = Array.from(
11893
12057
  { length: upperBinArrayIndex.sub(lowerBinArrayIndex).toNumber() + 1 },
11894
12058
  (_, index) => index + lowerBinArrayIndex.toNumber()
11895
- ).map((idx) => new BN9(idx));
12059
+ ).map((idx) => new BN10(idx));
11896
12060
  const binArrays = [];
11897
12061
  for (const idx of binArrayIndexes) {
11898
12062
  const [binArrayPubKey] = deriveBinArray(
@@ -11910,7 +12074,7 @@ var DLMM = class {
11910
12074
  const binArrayIndexes = Array.from(
11911
12075
  { length: upperBinArrayIndex.sub(lowerBinArrayIndex).toNumber() + 1 },
11912
12076
  (_, index) => index + lowerBinArrayIndex.toNumber()
11913
- ).map((idx) => new BN9(idx));
12077
+ ).map((idx) => new BN10(idx));
11914
12078
  for (const idx of binArrayIndexes) {
11915
12079
  const [binArray] = deriveBinArray(
11916
12080
  this.pubkey,
@@ -11958,14 +12122,14 @@ var DLMM = class {
11958
12122
  shouldIncludePreIx = true
11959
12123
  }) {
11960
12124
  const lowerBinArrayIndex = binIdToBinArrayIndex(
11961
- new BN9(position.positionData.lowerBinId)
12125
+ new BN10(position.positionData.lowerBinId)
11962
12126
  );
11963
12127
  const [binArrayLower] = deriveBinArray(
11964
12128
  this.pubkey,
11965
12129
  lowerBinArrayIndex,
11966
12130
  this.program.programId
11967
12131
  );
11968
- const upperBinArrayIndex = lowerBinArrayIndex.add(new BN9(1));
12132
+ const upperBinArrayIndex = lowerBinArrayIndex.add(new BN10(1));
11969
12133
  const [binArrayUpper] = deriveBinArray(
11970
12134
  this.pubkey,
11971
12135
  upperBinArrayIndex,
@@ -11983,7 +12147,7 @@ var DLMM = class {
11983
12147
  owner
11984
12148
  );
11985
12149
  ix && preInstructions.push(ix);
11986
- const claimTransaction = await this.program.methods.claimReward(new BN9(i)).accounts({
12150
+ const claimTransaction = await this.program.methods.claimReward(new BN10(i)).accounts({
11987
12151
  lbPair: this.pubkey,
11988
12152
  sender: owner,
11989
12153
  position: position.publicKey,
@@ -12005,13 +12169,13 @@ var DLMM = class {
12005
12169
  shouldIncludePostIx = true
12006
12170
  }) {
12007
12171
  const { lowerBinId, feeOwner } = position.positionData;
12008
- const lowerBinArrayIndex = binIdToBinArrayIndex(new BN9(lowerBinId));
12172
+ const lowerBinArrayIndex = binIdToBinArrayIndex(new BN10(lowerBinId));
12009
12173
  const [binArrayLower] = deriveBinArray(
12010
12174
  this.pubkey,
12011
12175
  lowerBinArrayIndex,
12012
12176
  this.program.programId
12013
12177
  );
12014
- const upperBinArrayIndex = lowerBinArrayIndex.add(new BN9(1));
12178
+ const upperBinArrayIndex = lowerBinArrayIndex.add(new BN10(1));
12015
12179
  const [binArrayUpper] = deriveBinArray(
12016
12180
  this.pubkey,
12017
12181
  upperBinArrayIndex,
@@ -12082,6 +12246,7 @@ export {
12082
12246
  BASIS_POINT_MAX,
12083
12247
  BIN_ARRAY_BITMAP_SIZE,
12084
12248
  BIN_ARRAY_FEE,
12249
+ BinLiquidity,
12085
12250
  BitmapType,
12086
12251
  ClockLayout,
12087
12252
  DLMMError,
@@ -12121,7 +12286,6 @@ export {
12121
12286
  chunkedFetchMultiplePoolAccount,
12122
12287
  chunkedGetMultipleAccountInfos,
12123
12288
  chunks,
12124
- computeBudgetIx,
12125
12289
  computeFee,
12126
12290
  computeFeeFromAmount,
12127
12291
  computeProtocolFee,
@@ -12137,6 +12301,7 @@ export {
12137
12301
  derivePresetParameter,
12138
12302
  derivePresetParameter2,
12139
12303
  deriveReserve,
12304
+ enumerateBins,
12140
12305
  findNextBinArrayIndexWithLiquidity,
12141
12306
  findNextBinArrayWithLiquidity,
12142
12307
  fromWeightDistributionToAmount,
@@ -12145,6 +12310,8 @@ export {
12145
12310
  getBinArrayLowerUpperBinId,
12146
12311
  getBinArraysRequiredByPositionRange,
12147
12312
  getBinFromBinArray,
12313
+ getEstimatedComputeUnitIxWithBuffer,
12314
+ getEstimatedComputeUnitUsageWithBuffer,
12148
12315
  getOrCreateATAInstruction,
12149
12316
  getOutAmount,
12150
12317
  getPriceOfBinByBinId,
@@ -12156,6 +12323,7 @@ export {
12156
12323
  isBinIdWithinBinArray,
12157
12324
  isOverflowDefaultBinArrayBitmap,
12158
12325
  parseLogs,
12326
+ range,
12159
12327
  swapExactInQuoteAtBin,
12160
12328
  swapExactOutQuoteAtBin,
12161
12329
  toAmountAskSide,