@magmaprotocol/magma-clmm-sdk 0.5.76 → 0.5.77

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.js CHANGED
@@ -37,7 +37,6 @@ var src_exports = {};
37
37
  __export(src_exports, {
38
38
  AMM_SWAP_MODULE: () => AMM_SWAP_MODULE,
39
39
  AmountSpecified: () => AmountSpecified,
40
- BinMath: () => BinMath,
41
40
  CLOCK_ADDRESS: () => CLOCK_ADDRESS,
42
41
  CachedContent: () => CachedContent,
43
42
  ClmmExpectSwapModule: () => ClmmExpectSwapModule,
@@ -65,7 +64,6 @@ __export(src_exports, {
65
64
  DeepbookCustodianV2Moudle: () => DeepbookCustodianV2Moudle,
66
65
  DeepbookEndpointsV2Moudle: () => DeepbookEndpointsV2Moudle,
67
66
  DeepbookUtils: () => DeepbookUtils,
68
- DlmmScript: () => DlmmScript,
69
67
  FEE_RATE_DENOMINATOR: () => FEE_RATE_DENOMINATOR,
70
68
  GAS_SYMBOL: () => GAS_SYMBOL,
71
69
  GAS_TYPE_ARG: () => GAS_TYPE_ARG,
@@ -93,7 +91,6 @@ __export(src_exports, {
93
91
  SUI_SYSTEM_STATE_OBJECT_ID: () => SUI_SYSTEM_STATE_OBJECT_ID,
94
92
  SplitSwap: () => SplitSwap,
95
93
  SplitUnit: () => SplitUnit,
96
- StrategyType: () => StrategyType,
97
94
  SwapDirection: () => SwapDirection,
98
95
  SwapModule: () => SwapModule,
99
96
  SwapUtils: () => SwapUtils,
@@ -115,10 +112,6 @@ __export(src_exports, {
115
112
  adjustForSlippage: () => adjustForSlippage,
116
113
  asIntN: () => asIntN,
117
114
  asUintN: () => asUintN,
118
- autoFillXByStrategy: () => autoFillXByStrategy,
119
- autoFillXByWeight: () => autoFillXByWeight,
120
- autoFillYByStrategy: () => autoFillYByStrategy,
121
- autoFillYByWeight: () => autoFillYByWeight,
122
115
  bufferToHex: () => bufferToHex,
123
116
  buildClmmPositionName: () => buildClmmPositionName,
124
117
  buildNFT: () => buildNFT,
@@ -157,14 +150,12 @@ __export(src_exports, {
157
150
  getAmountUnfixedDelta: () => getAmountUnfixedDelta,
158
151
  getCoinAFromLiquidity: () => getCoinAFromLiquidity,
159
152
  getCoinBFromLiquidity: () => getCoinBFromLiquidity,
160
- getCoinXYForLiquidity: () => getCoinXYForLiquidity,
161
153
  getDefaultSuiInputType: () => getDefaultSuiInputType,
162
154
  getDeltaA: () => getDeltaA,
163
155
  getDeltaB: () => getDeltaB,
164
156
  getDeltaDownFromOutput: () => getDeltaDownFromOutput,
165
157
  getDeltaUpFromInput: () => getDeltaUpFromInput,
166
158
  getFutureTime: () => getFutureTime,
167
- getLiquidityAndCoinYByCoinX: () => getLiquidityAndCoinYByCoinX,
168
159
  getLiquidityFromCoinA: () => getLiquidityFromCoinA,
169
160
  getLiquidityFromCoinB: () => getLiquidityFromCoinB,
170
161
  getLowerSqrtPriceFromCoinA: () => getLowerSqrtPriceFromCoinA,
@@ -188,7 +179,6 @@ __export(src_exports, {
188
179
  getObjectType: () => getObjectType,
189
180
  getObjectVersion: () => getObjectVersion,
190
181
  getPackagerConfigs: () => getPackagerConfigs,
191
- getPriceOfBinByBinId: () => getPriceOfBinByBinId,
192
182
  getRewardInTickRange: () => getRewardInTickRange,
193
183
  getSuiObjectData: () => getSuiObjectData,
194
184
  getTickDataFromUrlData: () => getTickDataFromUrlData,
@@ -212,16 +202,11 @@ __export(src_exports, {
212
202
  shortAddress: () => shortAddress,
213
203
  shortString: () => shortString,
214
204
  tickScore: () => tickScore,
215
- toAmountAskSide: () => toAmountAskSide,
216
- toAmountBidSide: () => toAmountBidSide,
217
- toAmountBothSide: () => toAmountBothSide,
218
- toAmountsBothSideByStrategy: () => toAmountsBothSideByStrategy,
219
205
  toBuffer: () => toBuffer,
220
206
  toCoinAmount: () => toCoinAmount,
221
207
  toDecimalsAmount: () => toDecimalsAmount,
222
208
  transClmmpoolDataWithoutTicks: () => transClmmpoolDataWithoutTicks,
223
- utf8to16: () => utf8to16,
224
- withLiquiditySlippage: () => withLiquiditySlippage
209
+ utf8to16: () => utf8to16
225
210
  });
226
211
  module.exports = __toCommonJS(src_exports);
227
212
 
@@ -257,7 +242,7 @@ var CachedContent = class {
257
242
  };
258
243
 
259
244
  // src/utils/common.ts
260
- var import_bn12 = __toESM(require("bn.js"));
245
+ var import_bn11 = __toESM(require("bn.js"));
261
246
  var import_bcs = require("@mysten/bcs");
262
247
  var import_ed25519 = require("@mysten/sui/keypairs/ed25519");
263
248
  var import_secp256k1 = require("@mysten/sui/keypairs/secp256k1");
@@ -523,7 +508,6 @@ var Voter = "voter";
523
508
  var RewardDistributor = "reward_distributor";
524
509
  var Gauge = "gauge";
525
510
  var Minter = "minter";
526
- var DlmmScript = "dlmm_script";
527
511
  var CoinInfoAddress = "0x1::coin::CoinInfo";
528
512
  var CoinStoreAddress = "0x1::coin::CoinStore";
529
513
  var DeepbookCustodianV2Moudle = "custodian_v2";
@@ -1812,476 +1796,8 @@ function collectFeesQuote(param) {
1812
1796
  return updateFees(param.position, fee_growth_inside_a, fee_growth_inside_b);
1813
1797
  }
1814
1798
 
1815
- // src/math/dlmmWeightToAmounts.ts
1816
- var import_bn9 = __toESM(require("bn.js"));
1817
- var import_decimal6 = __toESM(require("decimal.js"));
1818
- var import_calc_dlmm = require("@magmaprotocol/calc_dlmm");
1819
- function getPriceOfBinByBinId(binId, binStep) {
1820
- const twoDec = new import_decimal6.default(2);
1821
- const price = new import_decimal6.default((0, import_calc_dlmm.get_price_x128_from_real_id)(binId, binStep));
1822
- return price.div(twoDec.pow(128));
1823
- }
1824
- function autoFillYByWeight(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, distributions) {
1825
- const activeBins = distributions.filter((element) => {
1826
- return element.binId === activeId;
1827
- });
1828
- if (activeBins.length === 1) {
1829
- const p0 = getPriceOfBinByBinId(activeId, binStep);
1830
- let wx0 = new import_decimal6.default(0);
1831
- let wy0 = new import_decimal6.default(0);
1832
- const activeBin = activeBins[0];
1833
- if (amountXInActiveBin.isZero() && amountYInActiveBin.isZero()) {
1834
- wx0 = new import_decimal6.default(activeBin.weight).div(p0.mul(new import_decimal6.default(2)));
1835
- wy0 = new import_decimal6.default(activeBin.weight).div(new import_decimal6.default(2));
1836
- } else {
1837
- const amountXInActiveBinDec = new import_decimal6.default(amountXInActiveBin.toString());
1838
- const amountYInActiveBinDec = new import_decimal6.default(amountYInActiveBin.toString());
1839
- if (!amountXInActiveBin.isZero()) {
1840
- wx0 = new import_decimal6.default(activeBin.weight).div(p0.add(amountYInActiveBinDec.div(amountXInActiveBinDec)));
1841
- }
1842
- if (!amountYInActiveBin.isZero()) {
1843
- wy0 = new import_decimal6.default(activeBin.weight).div(new import_decimal6.default(1).add(p0.mul(amountXInActiveBinDec).div(amountYInActiveBinDec)));
1844
- }
1845
- }
1846
- let totalWeightX2 = wx0;
1847
- let totalWeightY2 = wy0;
1848
- distributions.forEach((element) => {
1849
- if (element.binId < activeId) {
1850
- totalWeightY2 = totalWeightY2.add(new import_decimal6.default(element.weight));
1851
- }
1852
- if (element.binId > activeId) {
1853
- const price = getPriceOfBinByBinId(element.binId, binStep);
1854
- const weighPerPrice = new import_decimal6.default(element.weight).div(price);
1855
- totalWeightX2 = totalWeightX2.add(weighPerPrice);
1856
- }
1857
- });
1858
- const kx2 = totalWeightX2.isZero() ? new import_decimal6.default(1) : new import_decimal6.default(amountX.toString()).div(totalWeightX2);
1859
- const amountY2 = kx2.mul(totalWeightY2);
1860
- return new import_bn9.default(amountY2.floor().toString());
1861
- }
1862
- let totalWeightX = new import_decimal6.default(0);
1863
- let totalWeightY = new import_decimal6.default(0);
1864
- distributions.forEach((element) => {
1865
- if (element.binId < activeId) {
1866
- totalWeightY = totalWeightY.add(new import_decimal6.default(element.weight));
1867
- } else {
1868
- const price = getPriceOfBinByBinId(element.binId, binStep);
1869
- const weighPerPrice = new import_decimal6.default(element.weight).div(price);
1870
- totalWeightX = totalWeightX.add(weighPerPrice);
1871
- }
1872
- });
1873
- const kx = totalWeightX.isZero() ? new import_decimal6.default(1) : new import_decimal6.default(amountX.toString()).div(totalWeightX);
1874
- const amountY = kx.mul(totalWeightY);
1875
- return new import_bn9.default(amountY.floor().toString());
1876
- }
1877
- function autoFillXByWeight(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, distributions) {
1878
- const activeBins = distributions.filter((element) => {
1879
- return element.binId === activeId;
1880
- });
1881
- if (activeBins.length === 1) {
1882
- const p0 = getPriceOfBinByBinId(activeId, binStep);
1883
- let wx0 = new import_decimal6.default(0);
1884
- let wy0 = new import_decimal6.default(0);
1885
- const activeBin = activeBins[0];
1886
- if (amountXInActiveBin.isZero() && amountYInActiveBin.isZero()) {
1887
- wx0 = new import_decimal6.default(activeBin.weight).div(p0.mul(new import_decimal6.default(2)));
1888
- wy0 = new import_decimal6.default(activeBin.weight).div(new import_decimal6.default(2));
1889
- } else {
1890
- const amountXInActiveBinDec = new import_decimal6.default(amountXInActiveBin.toString());
1891
- const amountYInActiveBinDec = new import_decimal6.default(amountYInActiveBin.toString());
1892
- if (!amountXInActiveBin.isZero()) {
1893
- wx0 = new import_decimal6.default(activeBin.weight).div(p0.add(amountYInActiveBinDec.div(amountXInActiveBinDec)));
1894
- }
1895
- if (!amountYInActiveBin.isZero()) {
1896
- wy0 = new import_decimal6.default(activeBin.weight).div(new import_decimal6.default(1).add(p0.mul(amountXInActiveBinDec).div(amountYInActiveBinDec)));
1897
- }
1898
- }
1899
- let totalWeightX2 = wx0;
1900
- let totalWeightY2 = wy0;
1901
- distributions.forEach((element) => {
1902
- if (element.binId < activeId) {
1903
- totalWeightY2 = totalWeightY2.add(new import_decimal6.default(element.weight));
1904
- }
1905
- if (element.binId > activeId) {
1906
- const price = getPriceOfBinByBinId(element.binId, binStep);
1907
- const weighPerPrice = new import_decimal6.default(element.weight).div(price);
1908
- totalWeightX2 = totalWeightX2.add(weighPerPrice);
1909
- }
1910
- });
1911
- const ky2 = totalWeightY2.isZero() ? new import_decimal6.default(1) : new import_decimal6.default(amountY.toString()).div(totalWeightY2);
1912
- const amountX2 = ky2.mul(totalWeightX2);
1913
- return new import_bn9.default(amountX2.floor().toString());
1914
- }
1915
- let totalWeightX = new import_decimal6.default(0);
1916
- let totalWeightY = new import_decimal6.default(0);
1917
- distributions.forEach((element) => {
1918
- if (element.binId < activeId) {
1919
- totalWeightY = totalWeightY.add(new import_decimal6.default(element.weight));
1920
- } else {
1921
- const price = getPriceOfBinByBinId(element.binId, binStep);
1922
- const weighPerPrice = new import_decimal6.default(element.weight).div(price);
1923
- totalWeightX = totalWeightX.add(weighPerPrice);
1924
- }
1925
- });
1926
- const ky = totalWeightY.isZero() ? new import_decimal6.default(1) : new import_decimal6.default(amountY.toString()).div(totalWeightY);
1927
- const amountX = ky.mul(totalWeightX);
1928
- return new import_bn9.default(amountX.floor().toString());
1929
- }
1930
- function toAmountBidSide(activeId, totalAmount, distributions) {
1931
- const totalWeight = distributions.reduce((sum, el) => {
1932
- return el.binId > activeId ? sum : sum.add(el.weight);
1933
- }, new import_decimal6.default(0));
1934
- if (totalWeight.cmp(new import_decimal6.default(0)) !== 1) {
1935
- throw Error("Invalid parameteres");
1936
- }
1937
- return distributions.map((bin) => {
1938
- if (bin.binId > activeId) {
1939
- return {
1940
- binId: bin.binId,
1941
- amount: new import_bn9.default(0)
1942
- };
1943
- }
1944
- return {
1945
- binId: bin.binId,
1946
- amount: new import_bn9.default(new import_decimal6.default(totalAmount.toString()).mul(new import_decimal6.default(bin.weight).div(totalWeight)).floor().toString())
1947
- };
1948
- });
1949
- }
1950
- function toAmountAskSide(activeId, binStep, totalAmount, distributions) {
1951
- const totalWeight = distributions.reduce((sum, el) => {
1952
- if (el.binId < activeId) {
1953
- return sum;
1954
- }
1955
- const price = getPriceOfBinByBinId(el.binId, binStep);
1956
- const weightPerPrice = new import_decimal6.default(el.weight).div(price);
1957
- return sum.add(weightPerPrice);
1958
- }, new import_decimal6.default(0));
1959
- if (totalWeight.cmp(new import_decimal6.default(0)) !== 1) {
1960
- throw Error("Invalid parameteres");
1961
- }
1962
- return distributions.map((bin) => {
1963
- if (bin.binId < activeId) {
1964
- return {
1965
- binId: bin.binId,
1966
- amount: new import_bn9.default(0)
1967
- };
1968
- }
1969
- const price = getPriceOfBinByBinId(bin.binId, binStep);
1970
- const weightPerPrice = new import_decimal6.default(bin.weight).div(price);
1971
- return {
1972
- binId: bin.binId,
1973
- amount: new import_bn9.default(new import_decimal6.default(totalAmount.toString()).mul(weightPerPrice).div(totalWeight).floor().toString())
1974
- };
1975
- });
1976
- }
1977
- function toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, distributions) {
1978
- if (activeId > distributions[distributions.length - 1].binId) {
1979
- const amounts = toAmountBidSide(activeId, amountY, distributions);
1980
- return amounts.map((bin) => {
1981
- return {
1982
- binId: bin.binId,
1983
- amountX: new import_bn9.default(0),
1984
- amountY: bin.amount
1985
- };
1986
- });
1987
- }
1988
- if (activeId < distributions[0].binId) {
1989
- const amounts = toAmountAskSide(activeId, binStep, amountX, distributions);
1990
- return amounts.map((bin) => {
1991
- return {
1992
- binId: bin.binId,
1993
- amountX: bin.amount,
1994
- amountY: new import_bn9.default(0)
1995
- };
1996
- });
1997
- }
1998
- const activeBins = distributions.filter((element) => {
1999
- return element.binId === activeId;
2000
- });
2001
- if (activeBins.length === 1) {
2002
- const p0 = getPriceOfBinByBinId(activeId, binStep);
2003
- let wx0 = new import_decimal6.default(0);
2004
- let wy0 = new import_decimal6.default(0);
2005
- const activeBin = activeBins[0];
2006
- if (amountXInActiveBin.isZero() && amountYInActiveBin.isZero()) {
2007
- wx0 = new import_decimal6.default(activeBin.weight).div(p0.mul(new import_decimal6.default(2)));
2008
- wy0 = new import_decimal6.default(activeBin.weight).div(new import_decimal6.default(2));
2009
- } else {
2010
- const amountXInActiveBinDec = new import_decimal6.default(amountXInActiveBin.toString());
2011
- const amountYInActiveBinDec = new import_decimal6.default(amountYInActiveBin.toString());
2012
- if (!amountXInActiveBin.isZero()) {
2013
- wx0 = new import_decimal6.default(activeBin.weight).div(p0.add(amountYInActiveBinDec.div(amountXInActiveBinDec)));
2014
- }
2015
- if (!amountYInActiveBin.isZero()) {
2016
- wy0 = new import_decimal6.default(activeBin.weight).div(new import_decimal6.default(1).add(p0.mul(amountXInActiveBinDec).div(amountYInActiveBinDec)));
2017
- }
2018
- }
2019
- let totalWeightX2 = wx0;
2020
- let totalWeightY2 = wy0;
2021
- distributions.forEach((element) => {
2022
- if (element.binId < activeId) {
2023
- totalWeightY2 = totalWeightY2.add(new import_decimal6.default(element.weight));
2024
- }
2025
- if (element.binId > activeId) {
2026
- const price = getPriceOfBinByBinId(element.binId, binStep);
2027
- const weighPerPrice = new import_decimal6.default(element.weight).div(price);
2028
- totalWeightX2 = totalWeightX2.add(weighPerPrice);
2029
- }
2030
- });
2031
- const kx2 = new import_decimal6.default(amountX.toString()).div(totalWeightX2);
2032
- const ky2 = new import_decimal6.default(amountY.toString()).div(totalWeightY2);
2033
- const k2 = kx2.lessThan(ky2) ? kx2 : ky2;
2034
- return distributions.map((bin) => {
2035
- if (bin.binId < activeId) {
2036
- const amount = k2.mul(new import_decimal6.default(bin.weight));
2037
- return {
2038
- binId: bin.binId,
2039
- amountX: new import_bn9.default(0),
2040
- amountY: new import_bn9.default(amount.floor().toString())
2041
- };
2042
- }
2043
- if (bin.binId > activeId) {
2044
- const price = getPriceOfBinByBinId(bin.binId, binStep);
2045
- const weighPerPrice = new import_decimal6.default(bin.weight).div(price);
2046
- const amount = k2.mul(weighPerPrice);
2047
- return {
2048
- binId: bin.binId,
2049
- amountX: new import_bn9.default(amount.floor().toString()),
2050
- amountY: new import_bn9.default(0)
2051
- };
2052
- }
2053
- const amountXActiveBin = k2.mul(wx0);
2054
- const amountYActiveBin = k2.mul(wy0);
2055
- return {
2056
- binId: bin.binId,
2057
- amountX: new import_bn9.default(amountXActiveBin.floor().toString()),
2058
- amountY: new import_bn9.default(amountYActiveBin.floor().toString())
2059
- };
2060
- });
2061
- }
2062
- let totalWeightX = new import_decimal6.default(0);
2063
- let totalWeightY = new import_decimal6.default(0);
2064
- distributions.forEach((element) => {
2065
- if (element.binId < activeId) {
2066
- totalWeightY = totalWeightY.add(new import_decimal6.default(element.weight));
2067
- } else {
2068
- const price = getPriceOfBinByBinId(element.binId, binStep);
2069
- const weighPerPrice = new import_decimal6.default(element.weight).div(price);
2070
- totalWeightX = totalWeightX.add(weighPerPrice);
2071
- }
2072
- });
2073
- const kx = new import_decimal6.default(amountX.toString()).div(totalWeightX);
2074
- const ky = new import_decimal6.default(amountY.toString()).div(totalWeightY);
2075
- const k = kx.lessThan(ky) ? kx : ky;
2076
- return distributions.map((bin) => {
2077
- if (bin.binId < activeId) {
2078
- const amount2 = k.mul(new import_decimal6.default(bin.weight));
2079
- return {
2080
- binId: bin.binId,
2081
- amountX: new import_bn9.default(0),
2082
- amountY: new import_bn9.default(amount2.floor().toString())
2083
- };
2084
- }
2085
- const price = getPriceOfBinByBinId(bin.binId, binStep);
2086
- const weighPerPrice = new import_decimal6.default(bin.weight).div(price);
2087
- const amount = k.mul(weighPerPrice);
2088
- return {
2089
- binId: bin.binId,
2090
- amountX: new import_bn9.default(amount.floor().toString()),
2091
- amountY: new import_bn9.default(0)
2092
- };
2093
- });
2094
- }
2095
-
2096
- // src/math/dlmmStrategy.ts
2097
- var StrategyType = /* @__PURE__ */ ((StrategyType2) => {
2098
- StrategyType2[StrategyType2["Spot"] = 1] = "Spot";
2099
- StrategyType2[StrategyType2["Curve"] = 2] = "Curve";
2100
- StrategyType2[StrategyType2["BidAsk"] = 3] = "BidAsk";
2101
- return StrategyType2;
2102
- })(StrategyType || {});
2103
- function toWeightSpotBalanced(minBinId, maxBinId) {
2104
- const distributions = [];
2105
- for (let i = minBinId; i <= maxBinId; i++) {
2106
- distributions.push({
2107
- binId: i,
2108
- weight: 1
2109
- });
2110
- }
2111
- return distributions;
2112
- }
2113
- var DEFAULT_MAX_WEIGHT = 2e3;
2114
- var DEFAULT_MIN_WEIGHT = 200;
2115
- function toWeightCurve(minBinId, maxBinId, activeId) {
2116
- if (activeId < minBinId || activeId > maxBinId) {
2117
- throw new ClmmpoolsError("Invalid strategy params", "InvalidParams" /* InvalidParams */);
2118
- }
2119
- const maxWeight = DEFAULT_MAX_WEIGHT;
2120
- const minWeight = DEFAULT_MIN_WEIGHT;
2121
- const diffWeight = maxWeight - minWeight;
2122
- const diffMinWeight = activeId > minBinId ? Math.floor(diffWeight / (activeId - minBinId)) : 0;
2123
- const diffMaxWeight = maxBinId > activeId ? Math.floor(diffWeight / (maxBinId - activeId)) : 0;
2124
- const distributions = [];
2125
- for (let i = minBinId; i <= maxBinId; i++) {
2126
- if (i < activeId) {
2127
- distributions.push({
2128
- binId: i,
2129
- weight: maxWeight - (activeId - i) * diffMinWeight
2130
- });
2131
- } else if (i > activeId) {
2132
- distributions.push({
2133
- binId: i,
2134
- weight: maxWeight - (i - activeId) * diffMaxWeight
2135
- });
2136
- } else {
2137
- distributions.push({
2138
- binId: i,
2139
- weight: maxWeight
2140
- });
2141
- }
2142
- }
2143
- return distributions;
2144
- }
2145
- function toWeightBidAsk(minBinId, maxBinId, activeId) {
2146
- if (activeId < minBinId || activeId > maxBinId) {
2147
- throw new ClmmpoolsError("Invalid strategy params", "InvalidParams" /* InvalidParams */);
2148
- }
2149
- const maxWeight = DEFAULT_MAX_WEIGHT;
2150
- const minWeight = DEFAULT_MIN_WEIGHT;
2151
- const diffWeight = maxWeight - minWeight;
2152
- const diffMinWeight = activeId > minBinId ? Math.floor(diffWeight / (activeId - minBinId)) : 0;
2153
- const diffMaxWeight = maxBinId > activeId ? Math.floor(diffWeight / (maxBinId - activeId)) : 0;
2154
- const distributions = [];
2155
- for (let i = minBinId; i <= maxBinId; i++) {
2156
- if (i < activeId) {
2157
- distributions.push({
2158
- binId: i,
2159
- weight: minWeight + (activeId - i) * diffMinWeight
2160
- });
2161
- } else if (i > activeId) {
2162
- distributions.push({
2163
- binId: i,
2164
- weight: minWeight + (i - activeId) * diffMaxWeight
2165
- });
2166
- } else {
2167
- distributions.push({
2168
- binId: i,
2169
- weight: minWeight
2170
- });
2171
- }
2172
- }
2173
- return distributions;
2174
- }
2175
- function autoFillYByStrategy(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, minBinId, maxBinId, strategyType) {
2176
- switch (strategyType) {
2177
- case 1 /* Spot */: {
2178
- const weights = toWeightSpotBalanced(minBinId, maxBinId);
2179
- return autoFillYByWeight(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, weights);
2180
- }
2181
- case 2 /* Curve */: {
2182
- const weights = toWeightCurve(minBinId, maxBinId, activeId);
2183
- return autoFillYByWeight(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, weights);
2184
- }
2185
- case 3 /* BidAsk */: {
2186
- const weights = toWeightBidAsk(minBinId, maxBinId, activeId);
2187
- return autoFillYByWeight(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, weights);
2188
- }
2189
- default:
2190
- throw new Error(`Unsupported strategy type: ${strategyType}`);
2191
- }
2192
- }
2193
- function autoFillXByStrategy(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, minBinId, maxBinId, strategyType) {
2194
- switch (strategyType) {
2195
- case 1 /* Spot */: {
2196
- const weights = toWeightSpotBalanced(minBinId, maxBinId);
2197
- return autoFillXByWeight(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2198
- }
2199
- case 2 /* Curve */: {
2200
- const weights = toWeightCurve(minBinId, maxBinId, activeId);
2201
- return autoFillXByWeight(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2202
- }
2203
- case 3 /* BidAsk */: {
2204
- const weights = toWeightBidAsk(minBinId, maxBinId, activeId);
2205
- return autoFillXByWeight(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2206
- }
2207
- default:
2208
- throw new Error(`Unsupported strategy type: ${strategyType}`);
2209
- }
2210
- }
2211
- function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amountX, amountY, amountXInActiveBin, amountYInActiveBin, strategyType) {
2212
- const isSingleSideX = amountY.isZero();
2213
- switch (strategyType) {
2214
- case 1 /* Spot */: {
2215
- const weights = toWeightSpotBalanced(minBinId, maxBinId);
2216
- return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2217
- }
2218
- case 2 /* Curve */: {
2219
- const weights = toWeightCurve(minBinId, maxBinId, activeId);
2220
- return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2221
- }
2222
- case 3 /* BidAsk */: {
2223
- const weights = toWeightBidAsk(minBinId, maxBinId, activeId);
2224
- return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2225
- }
2226
- default:
2227
- throw new Error(`Unsupported strategy type: ${strategyType}`);
2228
- }
2229
- }
2230
-
2231
- // src/math/LiquidityHelper.ts
2232
- var import_decimal8 = __toESM(require("decimal.js"));
2233
-
2234
- // src/utils/numbers.ts
2235
- var import_decimal7 = __toESM(require("decimal.js"));
2236
- function d(value) {
2237
- if (import_decimal7.default.isDecimal(value)) {
2238
- return value;
2239
- }
2240
- return new import_decimal7.default(value === void 0 ? 0 : value);
2241
- }
2242
- function decimalsMultiplier(decimals) {
2243
- return d(10).pow(d(decimals).abs());
2244
- }
2245
-
2246
- // src/math/LiquidityHelper.ts
2247
- function withLiquiditySlippage(value, slippage, mode) {
2248
- return d(value)[mode](d(value).mul(slippage)).toDP(0);
2249
- }
2250
- function getLiquidityAndCoinYByCoinX(coinInVal, reserveInSize, reserveOutSize, lpSupply) {
2251
- if (coinInVal.lessThanOrEqualTo(0)) {
2252
- throw new ClmmpoolsError("coinInVal is less than zero", "InvalidCoinAmount" /* InvalidCoinAmount */);
2253
- }
2254
- if (reserveInSize.lessThanOrEqualTo(0) || reserveOutSize.lessThanOrEqualTo(0)) {
2255
- return -1;
2256
- }
2257
- const coinYAmount = coinInVal.mul(reserveOutSize).div(reserveInSize);
2258
- const sqrtSupply = lpSupply;
2259
- const lpX = coinInVal.div(reserveInSize).mul(sqrtSupply);
2260
- const lpY = coinYAmount.div(reserveOutSize).mul(sqrtSupply);
2261
- const lpAmount = import_decimal8.default.min(lpX, lpY);
2262
- return {
2263
- coinYAmount,
2264
- lpAmount
2265
- };
2266
- }
2267
- function getCoinXYForLiquidity(liquidity, reserveInSize, reserveOutSize, lpSuply) {
2268
- if (liquidity.lessThanOrEqualTo(0)) {
2269
- throw new ClmmpoolsError("liquidity can't be equal or less than zero", "InvalidLiquidityAmount" /* InvalidLiquidityAmount */);
2270
- }
2271
- if (reserveInSize.lessThanOrEqualTo(0) || reserveOutSize.lessThanOrEqualTo(0)) {
2272
- throw new ClmmpoolsError("reserveInSize or reserveOutSize can not be equal or less than zero", "InvalidReserveAmount" /* InvalidReserveAmount */);
2273
- }
2274
- const sqrtSupply = lpSuply;
2275
- const coinXAmount = liquidity.div(sqrtSupply).mul(reserveInSize);
2276
- const coinYAmount = liquidity.div(sqrtSupply).mul(reserveOutSize);
2277
- return {
2278
- coinXAmount,
2279
- coinYAmount
2280
- };
2281
- }
2282
-
2283
1799
  // src/math/percentage.ts
2284
- var import_bn10 = __toESM(require("bn.js"));
1800
+ var import_bn9 = __toESM(require("bn.js"));
2285
1801
  var Percentage = class {
2286
1802
  numerator;
2287
1803
  denominator;
@@ -2309,8 +1825,8 @@ var Percentage = class {
2309
1825
  * @returns
2310
1826
  */
2311
1827
  static fromFraction(numerator, denominator) {
2312
- const num = typeof numerator === "number" ? new import_bn10.default(numerator.toString()) : numerator;
2313
- const denom = typeof denominator === "number" ? new import_bn10.default(denominator.toString()) : denominator;
1828
+ const num = typeof numerator === "number" ? new import_bn9.default(numerator.toString()) : numerator;
1829
+ const denom = typeof denominator === "number" ? new import_bn9.default(denominator.toString()) : denominator;
2314
1830
  return new Percentage(num, denom);
2315
1831
  }
2316
1832
  };
@@ -2410,7 +1926,7 @@ function adjustForCoinSlippage(tokenAmount, slippage, adjustUp) {
2410
1926
  }
2411
1927
 
2412
1928
  // src/math/SplitSwap.ts
2413
- var import_bn11 = __toESM(require("bn.js"));
1929
+ var import_bn10 = __toESM(require("bn.js"));
2414
1930
  var SplitUnit = /* @__PURE__ */ ((SplitUnit2) => {
2415
1931
  SplitUnit2[SplitUnit2["FIVE"] = 5] = "FIVE";
2416
1932
  SplitUnit2[SplitUnit2["TEN"] = 10] = "TEN";
@@ -2468,7 +1984,7 @@ function updateSplitSwapResult(maxIndex, currentIndex, splitSwapResult, stepResu
2468
1984
  return splitSwapResult;
2469
1985
  }
2470
1986
  function computeSplitSwap(a2b, byAmountIn, amounts, poolData, swapTicks) {
2471
- let currentLiquidity = new import_bn11.default(poolData.liquidity);
1987
+ let currentLiquidity = new import_bn10.default(poolData.liquidity);
2472
1988
  let { currentSqrtPrice } = poolData;
2473
1989
  let splitSwapResult = {
2474
1990
  amountInArray: [],
@@ -2531,7 +2047,7 @@ function computeSplitSwap(a2b, byAmountIn, amounts, poolData, swapTicks) {
2531
2047
  targetSqrtPrice,
2532
2048
  currentLiquidity,
2533
2049
  remainerAmount,
2534
- new import_bn11.default(poolData.feeRate),
2050
+ new import_bn10.default(poolData.feeRate),
2535
2051
  byAmountIn
2536
2052
  );
2537
2053
  tempStepResult = stepResult;
@@ -2543,7 +2059,7 @@ function computeSplitSwap(a2b, byAmountIn, amounts, poolData, swapTicks) {
2543
2059
  splitSwapResult.amountOutArray[i] = splitSwapResult.amountOutArray[i].add(stepResult.amountOut);
2544
2060
  splitSwapResult.feeAmountArray[i] = splitSwapResult.feeAmountArray[i].add(stepResult.feeAmount);
2545
2061
  if (stepResult.nextSqrtPrice.eq(tick.sqrtPrice)) {
2546
- signedLiquidityChange = a2b ? tick.liquidityNet.mul(new import_bn11.default(-1)) : tick.liquidityNet;
2062
+ signedLiquidityChange = a2b ? tick.liquidityNet.mul(new import_bn10.default(-1)) : tick.liquidityNet;
2547
2063
  currentLiquidity = signedLiquidityChange.gt(ZERO) ? currentLiquidity.add(signedLiquidityChange) : currentLiquidity.sub(signedLiquidityChange.abs());
2548
2064
  currentSqrtPrice = tick.sqrtPrice;
2549
2065
  } else {
@@ -2568,7 +2084,7 @@ function computeSplitSwap(a2b, byAmountIn, amounts, poolData, swapTicks) {
2568
2084
  break;
2569
2085
  }
2570
2086
  if (tempStepResult.nextSqrtPrice.eq(tick.sqrtPrice)) {
2571
- signedLiquidityChange = a2b ? tick.liquidityNet.mul(new import_bn11.default(-1)) : tick.liquidityNet;
2087
+ signedLiquidityChange = a2b ? tick.liquidityNet.mul(new import_bn10.default(-1)) : tick.liquidityNet;
2572
2088
  currentLiquidity = signedLiquidityChange.gt(ZERO) ? currentLiquidity.add(signedLiquidityChange) : currentLiquidity.sub(signedLiquidityChange.abs());
2573
2089
  currentSqrtPrice = tick.sqrtPrice;
2574
2090
  } else {
@@ -2623,22 +2139,17 @@ var SplitSwap = class {
2623
2139
  }
2624
2140
  };
2625
2141
 
2626
- // src/math/bin.ts
2627
- var import_decimal9 = __toESM(require("decimal.js"));
2628
- var import_calc_dlmm2 = require("@magmaprotocol/calc_dlmm");
2629
- var BinMath = class {
2630
- static getPriceOfBinByBinId(binId, binStep, decimalsA, decimalsB) {
2631
- const twoDec = new import_decimal9.default(2);
2632
- const price = new import_decimal9.default((0, import_calc_dlmm2.get_price_x128_from_real_id)(binId, binStep));
2633
- return price.div(twoDec.pow(128)).mul(import_decimal9.default.pow(10, decimalsA - decimalsB));
2634
- }
2635
- static getBinIdFromPrice(price, binStep, decimalsA, decimalsB) {
2636
- const twoDec = new import_decimal9.default(2);
2637
- const tenDec = new import_decimal9.default(10);
2638
- const realid = (0, import_calc_dlmm2.get_real_id_from_price_x128)(new import_decimal9.default(price).mul(tenDec.pow(decimalsB - decimalsA)).mul(twoDec.pow(128)).toDecimalPlaces(0).toString(), binStep);
2639
- return realid;
2142
+ // src/utils/numbers.ts
2143
+ var import_decimal6 = __toESM(require("decimal.js"));
2144
+ function d(value) {
2145
+ if (import_decimal6.default.isDecimal(value)) {
2146
+ return value;
2640
2147
  }
2641
- };
2148
+ return new import_decimal6.default(value === void 0 ? 0 : value);
2149
+ }
2150
+ function decimalsMultiplier(decimals) {
2151
+ return d(10).pow(d(decimals).abs());
2152
+ }
2642
2153
 
2643
2154
  // src/utils/objects.ts
2644
2155
  function getSuiObjectData(resp) {
@@ -2793,7 +2304,7 @@ function buildPool(objects) {
2793
2304
  const rewarders = [];
2794
2305
  fields.rewarder_manager.fields.rewarders.forEach((item) => {
2795
2306
  const { emissions_per_second } = item.fields;
2796
- const emissionSeconds = MathUtil.fromX64(new import_bn12.default(emissions_per_second));
2307
+ const emissionSeconds = MathUtil.fromX64(new import_bn11.default(emissions_per_second));
2797
2308
  const emissionsEveryDay = Math.floor(emissionSeconds.toNumber() * 60 * 60 * 24);
2798
2309
  rewarders.push({
2799
2310
  emissions_per_second,
@@ -2985,11 +2496,11 @@ function buildTickData(objects) {
2985
2496
  const possition = {
2986
2497
  objectId: getObjectId(objects),
2987
2498
  index: asIntN(BigInt(valueItem.index.fields.bits)),
2988
- sqrtPrice: new import_bn12.default(valueItem.sqrt_price),
2989
- liquidityNet: new import_bn12.default(valueItem.liquidity_net.fields.bits),
2990
- liquidityGross: new import_bn12.default(valueItem.liquidity_gross),
2991
- feeGrowthOutsideA: new import_bn12.default(valueItem.fee_growth_outside_a),
2992
- feeGrowthOutsideB: new import_bn12.default(valueItem.fee_growth_outside_b),
2499
+ sqrtPrice: new import_bn11.default(valueItem.sqrt_price),
2500
+ liquidityNet: new import_bn11.default(valueItem.liquidity_net.fields.bits),
2501
+ liquidityGross: new import_bn11.default(valueItem.liquidity_gross),
2502
+ feeGrowthOutsideA: new import_bn11.default(valueItem.fee_growth_outside_a),
2503
+ feeGrowthOutsideB: new import_bn11.default(valueItem.fee_growth_outside_b),
2993
2504
  rewardersGrowthOutside: valueItem.rewards_growth_outside
2994
2505
  };
2995
2506
  return possition;
@@ -2999,11 +2510,11 @@ function buildTickDataByEvent(fields) {
2999
2510
  throw new ClmmpoolsError(`Invalid tick fields.`, "InvalidTickFields" /* InvalidTickFields */);
3000
2511
  }
3001
2512
  const index = asIntN(BigInt(fields.index.bits));
3002
- const sqrtPrice = new import_bn12.default(fields.sqrt_price);
3003
- const liquidityNet = new import_bn12.default(fields.liquidity_net.bits);
3004
- const liquidityGross = new import_bn12.default(fields.liquidity_gross);
3005
- const feeGrowthOutsideA = new import_bn12.default(fields.fee_growth_outside_a);
3006
- const feeGrowthOutsideB = new import_bn12.default(fields.fee_growth_outside_b);
2513
+ const sqrtPrice = new import_bn11.default(fields.sqrt_price);
2514
+ const liquidityNet = new import_bn11.default(fields.liquidity_net.bits);
2515
+ const liquidityGross = new import_bn11.default(fields.liquidity_gross);
2516
+ const feeGrowthOutsideA = new import_bn11.default(fields.fee_growth_outside_a);
2517
+ const feeGrowthOutsideB = new import_bn11.default(fields.fee_growth_outside_b);
3007
2518
  const rewardersGrowthOutside = fields.rewards_growth_outside || [];
3008
2519
  const tick = {
3009
2520
  objectId: "",
@@ -3022,7 +2533,7 @@ function buildClmmPositionName(pool_index, position_index) {
3022
2533
  }
3023
2534
 
3024
2535
  // src/utils/tick.ts
3025
- var import_bn13 = __toESM(require("bn.js"));
2536
+ var import_bn12 = __toESM(require("bn.js"));
3026
2537
  var TickUtil = class {
3027
2538
  /**
3028
2539
  * Get min tick index.
@@ -3062,22 +2573,22 @@ function getRewardInTickRange(pool, tickLower, tickUpper, tickLowerIndex, tickUp
3062
2573
  let rewarder_growth_below = growthGlobal[i];
3063
2574
  if (tickLower !== null) {
3064
2575
  if (pool.current_tick_index < tickLowerIndex) {
3065
- rewarder_growth_below = growthGlobal[i].sub(new import_bn13.default(tickLower.rewardersGrowthOutside[i]));
2576
+ rewarder_growth_below = growthGlobal[i].sub(new import_bn12.default(tickLower.rewardersGrowthOutside[i]));
3066
2577
  } else {
3067
2578
  rewarder_growth_below = tickLower.rewardersGrowthOutside[i];
3068
2579
  }
3069
2580
  }
3070
- let rewarder_growth_above = new import_bn13.default(0);
2581
+ let rewarder_growth_above = new import_bn12.default(0);
3071
2582
  if (tickUpper !== null) {
3072
2583
  if (pool.current_tick_index >= tickUpperIndex) {
3073
- rewarder_growth_above = growthGlobal[i].sub(new import_bn13.default(tickUpper.rewardersGrowthOutside[i]));
2584
+ rewarder_growth_above = growthGlobal[i].sub(new import_bn12.default(tickUpper.rewardersGrowthOutside[i]));
3074
2585
  } else {
3075
2586
  rewarder_growth_above = tickUpper.rewardersGrowthOutside[i];
3076
2587
  }
3077
2588
  }
3078
2589
  const rewGrowthInside = MathUtil.subUnderflowU128(
3079
- MathUtil.subUnderflowU128(new import_bn13.default(growthGlobal[i]), new import_bn13.default(rewarder_growth_below)),
3080
- new import_bn13.default(rewarder_growth_above)
2590
+ MathUtil.subUnderflowU128(new import_bn12.default(growthGlobal[i]), new import_bn12.default(rewarder_growth_below)),
2591
+ new import_bn12.default(rewarder_growth_above)
3081
2592
  );
3082
2593
  rewarderGrowthInside.push(rewGrowthInside);
3083
2594
  }
@@ -3085,8 +2596,8 @@ function getRewardInTickRange(pool, tickLower, tickUpper, tickLowerIndex, tickUp
3085
2596
  }
3086
2597
 
3087
2598
  // src/utils/transaction-util.ts
3088
- var import_bn14 = __toESM(require("bn.js"));
3089
- var import_decimal10 = __toESM(require("decimal.js"));
2599
+ var import_bn13 = __toESM(require("bn.js"));
2600
+ var import_decimal7 = __toESM(require("decimal.js"));
3090
2601
  var import_transactions = require("@mysten/sui/transactions");
3091
2602
  function findAdjustCoin(coinPair) {
3092
2603
  const isAdjustCoinA = CoinAssist.isSuiCoin(coinPair.coinTypeA);
@@ -3094,7 +2605,7 @@ function findAdjustCoin(coinPair) {
3094
2605
  return { isAdjustCoinA, isAdjustCoinB };
3095
2606
  }
3096
2607
  function reverSlippageAmount(slippageAmount, slippage) {
3097
- return import_decimal10.default.ceil(d(slippageAmount).div(1 + slippage)).toString();
2608
+ return import_decimal7.default.ceil(d(slippageAmount).div(1 + slippage)).toString();
3098
2609
  }
3099
2610
  async function printTransaction(tx, isPrint = true) {
3100
2611
  console.log(`inputs`, tx.blockData.inputs);
@@ -3394,7 +2905,7 @@ var _TransactionUtil = class {
3394
2905
  const liquidityInput = ClmmPoolUtil.estLiquidityAndcoinAmountFromOneAmounts(
3395
2906
  Number(params.tick_lower),
3396
2907
  Number(params.tick_upper),
3397
- new import_bn14.default(coinAmount),
2908
+ new import_bn13.default(coinAmount),
3398
2909
  params.fix_amount_a,
3399
2910
  true,
3400
2911
  slippage,
@@ -3468,12 +2979,12 @@ var _TransactionUtil = class {
3468
2979
  max_amount_a = params.amount_a;
3469
2980
  min_amount_a = params.amount_a;
3470
2981
  max_amount_b = params.amount_b;
3471
- min_amount_b = new import_decimal10.default(params.amount_b).div(new import_decimal10.default(1).plus(new import_decimal10.default(params.slippage))).mul(new import_decimal10.default(1).minus(new import_decimal10.default(params.slippage))).toDecimalPlaces(0).toNumber();
2982
+ min_amount_b = new import_decimal7.default(params.amount_b).div(new import_decimal7.default(1).plus(new import_decimal7.default(params.slippage))).mul(new import_decimal7.default(1).minus(new import_decimal7.default(params.slippage))).toDecimalPlaces(0).toNumber();
3472
2983
  } else {
3473
2984
  max_amount_b = params.amount_b;
3474
2985
  min_amount_b = params.amount_b;
3475
2986
  max_amount_a = params.amount_a;
3476
- min_amount_a = new import_decimal10.default(params.amount_a).div(new import_decimal10.default(1).plus(new import_decimal10.default(params.slippage))).mul(new import_decimal10.default(1).minus(new import_decimal10.default(params.slippage))).toDecimalPlaces(0).toNumber();
2987
+ min_amount_a = new import_decimal7.default(params.amount_a).div(new import_decimal7.default(1).plus(new import_decimal7.default(params.slippage))).mul(new import_decimal7.default(1).minus(new import_decimal7.default(params.slippage))).toDecimalPlaces(0).toNumber();
3477
2988
  }
3478
2989
  const args = params.is_open ? [
3479
2990
  tx.object(clmmConfig.global_config_id),
@@ -4462,7 +3973,7 @@ var _TransactionUtil = class {
4462
3973
  const basePath = splitPath.basePaths[i];
4463
3974
  a2b.push(basePath.direction);
4464
3975
  poolAddress.push(basePath.poolAddress);
4465
- rawAmountLimit.push(new import_bn14.default(basePath.inputAmount.toString()));
3976
+ rawAmountLimit.push(new import_bn13.default(basePath.inputAmount.toString()));
4466
3977
  if (i === 0) {
4467
3978
  coinType.push(basePath.fromCoin, basePath.toCoin);
4468
3979
  } else {
@@ -4470,8 +3981,8 @@ var _TransactionUtil = class {
4470
3981
  }
4471
3982
  }
4472
3983
  const onePath = {
4473
- amountIn: new import_bn14.default(splitPath.inputAmount.toString()),
4474
- amountOut: new import_bn14.default(splitPath.outputAmount.toString()),
3984
+ amountIn: new import_bn13.default(splitPath.inputAmount.toString()),
3985
+ amountOut: new import_bn13.default(splitPath.outputAmount.toString()),
4475
3986
  poolAddress,
4476
3987
  a2b,
4477
3988
  rawAmountLimit,
@@ -4828,9 +4339,9 @@ var TxBlock = class {
4828
4339
  };
4829
4340
 
4830
4341
  // src/utils/deepbook-utils.ts
4831
- var import_bn15 = __toESM(require("bn.js"));
4342
+ var import_bn14 = __toESM(require("bn.js"));
4832
4343
  var import_transactions3 = require("@mysten/sui/transactions");
4833
- var FLOAT_SCALING = new import_bn15.default(1e9);
4344
+ var FLOAT_SCALING = new import_bn14.default(1e9);
4834
4345
  var DeepbookUtils = class {
4835
4346
  static createAccountCap(senderAddress, sdkOptions, tx, isTransfer = false) {
4836
4347
  if (senderAddress.length === 0) {
@@ -4976,9 +4487,9 @@ var DeepbookUtils = class {
4976
4487
  static async preSwap(sdk, pool, a2b, amountIn) {
4977
4488
  let isExceed = false;
4978
4489
  let amountOut = ZERO;
4979
- let remainAmount = new import_bn15.default(amountIn);
4490
+ let remainAmount = new import_bn14.default(amountIn);
4980
4491
  let feeAmount = ZERO;
4981
- const initAmountIn = new import_bn15.default(amountIn);
4492
+ const initAmountIn = new import_bn14.default(amountIn);
4982
4493
  if (a2b) {
4983
4494
  let bids = await this.getPoolBids(sdk, pool.poolID, pool.baseAsset, pool.quoteAsset);
4984
4495
  if (bids === null) {
@@ -4988,16 +4499,16 @@ var DeepbookUtils = class {
4988
4499
  return b.price - a.price;
4989
4500
  });
4990
4501
  for (let i = 0; i < bids.length; i += 1) {
4991
- const curBidAmount = new import_bn15.default(bids[i].quantity);
4992
- const curBidPrice = new import_bn15.default(bids[i].price);
4993
- const fee = curBidAmount.mul(new import_bn15.default(curBidPrice)).mul(new import_bn15.default(pool.takerFeeRate)).div(FLOAT_SCALING).div(FLOAT_SCALING);
4502
+ const curBidAmount = new import_bn14.default(bids[i].quantity);
4503
+ const curBidPrice = new import_bn14.default(bids[i].price);
4504
+ const fee = curBidAmount.mul(new import_bn14.default(curBidPrice)).mul(new import_bn14.default(pool.takerFeeRate)).div(FLOAT_SCALING).div(FLOAT_SCALING);
4994
4505
  if (remainAmount.gt(curBidAmount)) {
4995
4506
  remainAmount = remainAmount.sub(curBidAmount);
4996
4507
  amountOut = amountOut.add(curBidAmount.mul(curBidPrice).div(FLOAT_SCALING).sub(fee));
4997
4508
  feeAmount = feeAmount.add(fee);
4998
4509
  } else {
4999
- const curOut = remainAmount.mul(new import_bn15.default(bids[i].price)).div(FLOAT_SCALING);
5000
- const curFee = curOut.mul(new import_bn15.default(pool.takerFeeRate)).div(FLOAT_SCALING);
4510
+ const curOut = remainAmount.mul(new import_bn14.default(bids[i].price)).div(FLOAT_SCALING);
4511
+ const curFee = curOut.mul(new import_bn14.default(pool.takerFeeRate)).div(FLOAT_SCALING);
5001
4512
  amountOut = amountOut.add(curOut.sub(curFee));
5002
4513
  remainAmount = remainAmount.sub(remainAmount);
5003
4514
  feeAmount = feeAmount.add(curFee);
@@ -5012,15 +4523,15 @@ var DeepbookUtils = class {
5012
4523
  isExceed = true;
5013
4524
  }
5014
4525
  for (let i = 0; i < asks.length; i += 1) {
5015
- const curAskAmount = new import_bn15.default(asks[i].price).mul(new import_bn15.default(asks[i].quantity)).div(new import_bn15.default(1e9));
5016
- const fee = curAskAmount.mul(new import_bn15.default(pool.takerFeeRate)).div(FLOAT_SCALING);
4526
+ const curAskAmount = new import_bn14.default(asks[i].price).mul(new import_bn14.default(asks[i].quantity)).div(new import_bn14.default(1e9));
4527
+ const fee = curAskAmount.mul(new import_bn14.default(pool.takerFeeRate)).div(FLOAT_SCALING);
5017
4528
  const curAskAmountWithFee = curAskAmount.add(fee);
5018
4529
  if (remainAmount.gt(curAskAmount)) {
5019
- amountOut = amountOut.add(new import_bn15.default(asks[i].quantity));
4530
+ amountOut = amountOut.add(new import_bn14.default(asks[i].quantity));
5020
4531
  remainAmount = remainAmount.sub(curAskAmountWithFee);
5021
4532
  feeAmount = feeAmount.add(fee);
5022
4533
  } else {
5023
- const splitNums = new import_bn15.default(asks[i].quantity).div(new import_bn15.default(pool.lotSize));
4534
+ const splitNums = new import_bn14.default(asks[i].quantity).div(new import_bn14.default(pool.lotSize));
5024
4535
  const splitAmount = curAskAmountWithFee.div(splitNums);
5025
4536
  const swapSplitNum = remainAmount.div(splitAmount);
5026
4537
  amountOut = amountOut.add(swapSplitNum.muln(pool.lotSize));
@@ -5881,7 +5392,7 @@ var PoolModule = class {
5881
5392
  };
5882
5393
 
5883
5394
  // src/modules/positionModule.ts
5884
- var import_bn16 = __toESM(require("bn.js"));
5395
+ var import_bn15 = __toESM(require("bn.js"));
5885
5396
  var import_transactions5 = require("@mysten/sui/transactions");
5886
5397
  var import_utils15 = require("@mysten/sui/utils");
5887
5398
  var PositionModule = class {
@@ -6103,8 +5614,8 @@ var PositionModule = class {
6103
5614
  for (let i = 0; i < valueData.length; i += 1) {
6104
5615
  const { parsedJson } = valueData[i];
6105
5616
  const posRrewarderResult = {
6106
- feeOwedA: new import_bn16.default(parsedJson.fee_owned_a),
6107
- feeOwedB: new import_bn16.default(parsedJson.fee_owned_b),
5617
+ feeOwedA: new import_bn15.default(parsedJson.fee_owned_a),
5618
+ feeOwedB: new import_bn15.default(parsedJson.fee_owned_b),
6108
5619
  position_id: parsedJson.position_id
6109
5620
  };
6110
5621
  result.push(posRrewarderResult);
@@ -6480,7 +5991,7 @@ var PositionModule = class {
6480
5991
  };
6481
5992
 
6482
5993
  // src/modules/rewarderModule.ts
6483
- var import_bn17 = __toESM(require("bn.js"));
5994
+ var import_bn16 = __toESM(require("bn.js"));
6484
5995
  var import_transactions6 = require("@mysten/sui/transactions");
6485
5996
  var RewarderModule = class {
6486
5997
  _sdk;
@@ -6506,7 +6017,7 @@ var RewarderModule = class {
6506
6017
  }
6507
6018
  const emissionsEveryDay = [];
6508
6019
  for (const rewarderInfo of rewarderInfos) {
6509
- const emissionSeconds = MathUtil.fromX64(new import_bn17.default(rewarderInfo.emissions_per_second));
6020
+ const emissionSeconds = MathUtil.fromX64(new import_bn16.default(rewarderInfo.emissions_per_second));
6510
6021
  emissionsEveryDay.push({
6511
6022
  emissions: Math.floor(emissionSeconds.toNumber() * 60 * 60 * 24),
6512
6023
  coin_address: rewarderInfo.coinAddress
@@ -6525,20 +6036,20 @@ var RewarderModule = class {
6525
6036
  const currentPool = await this.sdk.Pool.getPool(poolID);
6526
6037
  const lastTime = currentPool.rewarder_last_updated_time;
6527
6038
  currentPool.rewarder_last_updated_time = currentTime.toString();
6528
- if (Number(currentPool.liquidity) === 0 || currentTime.eq(new import_bn17.default(lastTime))) {
6039
+ if (Number(currentPool.liquidity) === 0 || currentTime.eq(new import_bn16.default(lastTime))) {
6529
6040
  return currentPool;
6530
6041
  }
6531
- const timeDelta = currentTime.div(new import_bn17.default(1e3)).sub(new import_bn17.default(lastTime)).add(new import_bn17.default(15));
6042
+ const timeDelta = currentTime.div(new import_bn16.default(1e3)).sub(new import_bn16.default(lastTime)).add(new import_bn16.default(15));
6532
6043
  const rewarderInfos = currentPool.rewarder_infos;
6533
6044
  for (let i = 0; i < rewarderInfos.length; i += 1) {
6534
6045
  const rewarderInfo = rewarderInfos[i];
6535
6046
  const rewarderGrowthDelta = MathUtil.checkMulDivFloor(
6536
6047
  timeDelta,
6537
- new import_bn17.default(rewarderInfo.emissions_per_second),
6538
- new import_bn17.default(currentPool.liquidity),
6048
+ new import_bn16.default(rewarderInfo.emissions_per_second),
6049
+ new import_bn16.default(currentPool.liquidity),
6539
6050
  128
6540
6051
  );
6541
- this.growthGlobal[i] = new import_bn17.default(rewarderInfo.growth_global).add(new import_bn17.default(rewarderGrowthDelta));
6052
+ this.growthGlobal[i] = new import_bn16.default(rewarderInfo.growth_global).add(new import_bn16.default(rewarderGrowthDelta));
6542
6053
  }
6543
6054
  return currentPool;
6544
6055
  }
@@ -6553,7 +6064,7 @@ var RewarderModule = class {
6553
6064
  */
6554
6065
  async posRewardersAmount(poolID, positionHandle, positionID) {
6555
6066
  const currentTime = Date.parse((/* @__PURE__ */ new Date()).toString());
6556
- const pool = await this.updatePoolRewarder(poolID, new import_bn17.default(currentTime));
6067
+ const pool = await this.updatePoolRewarder(poolID, new import_bn16.default(currentTime));
6557
6068
  const position = await this.sdk.Position.getPositionRewarders(positionHandle, positionID);
6558
6069
  if (position === void 0) {
6559
6070
  return [];
@@ -6574,7 +6085,7 @@ var RewarderModule = class {
6574
6085
  */
6575
6086
  async poolRewardersAmount(accountAddress, poolID) {
6576
6087
  const currentTime = Date.parse((/* @__PURE__ */ new Date()).toString());
6577
- const pool = await this.updatePoolRewarder(poolID, new import_bn17.default(currentTime));
6088
+ const pool = await this.updatePoolRewarder(poolID, new import_bn16.default(currentTime));
6578
6089
  const positions = await this.sdk.Position.getPositionList(accountAddress, [poolID]);
6579
6090
  const tickDatas = await this.getPoolLowerAndUpperTicks(pool.ticks_handle, positions);
6580
6091
  const rewarderAmount = [ZERO, ZERO, ZERO];
@@ -6601,38 +6112,38 @@ var RewarderModule = class {
6601
6112
  const growthInside = [];
6602
6113
  const AmountOwed = [];
6603
6114
  if (rewardersInside.length > 0) {
6604
- let growthDelta0 = MathUtil.subUnderflowU128(rewardersInside[0], new import_bn17.default(position.reward_growth_inside_0));
6605
- if (growthDelta0.gt(new import_bn17.default("3402823669209384634633745948738404"))) {
6115
+ let growthDelta0 = MathUtil.subUnderflowU128(rewardersInside[0], new import_bn16.default(position.reward_growth_inside_0));
6116
+ if (growthDelta0.gt(new import_bn16.default("3402823669209384634633745948738404"))) {
6606
6117
  growthDelta0 = ONE;
6607
6118
  }
6608
- const amountOwed_0 = MathUtil.checkMulShiftRight(new import_bn17.default(position.liquidity), growthDelta0, 64, 128);
6119
+ const amountOwed_0 = MathUtil.checkMulShiftRight(new import_bn16.default(position.liquidity), growthDelta0, 64, 128);
6609
6120
  growthInside.push(rewardersInside[0]);
6610
6121
  AmountOwed.push({
6611
- amount_owed: new import_bn17.default(position.reward_amount_owed_0).add(amountOwed_0),
6122
+ amount_owed: new import_bn16.default(position.reward_amount_owed_0).add(amountOwed_0),
6612
6123
  coin_address: pool.rewarder_infos[0].coinAddress
6613
6124
  });
6614
6125
  }
6615
6126
  if (rewardersInside.length > 1) {
6616
- let growthDelta_1 = MathUtil.subUnderflowU128(rewardersInside[1], new import_bn17.default(position.reward_growth_inside_1));
6617
- if (growthDelta_1.gt(new import_bn17.default("3402823669209384634633745948738404"))) {
6127
+ let growthDelta_1 = MathUtil.subUnderflowU128(rewardersInside[1], new import_bn16.default(position.reward_growth_inside_1));
6128
+ if (growthDelta_1.gt(new import_bn16.default("3402823669209384634633745948738404"))) {
6618
6129
  growthDelta_1 = ONE;
6619
6130
  }
6620
- const amountOwed_1 = MathUtil.checkMulShiftRight(new import_bn17.default(position.liquidity), growthDelta_1, 64, 128);
6131
+ const amountOwed_1 = MathUtil.checkMulShiftRight(new import_bn16.default(position.liquidity), growthDelta_1, 64, 128);
6621
6132
  growthInside.push(rewardersInside[1]);
6622
6133
  AmountOwed.push({
6623
- amount_owed: new import_bn17.default(position.reward_amount_owed_1).add(amountOwed_1),
6134
+ amount_owed: new import_bn16.default(position.reward_amount_owed_1).add(amountOwed_1),
6624
6135
  coin_address: pool.rewarder_infos[1].coinAddress
6625
6136
  });
6626
6137
  }
6627
6138
  if (rewardersInside.length > 2) {
6628
- let growthDelta_2 = MathUtil.subUnderflowU128(rewardersInside[2], new import_bn17.default(position.reward_growth_inside_2));
6629
- if (growthDelta_2.gt(new import_bn17.default("3402823669209384634633745948738404"))) {
6139
+ let growthDelta_2 = MathUtil.subUnderflowU128(rewardersInside[2], new import_bn16.default(position.reward_growth_inside_2));
6140
+ if (growthDelta_2.gt(new import_bn16.default("3402823669209384634633745948738404"))) {
6630
6141
  growthDelta_2 = ONE;
6631
6142
  }
6632
- const amountOwed_2 = MathUtil.checkMulShiftRight(new import_bn17.default(position.liquidity), growthDelta_2, 64, 128);
6143
+ const amountOwed_2 = MathUtil.checkMulShiftRight(new import_bn16.default(position.liquidity), growthDelta_2, 64, 128);
6633
6144
  growthInside.push(rewardersInside[2]);
6634
6145
  AmountOwed.push({
6635
- amount_owed: new import_bn17.default(position.reward_amount_owed_2).add(amountOwed_2),
6146
+ amount_owed: new import_bn16.default(position.reward_amount_owed_2).add(amountOwed_2),
6636
6147
  coin_address: pool.rewarder_infos[2].coinAddress
6637
6148
  });
6638
6149
  }
@@ -6746,8 +6257,8 @@ var RewarderModule = class {
6746
6257
  for (let i = 0; i < valueData.length; i += 1) {
6747
6258
  const { parsedJson } = valueData[i];
6748
6259
  const posRrewarderResult = {
6749
- feeOwedA: new import_bn17.default(parsedJson.fee_owned_a),
6750
- feeOwedB: new import_bn17.default(parsedJson.fee_owned_b),
6260
+ feeOwedA: new import_bn16.default(parsedJson.fee_owned_a),
6261
+ feeOwedB: new import_bn16.default(parsedJson.fee_owned_b),
6751
6262
  position_id: parsedJson.position_id
6752
6263
  };
6753
6264
  result.push(posRrewarderResult);
@@ -6810,7 +6321,7 @@ var RewarderModule = class {
6810
6321
  };
6811
6322
  for (let j = 0; j < params[i].rewarderInfo.length; j += 1) {
6812
6323
  posRrewarderResult.rewarderAmountOwed.push({
6813
- amount_owed: new import_bn17.default(valueData[i].parsedJson.data[j]),
6324
+ amount_owed: new import_bn16.default(valueData[i].parsedJson.data[j]),
6814
6325
  coin_address: params[i].rewarderInfo[j].coinAddress
6815
6326
  });
6816
6327
  }
@@ -6969,7 +6480,7 @@ var RewarderModule = class {
6969
6480
  };
6970
6481
 
6971
6482
  // src/modules/routerModule.ts
6972
- var import_bn18 = __toESM(require("bn.js"));
6483
+ var import_bn17 = __toESM(require("bn.js"));
6973
6484
  var import_cc_graph = require("@syntsugar/cc-graph");
6974
6485
  var import_transactions7 = require("@mysten/sui/transactions");
6975
6486
  function _pairSymbol(base, quote) {
@@ -7251,8 +6762,8 @@ var RouterModule = class {
7251
6762
  if (swapWithMultiPoolParams != null) {
7252
6763
  const preSwapResult2 = await this.sdk.Swap.preSwapWithMultiPool(swapWithMultiPoolParams);
7253
6764
  const onePath2 = {
7254
- amountIn: new import_bn18.default(preSwapResult2.estimatedAmountIn),
7255
- amountOut: new import_bn18.default(preSwapResult2.estimatedAmountOut),
6765
+ amountIn: new import_bn17.default(preSwapResult2.estimatedAmountIn),
6766
+ amountOut: new import_bn17.default(preSwapResult2.estimatedAmountOut),
7256
6767
  poolAddress: [preSwapResult2.poolAddress],
7257
6768
  a2b: [preSwapResult2.aToB],
7258
6769
  rawAmountLimit: byAmountIn ? [preSwapResult2.estimatedAmountOut] : [preSwapResult2.estimatedAmountIn],
@@ -7265,8 +6776,8 @@ var RouterModule = class {
7265
6776
  priceSlippagePoint
7266
6777
  };
7267
6778
  const result2 = {
7268
- amountIn: new import_bn18.default(preSwapResult2.estimatedAmountIn),
7269
- amountOut: new import_bn18.default(preSwapResult2.estimatedAmountOut),
6779
+ amountIn: new import_bn17.default(preSwapResult2.estimatedAmountIn),
6780
+ amountOut: new import_bn17.default(preSwapResult2.estimatedAmountOut),
7270
6781
  paths: [onePath2],
7271
6782
  a2b: preSwapResult2.aToB,
7272
6783
  b2c: void 0,
@@ -7288,8 +6799,8 @@ var RouterModule = class {
7288
6799
  if (swapWithMultiPoolParams != null) {
7289
6800
  const preSwapResult2 = await this.sdk.Swap.preSwapWithMultiPool(swapWithMultiPoolParams);
7290
6801
  const onePath2 = {
7291
- amountIn: new import_bn18.default(preSwapResult2.estimatedAmountIn),
7292
- amountOut: new import_bn18.default(preSwapResult2.estimatedAmountOut),
6802
+ amountIn: new import_bn17.default(preSwapResult2.estimatedAmountIn),
6803
+ amountOut: new import_bn17.default(preSwapResult2.estimatedAmountOut),
7293
6804
  poolAddress: [preSwapResult2.poolAddress],
7294
6805
  a2b: [preSwapResult2.aToB],
7295
6806
  rawAmountLimit: byAmountIn ? [preSwapResult2.estimatedAmountOut] : [preSwapResult2.estimatedAmountIn],
@@ -7302,8 +6813,8 @@ var RouterModule = class {
7302
6813
  priceSlippagePoint
7303
6814
  };
7304
6815
  const result3 = {
7305
- amountIn: new import_bn18.default(preSwapResult2.estimatedAmountIn),
7306
- amountOut: new import_bn18.default(preSwapResult2.estimatedAmountOut),
6816
+ amountIn: new import_bn17.default(preSwapResult2.estimatedAmountIn),
6817
+ amountOut: new import_bn17.default(preSwapResult2.estimatedAmountOut),
7307
6818
  paths: [onePath2],
7308
6819
  a2b: preSwapResult2.aToB,
7309
6820
  b2c: void 0,
@@ -7384,8 +6895,8 @@ var RouterModule = class {
7384
6895
  if (swapWithMultiPoolParams != null) {
7385
6896
  const preSwapResult = await this.sdk.Swap.preSwapWithMultiPool(swapWithMultiPoolParams);
7386
6897
  const onePath = {
7387
- amountIn: new import_bn18.default(preSwapResult.estimatedAmountIn),
7388
- amountOut: new import_bn18.default(preSwapResult.estimatedAmountOut),
6898
+ amountIn: new import_bn17.default(preSwapResult.estimatedAmountIn),
6899
+ amountOut: new import_bn17.default(preSwapResult.estimatedAmountOut),
7389
6900
  poolAddress: [preSwapResult.poolAddress],
7390
6901
  a2b: [preSwapResult.aToB],
7391
6902
  rawAmountLimit: byAmountIn ? [preSwapResult.estimatedAmountOut] : [preSwapResult.estimatedAmountIn],
@@ -7398,8 +6909,8 @@ var RouterModule = class {
7398
6909
  priceSlippagePoint
7399
6910
  };
7400
6911
  const result = {
7401
- amountIn: new import_bn18.default(preSwapResult.estimatedAmountIn),
7402
- amountOut: new import_bn18.default(preSwapResult.estimatedAmountOut),
6912
+ amountIn: new import_bn17.default(preSwapResult.estimatedAmountIn),
6913
+ amountOut: new import_bn17.default(preSwapResult.estimatedAmountOut),
7403
6914
  paths: [onePath],
7404
6915
  a2b: preSwapResult.aToB,
7405
6916
  b2c: void 0,
@@ -7483,13 +6994,13 @@ var RouterModule = class {
7483
6994
  continue;
7484
6995
  }
7485
6996
  if (params[0].byAmountIn) {
7486
- const amount = new import_bn18.default(valueData[i].parsedJson.data.amount_out);
6997
+ const amount = new import_bn17.default(valueData[i].parsedJson.data.amount_out);
7487
6998
  if (amount.gt(tempMaxAmount)) {
7488
6999
  tempIndex = i;
7489
7000
  tempMaxAmount = amount;
7490
7001
  }
7491
7002
  } else {
7492
- const amount = params[i].stepNums > 1 ? new import_bn18.default(valueData[i].parsedJson.data.amount_in) : new import_bn18.default(valueData[i].parsedJson.data.amount_in).add(new import_bn18.default(valueData[i].parsedJson.data.fee_amount));
7003
+ const amount = params[i].stepNums > 1 ? new import_bn17.default(valueData[i].parsedJson.data.amount_in) : new import_bn17.default(valueData[i].parsedJson.data.amount_in).add(new import_bn17.default(valueData[i].parsedJson.data.fee_amount));
7493
7004
  if (amount.lt(tempMaxAmount)) {
7494
7005
  tempIndex = i;
7495
7006
  tempMaxAmount = amount;
@@ -7559,8 +7070,8 @@ var RouterModule = class {
7559
7070
  };
7560
7071
 
7561
7072
  // src/modules/swapModule.ts
7562
- var import_bn19 = __toESM(require("bn.js"));
7563
- var import_decimal11 = __toESM(require("decimal.js"));
7073
+ var import_bn18 = __toESM(require("bn.js"));
7074
+ var import_decimal8 = __toESM(require("decimal.js"));
7564
7075
  var import_transactions8 = require("@mysten/sui/transactions");
7565
7076
  var AMM_SWAP_MODULE = "amm_swap";
7566
7077
  var POOL_STRUCT = "Pool";
@@ -7578,14 +7089,14 @@ var SwapModule = class {
7578
7089
  const pathCount = item.basePaths.length;
7579
7090
  if (pathCount > 0) {
7580
7091
  const path = item.basePaths[0];
7581
- const feeRate = path.label === "Magma" ? new import_decimal11.default(path.feeRate).div(10 ** 6) : new import_decimal11.default(path.feeRate).div(10 ** 9);
7092
+ const feeRate = path.label === "Magma" ? new import_decimal8.default(path.feeRate).div(10 ** 6) : new import_decimal8.default(path.feeRate).div(10 ** 9);
7582
7093
  const feeAmount = d(path.inputAmount).div(10 ** path.fromDecimal).mul(feeRate);
7583
7094
  fee = fee.add(feeAmount);
7584
7095
  if (pathCount > 1) {
7585
7096
  const path2 = item.basePaths[1];
7586
- const price1 = path.direction ? path.currentPrice : new import_decimal11.default(1).div(path.currentPrice);
7587
- const price2 = path2.direction ? path2.currentPrice : new import_decimal11.default(1).div(path2.currentPrice);
7588
- const feeRate2 = path2.label === "Magma" ? new import_decimal11.default(path2.feeRate).div(10 ** 6) : new import_decimal11.default(path2.feeRate).div(10 ** 9);
7097
+ const price1 = path.direction ? path.currentPrice : new import_decimal8.default(1).div(path.currentPrice);
7098
+ const price2 = path2.direction ? path2.currentPrice : new import_decimal8.default(1).div(path2.currentPrice);
7099
+ const feeRate2 = path2.label === "Magma" ? new import_decimal8.default(path2.feeRate).div(10 ** 6) : new import_decimal8.default(path2.feeRate).div(10 ** 9);
7589
7100
  const feeAmount2 = d(path2.outputAmount).div(10 ** path2.toDecimal).mul(feeRate2);
7590
7101
  const fee2 = feeAmount2.div(price1.mul(price2));
7591
7102
  fee = fee.add(fee2);
@@ -7603,17 +7114,17 @@ var SwapModule = class {
7603
7114
  const outputAmount = d(path.outputAmount).div(10 ** path.toDecimal);
7604
7115
  const inputAmount = d(path.inputAmount).div(10 ** path.fromDecimal);
7605
7116
  const rate = outputAmount.div(inputAmount);
7606
- const cprice = path.direction ? new import_decimal11.default(path.currentPrice) : new import_decimal11.default(1).div(path.currentPrice);
7117
+ const cprice = path.direction ? new import_decimal8.default(path.currentPrice) : new import_decimal8.default(1).div(path.currentPrice);
7607
7118
  impactValue = impactValue.add(this.calculateSingleImpact(rate, cprice));
7608
7119
  }
7609
7120
  if (pathCount === 2) {
7610
7121
  const path = item.basePaths[0];
7611
7122
  const path2 = item.basePaths[1];
7612
- const cprice1 = path.direction ? new import_decimal11.default(path.currentPrice) : new import_decimal11.default(1).div(path.currentPrice);
7613
- const cprice2 = path2.direction ? new import_decimal11.default(path2.currentPrice) : new import_decimal11.default(1).div(path2.currentPrice);
7123
+ const cprice1 = path.direction ? new import_decimal8.default(path.currentPrice) : new import_decimal8.default(1).div(path.currentPrice);
7124
+ const cprice2 = path2.direction ? new import_decimal8.default(path2.currentPrice) : new import_decimal8.default(1).div(path2.currentPrice);
7614
7125
  const cprice = cprice1.mul(cprice2);
7615
- const outputAmount = new import_decimal11.default(path2.outputAmount).div(10 ** path2.toDecimal);
7616
- const inputAmount = new import_decimal11.default(path.inputAmount).div(10 ** path.fromDecimal);
7126
+ const outputAmount = new import_decimal8.default(path2.outputAmount).div(10 ** path2.toDecimal);
7127
+ const inputAmount = new import_decimal8.default(path.inputAmount).div(10 ** path.fromDecimal);
7617
7128
  const rate = outputAmount.div(inputAmount);
7618
7129
  impactValue = impactValue.add(this.calculateSingleImpact(rate, cprice));
7619
7130
  }
@@ -7675,13 +7186,13 @@ var SwapModule = class {
7675
7186
  continue;
7676
7187
  }
7677
7188
  if (params.byAmountIn) {
7678
- const amount = new import_bn19.default(valueData[i].parsedJson.data.amount_out);
7189
+ const amount = new import_bn18.default(valueData[i].parsedJson.data.amount_out);
7679
7190
  if (amount.gt(tempMaxAmount)) {
7680
7191
  tempIndex = i;
7681
7192
  tempMaxAmount = amount;
7682
7193
  }
7683
7194
  } else {
7684
- const amount = new import_bn19.default(valueData[i].parsedJson.data.amount_out);
7195
+ const amount = new import_bn18.default(valueData[i].parsedJson.data.amount_out);
7685
7196
  if (amount.lt(tempMaxAmount)) {
7686
7197
  tempIndex = i;
7687
7198
  tempMaxAmount = amount;
@@ -7745,7 +7256,7 @@ var SwapModule = class {
7745
7256
  return this.transformSwapData(params, valueData[0].parsedJson.data);
7746
7257
  }
7747
7258
  transformSwapData(params, data) {
7748
- const estimatedAmountIn = data.amount_in && data.fee_amount ? new import_bn19.default(data.amount_in).add(new import_bn19.default(data.fee_amount)).toString() : "";
7259
+ const estimatedAmountIn = data.amount_in && data.fee_amount ? new import_bn18.default(data.amount_in).add(new import_bn18.default(data.fee_amount)).toString() : "";
7749
7260
  return {
7750
7261
  poolAddress: params.pool.poolAddress,
7751
7262
  currentSqrtPrice: params.currentSqrtPrice,
@@ -7762,7 +7273,7 @@ var SwapModule = class {
7762
7273
  transformSwapWithMultiPoolData(params, jsonData) {
7763
7274
  const { data } = jsonData;
7764
7275
  console.log("json data. ", data);
7765
- const estimatedAmountIn = data.amount_in && data.fee_amount ? new import_bn19.default(data.amount_in).add(new import_bn19.default(data.fee_amount)).toString() : "";
7276
+ const estimatedAmountIn = data.amount_in && data.fee_amount ? new import_bn18.default(data.amount_in).add(new import_bn18.default(data.fee_amount)).toString() : "";
7766
7277
  return {
7767
7278
  poolAddress: params.poolAddress,
7768
7279
  estimatedAmountIn,
@@ -9275,8 +8786,8 @@ var TokenModule = class {
9275
8786
  };
9276
8787
 
9277
8788
  // src/modules/routerModuleV2.ts
9278
- var import_bn20 = __toESM(require("bn.js"));
9279
- var import_decimal12 = __toESM(require("decimal.js"));
8789
+ var import_bn19 = __toESM(require("bn.js"));
8790
+ var import_decimal9 = __toESM(require("decimal.js"));
9280
8791
  var import_uuid = require("uuid");
9281
8792
  var import_axios = __toESM(require("axios"));
9282
8793
  var RouterModuleV2 = class {
@@ -9293,7 +8804,7 @@ var RouterModuleV2 = class {
9293
8804
  if (label === "Magma") {
9294
8805
  return TickMath.sqrtPriceX64ToPrice(currentSqrtPrice, decimalA, decimalB);
9295
8806
  }
9296
- return new import_decimal12.default(currentSqrtPrice.toString()).div(new import_decimal12.default(10).pow(new import_decimal12.default(decimalB + 9 - decimalA)));
8807
+ return new import_decimal9.default(currentSqrtPrice.toString()).div(new import_decimal9.default(10).pow(new import_decimal9.default(decimalB + 9 - decimalA)));
9297
8808
  }
9298
8809
  parseJsonResult(data) {
9299
8810
  const result = {
@@ -9319,12 +8830,12 @@ var RouterModuleV2 = class {
9319
8830
  outputAmount: basePath.output_amount,
9320
8831
  inputAmount: basePath.input_amount,
9321
8832
  feeRate: basePath.fee_rate,
9322
- currentSqrtPrice: new import_bn20.default(basePath.current_sqrt_price.toString()),
9323
- afterSqrtPrice: basePath.label === "Magma" ? new import_bn20.default(basePath.after_sqrt_price.toString()) : ZERO,
8833
+ currentSqrtPrice: new import_bn19.default(basePath.current_sqrt_price.toString()),
8834
+ afterSqrtPrice: basePath.label === "Magma" ? new import_bn19.default(basePath.after_sqrt_price.toString()) : ZERO,
9324
8835
  fromDecimal: basePath.from_decimal,
9325
8836
  toDecimal: basePath.to_decimal,
9326
8837
  currentPrice: this.calculatePrice(
9327
- new import_bn20.default(basePath.current_sqrt_price.toString()),
8838
+ new import_bn19.default(basePath.current_sqrt_price.toString()),
9328
8839
  basePath.from_decimal,
9329
8840
  basePath.to_decimal,
9330
8841
  basePath.direction,
@@ -9407,7 +8918,7 @@ var RouterModuleV2 = class {
9407
8918
  const priceResult = await this.sdk.Router.priceUseV1(
9408
8919
  from,
9409
8920
  to,
9410
- new import_bn20.default(amount),
8921
+ new import_bn19.default(amount),
9411
8922
  byAmountIn,
9412
8923
  priceSplitPoint,
9413
8924
  partner,
@@ -9419,7 +8930,7 @@ var RouterModuleV2 = class {
9419
8930
  if (path.poolAddress.length > 1) {
9420
8931
  const fromDecimal0 = this.sdk.Router.tokenInfo(path.coinType[0]).decimals;
9421
8932
  const toDecimal0 = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
9422
- const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new import_bn20.default(priceResult.currentSqrtPrice[0]), fromDecimal0, toDecimal0) : TickMath.sqrtPriceX64ToPrice(new import_bn20.default(priceResult.currentSqrtPrice[0]), toDecimal0, fromDecimal0);
8933
+ const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new import_bn19.default(priceResult.currentSqrtPrice[0]), fromDecimal0, toDecimal0) : TickMath.sqrtPriceX64ToPrice(new import_bn19.default(priceResult.currentSqrtPrice[0]), toDecimal0, fromDecimal0);
9423
8934
  const path0 = {
9424
8935
  direction: path.a2b[0],
9425
8936
  label: "Magma",
@@ -9436,7 +8947,7 @@ var RouterModuleV2 = class {
9436
8947
  };
9437
8948
  const fromDecimal1 = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
9438
8949
  const toDecimal1 = this.sdk.Router.tokenInfo(path.coinType[2]).decimals;
9439
- const currentPrice1 = path.a2b[1] ? TickMath.sqrtPriceX64ToPrice(new import_bn20.default(priceResult.currentSqrtPrice[1]), fromDecimal1, toDecimal1) : TickMath.sqrtPriceX64ToPrice(new import_bn20.default(priceResult.currentSqrtPrice[1]), toDecimal1, fromDecimal1);
8950
+ const currentPrice1 = path.a2b[1] ? TickMath.sqrtPriceX64ToPrice(new import_bn19.default(priceResult.currentSqrtPrice[1]), fromDecimal1, toDecimal1) : TickMath.sqrtPriceX64ToPrice(new import_bn19.default(priceResult.currentSqrtPrice[1]), toDecimal1, fromDecimal1);
9440
8951
  const path1 = {
9441
8952
  direction: path.a2b[1],
9442
8953
  label: "Magma",
@@ -9455,7 +8966,7 @@ var RouterModuleV2 = class {
9455
8966
  } else {
9456
8967
  const fromDecimal = this.sdk.Router.tokenInfo(path.coinType[0]).decimals;
9457
8968
  const toDecimal = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
9458
- const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new import_bn20.default(priceResult.currentSqrtPrice[0]), fromDecimal, toDecimal) : TickMath.sqrtPriceX64ToPrice(new import_bn20.default(priceResult.currentSqrtPrice[0]), toDecimal, fromDecimal);
8969
+ const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new import_bn19.default(priceResult.currentSqrtPrice[0]), fromDecimal, toDecimal) : TickMath.sqrtPriceX64ToPrice(new import_bn19.default(priceResult.currentSqrtPrice[0]), toDecimal, fromDecimal);
9459
8970
  const path0 = {
9460
8971
  direction: path.a2b[0],
9461
8972
  label: "Magma",
@@ -9540,7 +9051,7 @@ var RouterModuleV2 = class {
9540
9051
  const priceResult = await this.sdk.Router.priceUseV1(
9541
9052
  from,
9542
9053
  to,
9543
- new import_bn20.default(amount),
9054
+ new import_bn19.default(amount),
9544
9055
  byAmountIn,
9545
9056
  priceSplitPoint,
9546
9057
  partner,
@@ -9552,7 +9063,7 @@ var RouterModuleV2 = class {
9552
9063
  if (path.poolAddress.length > 1) {
9553
9064
  const fromDecimal0 = this.sdk.Router.tokenInfo(path.coinType[0]).decimals;
9554
9065
  const toDecimal0 = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
9555
- const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new import_bn20.default(priceResult.currentSqrtPrice[0]), fromDecimal0, toDecimal0) : TickMath.sqrtPriceX64ToPrice(new import_bn20.default(priceResult.currentSqrtPrice[0]), toDecimal0, fromDecimal0);
9066
+ const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new import_bn19.default(priceResult.currentSqrtPrice[0]), fromDecimal0, toDecimal0) : TickMath.sqrtPriceX64ToPrice(new import_bn19.default(priceResult.currentSqrtPrice[0]), toDecimal0, fromDecimal0);
9556
9067
  const path0 = {
9557
9068
  direction: path.a2b[0],
9558
9069
  label: "Magma",
@@ -9569,7 +9080,7 @@ var RouterModuleV2 = class {
9569
9080
  };
9570
9081
  const fromDecimal1 = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
9571
9082
  const toDecimal1 = this.sdk.Router.tokenInfo(path.coinType[2]).decimals;
9572
- const currentPrice1 = path.a2b[1] ? TickMath.sqrtPriceX64ToPrice(new import_bn20.default(priceResult.currentSqrtPrice[1]), fromDecimal1, toDecimal1) : TickMath.sqrtPriceX64ToPrice(new import_bn20.default(priceResult.currentSqrtPrice[1]), toDecimal1, fromDecimal1);
9083
+ const currentPrice1 = path.a2b[1] ? TickMath.sqrtPriceX64ToPrice(new import_bn19.default(priceResult.currentSqrtPrice[1]), fromDecimal1, toDecimal1) : TickMath.sqrtPriceX64ToPrice(new import_bn19.default(priceResult.currentSqrtPrice[1]), toDecimal1, fromDecimal1);
9573
9084
  const path1 = {
9574
9085
  direction: path.a2b[1],
9575
9086
  label: "Magma",
@@ -9588,7 +9099,7 @@ var RouterModuleV2 = class {
9588
9099
  } else {
9589
9100
  const fromDecimal = this.sdk.Router.tokenInfo(path.coinType[0]).decimals;
9590
9101
  const toDecimal = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
9591
- const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new import_bn20.default(priceResult.currentSqrtPrice[0]), fromDecimal, toDecimal) : TickMath.sqrtPriceX64ToPrice(new import_bn20.default(priceResult.currentSqrtPrice[0]), toDecimal, fromDecimal);
9102
+ const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new import_bn19.default(priceResult.currentSqrtPrice[0]), fromDecimal, toDecimal) : TickMath.sqrtPriceX64ToPrice(new import_bn19.default(priceResult.currentSqrtPrice[0]), toDecimal, fromDecimal);
9592
9103
  const path0 = {
9593
9104
  direction: path.a2b[0],
9594
9105
  label: "Magma",
@@ -10461,21 +9972,6 @@ var GaugeModule = class {
10461
9972
  });
10462
9973
  return tx;
10463
9974
  }
10464
- async getAllRewardByPositions(paramsList) {
10465
- const tx = new import_transactions11.Transaction();
10466
- const { integrate } = this.sdk.sdkOptions;
10467
- const { magma_token } = getPackagerConfigs(this.sdk.sdkOptions.magma_config);
10468
- paramsList.forEach((params) => {
10469
- const typeArguments = [params.coinTypeA, params.coinTypeB, magma_token];
10470
- const args = [tx.object(params.gaugeId), tx.object(params.poolId), tx.object(params.positionId), tx.object(CLOCK_ADDRESS)];
10471
- tx.moveCall({
10472
- target: `${integrate.published_at}::${Gauge}::get_reward_by_position`,
10473
- arguments: args,
10474
- typeArguments
10475
- });
10476
- });
10477
- return tx;
10478
- }
10479
9975
  async getEpochRewardByPool(pool, incentive_tokens) {
10480
9976
  const tx = new import_transactions11.Transaction();
10481
9977
  const { integrate, simulationAccount } = this.sdk.sdkOptions;
@@ -10508,954 +10004,67 @@ var GaugeModule = class {
10508
10004
  }
10509
10005
  };
10510
10006
 
10511
- // src/modules/dlmm.ts
10512
- var import_transactions12 = require("@mysten/sui/transactions");
10513
- var import_calc_dlmm3 = require("@magmaprotocol/calc_dlmm");
10514
- var import_decimal13 = __toESM(require("decimal.js"));
10515
- var DlmmModule = class {
10516
- _sdk;
10007
+ // src/sdk.ts
10008
+ var MagmaClmmSDK = class {
10517
10009
  _cache = {};
10518
- constructor(sdk) {
10519
- this._sdk = sdk;
10520
- }
10521
- get sdk() {
10522
- return this._sdk;
10523
- }
10524
- async getPoolInfo(pools) {
10525
- const objects = await this._sdk.fullClient.batchGetObjects(pools, { showContent: true });
10526
- const poolList = [];
10527
- objects.forEach((obj) => {
10528
- if (obj.error != null || obj.data?.content?.dataType !== "moveObject") {
10529
- throw new ClmmpoolsError(`Invalid objects. error: ${obj.error}`, "InvalidType" /* InvalidType */);
10530
- }
10531
- const fields = getObjectFields(obj);
10532
- poolList.push({
10533
- pool_id: fields.id.id,
10534
- bin_step: fields.bin_step,
10535
- coin_a: fields.x.fields.name,
10536
- coin_b: fields.y.fields.name,
10537
- base_factor: fields.params.fields.base_factor,
10538
- base_fee: fields.params.fields.base_factor / 1e4 * (fields.bin_step / 1e4),
10539
- active_index: fields.params.fields.active_index
10540
- });
10541
- });
10542
- return poolList;
10543
- }
10544
- // eg: fetch pool active_index
10545
- async fetchPairParams(params) {
10546
- const tx = new import_transactions12.Transaction();
10547
- const { integrate, simulationAccount } = this.sdk.sdkOptions;
10548
- const typeArguments = [params.coinTypeA, params.coinTypeB];
10549
- const args = [tx.object(params.pair)];
10550
- tx.moveCall({
10551
- target: `${integrate.published_at}::${DlmmScript}::fetch_pair_params`,
10552
- arguments: args,
10553
- typeArguments
10554
- });
10555
- const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
10556
- transactionBlock: tx,
10557
- sender: simulationAccount.address
10558
- });
10559
- if (simulateRes.error != null) {
10560
- throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
10561
- }
10562
- let res = {
10563
- base_factor: 0,
10564
- filter_period: 0,
10565
- decay_period: 0,
10566
- reduction_factor: 0,
10567
- variable_fee_control: 0,
10568
- protocol_share: 0,
10569
- max_volatility_accumulator: 0,
10570
- volatility_accumulator: 0,
10571
- volatility_reference: 0,
10572
- index_reference: 0,
10573
- time_of_last_update: 0,
10574
- oracle_index: 0,
10575
- active_index: 0
10576
- };
10577
- simulateRes.events?.forEach((item) => {
10578
- console.log(extractStructTagFromType(item.type).name);
10579
- if (extractStructTagFromType(item.type).name === `EventPairParams`) {
10580
- res = item.parsedJson.params;
10581
- }
10582
- });
10583
- return res;
10584
- }
10585
- // NOTE: x, y should be sorted
10586
- async createPairPayload(params) {
10587
- const storage_id = (0, import_calc_dlmm3.get_storage_id_from_real_id)(
10588
- BinMath.getBinIdFromPrice(params.priceTokenBPerTokenA, params.bin_step, params.coinADecimal, params.coinBDecimal)
10589
- );
10590
- const tx = new import_transactions12.Transaction();
10591
- tx.setSender(this.sdk.senderAddress);
10592
- const { clmm_pool, dlmm_pool, integrate } = this.sdk.sdkOptions;
10593
- const { global_config_id } = getPackagerConfigs(clmm_pool);
10594
- const dlmmConfig = getPackagerConfigs(dlmm_pool);
10595
- const typeArguments = [params.coinTypeA, params.coinTypeB];
10596
- const args = [
10597
- tx.object(dlmmConfig.factory),
10598
- tx.object(global_config_id),
10599
- tx.pure.u64(params.base_fee),
10600
- tx.pure.u16(params.bin_step),
10601
- tx.pure.u32(storage_id)
10602
- ];
10603
- tx.moveCall({
10604
- target: `${integrate.published_at}::${DlmmScript}::create_pair`,
10605
- typeArguments,
10606
- arguments: args
10607
- });
10608
- return tx;
10609
- }
10610
- // async mintByStrategySingle(params: MintByStrategySingleParams): Promise<Transaction> {}
10611
- async mintByStrategy(params) {
10612
- const tx = new import_transactions12.Transaction();
10613
- const slippage = new import_decimal13.default(params.slippage);
10614
- const lower_slippage = new import_decimal13.default(1).sub(slippage.div(new import_decimal13.default(1e4)));
10615
- const upper_slippage = new import_decimal13.default(1).plus(slippage.div(new import_decimal13.default(1e4)));
10616
- tx.setSender(this.sdk.senderAddress);
10617
- const { dlmm_pool, integrate } = this.sdk.sdkOptions;
10618
- const dlmmConfig = getPackagerConfigs(dlmm_pool);
10619
- const typeArguments = [params.coinTypeA, params.coinTypeB];
10620
- const price = (0, import_calc_dlmm3.get_price_x128_from_real_id)(params.active_bin, params.bin_step);
10621
- const min_price = new import_decimal13.default(price).mul(lower_slippage);
10622
- const max_price = new import_decimal13.default(price).mul(upper_slippage);
10623
- const active_min = (0, import_calc_dlmm3.get_storage_id_from_real_id)((0, import_calc_dlmm3.get_real_id_from_price_x128)(min_price.toDecimalPlaces(0).toString(), params.bin_step));
10624
- const active_max = (0, import_calc_dlmm3.get_storage_id_from_real_id)((0, import_calc_dlmm3.get_real_id_from_price_x128)(max_price.toDecimalPlaces(0).toString(), params.bin_step));
10625
- const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10626
- let primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountATotal), params.coinTypeA, false, true);
10627
- let primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountBTotal), params.coinTypeB, false, true);
10628
- let amount_min = 0;
10629
- let amount_max = 0;
10630
- if (params.fixCoinA) {
10631
- amount_min = new import_decimal13.default(params.amountBTotal).mul(lower_slippage).toDecimalPlaces(0).toNumber();
10632
- amount_max = new import_decimal13.default(params.amountBTotal).mul(upper_slippage).toDecimalPlaces(0).toNumber();
10633
- primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amount_max), params.coinTypeB, false, true);
10634
- }
10635
- if (params.fixCoinB) {
10636
- amount_min = new import_decimal13.default(params.amountATotal).mul(lower_slippage).toDecimalPlaces(0).toNumber();
10637
- amount_max = new import_decimal13.default(params.amountATotal).mul(upper_slippage).toDecimalPlaces(0).toNumber();
10638
- primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amount_max), params.coinTypeB, false, true);
10639
- }
10640
- if (params.fixCoinA && params.fixCoinB) {
10641
- } else if (params.fixCoinA) {
10642
- params.amountBTotal = 0;
10643
- } else if (params.fixCoinB) {
10644
- params.amountATotal = 0;
10645
- }
10646
- const args = [
10647
- tx.object(params.pair),
10648
- tx.object(dlmmConfig.factory),
10649
- primaryCoinAInputs.targetCoin,
10650
- primaryCoinBInputs.targetCoin,
10651
- tx.pure.u64(params.amountATotal),
10652
- tx.pure.u64(params.amountBTotal),
10653
- tx.pure.u8(params.strategy),
10654
- tx.pure.u32((0, import_calc_dlmm3.get_storage_id_from_real_id)(params.min_bin)),
10655
- tx.pure.u32((0, import_calc_dlmm3.get_storage_id_from_real_id)(params.max_bin)),
10656
- tx.pure.u32(active_min),
10657
- tx.pure.u32(active_max),
10658
- tx.pure.u64(amount_min),
10659
- tx.pure.u64(amount_max),
10660
- tx.object(CLOCK_ADDRESS)
10661
- ];
10662
- tx.moveCall({
10663
- target: `${integrate.published_at}::${DlmmScript}::mint_by_strategy`,
10664
- typeArguments,
10665
- arguments: args
10666
- });
10667
- return tx;
10668
- }
10669
- // Create a position by percent
10670
- async mintPercent(params) {
10671
- const tx = new import_transactions12.Transaction();
10672
- tx.setSender(this.sdk.senderAddress);
10673
- const { dlmm_pool, integrate } = this.sdk.sdkOptions;
10674
- const dlmmConfig = getPackagerConfigs(dlmm_pool);
10675
- const typeArguments = [params.coinTypeA, params.coinTypeB];
10676
- const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10677
- const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountATotal), params.coinTypeA, false, true);
10678
- const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountBTotal), params.coinTypeB, false, true);
10679
- const args = [
10680
- tx.object(params.pair),
10681
- tx.object(dlmmConfig.factory),
10682
- primaryCoinAInputs.targetCoin,
10683
- primaryCoinBInputs.targetCoin,
10684
- tx.pure.u64(params.amountATotal),
10685
- tx.pure.u64(params.amountBTotal),
10686
- tx.pure.vector("u32", params.storageIds),
10687
- tx.pure.vector("u64", params.binsAPercent),
10688
- tx.pure.vector("u64", params.binsBPercent),
10689
- tx.pure.address(params.to),
10690
- tx.object(CLOCK_ADDRESS)
10691
- ];
10692
- tx.moveCall({
10693
- target: `${integrate.published_at}::${DlmmScript}::mint_percent`,
10694
- typeArguments,
10695
- arguments: args
10696
- });
10697
- return tx;
10698
- }
10699
- // Create a position by amount
10700
- async createPositionByAmount(params) {
10701
- const tx = new import_transactions12.Transaction();
10702
- tx.setSender(this.sdk.senderAddress);
10703
- const { dlmm_pool, integrate } = this.sdk.sdkOptions;
10704
- const dlmmConfig = getPackagerConfigs(dlmm_pool);
10705
- const typeArguments = [params.coinTypeA, params.coinTypeB];
10706
- const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10707
- const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountATotal), params.coinTypeA, false, true);
10708
- const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountBTotal), params.coinTypeB, false, true);
10709
- const args = [
10710
- tx.object(params.pair),
10711
- tx.object(dlmmConfig.factory),
10712
- primaryCoinAInputs.targetCoin,
10713
- primaryCoinBInputs.targetCoin,
10714
- tx.pure.vector("u32", params.storageIds),
10715
- tx.pure.vector("u64", params.amountsA),
10716
- tx.pure.vector("u64", params.amountsB),
10717
- tx.pure.address(params.to),
10718
- tx.object(CLOCK_ADDRESS)
10719
- ];
10720
- tx.moveCall({
10721
- target: `${integrate.published_at}::${DlmmScript}::mint_amounts`,
10722
- typeArguments,
10723
- arguments: args
10724
- });
10725
- return tx;
10726
- }
10727
- async addLiquidity(params) {
10728
- if (params.rewards_token.length === 0) {
10729
- return this._raisePositionByAmounts(params);
10730
- }
10731
- return this._raisePositionByAmountsReward(params);
10732
- }
10733
- async _raisePositionByAmounts(params) {
10734
- const tx = new import_transactions12.Transaction();
10735
- tx.setSender(this.sdk.senderAddress);
10736
- const { dlmm_pool, integrate } = this.sdk.sdkOptions;
10737
- const dlmmConfig = getPackagerConfigs(dlmm_pool);
10738
- const typeArguments = [params.coin_a, params.coin_b];
10739
- const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10740
- const amountATotal = params.amounts_a.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10741
- const amountBTotal = params.amounts_b.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10742
- const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountATotal), params.coin_a, false, true);
10743
- const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountBTotal), params.coin_b, false, true);
10744
- const args = [
10745
- tx.object(params.pool_id),
10746
- tx.object(dlmmConfig.factory),
10747
- tx.object(params.position_id),
10748
- primaryCoinAInputs.targetCoin,
10749
- primaryCoinBInputs.targetCoin,
10750
- tx.pure.vector("u64", params.amounts_a),
10751
- tx.pure.vector("u64", params.amounts_b),
10752
- tx.pure.address(params.receiver),
10753
- tx.object(CLOCK_ADDRESS)
10754
- ];
10755
- tx.moveCall({
10756
- target: `${integrate.published_at}::${DlmmScript}::raise_position_by_amounts`,
10757
- typeArguments,
10758
- arguments: args
10759
- });
10760
- return tx;
10761
- }
10762
- async _raisePositionByAmountsReward(params) {
10763
- const tx = new import_transactions12.Transaction();
10764
- tx.setSender(this.sdk.senderAddress);
10765
- const { dlmm_pool, integrate, clmm_pool } = this.sdk.sdkOptions;
10766
- const dlmmConfig = getPackagerConfigs(dlmm_pool);
10767
- const clmmConfigs = getPackagerConfigs(clmm_pool);
10768
- const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
10769
- const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10770
- const amountATotal = params.amounts_a.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10771
- const amountBTotal = params.amounts_b.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10772
- const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountATotal), params.coin_a, false, true);
10773
- const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountBTotal), params.coin_b, false, true);
10774
- const args = [
10775
- tx.object(params.pool_id),
10776
- tx.object(dlmmConfig.factory),
10777
- tx.object(clmmConfigs.global_vault_id),
10778
- tx.object(params.position_id),
10779
- primaryCoinAInputs.targetCoin,
10780
- primaryCoinBInputs.targetCoin,
10781
- tx.pure.vector("u64", params.amounts_a),
10782
- tx.pure.vector("u64", params.amounts_b),
10783
- tx.pure.address(params.receiver),
10784
- tx.object(CLOCK_ADDRESS)
10785
- ];
10786
- tx.moveCall({
10787
- target: `${integrate.published_at}::${DlmmScript}::raise_position_by_amounts_reward${params.rewards_token.length}`,
10788
- typeArguments,
10789
- arguments: args
10790
- });
10791
- return tx;
10792
- }
10793
- async burnPosition(params) {
10794
- const tx = new import_transactions12.Transaction();
10795
- tx.setSender(this.sdk.senderAddress);
10796
- const { integrate, clmm_pool } = this.sdk.sdkOptions;
10797
- const clmmConfigs = getPackagerConfigs(clmm_pool);
10798
- const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
10799
- let args = [tx.object(params.pool_id), tx.object(params.position_id), tx.object(CLOCK_ADDRESS)];
10800
- let target = `${integrate.published_at}::${DlmmScript}::burn_position`;
10801
- if (params.rewards_token.length > 0) {
10802
- args = [tx.object(params.pool_id), tx.object(clmmConfigs.global_vault_id), tx.object(params.position_id), tx.object(CLOCK_ADDRESS)];
10803
- target = `${integrate.published_at}::${DlmmScript}::burn_position_reward${params.rewards_token.length}`;
10804
- }
10805
- tx.moveCall({
10806
- target,
10807
- typeArguments,
10808
- arguments: args
10809
- });
10810
- return tx;
10811
- }
10812
- async shrinkPosition(params) {
10813
- const tx = new import_transactions12.Transaction();
10814
- tx.setSender(this.sdk.senderAddress);
10815
- const { integrate, clmm_pool } = this.sdk.sdkOptions;
10816
- const clmmConfigs = getPackagerConfigs(clmm_pool);
10817
- const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
10818
- let args = [tx.object(params.pool_id), tx.object(params.position_id), tx.pure.u64(params.delta_percentage), tx.object(CLOCK_ADDRESS)];
10819
- let target = `${integrate.published_at}::${DlmmScript}::shrink_position`;
10820
- if (params.rewards_token.length > 0) {
10821
- args = [
10822
- tx.object(params.pool_id),
10823
- tx.object(clmmConfigs.global_vault_id),
10824
- tx.object(params.position_id),
10825
- tx.pure.u64(params.delta_percentage),
10826
- tx.object(CLOCK_ADDRESS)
10827
- ];
10828
- target = `${integrate.published_at}::${DlmmScript}::shrink_position_reward${params.rewards_token.length}`;
10829
- }
10830
- tx.moveCall({
10831
- target,
10832
- typeArguments,
10833
- arguments: args
10834
- });
10835
- return tx;
10836
- }
10837
- async collectFeeAndReward(params) {
10838
- let tx = new import_transactions12.Transaction();
10839
- tx = await this.collectFees(params);
10840
- if (params.rewards_token.length > 0) {
10841
- tx = await this.collectReward(params);
10842
- }
10843
- return tx;
10844
- }
10845
- async collectReward(params, transaction) {
10846
- const tx = transaction || new import_transactions12.Transaction();
10847
- tx.setSender(this.sdk.senderAddress);
10848
- const { integrate, clmm_pool } = this.sdk.sdkOptions;
10849
- const clmmConfigs = getPackagerConfigs(clmm_pool);
10850
- const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
10851
- const args = [
10852
- tx.object(params.pool_id),
10853
- tx.object(clmmConfigs.global_vault_id),
10854
- tx.object(params.position_id),
10855
- tx.object(CLOCK_ADDRESS)
10856
- ];
10857
- let target = `${integrate.published_at}::${DlmmScript}::collect_reward`;
10858
- if (params.rewards_token.length > 1) {
10859
- target = `${integrate.published_at}::${DlmmScript}::collect_reward${params.rewards_token.length}`;
10860
- }
10861
- tx.moveCall({
10862
- target,
10863
- typeArguments,
10864
- arguments: args
10865
- });
10866
- return tx;
10867
- }
10868
- async collectFees(params, transaction) {
10869
- const tx = transaction || new import_transactions12.Transaction();
10870
- tx.setSender(this.sdk.senderAddress);
10871
- const { integrate } = this.sdk.sdkOptions;
10872
- const typeArguments = [params.coin_a, params.coin_b];
10873
- const args = [tx.object(params.pool_id), tx.object(params.position_id), tx.object(CLOCK_ADDRESS)];
10874
- const target = `${integrate.published_at}::${DlmmScript}::collect_fees`;
10875
- tx.moveCall({
10876
- target,
10877
- typeArguments,
10878
- arguments: args
10879
- });
10880
- return tx;
10881
- }
10882
- async createPairAddLiquidity(params) {
10883
- const tx = new import_transactions12.Transaction();
10884
- tx.setSender(this.sdk.senderAddress);
10885
- const { clmm_pool, dlmm_pool, integrate } = this.sdk.sdkOptions;
10886
- const { global_config_id } = getPackagerConfigs(clmm_pool);
10887
- const dlmmConfig = getPackagerConfigs(dlmm_pool);
10888
- const typeArguments = [params.coinTypeA, params.coinTypeB];
10889
- const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10890
- const amountATotal = params.amountsX.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10891
- const amountBTotal = params.amountsY.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10892
- const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountATotal), params.coinTypeA, false, true);
10893
- const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountBTotal), params.coinTypeB, false, true);
10894
- const storageIds = [];
10895
- params.realIds.forEach((i) => {
10896
- storageIds.push((0, import_calc_dlmm3.get_storage_id_from_real_id)(i));
10897
- });
10898
- const args = [
10899
- tx.object(dlmmConfig.factory),
10900
- tx.object(global_config_id),
10901
- tx.pure.u64(params.baseFee),
10902
- tx.pure.u16(params.binStep),
10903
- tx.pure.u32((0, import_calc_dlmm3.get_storage_id_from_real_id)(params.activeId)),
10904
- primaryCoinAInputs.targetCoin,
10905
- primaryCoinBInputs.targetCoin,
10906
- tx.pure.vector("u32", storageIds),
10907
- tx.pure.vector("u64", params.amountsX),
10908
- tx.pure.vector("u64", params.amountsY),
10909
- tx.pure.address(params.to),
10910
- tx.object(CLOCK_ADDRESS)
10911
- ];
10912
- const target = `${integrate.published_at}::${DlmmScript}::create_pair_add_liquidity`;
10913
- tx.moveCall({
10914
- target,
10915
- typeArguments,
10916
- arguments: args
10917
- });
10918
- return tx;
10919
- }
10920
- async swap(params) {
10921
- const tx = new import_transactions12.Transaction();
10922
- tx.setSender(this.sdk.senderAddress);
10923
- const { clmm_pool, integrate } = this.sdk.sdkOptions;
10924
- const { global_config_id } = getPackagerConfigs(clmm_pool);
10925
- const typeArguments = [params.coinTypeA, params.coinTypeB];
10926
- const allCoinAsset = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10927
- const primaryCoinInputA = TransactionUtil.buildCoinForAmount(
10928
- tx,
10929
- allCoinAsset,
10930
- params.swapForY ? BigInt(params.amountIn) : BigInt(0),
10931
- params.coinTypeA,
10932
- false,
10933
- true
10934
- );
10935
- const primaryCoinInputB = TransactionUtil.buildCoinForAmount(
10936
- tx,
10937
- allCoinAsset,
10938
- params.swapForY ? BigInt(0) : BigInt(params.amountIn),
10939
- params.coinTypeB,
10940
- false,
10941
- true
10942
- );
10943
- const args = [
10944
- tx.object(params.pair),
10945
- tx.object(global_config_id),
10946
- primaryCoinInputA.targetCoin,
10947
- primaryCoinInputB.targetCoin,
10948
- tx.pure.u64(params.amountIn),
10949
- tx.pure.u64(params.minAmountOut),
10950
- tx.pure.bool(params.swapForY),
10951
- tx.pure.address(params.to),
10952
- tx.object(CLOCK_ADDRESS)
10953
- ];
10954
- tx.moveCall({
10955
- target: `${integrate.published_at}::${DlmmScript}::swap`,
10956
- typeArguments,
10957
- arguments: args
10958
- });
10959
- return tx;
10960
- }
10961
- async fetchBins(params) {
10962
- const tx = new import_transactions12.Transaction();
10963
- const { integrate, simulationAccount } = this.sdk.sdkOptions;
10964
- const typeArguments = [params.coinTypeA, params.coinTypeB];
10965
- const args = [tx.object(params.pair), tx.pure.u64(params.offset), tx.pure.u64(params.limit)];
10966
- tx.moveCall({
10967
- target: `${integrate.published_at}::${DlmmScript}::fetch_bins`,
10968
- arguments: args,
10969
- typeArguments
10970
- });
10971
- const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
10972
- transactionBlock: tx,
10973
- sender: simulationAccount.address
10974
- });
10975
- if (simulateRes.error != null) {
10976
- throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
10977
- }
10978
- let res = [];
10979
- simulateRes.events?.forEach((item) => {
10980
- if (extractStructTagFromType(item.type).name === `EventFetchBins`) {
10981
- const { bins } = item.parsedJson;
10982
- res = bins;
10983
- }
10984
- });
10985
- return res;
10986
- }
10987
- /**
10988
- * Gets a list of positions for the given account address.
10989
- * @param accountAddress The account address to get positions for.
10990
- * @param assignPoolIds An array of pool IDs to filter the positions by.
10991
- * @returns array of Position objects.
10992
- */
10993
- async getUserPositionById(positionId, showDisplay = true) {
10994
- let position;
10995
- const ownerRes = await this._sdk.fullClient.getObject({
10996
- id: positionId,
10997
- options: { showContent: true, showType: true, showDisplay, showOwner: true }
10998
- });
10999
- const type = extractStructTagFromType(ownerRes.data.type);
11000
- if (type.full_address === this.buildPositionType()) {
11001
- position = this.buildPosition(ownerRes);
11002
- } else {
11003
- throw new ClmmpoolsError(`Dlmm Position not exists. Get Position error:${ownerRes.error}`, "InvalidPositionObject" /* InvalidPositionObject */);
11004
- }
11005
- const poolMap = /* @__PURE__ */ new Set();
11006
- poolMap.add(position.pool);
11007
- const pool = (await this.getPoolInfo(Array.from(poolMap)))[0];
11008
- const _params = [];
11009
- _params.push({
11010
- pool_id: pool.pool_id,
11011
- coin_a: pool.coin_a,
11012
- coin_b: pool.coin_b
11013
- });
11014
- const pool_reward_coins = await this.getPairRewarders(_params);
11015
- const positionLiquidity = await this.getPositionLiquidity({
11016
- pair: position.pool,
11017
- positionId: position.pos_object_id,
11018
- coinTypeA: pool.coin_a,
11019
- coinTypeB: pool.coin_b
11020
- });
11021
- const rewards_token = pool_reward_coins.get(position.pool) || [];
11022
- let positionRewards = { position_id: position.pos_object_id, reward: [], amount: [] };
11023
- if (rewards_token.length > 0) {
11024
- positionRewards = await this.getEarnedRewards({
11025
- pool_id: position.pool,
11026
- position_id: position.pos_object_id,
11027
- coin_a: pool.coin_a,
11028
- coin_b: pool.coin_b,
11029
- rewards_token: pool_reward_coins.get(position.pool) || []
11030
- });
11031
- }
11032
- const positionFees = await this.getEarnedFees({
11033
- pool_id: position.pool,
11034
- position_id: position.pos_object_id,
11035
- coin_a: pool.coin_a,
11036
- coin_b: pool.coin_b
11037
- });
11038
- return {
11039
- position,
11040
- liquidity: positionLiquidity,
11041
- rewards: positionRewards,
11042
- fees: positionFees,
11043
- contractPool: pool
11044
- };
11045
- }
11046
- /**
11047
- * Gets a list of positions for the given account address.
11048
- * @param accountAddress The account address to get positions for.
11049
- * @param assignPoolIds An array of pool IDs to filter the positions by.
11050
- * @returns array of Position objects.
11051
- */
11052
- async getUserPositions(accountAddress, assignPoolIds = [], showDisplay = true) {
11053
- const allPosition = [];
11054
- const ownerRes = await this._sdk.fullClient.getOwnedObjectsByPage(accountAddress, {
11055
- options: { showType: true, showContent: true, showDisplay, showOwner: true },
11056
- filter: { Package: this._sdk.sdkOptions.dlmm_pool.package_id }
11057
- });
11058
- const hasAssignPoolIds = assignPoolIds.length > 0;
11059
- for (const item of ownerRes.data) {
11060
- const type = extractStructTagFromType(item.data.type);
11061
- if (type.full_address === this.buildPositionType()) {
11062
- const position = this.buildPosition(item);
11063
- const cacheKey = `${position.pos_object_id}_getPositionList`;
11064
- this.updateCache(cacheKey, position, cacheTime24h);
11065
- if (hasAssignPoolIds) {
11066
- if (assignPoolIds.includes(position.pool)) {
11067
- allPosition.push(position);
11068
- }
11069
- } else {
11070
- allPosition.push(position);
11071
- }
11072
- }
11073
- }
11074
- const poolMap = /* @__PURE__ */ new Set();
11075
- for (const item of allPosition) {
11076
- poolMap.add(item.pool);
11077
- }
11078
- const poolList = await this.getPoolInfo(Array.from(poolMap));
11079
- this.updateCache(`${DlmmScript}_positionList_poolList`, poolList, cacheTime24h);
11080
- const _params = [];
11081
- for (const pool of poolList) {
11082
- _params.push({
11083
- pool_id: pool.pool_id,
11084
- coin_a: pool.coin_a,
11085
- coin_b: pool.coin_b
11086
- });
11087
- }
11088
- const pool_reward_coins = await this.getPairRewarders(_params);
11089
- const out = [];
11090
- for (const item of allPosition) {
11091
- const pool = poolList.find((pool2) => pool2.pool_id === item.pool);
11092
- const positionLiquidity = await this.getPositionLiquidity({
11093
- pair: item.pool,
11094
- positionId: item.pos_object_id,
11095
- coinTypeA: pool.coin_a,
11096
- coinTypeB: pool.coin_b
11097
- });
11098
- const rewards_token = pool_reward_coins.get(item.pool) || [];
11099
- let positionRewards = { position_id: item.pos_object_id, reward: [], amount: [] };
11100
- if (rewards_token.length > 0) {
11101
- positionRewards = await this.getEarnedRewards({
11102
- pool_id: item.pool,
11103
- position_id: item.pos_object_id,
11104
- coin_a: pool.coin_a,
11105
- coin_b: pool.coin_b,
11106
- rewards_token: pool_reward_coins.get(item.pool) || []
11107
- });
11108
- }
11109
- const positionFees = await this.getEarnedFees({
11110
- pool_id: item.pool,
11111
- position_id: item.pos_object_id,
11112
- coin_a: pool.coin_a,
11113
- coin_b: pool.coin_b
11114
- });
11115
- out.push({
11116
- position: item,
11117
- liquidity: positionLiquidity,
11118
- rewards: positionRewards,
11119
- fees: positionFees,
11120
- contractPool: pool
11121
- });
11122
- }
11123
- return out;
11124
- }
11125
- buildPosition(object) {
11126
- if (object.error != null || object.data?.content?.dataType !== "moveObject") {
11127
- throw new ClmmpoolsError(`Dlmm Position not exists. Get Position error:${object.error}`, "InvalidPositionObject" /* InvalidPositionObject */);
11128
- }
11129
- const fields = getObjectFields(object);
11130
- const ownerWarp = getObjectOwner(object);
11131
- return {
11132
- pos_object_id: fields.id.id,
11133
- owner: ownerWarp.AddressOwner,
11134
- pool: fields.pair_id,
11135
- bin_real_ids: fields.bin_ids.map((id) => (0, import_calc_dlmm3.get_real_id)(id)),
11136
- type: ""
11137
- };
11138
- }
11139
- // return [coin_a, coin_b]
11140
- async getPoolCoins(pools) {
11141
- const res = await this._sdk.fullClient.multiGetObjects({ ids: pools, options: { showContent: true } });
11142
- const poolCoins = /* @__PURE__ */ new Map();
11143
- res.forEach((item) => {
11144
- if (item.error != null || item.data?.content?.dataType !== "moveObject") {
11145
- throw new Error(`Failed to get poolCoins with err: ${item.error}`);
11146
- }
11147
- const type = getObjectType(item);
11148
- const poolTypeFields = extractStructTagFromType(type);
11149
- poolCoins.set(item.data.objectId, poolTypeFields.type_arguments);
11150
- });
11151
- return poolCoins;
11152
- }
11153
- buildPositionType() {
11154
- return `${this._sdk.sdkOptions.dlmm_pool.package_id}::dlmm_position::Position`;
11155
- }
11156
- async getPositionLiquidity(params) {
11157
- const tx = new import_transactions12.Transaction();
11158
- const { integrate, simulationAccount } = this.sdk.sdkOptions;
11159
- const typeArguments = [params.coinTypeA, params.coinTypeB];
11160
- const args = [tx.object(params.pair), tx.object(params.positionId)];
11161
- tx.moveCall({
11162
- target: `${integrate.published_at}::${DlmmScript}::position_liquidity`,
11163
- arguments: args,
11164
- typeArguments
11165
- });
11166
- const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11167
- transactionBlock: tx,
11168
- sender: simulationAccount.address
11169
- });
11170
- if (simulateRes.error != null) {
11171
- throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
11172
- }
11173
- const out = {
11174
- shares: 0,
11175
- liquidity: 0,
11176
- x_equivalent: 0,
11177
- y_equivalent: 0,
11178
- bin_real_ids: [],
11179
- bin_x_eq: [],
11180
- bin_y_eq: [],
11181
- bin_liquidity: []
11182
- };
11183
- simulateRes.events?.forEach((item) => {
11184
- if (extractStructTagFromType(item.type).name === `EventPositionLiquidity`) {
11185
- out.shares = item.parsedJson.shares;
11186
- out.liquidity = item.parsedJson.liquidity;
11187
- out.x_equivalent = item.parsedJson.x_equivalent;
11188
- out.y_equivalent = item.parsedJson.y_equivalent;
11189
- out.bin_real_ids = item.parsedJson.bin_ids.map((id) => (0, import_calc_dlmm3.get_real_id)(id));
11190
- out.bin_x_eq = item.parsedJson.bin_x_eq;
11191
- out.bin_y_eq = item.parsedJson.bin_y_eq;
11192
- out.bin_liquidity = item.parsedJson.bin_liquidity;
11193
- }
11194
- });
11195
- return out;
11196
- }
11197
- async getPairLiquidity(params) {
11198
- const tx = new import_transactions12.Transaction();
11199
- const { integrate, simulationAccount } = this.sdk.sdkOptions;
11200
- const typeArguments = [params.coinTypeA, params.coinTypeB];
11201
- const args = [tx.object(params.pair)];
11202
- tx.moveCall({
11203
- target: `${integrate.published_at}::${DlmmScript}::pair_liquidity`,
11204
- arguments: args,
11205
- typeArguments
11206
- });
11207
- const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11208
- transactionBlock: tx,
11209
- sender: simulationAccount.address
11210
- });
11211
- if (simulateRes.error != null) {
11212
- throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
11213
- }
11214
- const out = {
11215
- shares: 0,
11216
- liquidity: 0,
11217
- x: 0,
11218
- y: 0,
11219
- bin_ids: [],
11220
- bin_x: [],
11221
- bin_y: []
11222
- };
11223
- simulateRes.events?.forEach((item) => {
11224
- if (extractStructTagFromType(item.type).name === `EventPositionLiquidity`) {
11225
- out.shares = item.parsedJson.shares;
11226
- out.liquidity = item.parsedJson.liquidity;
11227
- out.x = item.parsedJson.x;
11228
- out.y = item.parsedJson.y;
11229
- out.bin_ids = item.bin_ids;
11230
- out.bin_x = item.bin_x;
11231
- out.bin_y = item.bin_y;
11232
- }
11233
- });
11234
- return out;
11235
- }
11236
- async getEarnedFees(params) {
11237
- const tx = new import_transactions12.Transaction();
11238
- const { integrate, simulationAccount } = this.sdk.sdkOptions;
11239
- const typeArguments = [params.coin_a, params.coin_b];
11240
- const args = [tx.object(params.pool_id), tx.object(params.position_id)];
11241
- tx.moveCall({
11242
- target: `${integrate.published_at}::${DlmmScript}::earned_fees`,
11243
- arguments: args,
11244
- typeArguments
11245
- });
11246
- const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11247
- transactionBlock: tx,
11248
- sender: simulationAccount.address
11249
- });
11250
- const out = {
11251
- position_id: "",
11252
- x: "",
11253
- y: "",
11254
- fee_x: 0,
11255
- fee_y: 0
11256
- };
11257
- if (simulateRes.error != null) {
11258
- throw new Error(`fetchPairRewards error code: ${simulateRes.error ?? "unknown error"}`);
11259
- }
11260
- simulateRes.events?.forEach((item) => {
11261
- if (extractStructTagFromType(item.type).name === `EventPositionLiquidity`) {
11262
- out.position_id = item.parsedJson.position_id;
11263
- out.x = item.parsedJson.x;
11264
- out.y = item.parsedJson.y;
11265
- out.fee_x = item.parsedJson.fee_x;
11266
- out.fee_y = item.parsedJson.fee_y;
11267
- }
11268
- });
11269
- return out;
11270
- }
11271
- async getEarnedRewards(params) {
11272
- const tx = new import_transactions12.Transaction();
11273
- const { integrate, simulationAccount } = this.sdk.sdkOptions;
11274
- const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
11275
- const args = [tx.object(params.pool_id), tx.object(params.position_id), tx.object(CLOCK_ADDRESS)];
11276
- let target = `${integrate.published_at}::${DlmmScript}::earned_rewards`;
11277
- if (params.rewards_token.length > 1) {
11278
- target = `${integrate.published_at}::${DlmmScript}::earned_rewards${params.rewards_token.length}`;
11279
- }
11280
- tx.moveCall({
11281
- target,
11282
- arguments: args,
11283
- typeArguments
11284
- });
11285
- const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11286
- transactionBlock: tx,
11287
- sender: simulationAccount.address
11288
- });
11289
- const out = {
11290
- position_id: "",
11291
- reward: [],
11292
- amount: []
11293
- };
11294
- if (simulateRes.error != null) {
11295
- throw new Error(`getEarnedRewards error code: ${simulateRes.error ?? "unknown error"}`);
11296
- }
11297
- simulateRes.events?.forEach((item) => {
11298
- if (extractStructTagFromType(item.type).name === `DlmmEventEarnedRewards`) {
11299
- out.position_id = item.parsedJson.position_id;
11300
- out.reward = [item.parsedJson.reward];
11301
- out.amount = [item.parsedJson.amount];
11302
- } else if (extractStructTagFromType(item.type).name === `DlmmEventEarnedRewards2`) {
11303
- out.position_id = item.parsedJson.position_id;
11304
- out.reward = [item.parsedJson.reward1, item.parsedJson.reward2];
11305
- out.amount = [item.parsedJson.amount1, item.parsedJson.amount2];
11306
- } else if (extractStructTagFromType(item.type).name === `EventEarnedRewards3`) {
11307
- out.position_id = item.parsedJson.position_id;
11308
- out.reward = [item.parsedJson.reward1, item.parsedJson.reward2, item.parsedJson.reward3];
11309
- out.amount = [item.parsedJson.amount1, item.parsedJson.amount2, item.parsedJson.amount3];
11310
- }
11311
- });
11312
- return out;
11313
- }
11314
- // return pool_id => reward_tokens
11315
- async getPairRewarders(params) {
11316
- let tx = new import_transactions12.Transaction();
11317
- for (const param of params) {
11318
- tx = await this._getPairRewarders(param, tx);
11319
- }
11320
- return this._parsePairRewarders(tx);
11321
- }
11322
- async _getPairRewarders(params, tx) {
11323
- tx = tx || new import_transactions12.Transaction();
11324
- const { integrate } = this.sdk.sdkOptions;
11325
- const typeArguments = [params.coin_a, params.coin_b];
11326
- const args = [tx.object(params.pool_id)];
11327
- tx.moveCall({
11328
- target: `${integrate.published_at}::${DlmmScript}::get_pair_rewarders`,
11329
- arguments: args,
11330
- typeArguments
11331
- });
11332
- return tx;
11333
- }
11334
- async _parsePairRewarders(tx) {
11335
- const { simulationAccount } = this.sdk.sdkOptions;
11336
- const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11337
- transactionBlock: tx,
11338
- sender: simulationAccount.address
11339
- });
11340
- const out = /* @__PURE__ */ new Map();
11341
- if (simulateRes.error != null) {
11342
- throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
11343
- }
11344
- simulateRes.events?.forEach((item) => {
11345
- if (extractStructTagFromType(item.type).name === `EventPairRewardTypes`) {
11346
- const pairRewards = {
11347
- pair_id: "",
11348
- tokens: []
11349
- };
11350
- pairRewards.pair_id = item.parsedJson.pair_id;
11351
- item.parsedJson.tokens.forEach((token) => {
11352
- pairRewards.tokens.push(token.name);
11353
- });
11354
- out.set(pairRewards.pair_id, pairRewards.tokens);
11355
- }
11356
- });
11357
- return out;
11358
- }
11359
- /**
11360
- * Updates the cache for the given key.
11361
- *
11362
- * @param key The key of the cache entry to update.
11363
- * @param data The data to store in the cache.
11364
- * @param time The time in minutes after which the cache entry should expire.
11365
- */
11366
- updateCache(key, data, time = cacheTime5min) {
11367
- let cacheData = this._cache[key];
11368
- if (cacheData) {
11369
- cacheData.overdueTime = getFutureTime(time);
11370
- cacheData.value = data;
11371
- } else {
11372
- cacheData = new CachedContent(data, getFutureTime(time));
11373
- }
11374
- this._cache[key] = cacheData;
11375
- }
11376
- /**
11377
- * Gets the cache entry for the given key.
11378
- *
11379
- * @param key The key of the cache entry to get.
11380
- * @param forceRefresh Whether to force a refresh of the cache entry.
11381
- * @returns The cache entry for the given key, or undefined if the cache entry does not exist or is expired.
11382
- */
11383
- getCache(key, forceRefresh = false) {
11384
- const cacheData = this._cache[key];
11385
- const isValid = cacheData?.isValid();
11386
- if (!forceRefresh && isValid) {
11387
- return cacheData.value;
11388
- }
11389
- if (!isValid) {
11390
- delete this._cache[key];
11391
- }
11392
- return void 0;
11393
- }
11394
- };
11395
-
11396
- // src/sdk.ts
11397
- var MagmaClmmSDK = class {
11398
- _cache = {};
11399
- /**
11400
- * RPC provider on the SUI chain
11401
- */
11402
- _rpcModule;
11403
- /**
11404
- * Provide interact with clmm pools with a pool router interface.
11405
- */
11406
- _pool;
11407
- /**
11408
- * Provide interact with clmm position with a position router interface.
11409
- */
11410
- _position;
11411
- /**
11412
- * Provide interact with a pool swap router interface.
11413
- */
11414
- _swap;
11415
- /**
11416
- * Provide interact with a lock interface.
11417
- */
11418
- _lock;
11419
- _gauge;
11420
- _dlmm;
11421
- /**
11422
- * Provide interact with a position rewarder interface.
11423
- */
11424
- _rewarder;
11425
- /**
11426
- * Provide interact with a pool router interface.
11427
- */
11428
- _router;
11429
- /**
11430
- * Provide interact with a pool routerV2 interface.
11431
- */
11432
- _router_v2;
11433
- /**
11434
- * Provide interact with pool and token config (contain token base info for metadat).
11435
- * @deprecated Please use MagmaConfig instead
11436
- */
11437
- _token;
11438
- /**
11439
- * Provide interact with clmm pool and coin and launchpad pool config
11440
- */
11441
- _config;
11442
- /**
11443
- * Provide sdk options
11444
- */
11445
- _sdkOptions;
11446
- /**
11447
- * After connecting the wallet, set the current wallet address to senderAddress.
11448
- */
11449
- _senderAddress = "";
11450
- constructor(options) {
11451
- this._sdkOptions = options;
11452
- this._rpcModule = new RpcModule({
11453
- url: options.fullRpcUrl
10010
+ /**
10011
+ * RPC provider on the SUI chain
10012
+ */
10013
+ _rpcModule;
10014
+ /**
10015
+ * Provide interact with clmm pools with a pool router interface.
10016
+ */
10017
+ _pool;
10018
+ /**
10019
+ * Provide interact with clmm position with a position router interface.
10020
+ */
10021
+ _position;
10022
+ /**
10023
+ * Provide interact with a pool swap router interface.
10024
+ */
10025
+ _swap;
10026
+ /**
10027
+ * Provide interact with a lock interface.
10028
+ */
10029
+ _lock;
10030
+ _gauge;
10031
+ /**
10032
+ * Provide interact with a position rewarder interface.
10033
+ */
10034
+ _rewarder;
10035
+ /**
10036
+ * Provide interact with a pool router interface.
10037
+ */
10038
+ _router;
10039
+ /**
10040
+ * Provide interact with a pool routerV2 interface.
10041
+ */
10042
+ _router_v2;
10043
+ /**
10044
+ * Provide interact with pool and token config (contain token base info for metadat).
10045
+ * @deprecated Please use MagmaConfig instead
10046
+ */
10047
+ _token;
10048
+ /**
10049
+ * Provide interact with clmm pool and coin and launchpad pool config
10050
+ */
10051
+ _config;
10052
+ /**
10053
+ * Provide sdk options
10054
+ */
10055
+ _sdkOptions;
10056
+ /**
10057
+ * After connecting the wallet, set the current wallet address to senderAddress.
10058
+ */
10059
+ _senderAddress = "";
10060
+ constructor(options) {
10061
+ this._sdkOptions = options;
10062
+ this._rpcModule = new RpcModule({
10063
+ url: options.fullRpcUrl
11454
10064
  });
11455
10065
  this._swap = new SwapModule(this);
11456
10066
  this._lock = new LockModule(this);
11457
10067
  this._gauge = new GaugeModule(this);
11458
- this._dlmm = new DlmmModule(this);
11459
10068
  this._pool = new PoolModule(this);
11460
10069
  this._position = new PositionModule(this);
11461
10070
  this._rewarder = new RewarderModule(this);
@@ -11493,9 +10102,6 @@ var MagmaClmmSDK = class {
11493
10102
  get Gauge() {
11494
10103
  return this._gauge;
11495
10104
  }
11496
- get Dlmm() {
11497
- return this._dlmm;
11498
- }
11499
10105
  /**
11500
10106
  * Getter for the fullClient property.
11501
10107
  * @returns {RpcModule} The fullClient property value.
@@ -11669,7 +10275,6 @@ var main_default = MagmaClmmSDK;
11669
10275
  var SDKConfig = {
11670
10276
  clmmConfig: {
11671
10277
  pools_id: "0xfa145b9de10fe858be81edd1c6cdffcf27be9d016de02a1345eb1009a68ba8b2",
11672
- // clmm and dlmm both use this global_config
11673
10278
  global_config_id: "0x4c4e1402401f72c7d8533d0ed8d5f8949da363c7a3319ccef261ffe153d32f8a",
11674
10279
  global_vault_id: "0xa7e1102f222b6eb81ccc8a126e7feb2353342be9df6f6646a77c4519da29c071",
11675
10280
  admin_cap_id: "0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75"
@@ -11689,11 +10294,7 @@ var SDKConfig = {
11689
10294
  distribution_cfg: "0xaff8d151ac29317201151f97d28c546b3c5923d8cfc5499f40dea61c4022c949",
11690
10295
  magma_token: "0x7161c6c6bb65f852797c8f7f5c4f8d57adaf796e1b840921f9e23fabeadfd54e::magma::MAGMA",
11691
10296
  minter_id: "0x4fa5766cd83b33b215b139fec27ac344040f3bbd84fcbee7b61fc671aadc51fa"
11692
- },
11693
- dlmmConfig: {
11694
- factory: ""
11695
- },
11696
- gaugeConfig: {}
10297
+ }
11697
10298
  };
11698
10299
  var clmmMainnet = {
11699
10300
  fullRpcUrl: (0, import_client2.getFullnodeUrl)("mainnet"),
@@ -11710,11 +10311,6 @@ var clmmMainnet = {
11710
10311
  published_at: "0x4a35d3dfef55ed3631b7158544c6322a23bc434fe4fca1234cb680ce0505f82d",
11711
10312
  config: SDKConfig.clmmConfig
11712
10313
  },
11713
- dlmm_pool: {
11714
- package_id: "",
11715
- published_at: "",
11716
- config: SDKConfig.dlmmConfig
11717
- },
11718
10314
  distribution: {
11719
10315
  package_id: "0xee4a1f231dc45a303389998fe26c4e39278cf68b404b32e4f0b9769129b8267b",
11720
10316
  published_at: "0xee4a1f231dc45a303389998fe26c4e39278cf68b404b32e4f0b9769129b8267b"
@@ -11768,9 +10364,6 @@ var SDKConfig2 = {
11768
10364
  distribution_cfg: "0x94e23846c975e2faf89a61bfc2b10ad64decab9069eb1f9fc39752b010868c74",
11769
10365
  magma_token: "0x45ac2371c33ca0df8dc784d62c8ce5126d42edd8c56820396524dff2ae0619b1::magma_token::MAGMA_TOKEN",
11770
10366
  minter_id: "0x89435d6b2a510ba50ca23303f10e91ec058f138a88f69a43fe03cd22edb214c5"
11771
- },
11772
- dlmmConfig: {
11773
- factory: ""
11774
10367
  }
11775
10368
  };
11776
10369
  var clmmTestnet = {
@@ -11785,11 +10378,6 @@ var clmmTestnet = {
11785
10378
  published_at: "0x23e0b5ab4aa63d0e6fd98fa5e247bcf9b36ad716b479d39e56b2ba9ff631e09d",
11786
10379
  config: SDKConfig2.clmmConfig
11787
10380
  },
11788
- dlmm_pool: {
11789
- package_id: "",
11790
- published_at: "",
11791
- config: SDKConfig2.dlmmConfig
11792
- },
11793
10381
  distribution: {
11794
10382
  package_id: "0x45ac2371c33ca0df8dc784d62c8ce5126d42edd8c56820396524dff2ae0619b1",
11795
10383
  published_at: "0x45ac2371c33ca0df8dc784d62c8ce5126d42edd8c56820396524dff2ae0619b1"
@@ -11838,7 +10426,6 @@ var src_default = MagmaClmmSDK;
11838
10426
  0 && (module.exports = {
11839
10427
  AMM_SWAP_MODULE,
11840
10428
  AmountSpecified,
11841
- BinMath,
11842
10429
  CLOCK_ADDRESS,
11843
10430
  CachedContent,
11844
10431
  ClmmExpectSwapModule,
@@ -11866,7 +10453,6 @@ var src_default = MagmaClmmSDK;
11866
10453
  DeepbookCustodianV2Moudle,
11867
10454
  DeepbookEndpointsV2Moudle,
11868
10455
  DeepbookUtils,
11869
- DlmmScript,
11870
10456
  FEE_RATE_DENOMINATOR,
11871
10457
  GAS_SYMBOL,
11872
10458
  GAS_TYPE_ARG,
@@ -11894,7 +10480,6 @@ var src_default = MagmaClmmSDK;
11894
10480
  SUI_SYSTEM_STATE_OBJECT_ID,
11895
10481
  SplitSwap,
11896
10482
  SplitUnit,
11897
- StrategyType,
11898
10483
  SwapDirection,
11899
10484
  SwapModule,
11900
10485
  SwapUtils,
@@ -11916,10 +10501,6 @@ var src_default = MagmaClmmSDK;
11916
10501
  adjustForSlippage,
11917
10502
  asIntN,
11918
10503
  asUintN,
11919
- autoFillXByStrategy,
11920
- autoFillXByWeight,
11921
- autoFillYByStrategy,
11922
- autoFillYByWeight,
11923
10504
  bufferToHex,
11924
10505
  buildClmmPositionName,
11925
10506
  buildNFT,
@@ -11957,14 +10538,12 @@ var src_default = MagmaClmmSDK;
11957
10538
  getAmountUnfixedDelta,
11958
10539
  getCoinAFromLiquidity,
11959
10540
  getCoinBFromLiquidity,
11960
- getCoinXYForLiquidity,
11961
10541
  getDefaultSuiInputType,
11962
10542
  getDeltaA,
11963
10543
  getDeltaB,
11964
10544
  getDeltaDownFromOutput,
11965
10545
  getDeltaUpFromInput,
11966
10546
  getFutureTime,
11967
- getLiquidityAndCoinYByCoinX,
11968
10547
  getLiquidityFromCoinA,
11969
10548
  getLiquidityFromCoinB,
11970
10549
  getLowerSqrtPriceFromCoinA,
@@ -11988,7 +10567,6 @@ var src_default = MagmaClmmSDK;
11988
10567
  getObjectType,
11989
10568
  getObjectVersion,
11990
10569
  getPackagerConfigs,
11991
- getPriceOfBinByBinId,
11992
10570
  getRewardInTickRange,
11993
10571
  getSuiObjectData,
11994
10572
  getTickDataFromUrlData,
@@ -12012,15 +10590,10 @@ var src_default = MagmaClmmSDK;
12012
10590
  shortAddress,
12013
10591
  shortString,
12014
10592
  tickScore,
12015
- toAmountAskSide,
12016
- toAmountBidSide,
12017
- toAmountBothSide,
12018
- toAmountsBothSideByStrategy,
12019
10593
  toBuffer,
12020
10594
  toCoinAmount,
12021
10595
  toDecimalsAmount,
12022
10596
  transClmmpoolDataWithoutTicks,
12023
- utf8to16,
12024
- withLiquiditySlippage
10597
+ utf8to16
12025
10598
  });
12026
10599
  //# sourceMappingURL=index.js.map