@magmaprotocol/magma-clmm-sdk 0.5.77 → 0.5.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -37,7 +37,7 @@ var CachedContent = class {
37
37
  };
38
38
 
39
39
  // src/utils/common.ts
40
- import BN11 from "bn.js";
40
+ import BN12 from "bn.js";
41
41
  import { fromB64, fromHEX } from "@mysten/bcs";
42
42
  import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
43
43
  import { Secp256k1Keypair } from "@mysten/sui/keypairs/secp256k1";
@@ -303,6 +303,7 @@ var Voter = "voter";
303
303
  var RewardDistributor = "reward_distributor";
304
304
  var Gauge = "gauge";
305
305
  var Minter = "minter";
306
+ var DlmmScript = "dlmm_script";
306
307
  var CoinInfoAddress = "0x1::coin::CoinInfo";
307
308
  var CoinStoreAddress = "0x1::coin::CoinStore";
308
309
  var DeepbookCustodianV2Moudle = "custodian_v2";
@@ -1591,8 +1592,476 @@ function collectFeesQuote(param) {
1591
1592
  return updateFees(param.position, fee_growth_inside_a, fee_growth_inside_b);
1592
1593
  }
1593
1594
 
1594
- // src/math/percentage.ts
1595
+ // src/math/dlmmWeightToAmounts.ts
1595
1596
  import BN9 from "bn.js";
1597
+ import Decimal3 from "decimal.js";
1598
+ import { get_price_x128_from_real_id } from "@magmaprotocol/calc_dlmm";
1599
+ function getPriceOfBinByBinId(binId, binStep) {
1600
+ const twoDec = new Decimal3(2);
1601
+ const price = new Decimal3(get_price_x128_from_real_id(binId, binStep));
1602
+ return price.div(twoDec.pow(128));
1603
+ }
1604
+ function autoFillYByWeight(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, distributions) {
1605
+ const activeBins = distributions.filter((element) => {
1606
+ return element.binId === activeId;
1607
+ });
1608
+ if (activeBins.length === 1) {
1609
+ const p0 = getPriceOfBinByBinId(activeId, binStep);
1610
+ let wx0 = new Decimal3(0);
1611
+ let wy0 = new Decimal3(0);
1612
+ const activeBin = activeBins[0];
1613
+ if (amountXInActiveBin.isZero() && amountYInActiveBin.isZero()) {
1614
+ wx0 = new Decimal3(activeBin.weight).div(p0.mul(new Decimal3(2)));
1615
+ wy0 = new Decimal3(activeBin.weight).div(new Decimal3(2));
1616
+ } else {
1617
+ const amountXInActiveBinDec = new Decimal3(amountXInActiveBin.toString());
1618
+ const amountYInActiveBinDec = new Decimal3(amountYInActiveBin.toString());
1619
+ if (!amountXInActiveBin.isZero()) {
1620
+ wx0 = new Decimal3(activeBin.weight).div(p0.add(amountYInActiveBinDec.div(amountXInActiveBinDec)));
1621
+ }
1622
+ if (!amountYInActiveBin.isZero()) {
1623
+ wy0 = new Decimal3(activeBin.weight).div(new Decimal3(1).add(p0.mul(amountXInActiveBinDec).div(amountYInActiveBinDec)));
1624
+ }
1625
+ }
1626
+ let totalWeightX2 = wx0;
1627
+ let totalWeightY2 = wy0;
1628
+ distributions.forEach((element) => {
1629
+ if (element.binId < activeId) {
1630
+ totalWeightY2 = totalWeightY2.add(new Decimal3(element.weight));
1631
+ }
1632
+ if (element.binId > activeId) {
1633
+ const price = getPriceOfBinByBinId(element.binId, binStep);
1634
+ const weighPerPrice = new Decimal3(element.weight).div(price);
1635
+ totalWeightX2 = totalWeightX2.add(weighPerPrice);
1636
+ }
1637
+ });
1638
+ const kx2 = totalWeightX2.isZero() ? new Decimal3(1) : new Decimal3(amountX.toString()).div(totalWeightX2);
1639
+ const amountY2 = kx2.mul(totalWeightY2);
1640
+ return new BN9(amountY2.floor().toString());
1641
+ }
1642
+ let totalWeightX = new Decimal3(0);
1643
+ let totalWeightY = new Decimal3(0);
1644
+ distributions.forEach((element) => {
1645
+ if (element.binId < activeId) {
1646
+ totalWeightY = totalWeightY.add(new Decimal3(element.weight));
1647
+ } else {
1648
+ const price = getPriceOfBinByBinId(element.binId, binStep);
1649
+ const weighPerPrice = new Decimal3(element.weight).div(price);
1650
+ totalWeightX = totalWeightX.add(weighPerPrice);
1651
+ }
1652
+ });
1653
+ const kx = totalWeightX.isZero() ? new Decimal3(1) : new Decimal3(amountX.toString()).div(totalWeightX);
1654
+ const amountY = kx.mul(totalWeightY);
1655
+ return new BN9(amountY.floor().toString());
1656
+ }
1657
+ function autoFillXByWeight(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, distributions) {
1658
+ const activeBins = distributions.filter((element) => {
1659
+ return element.binId === activeId;
1660
+ });
1661
+ if (activeBins.length === 1) {
1662
+ const p0 = getPriceOfBinByBinId(activeId, binStep);
1663
+ let wx0 = new Decimal3(0);
1664
+ let wy0 = new Decimal3(0);
1665
+ const activeBin = activeBins[0];
1666
+ if (amountXInActiveBin.isZero() && amountYInActiveBin.isZero()) {
1667
+ wx0 = new Decimal3(activeBin.weight).div(p0.mul(new Decimal3(2)));
1668
+ wy0 = new Decimal3(activeBin.weight).div(new Decimal3(2));
1669
+ } else {
1670
+ const amountXInActiveBinDec = new Decimal3(amountXInActiveBin.toString());
1671
+ const amountYInActiveBinDec = new Decimal3(amountYInActiveBin.toString());
1672
+ if (!amountXInActiveBin.isZero()) {
1673
+ wx0 = new Decimal3(activeBin.weight).div(p0.add(amountYInActiveBinDec.div(amountXInActiveBinDec)));
1674
+ }
1675
+ if (!amountYInActiveBin.isZero()) {
1676
+ wy0 = new Decimal3(activeBin.weight).div(new Decimal3(1).add(p0.mul(amountXInActiveBinDec).div(amountYInActiveBinDec)));
1677
+ }
1678
+ }
1679
+ let totalWeightX2 = wx0;
1680
+ let totalWeightY2 = wy0;
1681
+ distributions.forEach((element) => {
1682
+ if (element.binId < activeId) {
1683
+ totalWeightY2 = totalWeightY2.add(new Decimal3(element.weight));
1684
+ }
1685
+ if (element.binId > activeId) {
1686
+ const price = getPriceOfBinByBinId(element.binId, binStep);
1687
+ const weighPerPrice = new Decimal3(element.weight).div(price);
1688
+ totalWeightX2 = totalWeightX2.add(weighPerPrice);
1689
+ }
1690
+ });
1691
+ const ky2 = totalWeightY2.isZero() ? new Decimal3(1) : new Decimal3(amountY.toString()).div(totalWeightY2);
1692
+ const amountX2 = ky2.mul(totalWeightX2);
1693
+ return new BN9(amountX2.floor().toString());
1694
+ }
1695
+ let totalWeightX = new Decimal3(0);
1696
+ let totalWeightY = new Decimal3(0);
1697
+ distributions.forEach((element) => {
1698
+ if (element.binId < activeId) {
1699
+ totalWeightY = totalWeightY.add(new Decimal3(element.weight));
1700
+ } else {
1701
+ const price = getPriceOfBinByBinId(element.binId, binStep);
1702
+ const weighPerPrice = new Decimal3(element.weight).div(price);
1703
+ totalWeightX = totalWeightX.add(weighPerPrice);
1704
+ }
1705
+ });
1706
+ const ky = totalWeightY.isZero() ? new Decimal3(1) : new Decimal3(amountY.toString()).div(totalWeightY);
1707
+ const amountX = ky.mul(totalWeightX);
1708
+ return new BN9(amountX.floor().toString());
1709
+ }
1710
+ function toAmountBidSide(activeId, totalAmount, distributions) {
1711
+ const totalWeight = distributions.reduce((sum, el) => {
1712
+ return el.binId > activeId ? sum : sum.add(el.weight);
1713
+ }, new Decimal3(0));
1714
+ if (totalWeight.cmp(new Decimal3(0)) !== 1) {
1715
+ throw Error("Invalid parameteres");
1716
+ }
1717
+ return distributions.map((bin) => {
1718
+ if (bin.binId > activeId) {
1719
+ return {
1720
+ binId: bin.binId,
1721
+ amount: new BN9(0)
1722
+ };
1723
+ }
1724
+ return {
1725
+ binId: bin.binId,
1726
+ amount: new BN9(new Decimal3(totalAmount.toString()).mul(new Decimal3(bin.weight).div(totalWeight)).floor().toString())
1727
+ };
1728
+ });
1729
+ }
1730
+ function toAmountAskSide(activeId, binStep, totalAmount, distributions) {
1731
+ const totalWeight = distributions.reduce((sum, el) => {
1732
+ if (el.binId < activeId) {
1733
+ return sum;
1734
+ }
1735
+ const price = getPriceOfBinByBinId(el.binId, binStep);
1736
+ const weightPerPrice = new Decimal3(el.weight).div(price);
1737
+ return sum.add(weightPerPrice);
1738
+ }, new Decimal3(0));
1739
+ if (totalWeight.cmp(new Decimal3(0)) !== 1) {
1740
+ throw Error("Invalid parameteres");
1741
+ }
1742
+ return distributions.map((bin) => {
1743
+ if (bin.binId < activeId) {
1744
+ return {
1745
+ binId: bin.binId,
1746
+ amount: new BN9(0)
1747
+ };
1748
+ }
1749
+ const price = getPriceOfBinByBinId(bin.binId, binStep);
1750
+ const weightPerPrice = new Decimal3(bin.weight).div(price);
1751
+ return {
1752
+ binId: bin.binId,
1753
+ amount: new BN9(new Decimal3(totalAmount.toString()).mul(weightPerPrice).div(totalWeight).floor().toString())
1754
+ };
1755
+ });
1756
+ }
1757
+ function toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, distributions) {
1758
+ if (activeId > distributions[distributions.length - 1].binId) {
1759
+ const amounts = toAmountBidSide(activeId, amountY, distributions);
1760
+ return amounts.map((bin) => {
1761
+ return {
1762
+ binId: bin.binId,
1763
+ amountX: new BN9(0),
1764
+ amountY: bin.amount
1765
+ };
1766
+ });
1767
+ }
1768
+ if (activeId < distributions[0].binId) {
1769
+ const amounts = toAmountAskSide(activeId, binStep, amountX, distributions);
1770
+ return amounts.map((bin) => {
1771
+ return {
1772
+ binId: bin.binId,
1773
+ amountX: bin.amount,
1774
+ amountY: new BN9(0)
1775
+ };
1776
+ });
1777
+ }
1778
+ const activeBins = distributions.filter((element) => {
1779
+ return element.binId === activeId;
1780
+ });
1781
+ if (activeBins.length === 1) {
1782
+ const p0 = getPriceOfBinByBinId(activeId, binStep);
1783
+ let wx0 = new Decimal3(0);
1784
+ let wy0 = new Decimal3(0);
1785
+ const activeBin = activeBins[0];
1786
+ if (amountXInActiveBin.isZero() && amountYInActiveBin.isZero()) {
1787
+ wx0 = new Decimal3(activeBin.weight).div(p0.mul(new Decimal3(2)));
1788
+ wy0 = new Decimal3(activeBin.weight).div(new Decimal3(2));
1789
+ } else {
1790
+ const amountXInActiveBinDec = new Decimal3(amountXInActiveBin.toString());
1791
+ const amountYInActiveBinDec = new Decimal3(amountYInActiveBin.toString());
1792
+ if (!amountXInActiveBin.isZero()) {
1793
+ wx0 = new Decimal3(activeBin.weight).div(p0.add(amountYInActiveBinDec.div(amountXInActiveBinDec)));
1794
+ }
1795
+ if (!amountYInActiveBin.isZero()) {
1796
+ wy0 = new Decimal3(activeBin.weight).div(new Decimal3(1).add(p0.mul(amountXInActiveBinDec).div(amountYInActiveBinDec)));
1797
+ }
1798
+ }
1799
+ let totalWeightX2 = wx0;
1800
+ let totalWeightY2 = wy0;
1801
+ distributions.forEach((element) => {
1802
+ if (element.binId < activeId) {
1803
+ totalWeightY2 = totalWeightY2.add(new Decimal3(element.weight));
1804
+ }
1805
+ if (element.binId > activeId) {
1806
+ const price = getPriceOfBinByBinId(element.binId, binStep);
1807
+ const weighPerPrice = new Decimal3(element.weight).div(price);
1808
+ totalWeightX2 = totalWeightX2.add(weighPerPrice);
1809
+ }
1810
+ });
1811
+ const kx2 = new Decimal3(amountX.toString()).div(totalWeightX2);
1812
+ const ky2 = new Decimal3(amountY.toString()).div(totalWeightY2);
1813
+ const k2 = kx2.lessThan(ky2) ? kx2 : ky2;
1814
+ return distributions.map((bin) => {
1815
+ if (bin.binId < activeId) {
1816
+ const amount = k2.mul(new Decimal3(bin.weight));
1817
+ return {
1818
+ binId: bin.binId,
1819
+ amountX: new BN9(0),
1820
+ amountY: new BN9(amount.floor().toString())
1821
+ };
1822
+ }
1823
+ if (bin.binId > activeId) {
1824
+ const price = getPriceOfBinByBinId(bin.binId, binStep);
1825
+ const weighPerPrice = new Decimal3(bin.weight).div(price);
1826
+ const amount = k2.mul(weighPerPrice);
1827
+ return {
1828
+ binId: bin.binId,
1829
+ amountX: new BN9(amount.floor().toString()),
1830
+ amountY: new BN9(0)
1831
+ };
1832
+ }
1833
+ const amountXActiveBin = k2.mul(wx0);
1834
+ const amountYActiveBin = k2.mul(wy0);
1835
+ return {
1836
+ binId: bin.binId,
1837
+ amountX: new BN9(amountXActiveBin.floor().toString()),
1838
+ amountY: new BN9(amountYActiveBin.floor().toString())
1839
+ };
1840
+ });
1841
+ }
1842
+ let totalWeightX = new Decimal3(0);
1843
+ let totalWeightY = new Decimal3(0);
1844
+ distributions.forEach((element) => {
1845
+ if (element.binId < activeId) {
1846
+ totalWeightY = totalWeightY.add(new Decimal3(element.weight));
1847
+ } else {
1848
+ const price = getPriceOfBinByBinId(element.binId, binStep);
1849
+ const weighPerPrice = new Decimal3(element.weight).div(price);
1850
+ totalWeightX = totalWeightX.add(weighPerPrice);
1851
+ }
1852
+ });
1853
+ const kx = new Decimal3(amountX.toString()).div(totalWeightX);
1854
+ const ky = new Decimal3(amountY.toString()).div(totalWeightY);
1855
+ const k = kx.lessThan(ky) ? kx : ky;
1856
+ return distributions.map((bin) => {
1857
+ if (bin.binId < activeId) {
1858
+ const amount2 = k.mul(new Decimal3(bin.weight));
1859
+ return {
1860
+ binId: bin.binId,
1861
+ amountX: new BN9(0),
1862
+ amountY: new BN9(amount2.floor().toString())
1863
+ };
1864
+ }
1865
+ const price = getPriceOfBinByBinId(bin.binId, binStep);
1866
+ const weighPerPrice = new Decimal3(bin.weight).div(price);
1867
+ const amount = k.mul(weighPerPrice);
1868
+ return {
1869
+ binId: bin.binId,
1870
+ amountX: new BN9(amount.floor().toString()),
1871
+ amountY: new BN9(0)
1872
+ };
1873
+ });
1874
+ }
1875
+
1876
+ // src/math/dlmmStrategy.ts
1877
+ var StrategyType = /* @__PURE__ */ ((StrategyType2) => {
1878
+ StrategyType2[StrategyType2["Spot"] = 1] = "Spot";
1879
+ StrategyType2[StrategyType2["Curve"] = 2] = "Curve";
1880
+ StrategyType2[StrategyType2["BidAsk"] = 3] = "BidAsk";
1881
+ return StrategyType2;
1882
+ })(StrategyType || {});
1883
+ function toWeightSpotBalanced(minBinId, maxBinId) {
1884
+ const distributions = [];
1885
+ for (let i = minBinId; i <= maxBinId; i++) {
1886
+ distributions.push({
1887
+ binId: i,
1888
+ weight: 1
1889
+ });
1890
+ }
1891
+ return distributions;
1892
+ }
1893
+ var DEFAULT_MAX_WEIGHT = 2e3;
1894
+ var DEFAULT_MIN_WEIGHT = 200;
1895
+ function toWeightCurve(minBinId, maxBinId, activeId) {
1896
+ if (activeId < minBinId || activeId > maxBinId) {
1897
+ throw new ClmmpoolsError("Invalid strategy params", "InvalidParams" /* InvalidParams */);
1898
+ }
1899
+ const maxWeight = DEFAULT_MAX_WEIGHT;
1900
+ const minWeight = DEFAULT_MIN_WEIGHT;
1901
+ const diffWeight = maxWeight - minWeight;
1902
+ const diffMinWeight = activeId > minBinId ? Math.floor(diffWeight / (activeId - minBinId)) : 0;
1903
+ const diffMaxWeight = maxBinId > activeId ? Math.floor(diffWeight / (maxBinId - activeId)) : 0;
1904
+ const distributions = [];
1905
+ for (let i = minBinId; i <= maxBinId; i++) {
1906
+ if (i < activeId) {
1907
+ distributions.push({
1908
+ binId: i,
1909
+ weight: maxWeight - (activeId - i) * diffMinWeight
1910
+ });
1911
+ } else if (i > activeId) {
1912
+ distributions.push({
1913
+ binId: i,
1914
+ weight: maxWeight - (i - activeId) * diffMaxWeight
1915
+ });
1916
+ } else {
1917
+ distributions.push({
1918
+ binId: i,
1919
+ weight: maxWeight
1920
+ });
1921
+ }
1922
+ }
1923
+ return distributions;
1924
+ }
1925
+ function toWeightBidAsk(minBinId, maxBinId, activeId) {
1926
+ if (activeId < minBinId || activeId > maxBinId) {
1927
+ throw new ClmmpoolsError("Invalid strategy params", "InvalidParams" /* InvalidParams */);
1928
+ }
1929
+ const maxWeight = DEFAULT_MAX_WEIGHT;
1930
+ const minWeight = DEFAULT_MIN_WEIGHT;
1931
+ const diffWeight = maxWeight - minWeight;
1932
+ const diffMinWeight = activeId > minBinId ? Math.floor(diffWeight / (activeId - minBinId)) : 0;
1933
+ const diffMaxWeight = maxBinId > activeId ? Math.floor(diffWeight / (maxBinId - activeId)) : 0;
1934
+ const distributions = [];
1935
+ for (let i = minBinId; i <= maxBinId; i++) {
1936
+ if (i < activeId) {
1937
+ distributions.push({
1938
+ binId: i,
1939
+ weight: minWeight + (activeId - i) * diffMinWeight
1940
+ });
1941
+ } else if (i > activeId) {
1942
+ distributions.push({
1943
+ binId: i,
1944
+ weight: minWeight + (i - activeId) * diffMaxWeight
1945
+ });
1946
+ } else {
1947
+ distributions.push({
1948
+ binId: i,
1949
+ weight: minWeight
1950
+ });
1951
+ }
1952
+ }
1953
+ return distributions;
1954
+ }
1955
+ function autoFillYByStrategy(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, minBinId, maxBinId, strategyType) {
1956
+ switch (strategyType) {
1957
+ case 1 /* Spot */: {
1958
+ const weights = toWeightSpotBalanced(minBinId, maxBinId);
1959
+ return autoFillYByWeight(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, weights);
1960
+ }
1961
+ case 2 /* Curve */: {
1962
+ const weights = toWeightCurve(minBinId, maxBinId, activeId);
1963
+ return autoFillYByWeight(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, weights);
1964
+ }
1965
+ case 3 /* BidAsk */: {
1966
+ const weights = toWeightBidAsk(minBinId, maxBinId, activeId);
1967
+ return autoFillYByWeight(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, weights);
1968
+ }
1969
+ default:
1970
+ throw new Error(`Unsupported strategy type: ${strategyType}`);
1971
+ }
1972
+ }
1973
+ function autoFillXByStrategy(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, minBinId, maxBinId, strategyType) {
1974
+ switch (strategyType) {
1975
+ case 1 /* Spot */: {
1976
+ const weights = toWeightSpotBalanced(minBinId, maxBinId);
1977
+ return autoFillXByWeight(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, weights);
1978
+ }
1979
+ case 2 /* Curve */: {
1980
+ const weights = toWeightCurve(minBinId, maxBinId, activeId);
1981
+ return autoFillXByWeight(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, weights);
1982
+ }
1983
+ case 3 /* BidAsk */: {
1984
+ const weights = toWeightBidAsk(minBinId, maxBinId, activeId);
1985
+ return autoFillXByWeight(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, weights);
1986
+ }
1987
+ default:
1988
+ throw new Error(`Unsupported strategy type: ${strategyType}`);
1989
+ }
1990
+ }
1991
+ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amountX, amountY, amountXInActiveBin, amountYInActiveBin, strategyType) {
1992
+ const isSingleSideX = amountY.isZero();
1993
+ switch (strategyType) {
1994
+ case 1 /* Spot */: {
1995
+ const weights = toWeightSpotBalanced(minBinId, maxBinId);
1996
+ return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights);
1997
+ }
1998
+ case 2 /* Curve */: {
1999
+ const weights = toWeightCurve(minBinId, maxBinId, activeId);
2000
+ return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2001
+ }
2002
+ case 3 /* BidAsk */: {
2003
+ const weights = toWeightBidAsk(minBinId, maxBinId, activeId);
2004
+ return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2005
+ }
2006
+ default:
2007
+ throw new Error(`Unsupported strategy type: ${strategyType}`);
2008
+ }
2009
+ }
2010
+
2011
+ // src/math/LiquidityHelper.ts
2012
+ import Decimal5 from "decimal.js";
2013
+
2014
+ // src/utils/numbers.ts
2015
+ import Decimal4 from "decimal.js";
2016
+ function d(value) {
2017
+ if (Decimal4.isDecimal(value)) {
2018
+ return value;
2019
+ }
2020
+ return new Decimal4(value === void 0 ? 0 : value);
2021
+ }
2022
+ function decimalsMultiplier(decimals) {
2023
+ return d(10).pow(d(decimals).abs());
2024
+ }
2025
+
2026
+ // src/math/LiquidityHelper.ts
2027
+ function withLiquiditySlippage(value, slippage, mode) {
2028
+ return d(value)[mode](d(value).mul(slippage)).toDP(0);
2029
+ }
2030
+ function getLiquidityAndCoinYByCoinX(coinInVal, reserveInSize, reserveOutSize, lpSupply) {
2031
+ if (coinInVal.lessThanOrEqualTo(0)) {
2032
+ throw new ClmmpoolsError("coinInVal is less than zero", "InvalidCoinAmount" /* InvalidCoinAmount */);
2033
+ }
2034
+ if (reserveInSize.lessThanOrEqualTo(0) || reserveOutSize.lessThanOrEqualTo(0)) {
2035
+ return -1;
2036
+ }
2037
+ const coinYAmount = coinInVal.mul(reserveOutSize).div(reserveInSize);
2038
+ const sqrtSupply = lpSupply;
2039
+ const lpX = coinInVal.div(reserveInSize).mul(sqrtSupply);
2040
+ const lpY = coinYAmount.div(reserveOutSize).mul(sqrtSupply);
2041
+ const lpAmount = Decimal5.min(lpX, lpY);
2042
+ return {
2043
+ coinYAmount,
2044
+ lpAmount
2045
+ };
2046
+ }
2047
+ function getCoinXYForLiquidity(liquidity, reserveInSize, reserveOutSize, lpSuply) {
2048
+ if (liquidity.lessThanOrEqualTo(0)) {
2049
+ throw new ClmmpoolsError("liquidity can't be equal or less than zero", "InvalidLiquidityAmount" /* InvalidLiquidityAmount */);
2050
+ }
2051
+ if (reserveInSize.lessThanOrEqualTo(0) || reserveOutSize.lessThanOrEqualTo(0)) {
2052
+ throw new ClmmpoolsError("reserveInSize or reserveOutSize can not be equal or less than zero", "InvalidReserveAmount" /* InvalidReserveAmount */);
2053
+ }
2054
+ const sqrtSupply = lpSuply;
2055
+ const coinXAmount = liquidity.div(sqrtSupply).mul(reserveInSize);
2056
+ const coinYAmount = liquidity.div(sqrtSupply).mul(reserveOutSize);
2057
+ return {
2058
+ coinXAmount,
2059
+ coinYAmount
2060
+ };
2061
+ }
2062
+
2063
+ // src/math/percentage.ts
2064
+ import BN10 from "bn.js";
1596
2065
  var Percentage = class {
1597
2066
  numerator;
1598
2067
  denominator;
@@ -1620,8 +2089,8 @@ var Percentage = class {
1620
2089
  * @returns
1621
2090
  */
1622
2091
  static fromFraction(numerator, denominator) {
1623
- const num = typeof numerator === "number" ? new BN9(numerator.toString()) : numerator;
1624
- const denom = typeof denominator === "number" ? new BN9(denominator.toString()) : denominator;
2092
+ const num = typeof numerator === "number" ? new BN10(numerator.toString()) : numerator;
2093
+ const denom = typeof denominator === "number" ? new BN10(denominator.toString()) : denominator;
1625
2094
  return new Percentage(num, denom);
1626
2095
  }
1627
2096
  };
@@ -1721,7 +2190,7 @@ function adjustForCoinSlippage(tokenAmount, slippage, adjustUp) {
1721
2190
  }
1722
2191
 
1723
2192
  // src/math/SplitSwap.ts
1724
- import BN10 from "bn.js";
2193
+ import BN11 from "bn.js";
1725
2194
  var SplitUnit = /* @__PURE__ */ ((SplitUnit2) => {
1726
2195
  SplitUnit2[SplitUnit2["FIVE"] = 5] = "FIVE";
1727
2196
  SplitUnit2[SplitUnit2["TEN"] = 10] = "TEN";
@@ -1779,7 +2248,7 @@ function updateSplitSwapResult(maxIndex, currentIndex, splitSwapResult, stepResu
1779
2248
  return splitSwapResult;
1780
2249
  }
1781
2250
  function computeSplitSwap(a2b, byAmountIn, amounts, poolData, swapTicks) {
1782
- let currentLiquidity = new BN10(poolData.liquidity);
2251
+ let currentLiquidity = new BN11(poolData.liquidity);
1783
2252
  let { currentSqrtPrice } = poolData;
1784
2253
  let splitSwapResult = {
1785
2254
  amountInArray: [],
@@ -1842,7 +2311,7 @@ function computeSplitSwap(a2b, byAmountIn, amounts, poolData, swapTicks) {
1842
2311
  targetSqrtPrice,
1843
2312
  currentLiquidity,
1844
2313
  remainerAmount,
1845
- new BN10(poolData.feeRate),
2314
+ new BN11(poolData.feeRate),
1846
2315
  byAmountIn
1847
2316
  );
1848
2317
  tempStepResult = stepResult;
@@ -1854,7 +2323,7 @@ function computeSplitSwap(a2b, byAmountIn, amounts, poolData, swapTicks) {
1854
2323
  splitSwapResult.amountOutArray[i] = splitSwapResult.amountOutArray[i].add(stepResult.amountOut);
1855
2324
  splitSwapResult.feeAmountArray[i] = splitSwapResult.feeAmountArray[i].add(stepResult.feeAmount);
1856
2325
  if (stepResult.nextSqrtPrice.eq(tick.sqrtPrice)) {
1857
- signedLiquidityChange = a2b ? tick.liquidityNet.mul(new BN10(-1)) : tick.liquidityNet;
2326
+ signedLiquidityChange = a2b ? tick.liquidityNet.mul(new BN11(-1)) : tick.liquidityNet;
1858
2327
  currentLiquidity = signedLiquidityChange.gt(ZERO) ? currentLiquidity.add(signedLiquidityChange) : currentLiquidity.sub(signedLiquidityChange.abs());
1859
2328
  currentSqrtPrice = tick.sqrtPrice;
1860
2329
  } else {
@@ -1879,7 +2348,7 @@ function computeSplitSwap(a2b, byAmountIn, amounts, poolData, swapTicks) {
1879
2348
  break;
1880
2349
  }
1881
2350
  if (tempStepResult.nextSqrtPrice.eq(tick.sqrtPrice)) {
1882
- signedLiquidityChange = a2b ? tick.liquidityNet.mul(new BN10(-1)) : tick.liquidityNet;
2351
+ signedLiquidityChange = a2b ? tick.liquidityNet.mul(new BN11(-1)) : tick.liquidityNet;
1883
2352
  currentLiquidity = signedLiquidityChange.gt(ZERO) ? currentLiquidity.add(signedLiquidityChange) : currentLiquidity.sub(signedLiquidityChange.abs());
1884
2353
  currentSqrtPrice = tick.sqrtPrice;
1885
2354
  } else {
@@ -1934,17 +2403,22 @@ var SplitSwap = class {
1934
2403
  }
1935
2404
  };
1936
2405
 
1937
- // src/utils/numbers.ts
1938
- import Decimal3 from "decimal.js";
1939
- function d(value) {
1940
- if (Decimal3.isDecimal(value)) {
1941
- return value;
2406
+ // src/math/bin.ts
2407
+ import Decimal6 from "decimal.js";
2408
+ import { get_price_x128_from_real_id as get_price_x128_from_real_id2, get_real_id_from_price_x128 } from "@magmaprotocol/calc_dlmm";
2409
+ var BinMath = class {
2410
+ static getPriceOfBinByBinId(binId, binStep, decimalsA, decimalsB) {
2411
+ const twoDec = new Decimal6(2);
2412
+ const price = new Decimal6(get_price_x128_from_real_id2(binId, binStep));
2413
+ return price.div(twoDec.pow(128)).mul(Decimal6.pow(10, decimalsA - decimalsB));
2414
+ }
2415
+ static getBinIdFromPrice(price, binStep, decimalsA, decimalsB) {
2416
+ const twoDec = new Decimal6(2);
2417
+ const tenDec = new Decimal6(10);
2418
+ const realid = get_real_id_from_price_x128(new Decimal6(price).mul(tenDec.pow(decimalsB - decimalsA)).mul(twoDec.pow(128)).toDecimalPlaces(0).toString(), binStep);
2419
+ return realid;
1942
2420
  }
1943
- return new Decimal3(value === void 0 ? 0 : value);
1944
- }
1945
- function decimalsMultiplier(decimals) {
1946
- return d(10).pow(d(decimals).abs());
1947
- }
2421
+ };
1948
2422
 
1949
2423
  // src/utils/objects.ts
1950
2424
  function getSuiObjectData(resp) {
@@ -2099,7 +2573,7 @@ function buildPool(objects) {
2099
2573
  const rewarders = [];
2100
2574
  fields.rewarder_manager.fields.rewarders.forEach((item) => {
2101
2575
  const { emissions_per_second } = item.fields;
2102
- const emissionSeconds = MathUtil.fromX64(new BN11(emissions_per_second));
2576
+ const emissionSeconds = MathUtil.fromX64(new BN12(emissions_per_second));
2103
2577
  const emissionsEveryDay = Math.floor(emissionSeconds.toNumber() * 60 * 60 * 24);
2104
2578
  rewarders.push({
2105
2579
  emissions_per_second,
@@ -2291,11 +2765,11 @@ function buildTickData(objects) {
2291
2765
  const possition = {
2292
2766
  objectId: getObjectId(objects),
2293
2767
  index: asIntN(BigInt(valueItem.index.fields.bits)),
2294
- sqrtPrice: new BN11(valueItem.sqrt_price),
2295
- liquidityNet: new BN11(valueItem.liquidity_net.fields.bits),
2296
- liquidityGross: new BN11(valueItem.liquidity_gross),
2297
- feeGrowthOutsideA: new BN11(valueItem.fee_growth_outside_a),
2298
- feeGrowthOutsideB: new BN11(valueItem.fee_growth_outside_b),
2768
+ sqrtPrice: new BN12(valueItem.sqrt_price),
2769
+ liquidityNet: new BN12(valueItem.liquidity_net.fields.bits),
2770
+ liquidityGross: new BN12(valueItem.liquidity_gross),
2771
+ feeGrowthOutsideA: new BN12(valueItem.fee_growth_outside_a),
2772
+ feeGrowthOutsideB: new BN12(valueItem.fee_growth_outside_b),
2299
2773
  rewardersGrowthOutside: valueItem.rewards_growth_outside
2300
2774
  };
2301
2775
  return possition;
@@ -2305,11 +2779,11 @@ function buildTickDataByEvent(fields) {
2305
2779
  throw new ClmmpoolsError(`Invalid tick fields.`, "InvalidTickFields" /* InvalidTickFields */);
2306
2780
  }
2307
2781
  const index = asIntN(BigInt(fields.index.bits));
2308
- const sqrtPrice = new BN11(fields.sqrt_price);
2309
- const liquidityNet = new BN11(fields.liquidity_net.bits);
2310
- const liquidityGross = new BN11(fields.liquidity_gross);
2311
- const feeGrowthOutsideA = new BN11(fields.fee_growth_outside_a);
2312
- const feeGrowthOutsideB = new BN11(fields.fee_growth_outside_b);
2782
+ const sqrtPrice = new BN12(fields.sqrt_price);
2783
+ const liquidityNet = new BN12(fields.liquidity_net.bits);
2784
+ const liquidityGross = new BN12(fields.liquidity_gross);
2785
+ const feeGrowthOutsideA = new BN12(fields.fee_growth_outside_a);
2786
+ const feeGrowthOutsideB = new BN12(fields.fee_growth_outside_b);
2313
2787
  const rewardersGrowthOutside = fields.rewards_growth_outside || [];
2314
2788
  const tick = {
2315
2789
  objectId: "",
@@ -2328,7 +2802,7 @@ function buildClmmPositionName(pool_index, position_index) {
2328
2802
  }
2329
2803
 
2330
2804
  // src/utils/tick.ts
2331
- import BN12 from "bn.js";
2805
+ import BN13 from "bn.js";
2332
2806
  var TickUtil = class {
2333
2807
  /**
2334
2808
  * Get min tick index.
@@ -2368,22 +2842,22 @@ function getRewardInTickRange(pool, tickLower, tickUpper, tickLowerIndex, tickUp
2368
2842
  let rewarder_growth_below = growthGlobal[i];
2369
2843
  if (tickLower !== null) {
2370
2844
  if (pool.current_tick_index < tickLowerIndex) {
2371
- rewarder_growth_below = growthGlobal[i].sub(new BN12(tickLower.rewardersGrowthOutside[i]));
2845
+ rewarder_growth_below = growthGlobal[i].sub(new BN13(tickLower.rewardersGrowthOutside[i]));
2372
2846
  } else {
2373
2847
  rewarder_growth_below = tickLower.rewardersGrowthOutside[i];
2374
2848
  }
2375
2849
  }
2376
- let rewarder_growth_above = new BN12(0);
2850
+ let rewarder_growth_above = new BN13(0);
2377
2851
  if (tickUpper !== null) {
2378
2852
  if (pool.current_tick_index >= tickUpperIndex) {
2379
- rewarder_growth_above = growthGlobal[i].sub(new BN12(tickUpper.rewardersGrowthOutside[i]));
2853
+ rewarder_growth_above = growthGlobal[i].sub(new BN13(tickUpper.rewardersGrowthOutside[i]));
2380
2854
  } else {
2381
2855
  rewarder_growth_above = tickUpper.rewardersGrowthOutside[i];
2382
2856
  }
2383
2857
  }
2384
2858
  const rewGrowthInside = MathUtil.subUnderflowU128(
2385
- MathUtil.subUnderflowU128(new BN12(growthGlobal[i]), new BN12(rewarder_growth_below)),
2386
- new BN12(rewarder_growth_above)
2859
+ MathUtil.subUnderflowU128(new BN13(growthGlobal[i]), new BN13(rewarder_growth_below)),
2860
+ new BN13(rewarder_growth_above)
2387
2861
  );
2388
2862
  rewarderGrowthInside.push(rewGrowthInside);
2389
2863
  }
@@ -2391,8 +2865,8 @@ function getRewardInTickRange(pool, tickLower, tickUpper, tickLowerIndex, tickUp
2391
2865
  }
2392
2866
 
2393
2867
  // src/utils/transaction-util.ts
2394
- import BN13 from "bn.js";
2395
- import Decimal4 from "decimal.js";
2868
+ import BN14 from "bn.js";
2869
+ import Decimal7 from "decimal.js";
2396
2870
  import { Transaction } from "@mysten/sui/transactions";
2397
2871
  function findAdjustCoin(coinPair) {
2398
2872
  const isAdjustCoinA = CoinAssist.isSuiCoin(coinPair.coinTypeA);
@@ -2400,7 +2874,7 @@ function findAdjustCoin(coinPair) {
2400
2874
  return { isAdjustCoinA, isAdjustCoinB };
2401
2875
  }
2402
2876
  function reverSlippageAmount(slippageAmount, slippage) {
2403
- return Decimal4.ceil(d(slippageAmount).div(1 + slippage)).toString();
2877
+ return Decimal7.ceil(d(slippageAmount).div(1 + slippage)).toString();
2404
2878
  }
2405
2879
  async function printTransaction(tx, isPrint = true) {
2406
2880
  console.log(`inputs`, tx.blockData.inputs);
@@ -2700,7 +3174,7 @@ var _TransactionUtil = class {
2700
3174
  const liquidityInput = ClmmPoolUtil.estLiquidityAndcoinAmountFromOneAmounts(
2701
3175
  Number(params.tick_lower),
2702
3176
  Number(params.tick_upper),
2703
- new BN13(coinAmount),
3177
+ new BN14(coinAmount),
2704
3178
  params.fix_amount_a,
2705
3179
  true,
2706
3180
  slippage,
@@ -2774,12 +3248,12 @@ var _TransactionUtil = class {
2774
3248
  max_amount_a = params.amount_a;
2775
3249
  min_amount_a = params.amount_a;
2776
3250
  max_amount_b = params.amount_b;
2777
- min_amount_b = new Decimal4(params.amount_b).div(new Decimal4(1).plus(new Decimal4(params.slippage))).mul(new Decimal4(1).minus(new Decimal4(params.slippage))).toDecimalPlaces(0).toNumber();
3251
+ min_amount_b = new Decimal7(params.amount_b).div(new Decimal7(1).plus(new Decimal7(params.slippage))).mul(new Decimal7(1).minus(new Decimal7(params.slippage))).toDecimalPlaces(0).toNumber();
2778
3252
  } else {
2779
3253
  max_amount_b = params.amount_b;
2780
3254
  min_amount_b = params.amount_b;
2781
3255
  max_amount_a = params.amount_a;
2782
- min_amount_a = new Decimal4(params.amount_a).div(new Decimal4(1).plus(new Decimal4(params.slippage))).mul(new Decimal4(1).minus(new Decimal4(params.slippage))).toDecimalPlaces(0).toNumber();
3256
+ min_amount_a = new Decimal7(params.amount_a).div(new Decimal7(1).plus(new Decimal7(params.slippage))).mul(new Decimal7(1).minus(new Decimal7(params.slippage))).toDecimalPlaces(0).toNumber();
2783
3257
  }
2784
3258
  const args = params.is_open ? [
2785
3259
  tx.object(clmmConfig.global_config_id),
@@ -3768,7 +4242,7 @@ var _TransactionUtil = class {
3768
4242
  const basePath = splitPath.basePaths[i];
3769
4243
  a2b.push(basePath.direction);
3770
4244
  poolAddress.push(basePath.poolAddress);
3771
- rawAmountLimit.push(new BN13(basePath.inputAmount.toString()));
4245
+ rawAmountLimit.push(new BN14(basePath.inputAmount.toString()));
3772
4246
  if (i === 0) {
3773
4247
  coinType.push(basePath.fromCoin, basePath.toCoin);
3774
4248
  } else {
@@ -3776,8 +4250,8 @@ var _TransactionUtil = class {
3776
4250
  }
3777
4251
  }
3778
4252
  const onePath = {
3779
- amountIn: new BN13(splitPath.inputAmount.toString()),
3780
- amountOut: new BN13(splitPath.outputAmount.toString()),
4253
+ amountIn: new BN14(splitPath.inputAmount.toString()),
4254
+ amountOut: new BN14(splitPath.outputAmount.toString()),
3781
4255
  poolAddress,
3782
4256
  a2b,
3783
4257
  rawAmountLimit,
@@ -4134,9 +4608,9 @@ var TxBlock = class {
4134
4608
  };
4135
4609
 
4136
4610
  // src/utils/deepbook-utils.ts
4137
- import BN14 from "bn.js";
4611
+ import BN15 from "bn.js";
4138
4612
  import { Transaction as Transaction3 } from "@mysten/sui/transactions";
4139
- var FLOAT_SCALING = new BN14(1e9);
4613
+ var FLOAT_SCALING = new BN15(1e9);
4140
4614
  var DeepbookUtils = class {
4141
4615
  static createAccountCap(senderAddress, sdkOptions, tx, isTransfer = false) {
4142
4616
  if (senderAddress.length === 0) {
@@ -4282,9 +4756,9 @@ var DeepbookUtils = class {
4282
4756
  static async preSwap(sdk, pool, a2b, amountIn) {
4283
4757
  let isExceed = false;
4284
4758
  let amountOut = ZERO;
4285
- let remainAmount = new BN14(amountIn);
4759
+ let remainAmount = new BN15(amountIn);
4286
4760
  let feeAmount = ZERO;
4287
- const initAmountIn = new BN14(amountIn);
4761
+ const initAmountIn = new BN15(amountIn);
4288
4762
  if (a2b) {
4289
4763
  let bids = await this.getPoolBids(sdk, pool.poolID, pool.baseAsset, pool.quoteAsset);
4290
4764
  if (bids === null) {
@@ -4294,16 +4768,16 @@ var DeepbookUtils = class {
4294
4768
  return b.price - a.price;
4295
4769
  });
4296
4770
  for (let i = 0; i < bids.length; i += 1) {
4297
- const curBidAmount = new BN14(bids[i].quantity);
4298
- const curBidPrice = new BN14(bids[i].price);
4299
- const fee = curBidAmount.mul(new BN14(curBidPrice)).mul(new BN14(pool.takerFeeRate)).div(FLOAT_SCALING).div(FLOAT_SCALING);
4771
+ const curBidAmount = new BN15(bids[i].quantity);
4772
+ const curBidPrice = new BN15(bids[i].price);
4773
+ const fee = curBidAmount.mul(new BN15(curBidPrice)).mul(new BN15(pool.takerFeeRate)).div(FLOAT_SCALING).div(FLOAT_SCALING);
4300
4774
  if (remainAmount.gt(curBidAmount)) {
4301
4775
  remainAmount = remainAmount.sub(curBidAmount);
4302
4776
  amountOut = amountOut.add(curBidAmount.mul(curBidPrice).div(FLOAT_SCALING).sub(fee));
4303
4777
  feeAmount = feeAmount.add(fee);
4304
4778
  } else {
4305
- const curOut = remainAmount.mul(new BN14(bids[i].price)).div(FLOAT_SCALING);
4306
- const curFee = curOut.mul(new BN14(pool.takerFeeRate)).div(FLOAT_SCALING);
4779
+ const curOut = remainAmount.mul(new BN15(bids[i].price)).div(FLOAT_SCALING);
4780
+ const curFee = curOut.mul(new BN15(pool.takerFeeRate)).div(FLOAT_SCALING);
4307
4781
  amountOut = amountOut.add(curOut.sub(curFee));
4308
4782
  remainAmount = remainAmount.sub(remainAmount);
4309
4783
  feeAmount = feeAmount.add(curFee);
@@ -4318,15 +4792,15 @@ var DeepbookUtils = class {
4318
4792
  isExceed = true;
4319
4793
  }
4320
4794
  for (let i = 0; i < asks.length; i += 1) {
4321
- const curAskAmount = new BN14(asks[i].price).mul(new BN14(asks[i].quantity)).div(new BN14(1e9));
4322
- const fee = curAskAmount.mul(new BN14(pool.takerFeeRate)).div(FLOAT_SCALING);
4795
+ const curAskAmount = new BN15(asks[i].price).mul(new BN15(asks[i].quantity)).div(new BN15(1e9));
4796
+ const fee = curAskAmount.mul(new BN15(pool.takerFeeRate)).div(FLOAT_SCALING);
4323
4797
  const curAskAmountWithFee = curAskAmount.add(fee);
4324
4798
  if (remainAmount.gt(curAskAmount)) {
4325
- amountOut = amountOut.add(new BN14(asks[i].quantity));
4799
+ amountOut = amountOut.add(new BN15(asks[i].quantity));
4326
4800
  remainAmount = remainAmount.sub(curAskAmountWithFee);
4327
4801
  feeAmount = feeAmount.add(fee);
4328
4802
  } else {
4329
- const splitNums = new BN14(asks[i].quantity).div(new BN14(pool.lotSize));
4803
+ const splitNums = new BN15(asks[i].quantity).div(new BN15(pool.lotSize));
4330
4804
  const splitAmount = curAskAmountWithFee.div(splitNums);
4331
4805
  const swapSplitNum = remainAmount.div(splitAmount);
4332
4806
  amountOut = amountOut.add(swapSplitNum.muln(pool.lotSize));
@@ -5187,7 +5661,7 @@ var PoolModule = class {
5187
5661
  };
5188
5662
 
5189
5663
  // src/modules/positionModule.ts
5190
- import BN15 from "bn.js";
5664
+ import BN16 from "bn.js";
5191
5665
  import { Transaction as Transaction5 } from "@mysten/sui/transactions";
5192
5666
  import { isValidSuiObjectId } from "@mysten/sui/utils";
5193
5667
  var PositionModule = class {
@@ -5409,8 +5883,8 @@ var PositionModule = class {
5409
5883
  for (let i = 0; i < valueData.length; i += 1) {
5410
5884
  const { parsedJson } = valueData[i];
5411
5885
  const posRrewarderResult = {
5412
- feeOwedA: new BN15(parsedJson.fee_owned_a),
5413
- feeOwedB: new BN15(parsedJson.fee_owned_b),
5886
+ feeOwedA: new BN16(parsedJson.fee_owned_a),
5887
+ feeOwedB: new BN16(parsedJson.fee_owned_b),
5414
5888
  position_id: parsedJson.position_id
5415
5889
  };
5416
5890
  result.push(posRrewarderResult);
@@ -5786,7 +6260,7 @@ var PositionModule = class {
5786
6260
  };
5787
6261
 
5788
6262
  // src/modules/rewarderModule.ts
5789
- import BN16 from "bn.js";
6263
+ import BN17 from "bn.js";
5790
6264
  import { Transaction as Transaction6 } from "@mysten/sui/transactions";
5791
6265
  var RewarderModule = class {
5792
6266
  _sdk;
@@ -5812,7 +6286,7 @@ var RewarderModule = class {
5812
6286
  }
5813
6287
  const emissionsEveryDay = [];
5814
6288
  for (const rewarderInfo of rewarderInfos) {
5815
- const emissionSeconds = MathUtil.fromX64(new BN16(rewarderInfo.emissions_per_second));
6289
+ const emissionSeconds = MathUtil.fromX64(new BN17(rewarderInfo.emissions_per_second));
5816
6290
  emissionsEveryDay.push({
5817
6291
  emissions: Math.floor(emissionSeconds.toNumber() * 60 * 60 * 24),
5818
6292
  coin_address: rewarderInfo.coinAddress
@@ -5831,20 +6305,20 @@ var RewarderModule = class {
5831
6305
  const currentPool = await this.sdk.Pool.getPool(poolID);
5832
6306
  const lastTime = currentPool.rewarder_last_updated_time;
5833
6307
  currentPool.rewarder_last_updated_time = currentTime.toString();
5834
- if (Number(currentPool.liquidity) === 0 || currentTime.eq(new BN16(lastTime))) {
6308
+ if (Number(currentPool.liquidity) === 0 || currentTime.eq(new BN17(lastTime))) {
5835
6309
  return currentPool;
5836
6310
  }
5837
- const timeDelta = currentTime.div(new BN16(1e3)).sub(new BN16(lastTime)).add(new BN16(15));
6311
+ const timeDelta = currentTime.div(new BN17(1e3)).sub(new BN17(lastTime)).add(new BN17(15));
5838
6312
  const rewarderInfos = currentPool.rewarder_infos;
5839
6313
  for (let i = 0; i < rewarderInfos.length; i += 1) {
5840
6314
  const rewarderInfo = rewarderInfos[i];
5841
6315
  const rewarderGrowthDelta = MathUtil.checkMulDivFloor(
5842
6316
  timeDelta,
5843
- new BN16(rewarderInfo.emissions_per_second),
5844
- new BN16(currentPool.liquidity),
6317
+ new BN17(rewarderInfo.emissions_per_second),
6318
+ new BN17(currentPool.liquidity),
5845
6319
  128
5846
6320
  );
5847
- this.growthGlobal[i] = new BN16(rewarderInfo.growth_global).add(new BN16(rewarderGrowthDelta));
6321
+ this.growthGlobal[i] = new BN17(rewarderInfo.growth_global).add(new BN17(rewarderGrowthDelta));
5848
6322
  }
5849
6323
  return currentPool;
5850
6324
  }
@@ -5859,7 +6333,7 @@ var RewarderModule = class {
5859
6333
  */
5860
6334
  async posRewardersAmount(poolID, positionHandle, positionID) {
5861
6335
  const currentTime = Date.parse((/* @__PURE__ */ new Date()).toString());
5862
- const pool = await this.updatePoolRewarder(poolID, new BN16(currentTime));
6336
+ const pool = await this.updatePoolRewarder(poolID, new BN17(currentTime));
5863
6337
  const position = await this.sdk.Position.getPositionRewarders(positionHandle, positionID);
5864
6338
  if (position === void 0) {
5865
6339
  return [];
@@ -5880,7 +6354,7 @@ var RewarderModule = class {
5880
6354
  */
5881
6355
  async poolRewardersAmount(accountAddress, poolID) {
5882
6356
  const currentTime = Date.parse((/* @__PURE__ */ new Date()).toString());
5883
- const pool = await this.updatePoolRewarder(poolID, new BN16(currentTime));
6357
+ const pool = await this.updatePoolRewarder(poolID, new BN17(currentTime));
5884
6358
  const positions = await this.sdk.Position.getPositionList(accountAddress, [poolID]);
5885
6359
  const tickDatas = await this.getPoolLowerAndUpperTicks(pool.ticks_handle, positions);
5886
6360
  const rewarderAmount = [ZERO, ZERO, ZERO];
@@ -5907,38 +6381,38 @@ var RewarderModule = class {
5907
6381
  const growthInside = [];
5908
6382
  const AmountOwed = [];
5909
6383
  if (rewardersInside.length > 0) {
5910
- let growthDelta0 = MathUtil.subUnderflowU128(rewardersInside[0], new BN16(position.reward_growth_inside_0));
5911
- if (growthDelta0.gt(new BN16("3402823669209384634633745948738404"))) {
6384
+ let growthDelta0 = MathUtil.subUnderflowU128(rewardersInside[0], new BN17(position.reward_growth_inside_0));
6385
+ if (growthDelta0.gt(new BN17("3402823669209384634633745948738404"))) {
5912
6386
  growthDelta0 = ONE;
5913
6387
  }
5914
- const amountOwed_0 = MathUtil.checkMulShiftRight(new BN16(position.liquidity), growthDelta0, 64, 128);
6388
+ const amountOwed_0 = MathUtil.checkMulShiftRight(new BN17(position.liquidity), growthDelta0, 64, 128);
5915
6389
  growthInside.push(rewardersInside[0]);
5916
6390
  AmountOwed.push({
5917
- amount_owed: new BN16(position.reward_amount_owed_0).add(amountOwed_0),
6391
+ amount_owed: new BN17(position.reward_amount_owed_0).add(amountOwed_0),
5918
6392
  coin_address: pool.rewarder_infos[0].coinAddress
5919
6393
  });
5920
6394
  }
5921
6395
  if (rewardersInside.length > 1) {
5922
- let growthDelta_1 = MathUtil.subUnderflowU128(rewardersInside[1], new BN16(position.reward_growth_inside_1));
5923
- if (growthDelta_1.gt(new BN16("3402823669209384634633745948738404"))) {
6396
+ let growthDelta_1 = MathUtil.subUnderflowU128(rewardersInside[1], new BN17(position.reward_growth_inside_1));
6397
+ if (growthDelta_1.gt(new BN17("3402823669209384634633745948738404"))) {
5924
6398
  growthDelta_1 = ONE;
5925
6399
  }
5926
- const amountOwed_1 = MathUtil.checkMulShiftRight(new BN16(position.liquidity), growthDelta_1, 64, 128);
6400
+ const amountOwed_1 = MathUtil.checkMulShiftRight(new BN17(position.liquidity), growthDelta_1, 64, 128);
5927
6401
  growthInside.push(rewardersInside[1]);
5928
6402
  AmountOwed.push({
5929
- amount_owed: new BN16(position.reward_amount_owed_1).add(amountOwed_1),
6403
+ amount_owed: new BN17(position.reward_amount_owed_1).add(amountOwed_1),
5930
6404
  coin_address: pool.rewarder_infos[1].coinAddress
5931
6405
  });
5932
6406
  }
5933
6407
  if (rewardersInside.length > 2) {
5934
- let growthDelta_2 = MathUtil.subUnderflowU128(rewardersInside[2], new BN16(position.reward_growth_inside_2));
5935
- if (growthDelta_2.gt(new BN16("3402823669209384634633745948738404"))) {
6408
+ let growthDelta_2 = MathUtil.subUnderflowU128(rewardersInside[2], new BN17(position.reward_growth_inside_2));
6409
+ if (growthDelta_2.gt(new BN17("3402823669209384634633745948738404"))) {
5936
6410
  growthDelta_2 = ONE;
5937
6411
  }
5938
- const amountOwed_2 = MathUtil.checkMulShiftRight(new BN16(position.liquidity), growthDelta_2, 64, 128);
6412
+ const amountOwed_2 = MathUtil.checkMulShiftRight(new BN17(position.liquidity), growthDelta_2, 64, 128);
5939
6413
  growthInside.push(rewardersInside[2]);
5940
6414
  AmountOwed.push({
5941
- amount_owed: new BN16(position.reward_amount_owed_2).add(amountOwed_2),
6415
+ amount_owed: new BN17(position.reward_amount_owed_2).add(amountOwed_2),
5942
6416
  coin_address: pool.rewarder_infos[2].coinAddress
5943
6417
  });
5944
6418
  }
@@ -6052,8 +6526,8 @@ var RewarderModule = class {
6052
6526
  for (let i = 0; i < valueData.length; i += 1) {
6053
6527
  const { parsedJson } = valueData[i];
6054
6528
  const posRrewarderResult = {
6055
- feeOwedA: new BN16(parsedJson.fee_owned_a),
6056
- feeOwedB: new BN16(parsedJson.fee_owned_b),
6529
+ feeOwedA: new BN17(parsedJson.fee_owned_a),
6530
+ feeOwedB: new BN17(parsedJson.fee_owned_b),
6057
6531
  position_id: parsedJson.position_id
6058
6532
  };
6059
6533
  result.push(posRrewarderResult);
@@ -6116,7 +6590,7 @@ var RewarderModule = class {
6116
6590
  };
6117
6591
  for (let j = 0; j < params[i].rewarderInfo.length; j += 1) {
6118
6592
  posRrewarderResult.rewarderAmountOwed.push({
6119
- amount_owed: new BN16(valueData[i].parsedJson.data[j]),
6593
+ amount_owed: new BN17(valueData[i].parsedJson.data[j]),
6120
6594
  coin_address: params[i].rewarderInfo[j].coinAddress
6121
6595
  });
6122
6596
  }
@@ -6187,21 +6661,45 @@ var RewarderModule = class {
6187
6661
  * @param tx
6188
6662
  * @returns
6189
6663
  */
6190
- async batchCollectRewardePayload(params, tx) {
6664
+ async batchCollectRewardePayload(params, tx, inputCoinA, inputCoinB) {
6191
6665
  if (!checkInvalidSuiAddress(this._sdk.senderAddress)) {
6192
6666
  throw new ClmmpoolsError("this config sdk senderAddress is not set right", "InvalidSendAddress" /* InvalidSendAddress */);
6193
6667
  }
6194
6668
  const allCoinAsset = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress, null);
6195
6669
  tx = tx || new Transaction6();
6196
- const coinIdList = [];
6670
+ const coinIdMaps = {};
6197
6671
  params.forEach((item) => {
6198
6672
  const coinTypeA = normalizeCoinType(item.coinTypeA);
6199
6673
  const coinTypeB = normalizeCoinType(item.coinTypeB);
6200
6674
  if (item.collect_fee) {
6201
- const coinAInput = TransactionUtil.buildCoinForAmount(tx, allCoinAsset, BigInt(0), coinTypeA, false, true);
6202
- const coinBInput = TransactionUtil.buildCoinForAmount(tx, allCoinAsset, BigInt(0), coinTypeB, false, true);
6203
- coinIdList.push({ coin: coinAInput, coin_addr: coinTypeA });
6204
- coinIdList.push({ coin: coinBInput, coin_addr: coinTypeB });
6675
+ let coinAInput = coinIdMaps[coinTypeA];
6676
+ if (coinAInput == null) {
6677
+ if (inputCoinA == null) {
6678
+ coinAInput = TransactionUtil.buildCoinForAmount(tx, allCoinAsset, BigInt(0), coinTypeA, false);
6679
+ } else {
6680
+ coinAInput = {
6681
+ targetCoin: inputCoinA,
6682
+ remainCoins: [],
6683
+ isMintZeroCoin: false,
6684
+ tragetCoinAmount: "0"
6685
+ };
6686
+ }
6687
+ coinIdMaps[coinTypeA] = coinAInput;
6688
+ }
6689
+ let coinBInput = coinIdMaps[coinTypeB];
6690
+ if (coinBInput == null) {
6691
+ if (inputCoinB == null) {
6692
+ coinBInput = TransactionUtil.buildCoinForAmount(tx, allCoinAsset, BigInt(0), coinTypeB, false);
6693
+ } else {
6694
+ coinBInput = {
6695
+ targetCoin: inputCoinB,
6696
+ remainCoins: [],
6697
+ isMintZeroCoin: false,
6698
+ tragetCoinAmount: "0"
6699
+ };
6700
+ }
6701
+ coinIdMaps[coinTypeB] = coinBInput;
6702
+ }
6205
6703
  tx = this._sdk.Position.createCollectFeeNoSendPaylod(
6206
6704
  {
6207
6705
  pool_id: item.pool_id,
@@ -6217,14 +6715,20 @@ var RewarderModule = class {
6217
6715
  const primaryCoinInputs = [];
6218
6716
  item.rewarder_coin_types.forEach((type) => {
6219
6717
  const coinType = normalizeCoinType(type);
6220
- const coinInput = TransactionUtil.buildCoinForAmount(tx, allCoinAsset, BigInt(0), coinType, false, true);
6718
+ let coinInput = coinIdMaps[type];
6719
+ if (coinInput === void 0) {
6720
+ coinInput = TransactionUtil.buildCoinForAmount(tx, allCoinAsset, BigInt(0), coinType, false);
6721
+ coinIdMaps[coinType] = coinInput;
6722
+ }
6221
6723
  primaryCoinInputs.push(coinInput.targetCoin);
6222
- coinIdList.push({ coin: coinInput, coin_addr: coinType });
6223
6724
  });
6224
6725
  tx = this.createCollectRewarderNoSendPaylod(item, tx, primaryCoinInputs);
6225
6726
  });
6226
- coinIdList.forEach((item) => {
6227
- TransactionUtil.buildTransferCoin(this._sdk, tx, item.coin.targetCoin, item.coin_addr, this._sdk.senderAddress);
6727
+ Object.keys(coinIdMaps).forEach((key) => {
6728
+ const value = coinIdMaps[key];
6729
+ if (value.isMintZeroCoin) {
6730
+ TransactionUtil.buildTransferCoin(this._sdk, tx, value.targetCoin, key, this._sdk.senderAddress);
6731
+ }
6228
6732
  });
6229
6733
  return tx;
6230
6734
  }
@@ -6275,7 +6779,7 @@ var RewarderModule = class {
6275
6779
  };
6276
6780
 
6277
6781
  // src/modules/routerModule.ts
6278
- import BN17 from "bn.js";
6782
+ import BN18 from "bn.js";
6279
6783
  import { Graph, GraphEdge, GraphVertex } from "@syntsugar/cc-graph";
6280
6784
  import { Transaction as Transaction7 } from "@mysten/sui/transactions";
6281
6785
  function _pairSymbol(base, quote) {
@@ -6557,8 +7061,8 @@ var RouterModule = class {
6557
7061
  if (swapWithMultiPoolParams != null) {
6558
7062
  const preSwapResult2 = await this.sdk.Swap.preSwapWithMultiPool(swapWithMultiPoolParams);
6559
7063
  const onePath2 = {
6560
- amountIn: new BN17(preSwapResult2.estimatedAmountIn),
6561
- amountOut: new BN17(preSwapResult2.estimatedAmountOut),
7064
+ amountIn: new BN18(preSwapResult2.estimatedAmountIn),
7065
+ amountOut: new BN18(preSwapResult2.estimatedAmountOut),
6562
7066
  poolAddress: [preSwapResult2.poolAddress],
6563
7067
  a2b: [preSwapResult2.aToB],
6564
7068
  rawAmountLimit: byAmountIn ? [preSwapResult2.estimatedAmountOut] : [preSwapResult2.estimatedAmountIn],
@@ -6571,8 +7075,8 @@ var RouterModule = class {
6571
7075
  priceSlippagePoint
6572
7076
  };
6573
7077
  const result2 = {
6574
- amountIn: new BN17(preSwapResult2.estimatedAmountIn),
6575
- amountOut: new BN17(preSwapResult2.estimatedAmountOut),
7078
+ amountIn: new BN18(preSwapResult2.estimatedAmountIn),
7079
+ amountOut: new BN18(preSwapResult2.estimatedAmountOut),
6576
7080
  paths: [onePath2],
6577
7081
  a2b: preSwapResult2.aToB,
6578
7082
  b2c: void 0,
@@ -6594,8 +7098,8 @@ var RouterModule = class {
6594
7098
  if (swapWithMultiPoolParams != null) {
6595
7099
  const preSwapResult2 = await this.sdk.Swap.preSwapWithMultiPool(swapWithMultiPoolParams);
6596
7100
  const onePath2 = {
6597
- amountIn: new BN17(preSwapResult2.estimatedAmountIn),
6598
- amountOut: new BN17(preSwapResult2.estimatedAmountOut),
7101
+ amountIn: new BN18(preSwapResult2.estimatedAmountIn),
7102
+ amountOut: new BN18(preSwapResult2.estimatedAmountOut),
6599
7103
  poolAddress: [preSwapResult2.poolAddress],
6600
7104
  a2b: [preSwapResult2.aToB],
6601
7105
  rawAmountLimit: byAmountIn ? [preSwapResult2.estimatedAmountOut] : [preSwapResult2.estimatedAmountIn],
@@ -6608,8 +7112,8 @@ var RouterModule = class {
6608
7112
  priceSlippagePoint
6609
7113
  };
6610
7114
  const result3 = {
6611
- amountIn: new BN17(preSwapResult2.estimatedAmountIn),
6612
- amountOut: new BN17(preSwapResult2.estimatedAmountOut),
7115
+ amountIn: new BN18(preSwapResult2.estimatedAmountIn),
7116
+ amountOut: new BN18(preSwapResult2.estimatedAmountOut),
6613
7117
  paths: [onePath2],
6614
7118
  a2b: preSwapResult2.aToB,
6615
7119
  b2c: void 0,
@@ -6690,8 +7194,8 @@ var RouterModule = class {
6690
7194
  if (swapWithMultiPoolParams != null) {
6691
7195
  const preSwapResult = await this.sdk.Swap.preSwapWithMultiPool(swapWithMultiPoolParams);
6692
7196
  const onePath = {
6693
- amountIn: new BN17(preSwapResult.estimatedAmountIn),
6694
- amountOut: new BN17(preSwapResult.estimatedAmountOut),
7197
+ amountIn: new BN18(preSwapResult.estimatedAmountIn),
7198
+ amountOut: new BN18(preSwapResult.estimatedAmountOut),
6695
7199
  poolAddress: [preSwapResult.poolAddress],
6696
7200
  a2b: [preSwapResult.aToB],
6697
7201
  rawAmountLimit: byAmountIn ? [preSwapResult.estimatedAmountOut] : [preSwapResult.estimatedAmountIn],
@@ -6704,8 +7208,8 @@ var RouterModule = class {
6704
7208
  priceSlippagePoint
6705
7209
  };
6706
7210
  const result = {
6707
- amountIn: new BN17(preSwapResult.estimatedAmountIn),
6708
- amountOut: new BN17(preSwapResult.estimatedAmountOut),
7211
+ amountIn: new BN18(preSwapResult.estimatedAmountIn),
7212
+ amountOut: new BN18(preSwapResult.estimatedAmountOut),
6709
7213
  paths: [onePath],
6710
7214
  a2b: preSwapResult.aToB,
6711
7215
  b2c: void 0,
@@ -6789,13 +7293,13 @@ var RouterModule = class {
6789
7293
  continue;
6790
7294
  }
6791
7295
  if (params[0].byAmountIn) {
6792
- const amount = new BN17(valueData[i].parsedJson.data.amount_out);
7296
+ const amount = new BN18(valueData[i].parsedJson.data.amount_out);
6793
7297
  if (amount.gt(tempMaxAmount)) {
6794
7298
  tempIndex = i;
6795
7299
  tempMaxAmount = amount;
6796
7300
  }
6797
7301
  } else {
6798
- const amount = params[i].stepNums > 1 ? new BN17(valueData[i].parsedJson.data.amount_in) : new BN17(valueData[i].parsedJson.data.amount_in).add(new BN17(valueData[i].parsedJson.data.fee_amount));
7302
+ const amount = params[i].stepNums > 1 ? new BN18(valueData[i].parsedJson.data.amount_in) : new BN18(valueData[i].parsedJson.data.amount_in).add(new BN18(valueData[i].parsedJson.data.fee_amount));
6799
7303
  if (amount.lt(tempMaxAmount)) {
6800
7304
  tempIndex = i;
6801
7305
  tempMaxAmount = amount;
@@ -6865,8 +7369,8 @@ var RouterModule = class {
6865
7369
  };
6866
7370
 
6867
7371
  // src/modules/swapModule.ts
6868
- import BN18 from "bn.js";
6869
- import Decimal5 from "decimal.js";
7372
+ import BN19 from "bn.js";
7373
+ import Decimal8 from "decimal.js";
6870
7374
  import { Transaction as Transaction8 } from "@mysten/sui/transactions";
6871
7375
  var AMM_SWAP_MODULE = "amm_swap";
6872
7376
  var POOL_STRUCT = "Pool";
@@ -6884,14 +7388,14 @@ var SwapModule = class {
6884
7388
  const pathCount = item.basePaths.length;
6885
7389
  if (pathCount > 0) {
6886
7390
  const path = item.basePaths[0];
6887
- const feeRate = path.label === "Magma" ? new Decimal5(path.feeRate).div(10 ** 6) : new Decimal5(path.feeRate).div(10 ** 9);
7391
+ const feeRate = path.label === "Magma" ? new Decimal8(path.feeRate).div(10 ** 6) : new Decimal8(path.feeRate).div(10 ** 9);
6888
7392
  const feeAmount = d(path.inputAmount).div(10 ** path.fromDecimal).mul(feeRate);
6889
7393
  fee = fee.add(feeAmount);
6890
7394
  if (pathCount > 1) {
6891
7395
  const path2 = item.basePaths[1];
6892
- const price1 = path.direction ? path.currentPrice : new Decimal5(1).div(path.currentPrice);
6893
- const price2 = path2.direction ? path2.currentPrice : new Decimal5(1).div(path2.currentPrice);
6894
- const feeRate2 = path2.label === "Magma" ? new Decimal5(path2.feeRate).div(10 ** 6) : new Decimal5(path2.feeRate).div(10 ** 9);
7396
+ const price1 = path.direction ? path.currentPrice : new Decimal8(1).div(path.currentPrice);
7397
+ const price2 = path2.direction ? path2.currentPrice : new Decimal8(1).div(path2.currentPrice);
7398
+ const feeRate2 = path2.label === "Magma" ? new Decimal8(path2.feeRate).div(10 ** 6) : new Decimal8(path2.feeRate).div(10 ** 9);
6895
7399
  const feeAmount2 = d(path2.outputAmount).div(10 ** path2.toDecimal).mul(feeRate2);
6896
7400
  const fee2 = feeAmount2.div(price1.mul(price2));
6897
7401
  fee = fee.add(fee2);
@@ -6909,17 +7413,17 @@ var SwapModule = class {
6909
7413
  const outputAmount = d(path.outputAmount).div(10 ** path.toDecimal);
6910
7414
  const inputAmount = d(path.inputAmount).div(10 ** path.fromDecimal);
6911
7415
  const rate = outputAmount.div(inputAmount);
6912
- const cprice = path.direction ? new Decimal5(path.currentPrice) : new Decimal5(1).div(path.currentPrice);
7416
+ const cprice = path.direction ? new Decimal8(path.currentPrice) : new Decimal8(1).div(path.currentPrice);
6913
7417
  impactValue = impactValue.add(this.calculateSingleImpact(rate, cprice));
6914
7418
  }
6915
7419
  if (pathCount === 2) {
6916
7420
  const path = item.basePaths[0];
6917
7421
  const path2 = item.basePaths[1];
6918
- const cprice1 = path.direction ? new Decimal5(path.currentPrice) : new Decimal5(1).div(path.currentPrice);
6919
- const cprice2 = path2.direction ? new Decimal5(path2.currentPrice) : new Decimal5(1).div(path2.currentPrice);
7422
+ const cprice1 = path.direction ? new Decimal8(path.currentPrice) : new Decimal8(1).div(path.currentPrice);
7423
+ const cprice2 = path2.direction ? new Decimal8(path2.currentPrice) : new Decimal8(1).div(path2.currentPrice);
6920
7424
  const cprice = cprice1.mul(cprice2);
6921
- const outputAmount = new Decimal5(path2.outputAmount).div(10 ** path2.toDecimal);
6922
- const inputAmount = new Decimal5(path.inputAmount).div(10 ** path.fromDecimal);
7425
+ const outputAmount = new Decimal8(path2.outputAmount).div(10 ** path2.toDecimal);
7426
+ const inputAmount = new Decimal8(path.inputAmount).div(10 ** path.fromDecimal);
6923
7427
  const rate = outputAmount.div(inputAmount);
6924
7428
  impactValue = impactValue.add(this.calculateSingleImpact(rate, cprice));
6925
7429
  }
@@ -6981,13 +7485,13 @@ var SwapModule = class {
6981
7485
  continue;
6982
7486
  }
6983
7487
  if (params.byAmountIn) {
6984
- const amount = new BN18(valueData[i].parsedJson.data.amount_out);
7488
+ const amount = new BN19(valueData[i].parsedJson.data.amount_out);
6985
7489
  if (amount.gt(tempMaxAmount)) {
6986
7490
  tempIndex = i;
6987
7491
  tempMaxAmount = amount;
6988
7492
  }
6989
7493
  } else {
6990
- const amount = new BN18(valueData[i].parsedJson.data.amount_out);
7494
+ const amount = new BN19(valueData[i].parsedJson.data.amount_out);
6991
7495
  if (amount.lt(tempMaxAmount)) {
6992
7496
  tempIndex = i;
6993
7497
  tempMaxAmount = amount;
@@ -7051,7 +7555,7 @@ var SwapModule = class {
7051
7555
  return this.transformSwapData(params, valueData[0].parsedJson.data);
7052
7556
  }
7053
7557
  transformSwapData(params, data) {
7054
- const estimatedAmountIn = data.amount_in && data.fee_amount ? new BN18(data.amount_in).add(new BN18(data.fee_amount)).toString() : "";
7558
+ const estimatedAmountIn = data.amount_in && data.fee_amount ? new BN19(data.amount_in).add(new BN19(data.fee_amount)).toString() : "";
7055
7559
  return {
7056
7560
  poolAddress: params.pool.poolAddress,
7057
7561
  currentSqrtPrice: params.currentSqrtPrice,
@@ -7068,7 +7572,7 @@ var SwapModule = class {
7068
7572
  transformSwapWithMultiPoolData(params, jsonData) {
7069
7573
  const { data } = jsonData;
7070
7574
  console.log("json data. ", data);
7071
- const estimatedAmountIn = data.amount_in && data.fee_amount ? new BN18(data.amount_in).add(new BN18(data.fee_amount)).toString() : "";
7575
+ const estimatedAmountIn = data.amount_in && data.fee_amount ? new BN19(data.amount_in).add(new BN19(data.fee_amount)).toString() : "";
7072
7576
  return {
7073
7577
  poolAddress: params.poolAddress,
7074
7578
  estimatedAmountIn,
@@ -8581,8 +9085,8 @@ var TokenModule = class {
8581
9085
  };
8582
9086
 
8583
9087
  // src/modules/routerModuleV2.ts
8584
- import BN19 from "bn.js";
8585
- import Decimal6 from "decimal.js";
9088
+ import BN20 from "bn.js";
9089
+ import Decimal9 from "decimal.js";
8586
9090
  import { v4 as uuidv4 } from "uuid";
8587
9091
  import axios from "axios";
8588
9092
  var RouterModuleV2 = class {
@@ -8599,7 +9103,7 @@ var RouterModuleV2 = class {
8599
9103
  if (label === "Magma") {
8600
9104
  return TickMath.sqrtPriceX64ToPrice(currentSqrtPrice, decimalA, decimalB);
8601
9105
  }
8602
- return new Decimal6(currentSqrtPrice.toString()).div(new Decimal6(10).pow(new Decimal6(decimalB + 9 - decimalA)));
9106
+ return new Decimal9(currentSqrtPrice.toString()).div(new Decimal9(10).pow(new Decimal9(decimalB + 9 - decimalA)));
8603
9107
  }
8604
9108
  parseJsonResult(data) {
8605
9109
  const result = {
@@ -8625,12 +9129,12 @@ var RouterModuleV2 = class {
8625
9129
  outputAmount: basePath.output_amount,
8626
9130
  inputAmount: basePath.input_amount,
8627
9131
  feeRate: basePath.fee_rate,
8628
- currentSqrtPrice: new BN19(basePath.current_sqrt_price.toString()),
8629
- afterSqrtPrice: basePath.label === "Magma" ? new BN19(basePath.after_sqrt_price.toString()) : ZERO,
9132
+ currentSqrtPrice: new BN20(basePath.current_sqrt_price.toString()),
9133
+ afterSqrtPrice: basePath.label === "Magma" ? new BN20(basePath.after_sqrt_price.toString()) : ZERO,
8630
9134
  fromDecimal: basePath.from_decimal,
8631
9135
  toDecimal: basePath.to_decimal,
8632
9136
  currentPrice: this.calculatePrice(
8633
- new BN19(basePath.current_sqrt_price.toString()),
9137
+ new BN20(basePath.current_sqrt_price.toString()),
8634
9138
  basePath.from_decimal,
8635
9139
  basePath.to_decimal,
8636
9140
  basePath.direction,
@@ -8713,7 +9217,7 @@ var RouterModuleV2 = class {
8713
9217
  const priceResult = await this.sdk.Router.priceUseV1(
8714
9218
  from,
8715
9219
  to,
8716
- new BN19(amount),
9220
+ new BN20(amount),
8717
9221
  byAmountIn,
8718
9222
  priceSplitPoint,
8719
9223
  partner,
@@ -8725,7 +9229,7 @@ var RouterModuleV2 = class {
8725
9229
  if (path.poolAddress.length > 1) {
8726
9230
  const fromDecimal0 = this.sdk.Router.tokenInfo(path.coinType[0]).decimals;
8727
9231
  const toDecimal0 = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
8728
- const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new BN19(priceResult.currentSqrtPrice[0]), fromDecimal0, toDecimal0) : TickMath.sqrtPriceX64ToPrice(new BN19(priceResult.currentSqrtPrice[0]), toDecimal0, fromDecimal0);
9232
+ const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), fromDecimal0, toDecimal0) : TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), toDecimal0, fromDecimal0);
8729
9233
  const path0 = {
8730
9234
  direction: path.a2b[0],
8731
9235
  label: "Magma",
@@ -8742,7 +9246,7 @@ var RouterModuleV2 = class {
8742
9246
  };
8743
9247
  const fromDecimal1 = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
8744
9248
  const toDecimal1 = this.sdk.Router.tokenInfo(path.coinType[2]).decimals;
8745
- const currentPrice1 = path.a2b[1] ? TickMath.sqrtPriceX64ToPrice(new BN19(priceResult.currentSqrtPrice[1]), fromDecimal1, toDecimal1) : TickMath.sqrtPriceX64ToPrice(new BN19(priceResult.currentSqrtPrice[1]), toDecimal1, fromDecimal1);
9249
+ const currentPrice1 = path.a2b[1] ? TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[1]), fromDecimal1, toDecimal1) : TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[1]), toDecimal1, fromDecimal1);
8746
9250
  const path1 = {
8747
9251
  direction: path.a2b[1],
8748
9252
  label: "Magma",
@@ -8761,7 +9265,7 @@ var RouterModuleV2 = class {
8761
9265
  } else {
8762
9266
  const fromDecimal = this.sdk.Router.tokenInfo(path.coinType[0]).decimals;
8763
9267
  const toDecimal = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
8764
- const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new BN19(priceResult.currentSqrtPrice[0]), fromDecimal, toDecimal) : TickMath.sqrtPriceX64ToPrice(new BN19(priceResult.currentSqrtPrice[0]), toDecimal, fromDecimal);
9268
+ const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), fromDecimal, toDecimal) : TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), toDecimal, fromDecimal);
8765
9269
  const path0 = {
8766
9270
  direction: path.a2b[0],
8767
9271
  label: "Magma",
@@ -8846,7 +9350,7 @@ var RouterModuleV2 = class {
8846
9350
  const priceResult = await this.sdk.Router.priceUseV1(
8847
9351
  from,
8848
9352
  to,
8849
- new BN19(amount),
9353
+ new BN20(amount),
8850
9354
  byAmountIn,
8851
9355
  priceSplitPoint,
8852
9356
  partner,
@@ -8858,7 +9362,7 @@ var RouterModuleV2 = class {
8858
9362
  if (path.poolAddress.length > 1) {
8859
9363
  const fromDecimal0 = this.sdk.Router.tokenInfo(path.coinType[0]).decimals;
8860
9364
  const toDecimal0 = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
8861
- const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new BN19(priceResult.currentSqrtPrice[0]), fromDecimal0, toDecimal0) : TickMath.sqrtPriceX64ToPrice(new BN19(priceResult.currentSqrtPrice[0]), toDecimal0, fromDecimal0);
9365
+ const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), fromDecimal0, toDecimal0) : TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), toDecimal0, fromDecimal0);
8862
9366
  const path0 = {
8863
9367
  direction: path.a2b[0],
8864
9368
  label: "Magma",
@@ -8875,7 +9379,7 @@ var RouterModuleV2 = class {
8875
9379
  };
8876
9380
  const fromDecimal1 = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
8877
9381
  const toDecimal1 = this.sdk.Router.tokenInfo(path.coinType[2]).decimals;
8878
- const currentPrice1 = path.a2b[1] ? TickMath.sqrtPriceX64ToPrice(new BN19(priceResult.currentSqrtPrice[1]), fromDecimal1, toDecimal1) : TickMath.sqrtPriceX64ToPrice(new BN19(priceResult.currentSqrtPrice[1]), toDecimal1, fromDecimal1);
9382
+ const currentPrice1 = path.a2b[1] ? TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[1]), fromDecimal1, toDecimal1) : TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[1]), toDecimal1, fromDecimal1);
8879
9383
  const path1 = {
8880
9384
  direction: path.a2b[1],
8881
9385
  label: "Magma",
@@ -8894,7 +9398,7 @@ var RouterModuleV2 = class {
8894
9398
  } else {
8895
9399
  const fromDecimal = this.sdk.Router.tokenInfo(path.coinType[0]).decimals;
8896
9400
  const toDecimal = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
8897
- const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new BN19(priceResult.currentSqrtPrice[0]), fromDecimal, toDecimal) : TickMath.sqrtPriceX64ToPrice(new BN19(priceResult.currentSqrtPrice[0]), toDecimal, fromDecimal);
9401
+ const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), fromDecimal, toDecimal) : TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), toDecimal, fromDecimal);
8898
9402
  const path0 = {
8899
9403
  direction: path.a2b[0],
8900
9404
  label: "Magma",
@@ -9769,6 +10273,21 @@ var GaugeModule = class {
9769
10273
  });
9770
10274
  return tx;
9771
10275
  }
10276
+ async getAllRewardByPositions(paramsList) {
10277
+ const tx = new Transaction11();
10278
+ const { integrate } = this.sdk.sdkOptions;
10279
+ const { magma_token } = getPackagerConfigs(this.sdk.sdkOptions.magma_config);
10280
+ paramsList.forEach((params) => {
10281
+ const typeArguments = [params.coinTypeA, params.coinTypeB, magma_token];
10282
+ const args = [tx.object(params.gaugeId), tx.object(params.poolId), tx.object(params.positionId), tx.object(CLOCK_ADDRESS)];
10283
+ tx.moveCall({
10284
+ target: `${integrate.published_at}::${Gauge}::get_reward_by_position`,
10285
+ arguments: args,
10286
+ typeArguments
10287
+ });
10288
+ });
10289
+ return tx;
10290
+ }
9772
10291
  async getEpochRewardByPool(pool, incentive_tokens) {
9773
10292
  const tx = new Transaction11();
9774
10293
  const { integrate, simulationAccount } = this.sdk.sdkOptions;
@@ -9801,67 +10320,962 @@ var GaugeModule = class {
9801
10320
  }
9802
10321
  };
9803
10322
 
9804
- // src/sdk.ts
9805
- var MagmaClmmSDK = class {
10323
+ // src/modules/dlmm.ts
10324
+ import { Transaction as Transaction12 } from "@mysten/sui/transactions";
10325
+ import {
10326
+ get_price_x128_from_real_id as get_price_x128_from_real_id3,
10327
+ get_real_id,
10328
+ get_real_id_from_price_x128 as get_real_id_from_price_x1282,
10329
+ get_storage_id_from_real_id
10330
+ } from "@magmaprotocol/calc_dlmm";
10331
+ import Decimal10 from "decimal.js";
10332
+ var DlmmModule = class {
10333
+ _sdk;
9806
10334
  _cache = {};
9807
- /**
9808
- * RPC provider on the SUI chain
9809
- */
9810
- _rpcModule;
9811
- /**
9812
- * Provide interact with clmm pools with a pool router interface.
9813
- */
9814
- _pool;
9815
- /**
9816
- * Provide interact with clmm position with a position router interface.
9817
- */
9818
- _position;
9819
- /**
9820
- * Provide interact with a pool swap router interface.
9821
- */
9822
- _swap;
9823
- /**
9824
- * Provide interact with a lock interface.
9825
- */
9826
- _lock;
9827
- _gauge;
9828
- /**
9829
- * Provide interact with a position rewarder interface.
9830
- */
9831
- _rewarder;
9832
- /**
9833
- * Provide interact with a pool router interface.
9834
- */
9835
- _router;
9836
- /**
9837
- * Provide interact with a pool routerV2 interface.
9838
- */
9839
- _router_v2;
9840
- /**
9841
- * Provide interact with pool and token config (contain token base info for metadat).
9842
- * @deprecated Please use MagmaConfig instead
9843
- */
9844
- _token;
9845
- /**
9846
- * Provide interact with clmm pool and coin and launchpad pool config
9847
- */
9848
- _config;
9849
- /**
9850
- * Provide sdk options
9851
- */
9852
- _sdkOptions;
9853
- /**
9854
- * After connecting the wallet, set the current wallet address to senderAddress.
9855
- */
9856
- _senderAddress = "";
9857
- constructor(options) {
9858
- this._sdkOptions = options;
9859
- this._rpcModule = new RpcModule({
9860
- url: options.fullRpcUrl
9861
- });
10335
+ constructor(sdk) {
10336
+ this._sdk = sdk;
10337
+ }
10338
+ get sdk() {
10339
+ return this._sdk;
10340
+ }
10341
+ async getPoolInfo(pools) {
10342
+ const objects = await this._sdk.fullClient.batchGetObjects(pools, { showContent: true });
10343
+ const poolList = [];
10344
+ objects.forEach((obj) => {
10345
+ if (obj.error != null || obj.data?.content?.dataType !== "moveObject") {
10346
+ throw new ClmmpoolsError(`Invalid objects. error: ${obj.error}`, "InvalidType" /* InvalidType */);
10347
+ }
10348
+ const fields = getObjectFields(obj);
10349
+ poolList.push({
10350
+ pool_id: fields.id.id,
10351
+ bin_step: fields.bin_step,
10352
+ coin_a: fields.x.fields.name,
10353
+ coin_b: fields.y.fields.name,
10354
+ base_factor: fields.params.fields.base_factor,
10355
+ base_fee: fields.params.fields.base_factor / 1e4 * (fields.bin_step / 1e4),
10356
+ active_index: fields.params.fields.active_index,
10357
+ real_bin_id: get_real_id(fields.params.fields.active_index),
10358
+ coinAmountA: fields.reserve_x,
10359
+ coinAmountB: fields.reserve_y
10360
+ });
10361
+ });
10362
+ return poolList;
10363
+ }
10364
+ // eg: fetch pool active_index
10365
+ async fetchPairParams(params) {
10366
+ const tx = new Transaction12();
10367
+ const { integrate, simulationAccount } = this.sdk.sdkOptions;
10368
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10369
+ const args = [tx.object(params.pair)];
10370
+ tx.moveCall({
10371
+ target: `${integrate.published_at}::${DlmmScript}::fetch_pair_params`,
10372
+ arguments: args,
10373
+ typeArguments
10374
+ });
10375
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
10376
+ transactionBlock: tx,
10377
+ sender: simulationAccount.address
10378
+ });
10379
+ if (simulateRes.error != null) {
10380
+ throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
10381
+ }
10382
+ let res = {
10383
+ base_factor: 0,
10384
+ filter_period: 0,
10385
+ decay_period: 0,
10386
+ reduction_factor: 0,
10387
+ variable_fee_control: 0,
10388
+ protocol_share: 0,
10389
+ max_volatility_accumulator: 0,
10390
+ volatility_accumulator: 0,
10391
+ volatility_reference: 0,
10392
+ index_reference: 0,
10393
+ time_of_last_update: 0,
10394
+ oracle_index: 0,
10395
+ active_index: 0
10396
+ };
10397
+ simulateRes.events?.forEach((item) => {
10398
+ console.log(extractStructTagFromType(item.type).name);
10399
+ if (extractStructTagFromType(item.type).name === `EventPairParams`) {
10400
+ res = item.parsedJson.params;
10401
+ }
10402
+ });
10403
+ return res;
10404
+ }
10405
+ // NOTE: x, y should be sorted
10406
+ async createPairPayload(params) {
10407
+ const storage_id = get_storage_id_from_real_id(
10408
+ BinMath.getBinIdFromPrice(params.priceTokenBPerTokenA, params.bin_step, params.coinADecimal, params.coinBDecimal)
10409
+ );
10410
+ const tx = new Transaction12();
10411
+ tx.setSender(this.sdk.senderAddress);
10412
+ const { clmm_pool, dlmm_pool, integrate } = this.sdk.sdkOptions;
10413
+ const { global_config_id } = getPackagerConfigs(clmm_pool);
10414
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10415
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10416
+ const args = [
10417
+ tx.object(dlmmConfig.factory),
10418
+ tx.object(global_config_id),
10419
+ tx.pure.u64(params.base_fee),
10420
+ tx.pure.u16(params.bin_step),
10421
+ tx.pure.u32(storage_id)
10422
+ ];
10423
+ tx.moveCall({
10424
+ target: `${integrate.published_at}::${DlmmScript}::create_pair`,
10425
+ typeArguments,
10426
+ arguments: args
10427
+ });
10428
+ return tx;
10429
+ }
10430
+ // async mintByStrategySingle(params: MintByStrategySingleParams): Promise<Transaction> {}
10431
+ async mintByStrategy(params) {
10432
+ const tx = new Transaction12();
10433
+ const slippage = new Decimal10(params.slippage);
10434
+ const lower_slippage = new Decimal10(1).sub(slippage.div(new Decimal10(1e4)));
10435
+ const upper_slippage = new Decimal10(1).plus(slippage.div(new Decimal10(1e4)));
10436
+ tx.setSender(this.sdk.senderAddress);
10437
+ const { dlmm_pool, integrate } = this.sdk.sdkOptions;
10438
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10439
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10440
+ const price = get_price_x128_from_real_id3(params.active_bin, params.bin_step);
10441
+ const min_price = new Decimal10(price).mul(lower_slippage);
10442
+ const max_price = new Decimal10(price).mul(upper_slippage);
10443
+ const active_min = get_storage_id_from_real_id(get_real_id_from_price_x1282(min_price.toDecimalPlaces(0).toString(), params.bin_step));
10444
+ const active_max = get_storage_id_from_real_id(get_real_id_from_price_x1282(max_price.toDecimalPlaces(0).toString(), params.bin_step));
10445
+ const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10446
+ let primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountATotal), params.coinTypeA, false, true);
10447
+ let primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountBTotal), params.coinTypeB, false, true);
10448
+ let amount_min = 0;
10449
+ let amount_max = 0;
10450
+ if (params.fixCoinA) {
10451
+ amount_min = new Decimal10(params.amountBTotal).mul(lower_slippage).toDecimalPlaces(0).toNumber();
10452
+ amount_max = new Decimal10(params.amountBTotal).mul(upper_slippage).toDecimalPlaces(0).toNumber();
10453
+ primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amount_max), params.coinTypeB, false, true);
10454
+ }
10455
+ if (params.fixCoinB) {
10456
+ amount_min = new Decimal10(params.amountATotal).mul(lower_slippage).toDecimalPlaces(0).toNumber();
10457
+ amount_max = new Decimal10(params.amountATotal).mul(upper_slippage).toDecimalPlaces(0).toNumber();
10458
+ primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amount_max), params.coinTypeB, false, true);
10459
+ }
10460
+ if (params.fixCoinA && params.fixCoinB) {
10461
+ } else if (params.fixCoinA) {
10462
+ params.amountBTotal = 0;
10463
+ } else if (params.fixCoinB) {
10464
+ params.amountATotal = 0;
10465
+ }
10466
+ const args = [
10467
+ tx.object(params.pair),
10468
+ tx.object(dlmmConfig.factory),
10469
+ primaryCoinAInputs.targetCoin,
10470
+ primaryCoinBInputs.targetCoin,
10471
+ tx.pure.u64(params.amountATotal),
10472
+ tx.pure.u64(params.amountBTotal),
10473
+ tx.pure.u8(params.strategy),
10474
+ tx.pure.u32(get_storage_id_from_real_id(params.min_bin)),
10475
+ tx.pure.u32(get_storage_id_from_real_id(params.max_bin)),
10476
+ tx.pure.u32(active_min),
10477
+ tx.pure.u32(active_max),
10478
+ tx.pure.u64(amount_min),
10479
+ tx.pure.u64(amount_max),
10480
+ tx.object(CLOCK_ADDRESS)
10481
+ ];
10482
+ tx.moveCall({
10483
+ target: `${integrate.published_at}::${DlmmScript}::mint_by_strategy`,
10484
+ typeArguments,
10485
+ arguments: args
10486
+ });
10487
+ return tx;
10488
+ }
10489
+ // Create a position by percent
10490
+ async mintPercent(params) {
10491
+ const tx = new Transaction12();
10492
+ tx.setSender(this.sdk.senderAddress);
10493
+ const { dlmm_pool, integrate } = this.sdk.sdkOptions;
10494
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10495
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10496
+ const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10497
+ const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountATotal), params.coinTypeA, false, true);
10498
+ const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountBTotal), params.coinTypeB, false, true);
10499
+ const args = [
10500
+ tx.object(params.pair),
10501
+ tx.object(dlmmConfig.factory),
10502
+ primaryCoinAInputs.targetCoin,
10503
+ primaryCoinBInputs.targetCoin,
10504
+ tx.pure.u64(params.amountATotal),
10505
+ tx.pure.u64(params.amountBTotal),
10506
+ tx.pure.vector("u32", params.storageIds),
10507
+ tx.pure.vector("u64", params.binsAPercent),
10508
+ tx.pure.vector("u64", params.binsBPercent),
10509
+ tx.pure.address(params.to),
10510
+ tx.object(CLOCK_ADDRESS)
10511
+ ];
10512
+ tx.moveCall({
10513
+ target: `${integrate.published_at}::${DlmmScript}::mint_percent`,
10514
+ typeArguments,
10515
+ arguments: args
10516
+ });
10517
+ return tx;
10518
+ }
10519
+ // Create a position by amount
10520
+ async createPositionByAmount(params) {
10521
+ const tx = new Transaction12();
10522
+ tx.setSender(this.sdk.senderAddress);
10523
+ const { dlmm_pool, integrate } = this.sdk.sdkOptions;
10524
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10525
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10526
+ const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10527
+ const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountATotal), params.coinTypeA, false, true);
10528
+ const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountBTotal), params.coinTypeB, false, true);
10529
+ const args = [
10530
+ tx.object(params.pair),
10531
+ tx.object(dlmmConfig.factory),
10532
+ primaryCoinAInputs.targetCoin,
10533
+ primaryCoinBInputs.targetCoin,
10534
+ tx.pure.vector("u32", params.storageIds),
10535
+ tx.pure.vector("u64", params.amountsA),
10536
+ tx.pure.vector("u64", params.amountsB),
10537
+ tx.pure.address(params.to),
10538
+ tx.object(CLOCK_ADDRESS)
10539
+ ];
10540
+ tx.moveCall({
10541
+ target: `${integrate.published_at}::${DlmmScript}::mint_amounts`,
10542
+ typeArguments,
10543
+ arguments: args
10544
+ });
10545
+ return tx;
10546
+ }
10547
+ async addLiquidity(params) {
10548
+ if (params.rewards_token.length === 0) {
10549
+ return this._raisePositionByAmounts(params);
10550
+ }
10551
+ return this._raisePositionByAmountsReward(params);
10552
+ }
10553
+ async _raisePositionByAmounts(params) {
10554
+ const tx = new Transaction12();
10555
+ tx.setSender(this.sdk.senderAddress);
10556
+ const { dlmm_pool, integrate } = this.sdk.sdkOptions;
10557
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10558
+ const typeArguments = [params.coin_a, params.coin_b];
10559
+ const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10560
+ const amountATotal = params.amounts_a.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10561
+ const amountBTotal = params.amounts_b.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10562
+ const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountATotal), params.coin_a, false, true);
10563
+ const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountBTotal), params.coin_b, false, true);
10564
+ const args = [
10565
+ tx.object(params.pool_id),
10566
+ tx.object(dlmmConfig.factory),
10567
+ tx.object(params.position_id),
10568
+ primaryCoinAInputs.targetCoin,
10569
+ primaryCoinBInputs.targetCoin,
10570
+ tx.pure.vector("u64", params.amounts_a),
10571
+ tx.pure.vector("u64", params.amounts_b),
10572
+ tx.pure.address(params.receiver),
10573
+ tx.object(CLOCK_ADDRESS)
10574
+ ];
10575
+ tx.moveCall({
10576
+ target: `${integrate.published_at}::${DlmmScript}::raise_position_by_amounts`,
10577
+ typeArguments,
10578
+ arguments: args
10579
+ });
10580
+ return tx;
10581
+ }
10582
+ async _raisePositionByAmountsReward(params) {
10583
+ const tx = new Transaction12();
10584
+ tx.setSender(this.sdk.senderAddress);
10585
+ const { dlmm_pool, integrate, clmm_pool } = this.sdk.sdkOptions;
10586
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10587
+ const clmmConfigs = getPackagerConfigs(clmm_pool);
10588
+ const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
10589
+ const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10590
+ const amountATotal = params.amounts_a.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10591
+ const amountBTotal = params.amounts_b.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10592
+ const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountATotal), params.coin_a, false, true);
10593
+ const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountBTotal), params.coin_b, false, true);
10594
+ const args = [
10595
+ tx.object(params.pool_id),
10596
+ tx.object(dlmmConfig.factory),
10597
+ tx.object(clmmConfigs.global_vault_id),
10598
+ tx.object(params.position_id),
10599
+ primaryCoinAInputs.targetCoin,
10600
+ primaryCoinBInputs.targetCoin,
10601
+ tx.pure.vector("u64", params.amounts_a),
10602
+ tx.pure.vector("u64", params.amounts_b),
10603
+ tx.pure.address(params.receiver),
10604
+ tx.object(CLOCK_ADDRESS)
10605
+ ];
10606
+ tx.moveCall({
10607
+ target: `${integrate.published_at}::${DlmmScript}::raise_position_by_amounts_reward${params.rewards_token.length}`,
10608
+ typeArguments,
10609
+ arguments: args
10610
+ });
10611
+ return tx;
10612
+ }
10613
+ async burnPosition(params) {
10614
+ const tx = new Transaction12();
10615
+ tx.setSender(this.sdk.senderAddress);
10616
+ const { integrate, clmm_pool } = this.sdk.sdkOptions;
10617
+ const clmmConfigs = getPackagerConfigs(clmm_pool);
10618
+ const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
10619
+ let args = [tx.object(params.pool_id), tx.object(params.position_id), tx.object(CLOCK_ADDRESS)];
10620
+ let target = `${integrate.published_at}::${DlmmScript}::burn_position`;
10621
+ if (params.rewards_token.length > 0) {
10622
+ args = [tx.object(params.pool_id), tx.object(clmmConfigs.global_vault_id), tx.object(params.position_id), tx.object(CLOCK_ADDRESS)];
10623
+ target = `${integrate.published_at}::${DlmmScript}::burn_position_reward${params.rewards_token.length}`;
10624
+ }
10625
+ tx.moveCall({
10626
+ target,
10627
+ typeArguments,
10628
+ arguments: args
10629
+ });
10630
+ return tx;
10631
+ }
10632
+ async shrinkPosition(params) {
10633
+ const tx = new Transaction12();
10634
+ tx.setSender(this.sdk.senderAddress);
10635
+ const { integrate, clmm_pool } = this.sdk.sdkOptions;
10636
+ const clmmConfigs = getPackagerConfigs(clmm_pool);
10637
+ const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
10638
+ let args = [tx.object(params.pool_id), tx.object(params.position_id), tx.pure.u64(params.delta_percentage), tx.object(CLOCK_ADDRESS)];
10639
+ let target = `${integrate.published_at}::${DlmmScript}::shrink_position`;
10640
+ if (params.rewards_token.length > 0) {
10641
+ args = [
10642
+ tx.object(params.pool_id),
10643
+ tx.object(clmmConfigs.global_vault_id),
10644
+ tx.object(params.position_id),
10645
+ tx.pure.u64(params.delta_percentage),
10646
+ tx.object(CLOCK_ADDRESS)
10647
+ ];
10648
+ target = `${integrate.published_at}::${DlmmScript}::shrink_position_reward${params.rewards_token.length}`;
10649
+ }
10650
+ tx.moveCall({
10651
+ target,
10652
+ typeArguments,
10653
+ arguments: args
10654
+ });
10655
+ return tx;
10656
+ }
10657
+ async collectFeeAndReward(params) {
10658
+ let tx = new Transaction12();
10659
+ tx = await this.collectFees(params);
10660
+ if (params.rewards_token.length > 0) {
10661
+ tx = await this.collectReward(params);
10662
+ }
10663
+ return tx;
10664
+ }
10665
+ async collectReward(params, transaction) {
10666
+ const tx = transaction || new Transaction12();
10667
+ tx.setSender(this.sdk.senderAddress);
10668
+ const { integrate, clmm_pool } = this.sdk.sdkOptions;
10669
+ const clmmConfigs = getPackagerConfigs(clmm_pool);
10670
+ const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
10671
+ const args = [
10672
+ tx.object(params.pool_id),
10673
+ tx.object(clmmConfigs.global_vault_id),
10674
+ tx.object(params.position_id),
10675
+ tx.object(CLOCK_ADDRESS)
10676
+ ];
10677
+ let target = `${integrate.published_at}::${DlmmScript}::collect_reward`;
10678
+ if (params.rewards_token.length > 1) {
10679
+ target = `${integrate.published_at}::${DlmmScript}::collect_reward${params.rewards_token.length}`;
10680
+ }
10681
+ tx.moveCall({
10682
+ target,
10683
+ typeArguments,
10684
+ arguments: args
10685
+ });
10686
+ return tx;
10687
+ }
10688
+ async collectFees(params, transaction) {
10689
+ const tx = transaction || new Transaction12();
10690
+ tx.setSender(this.sdk.senderAddress);
10691
+ const { integrate } = this.sdk.sdkOptions;
10692
+ const typeArguments = [params.coin_a, params.coin_b];
10693
+ const args = [tx.object(params.pool_id), tx.object(params.position_id), tx.object(CLOCK_ADDRESS)];
10694
+ const target = `${integrate.published_at}::${DlmmScript}::collect_fees`;
10695
+ tx.moveCall({
10696
+ target,
10697
+ typeArguments,
10698
+ arguments: args
10699
+ });
10700
+ return tx;
10701
+ }
10702
+ async createPairAddLiquidity(params) {
10703
+ const tx = new Transaction12();
10704
+ tx.setSender(this.sdk.senderAddress);
10705
+ const { clmm_pool, dlmm_pool, integrate } = this.sdk.sdkOptions;
10706
+ const { global_config_id } = getPackagerConfigs(clmm_pool);
10707
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10708
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10709
+ const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10710
+ const amountATotal = params.amountsX.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10711
+ const amountBTotal = params.amountsY.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10712
+ const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountATotal), params.coinTypeA, false, true);
10713
+ const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountBTotal), params.coinTypeB, false, true);
10714
+ const storageIds = [];
10715
+ params.realIds.forEach((i) => {
10716
+ storageIds.push(get_storage_id_from_real_id(i));
10717
+ });
10718
+ const args = [
10719
+ tx.object(dlmmConfig.factory),
10720
+ tx.object(global_config_id),
10721
+ tx.pure.u64(params.baseFee),
10722
+ tx.pure.u16(params.binStep),
10723
+ tx.pure.u32(get_storage_id_from_real_id(params.activeId)),
10724
+ primaryCoinAInputs.targetCoin,
10725
+ primaryCoinBInputs.targetCoin,
10726
+ tx.pure.vector("u32", storageIds),
10727
+ tx.pure.vector("u64", params.amountsX),
10728
+ tx.pure.vector("u64", params.amountsY),
10729
+ tx.pure.address(params.to),
10730
+ tx.object(CLOCK_ADDRESS)
10731
+ ];
10732
+ const target = `${integrate.published_at}::${DlmmScript}::create_pair_add_liquidity`;
10733
+ tx.moveCall({
10734
+ target,
10735
+ typeArguments,
10736
+ arguments: args
10737
+ });
10738
+ return tx;
10739
+ }
10740
+ async swap(params) {
10741
+ const tx = new Transaction12();
10742
+ tx.setSender(this.sdk.senderAddress);
10743
+ const { clmm_pool, integrate } = this.sdk.sdkOptions;
10744
+ const { global_config_id } = getPackagerConfigs(clmm_pool);
10745
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10746
+ const allCoinAsset = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10747
+ const primaryCoinInputA = TransactionUtil.buildCoinForAmount(
10748
+ tx,
10749
+ allCoinAsset,
10750
+ params.swapForY ? BigInt(params.amountIn) : BigInt(0),
10751
+ params.coinTypeA,
10752
+ false,
10753
+ true
10754
+ );
10755
+ const primaryCoinInputB = TransactionUtil.buildCoinForAmount(
10756
+ tx,
10757
+ allCoinAsset,
10758
+ params.swapForY ? BigInt(0) : BigInt(params.amountIn),
10759
+ params.coinTypeB,
10760
+ false,
10761
+ true
10762
+ );
10763
+ const args = [
10764
+ tx.object(params.pair),
10765
+ tx.object(global_config_id),
10766
+ primaryCoinInputA.targetCoin,
10767
+ primaryCoinInputB.targetCoin,
10768
+ tx.pure.u64(params.amountIn),
10769
+ tx.pure.u64(params.minAmountOut),
10770
+ tx.pure.bool(params.swapForY),
10771
+ tx.pure.address(params.to),
10772
+ tx.object(CLOCK_ADDRESS)
10773
+ ];
10774
+ tx.moveCall({
10775
+ target: `${integrate.published_at}::${DlmmScript}::swap`,
10776
+ typeArguments,
10777
+ arguments: args
10778
+ });
10779
+ return tx;
10780
+ }
10781
+ async fetchBins(params) {
10782
+ const tx = new Transaction12();
10783
+ const { integrate, simulationAccount } = this.sdk.sdkOptions;
10784
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10785
+ const args = [tx.object(params.pair), tx.pure.u64(params.offset), tx.pure.u64(params.limit)];
10786
+ tx.moveCall({
10787
+ target: `${integrate.published_at}::${DlmmScript}::fetch_bins`,
10788
+ arguments: args,
10789
+ typeArguments
10790
+ });
10791
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
10792
+ transactionBlock: tx,
10793
+ sender: simulationAccount.address
10794
+ });
10795
+ if (simulateRes.error != null) {
10796
+ throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
10797
+ }
10798
+ let res = [];
10799
+ simulateRes.events?.forEach((item) => {
10800
+ if (extractStructTagFromType(item.type).name === `EventFetchBins`) {
10801
+ const { bins } = item.parsedJson;
10802
+ res = bins;
10803
+ }
10804
+ });
10805
+ return res;
10806
+ }
10807
+ /**
10808
+ * Gets a list of positions for the given account address.
10809
+ * @param accountAddress The account address to get positions for.
10810
+ * @param assignPoolIds An array of pool IDs to filter the positions by.
10811
+ * @returns array of Position objects.
10812
+ */
10813
+ async getUserPositionById(positionId, showDisplay = true) {
10814
+ let position;
10815
+ const ownerRes = await this._sdk.fullClient.getObject({
10816
+ id: positionId,
10817
+ options: { showContent: true, showType: true, showDisplay, showOwner: true }
10818
+ });
10819
+ const type = extractStructTagFromType(ownerRes.data.type);
10820
+ if (type.full_address === this.buildPositionType()) {
10821
+ position = this.buildPosition(ownerRes);
10822
+ } else {
10823
+ throw new ClmmpoolsError(`Dlmm Position not exists. Get Position error:${ownerRes.error}`, "InvalidPositionObject" /* InvalidPositionObject */);
10824
+ }
10825
+ const poolMap = /* @__PURE__ */ new Set();
10826
+ poolMap.add(position.pool);
10827
+ const pool = (await this.getPoolInfo(Array.from(poolMap)))[0];
10828
+ const _params = [];
10829
+ _params.push({
10830
+ pool_id: pool.pool_id,
10831
+ coin_a: pool.coin_a,
10832
+ coin_b: pool.coin_b
10833
+ });
10834
+ const pool_reward_coins = await this.getPairRewarders(_params);
10835
+ const positionLiquidity = await this.getPositionLiquidity({
10836
+ pair: position.pool,
10837
+ positionId: position.pos_object_id,
10838
+ coinTypeA: pool.coin_a,
10839
+ coinTypeB: pool.coin_b
10840
+ });
10841
+ const rewards_token = pool_reward_coins.get(position.pool) || [];
10842
+ let positionRewards = { position_id: position.pos_object_id, reward: [], amount: [] };
10843
+ if (rewards_token.length > 0) {
10844
+ positionRewards = await this.getEarnedRewards({
10845
+ pool_id: position.pool,
10846
+ position_id: position.pos_object_id,
10847
+ coin_a: pool.coin_a,
10848
+ coin_b: pool.coin_b,
10849
+ rewards_token: pool_reward_coins.get(position.pool) || []
10850
+ });
10851
+ }
10852
+ const positionFees = await this.getEarnedFees({
10853
+ pool_id: position.pool,
10854
+ position_id: position.pos_object_id,
10855
+ coin_a: pool.coin_a,
10856
+ coin_b: pool.coin_b
10857
+ });
10858
+ return {
10859
+ position,
10860
+ liquidity: positionLiquidity,
10861
+ rewards: positionRewards,
10862
+ fees: positionFees,
10863
+ contractPool: pool
10864
+ };
10865
+ }
10866
+ /**
10867
+ * Gets a list of positions for the given account address.
10868
+ * @param accountAddress The account address to get positions for.
10869
+ * @param assignPoolIds An array of pool IDs to filter the positions by.
10870
+ * @returns array of Position objects.
10871
+ */
10872
+ async getUserPositions(accountAddress, assignPoolIds = [], showDisplay = true) {
10873
+ const allPosition = [];
10874
+ const ownerRes = await this._sdk.fullClient.getOwnedObjectsByPage(accountAddress, {
10875
+ options: { showType: true, showContent: true, showDisplay, showOwner: true },
10876
+ filter: { Package: this._sdk.sdkOptions.dlmm_pool.package_id }
10877
+ });
10878
+ const hasAssignPoolIds = assignPoolIds.length > 0;
10879
+ for (const item of ownerRes.data) {
10880
+ const type = extractStructTagFromType(item.data.type);
10881
+ if (type.full_address === this.buildPositionType()) {
10882
+ const position = this.buildPosition(item);
10883
+ const cacheKey = `${position.pos_object_id}_getPositionList`;
10884
+ this.updateCache(cacheKey, position, cacheTime24h);
10885
+ if (hasAssignPoolIds) {
10886
+ if (assignPoolIds.includes(position.pool)) {
10887
+ allPosition.push(position);
10888
+ }
10889
+ } else {
10890
+ allPosition.push(position);
10891
+ }
10892
+ }
10893
+ }
10894
+ const poolMap = /* @__PURE__ */ new Set();
10895
+ for (const item of allPosition) {
10896
+ poolMap.add(item.pool);
10897
+ }
10898
+ const poolList = await this.getPoolInfo(Array.from(poolMap));
10899
+ this.updateCache(`${DlmmScript}_positionList_poolList`, poolList, cacheTime24h);
10900
+ const _params = [];
10901
+ for (const pool of poolList) {
10902
+ _params.push({
10903
+ pool_id: pool.pool_id,
10904
+ coin_a: pool.coin_a,
10905
+ coin_b: pool.coin_b
10906
+ });
10907
+ }
10908
+ const pool_reward_coins = await this.getPairRewarders(_params);
10909
+ const out = [];
10910
+ for (const item of allPosition) {
10911
+ const pool = poolList.find((pool2) => pool2.pool_id === item.pool);
10912
+ const positionLiquidity = await this.getPositionLiquidity({
10913
+ pair: item.pool,
10914
+ positionId: item.pos_object_id,
10915
+ coinTypeA: pool.coin_a,
10916
+ coinTypeB: pool.coin_b
10917
+ });
10918
+ const rewards_token = pool_reward_coins.get(item.pool) || [];
10919
+ let positionRewards = { position_id: item.pos_object_id, reward: [], amount: [] };
10920
+ if (rewards_token.length > 0) {
10921
+ positionRewards = await this.getEarnedRewards({
10922
+ pool_id: item.pool,
10923
+ position_id: item.pos_object_id,
10924
+ coin_a: pool.coin_a,
10925
+ coin_b: pool.coin_b,
10926
+ rewards_token: pool_reward_coins.get(item.pool) || []
10927
+ });
10928
+ }
10929
+ const positionFees = await this.getEarnedFees({
10930
+ pool_id: item.pool,
10931
+ position_id: item.pos_object_id,
10932
+ coin_a: pool.coin_a,
10933
+ coin_b: pool.coin_b
10934
+ });
10935
+ out.push({
10936
+ position: item,
10937
+ liquidity: positionLiquidity,
10938
+ rewards: positionRewards,
10939
+ fees: positionFees,
10940
+ contractPool: pool
10941
+ });
10942
+ }
10943
+ return out;
10944
+ }
10945
+ buildPosition(object) {
10946
+ if (object.error != null || object.data?.content?.dataType !== "moveObject") {
10947
+ throw new ClmmpoolsError(`Dlmm Position not exists. Get Position error:${object.error}`, "InvalidPositionObject" /* InvalidPositionObject */);
10948
+ }
10949
+ const fields = getObjectFields(object);
10950
+ const ownerWarp = getObjectOwner(object);
10951
+ return {
10952
+ pos_object_id: fields.id.id,
10953
+ owner: ownerWarp.AddressOwner,
10954
+ pool: fields.pair_id,
10955
+ bin_real_ids: fields.bin_ids.map((id) => get_real_id(id)),
10956
+ type: ""
10957
+ };
10958
+ }
10959
+ // return [coin_a, coin_b]
10960
+ async getPoolCoins(pools) {
10961
+ const res = await this._sdk.fullClient.multiGetObjects({ ids: pools, options: { showContent: true } });
10962
+ const poolCoins = /* @__PURE__ */ new Map();
10963
+ res.forEach((item) => {
10964
+ if (item.error != null || item.data?.content?.dataType !== "moveObject") {
10965
+ throw new Error(`Failed to get poolCoins with err: ${item.error}`);
10966
+ }
10967
+ const type = getObjectType(item);
10968
+ const poolTypeFields = extractStructTagFromType(type);
10969
+ poolCoins.set(item.data.objectId, poolTypeFields.type_arguments);
10970
+ });
10971
+ return poolCoins;
10972
+ }
10973
+ buildPositionType() {
10974
+ return `${this._sdk.sdkOptions.dlmm_pool.package_id}::dlmm_position::Position`;
10975
+ }
10976
+ async getPositionLiquidity(params) {
10977
+ const tx = new Transaction12();
10978
+ const { integrate, simulationAccount } = this.sdk.sdkOptions;
10979
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10980
+ const args = [tx.object(params.pair), tx.object(params.positionId)];
10981
+ tx.moveCall({
10982
+ target: `${integrate.published_at}::${DlmmScript}::position_liquidity`,
10983
+ arguments: args,
10984
+ typeArguments
10985
+ });
10986
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
10987
+ transactionBlock: tx,
10988
+ sender: simulationAccount.address
10989
+ });
10990
+ if (simulateRes.error != null) {
10991
+ throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
10992
+ }
10993
+ const out = {
10994
+ shares: 0,
10995
+ liquidity: 0,
10996
+ x_equivalent: 0,
10997
+ y_equivalent: 0,
10998
+ bin_real_ids: [],
10999
+ bin_x_eq: [],
11000
+ bin_y_eq: [],
11001
+ bin_liquidity: []
11002
+ };
11003
+ simulateRes.events?.forEach((item) => {
11004
+ if (extractStructTagFromType(item.type).name === `EventPositionLiquidity`) {
11005
+ out.shares = item.parsedJson.shares;
11006
+ out.liquidity = item.parsedJson.liquidity;
11007
+ out.x_equivalent = item.parsedJson.x_equivalent;
11008
+ out.y_equivalent = item.parsedJson.y_equivalent;
11009
+ out.bin_real_ids = item.parsedJson.bin_ids.map((id) => get_real_id(id));
11010
+ out.bin_x_eq = item.parsedJson.bin_x_eq;
11011
+ out.bin_y_eq = item.parsedJson.bin_y_eq;
11012
+ out.bin_liquidity = item.parsedJson.bin_liquidity;
11013
+ }
11014
+ });
11015
+ return out;
11016
+ }
11017
+ async getPairLiquidity(params) {
11018
+ const tx = new Transaction12();
11019
+ const { integrate, simulationAccount } = this.sdk.sdkOptions;
11020
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
11021
+ const args = [tx.object(params.pair)];
11022
+ tx.moveCall({
11023
+ target: `${integrate.published_at}::${DlmmScript}::pair_liquidity`,
11024
+ arguments: args,
11025
+ typeArguments
11026
+ });
11027
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11028
+ transactionBlock: tx,
11029
+ sender: simulationAccount.address
11030
+ });
11031
+ if (simulateRes.error != null) {
11032
+ throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
11033
+ }
11034
+ const out = {
11035
+ shares: 0,
11036
+ liquidity: 0,
11037
+ x: 0,
11038
+ y: 0,
11039
+ bin_ids: [],
11040
+ bin_x: [],
11041
+ bin_y: []
11042
+ };
11043
+ simulateRes.events?.forEach((item) => {
11044
+ if (extractStructTagFromType(item.type).name === `EventPositionLiquidity`) {
11045
+ out.shares = item.parsedJson.shares;
11046
+ out.liquidity = item.parsedJson.liquidity;
11047
+ out.x = item.parsedJson.x;
11048
+ out.y = item.parsedJson.y;
11049
+ out.bin_ids = item.bin_ids;
11050
+ out.bin_x = item.bin_x;
11051
+ out.bin_y = item.bin_y;
11052
+ }
11053
+ });
11054
+ return out;
11055
+ }
11056
+ async getEarnedFees(params) {
11057
+ const tx = new Transaction12();
11058
+ const { integrate, simulationAccount } = this.sdk.sdkOptions;
11059
+ const typeArguments = [params.coin_a, params.coin_b];
11060
+ const args = [tx.object(params.pool_id), tx.object(params.position_id)];
11061
+ tx.moveCall({
11062
+ target: `${integrate.published_at}::${DlmmScript}::earned_fees`,
11063
+ arguments: args,
11064
+ typeArguments
11065
+ });
11066
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11067
+ transactionBlock: tx,
11068
+ sender: simulationAccount.address
11069
+ });
11070
+ const out = {
11071
+ position_id: "",
11072
+ x: "",
11073
+ y: "",
11074
+ fee_x: 0,
11075
+ fee_y: 0
11076
+ };
11077
+ if (simulateRes.error != null) {
11078
+ throw new Error(`fetchPairRewards error code: ${simulateRes.error ?? "unknown error"}`);
11079
+ }
11080
+ simulateRes.events?.forEach((item) => {
11081
+ if (extractStructTagFromType(item.type).name === `EventPositionLiquidity`) {
11082
+ out.position_id = item.parsedJson.position_id;
11083
+ out.x = item.parsedJson.x;
11084
+ out.y = item.parsedJson.y;
11085
+ out.fee_x = item.parsedJson.fee_x;
11086
+ out.fee_y = item.parsedJson.fee_y;
11087
+ }
11088
+ });
11089
+ return out;
11090
+ }
11091
+ async getEarnedRewards(params) {
11092
+ const tx = new Transaction12();
11093
+ const { integrate, simulationAccount } = this.sdk.sdkOptions;
11094
+ const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
11095
+ const args = [tx.object(params.pool_id), tx.object(params.position_id), tx.object(CLOCK_ADDRESS)];
11096
+ let target = `${integrate.published_at}::${DlmmScript}::earned_rewards`;
11097
+ if (params.rewards_token.length > 1) {
11098
+ target = `${integrate.published_at}::${DlmmScript}::earned_rewards${params.rewards_token.length}`;
11099
+ }
11100
+ tx.moveCall({
11101
+ target,
11102
+ arguments: args,
11103
+ typeArguments
11104
+ });
11105
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11106
+ transactionBlock: tx,
11107
+ sender: simulationAccount.address
11108
+ });
11109
+ const out = {
11110
+ position_id: "",
11111
+ reward: [],
11112
+ amount: []
11113
+ };
11114
+ if (simulateRes.error != null) {
11115
+ throw new Error(`getEarnedRewards error code: ${simulateRes.error ?? "unknown error"}`);
11116
+ }
11117
+ simulateRes.events?.forEach((item) => {
11118
+ if (extractStructTagFromType(item.type).name === `DlmmEventEarnedRewards`) {
11119
+ out.position_id = item.parsedJson.position_id;
11120
+ out.reward = [item.parsedJson.reward];
11121
+ out.amount = [item.parsedJson.amount];
11122
+ } else if (extractStructTagFromType(item.type).name === `DlmmEventEarnedRewards2`) {
11123
+ out.position_id = item.parsedJson.position_id;
11124
+ out.reward = [item.parsedJson.reward1, item.parsedJson.reward2];
11125
+ out.amount = [item.parsedJson.amount1, item.parsedJson.amount2];
11126
+ } else if (extractStructTagFromType(item.type).name === `EventEarnedRewards3`) {
11127
+ out.position_id = item.parsedJson.position_id;
11128
+ out.reward = [item.parsedJson.reward1, item.parsedJson.reward2, item.parsedJson.reward3];
11129
+ out.amount = [item.parsedJson.amount1, item.parsedJson.amount2, item.parsedJson.amount3];
11130
+ }
11131
+ });
11132
+ return out;
11133
+ }
11134
+ // return pool_id => reward_tokens
11135
+ async getPairRewarders(params) {
11136
+ let tx = new Transaction12();
11137
+ for (const param of params) {
11138
+ tx = await this._getPairRewarders(param, tx);
11139
+ }
11140
+ return this._parsePairRewarders(tx);
11141
+ }
11142
+ async _getPairRewarders(params, tx) {
11143
+ tx = tx || new Transaction12();
11144
+ const { integrate } = this.sdk.sdkOptions;
11145
+ const typeArguments = [params.coin_a, params.coin_b];
11146
+ const args = [tx.object(params.pool_id)];
11147
+ tx.moveCall({
11148
+ target: `${integrate.published_at}::${DlmmScript}::get_pair_rewarders`,
11149
+ arguments: args,
11150
+ typeArguments
11151
+ });
11152
+ return tx;
11153
+ }
11154
+ async _parsePairRewarders(tx) {
11155
+ const { simulationAccount } = this.sdk.sdkOptions;
11156
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11157
+ transactionBlock: tx,
11158
+ sender: simulationAccount.address
11159
+ });
11160
+ const out = /* @__PURE__ */ new Map();
11161
+ if (simulateRes.error != null) {
11162
+ throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
11163
+ }
11164
+ simulateRes.events?.forEach((item) => {
11165
+ if (extractStructTagFromType(item.type).name === `EventPairRewardTypes`) {
11166
+ const pairRewards = {
11167
+ pair_id: "",
11168
+ tokens: []
11169
+ };
11170
+ pairRewards.pair_id = item.parsedJson.pair_id;
11171
+ item.parsedJson.tokens.forEach((token) => {
11172
+ pairRewards.tokens.push(token.name);
11173
+ });
11174
+ out.set(pairRewards.pair_id, pairRewards.tokens);
11175
+ }
11176
+ });
11177
+ return out;
11178
+ }
11179
+ /**
11180
+ * Updates the cache for the given key.
11181
+ *
11182
+ * @param key The key of the cache entry to update.
11183
+ * @param data The data to store in the cache.
11184
+ * @param time The time in minutes after which the cache entry should expire.
11185
+ */
11186
+ updateCache(key, data, time = cacheTime5min) {
11187
+ let cacheData = this._cache[key];
11188
+ if (cacheData) {
11189
+ cacheData.overdueTime = getFutureTime(time);
11190
+ cacheData.value = data;
11191
+ } else {
11192
+ cacheData = new CachedContent(data, getFutureTime(time));
11193
+ }
11194
+ this._cache[key] = cacheData;
11195
+ }
11196
+ /**
11197
+ * Gets the cache entry for the given key.
11198
+ *
11199
+ * @param key The key of the cache entry to get.
11200
+ * @param forceRefresh Whether to force a refresh of the cache entry.
11201
+ * @returns The cache entry for the given key, or undefined if the cache entry does not exist or is expired.
11202
+ */
11203
+ getCache(key, forceRefresh = false) {
11204
+ const cacheData = this._cache[key];
11205
+ const isValid = cacheData?.isValid();
11206
+ if (!forceRefresh && isValid) {
11207
+ return cacheData.value;
11208
+ }
11209
+ if (!isValid) {
11210
+ delete this._cache[key];
11211
+ }
11212
+ return void 0;
11213
+ }
11214
+ };
11215
+
11216
+ // src/sdk.ts
11217
+ var MagmaClmmSDK = class {
11218
+ _cache = {};
11219
+ /**
11220
+ * RPC provider on the SUI chain
11221
+ */
11222
+ _rpcModule;
11223
+ /**
11224
+ * Provide interact with clmm pools with a pool router interface.
11225
+ */
11226
+ _pool;
11227
+ /**
11228
+ * Provide interact with clmm position with a position router interface.
11229
+ */
11230
+ _position;
11231
+ /**
11232
+ * Provide interact with a pool swap router interface.
11233
+ */
11234
+ _swap;
11235
+ /**
11236
+ * Provide interact with a lock interface.
11237
+ */
11238
+ _lock;
11239
+ _gauge;
11240
+ _dlmm;
11241
+ /**
11242
+ * Provide interact with a position rewarder interface.
11243
+ */
11244
+ _rewarder;
11245
+ /**
11246
+ * Provide interact with a pool router interface.
11247
+ */
11248
+ _router;
11249
+ /**
11250
+ * Provide interact with a pool routerV2 interface.
11251
+ */
11252
+ _router_v2;
11253
+ /**
11254
+ * Provide interact with pool and token config (contain token base info for metadat).
11255
+ * @deprecated Please use MagmaConfig instead
11256
+ */
11257
+ _token;
11258
+ /**
11259
+ * Provide interact with clmm pool and coin and launchpad pool config
11260
+ */
11261
+ _config;
11262
+ /**
11263
+ * Provide sdk options
11264
+ */
11265
+ _sdkOptions;
11266
+ /**
11267
+ * After connecting the wallet, set the current wallet address to senderAddress.
11268
+ */
11269
+ _senderAddress = "";
11270
+ constructor(options) {
11271
+ this._sdkOptions = options;
11272
+ this._rpcModule = new RpcModule({
11273
+ url: options.fullRpcUrl
11274
+ });
9862
11275
  this._swap = new SwapModule(this);
9863
11276
  this._lock = new LockModule(this);
9864
11277
  this._gauge = new GaugeModule(this);
11278
+ this._dlmm = new DlmmModule(this);
9865
11279
  this._pool = new PoolModule(this);
9866
11280
  this._position = new PositionModule(this);
9867
11281
  this._rewarder = new RewarderModule(this);
@@ -9899,6 +11313,9 @@ var MagmaClmmSDK = class {
9899
11313
  get Gauge() {
9900
11314
  return this._gauge;
9901
11315
  }
11316
+ get Dlmm() {
11317
+ return this._dlmm;
11318
+ }
9902
11319
  /**
9903
11320
  * Getter for the fullClient property.
9904
11321
  * @returns {RpcModule} The fullClient property value.
@@ -10072,6 +11489,7 @@ var main_default = MagmaClmmSDK;
10072
11489
  var SDKConfig = {
10073
11490
  clmmConfig: {
10074
11491
  pools_id: "0xfa145b9de10fe858be81edd1c6cdffcf27be9d016de02a1345eb1009a68ba8b2",
11492
+ // clmm and dlmm both use this global_config
10075
11493
  global_config_id: "0x4c4e1402401f72c7d8533d0ed8d5f8949da363c7a3319ccef261ffe153d32f8a",
10076
11494
  global_vault_id: "0xa7e1102f222b6eb81ccc8a126e7feb2353342be9df6f6646a77c4519da29c071",
10077
11495
  admin_cap_id: "0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75"
@@ -10091,7 +11509,11 @@ var SDKConfig = {
10091
11509
  distribution_cfg: "0xaff8d151ac29317201151f97d28c546b3c5923d8cfc5499f40dea61c4022c949",
10092
11510
  magma_token: "0x7161c6c6bb65f852797c8f7f5c4f8d57adaf796e1b840921f9e23fabeadfd54e::magma::MAGMA",
10093
11511
  minter_id: "0x4fa5766cd83b33b215b139fec27ac344040f3bbd84fcbee7b61fc671aadc51fa"
10094
- }
11512
+ },
11513
+ dlmmConfig: {
11514
+ factory: ""
11515
+ },
11516
+ gaugeConfig: {}
10095
11517
  };
10096
11518
  var clmmMainnet = {
10097
11519
  fullRpcUrl: getFullnodeUrl("mainnet"),
@@ -10108,6 +11530,11 @@ var clmmMainnet = {
10108
11530
  published_at: "0x4a35d3dfef55ed3631b7158544c6322a23bc434fe4fca1234cb680ce0505f82d",
10109
11531
  config: SDKConfig.clmmConfig
10110
11532
  },
11533
+ dlmm_pool: {
11534
+ package_id: "",
11535
+ published_at: "",
11536
+ config: SDKConfig.dlmmConfig
11537
+ },
10111
11538
  distribution: {
10112
11539
  package_id: "0xee4a1f231dc45a303389998fe26c4e39278cf68b404b32e4f0b9769129b8267b",
10113
11540
  published_at: "0xee4a1f231dc45a303389998fe26c4e39278cf68b404b32e4f0b9769129b8267b"
@@ -10161,6 +11588,9 @@ var SDKConfig2 = {
10161
11588
  distribution_cfg: "0x94e23846c975e2faf89a61bfc2b10ad64decab9069eb1f9fc39752b010868c74",
10162
11589
  magma_token: "0x45ac2371c33ca0df8dc784d62c8ce5126d42edd8c56820396524dff2ae0619b1::magma_token::MAGMA_TOKEN",
10163
11590
  minter_id: "0x89435d6b2a510ba50ca23303f10e91ec058f138a88f69a43fe03cd22edb214c5"
11591
+ },
11592
+ dlmmConfig: {
11593
+ factory: ""
10164
11594
  }
10165
11595
  };
10166
11596
  var clmmTestnet = {
@@ -10175,6 +11605,11 @@ var clmmTestnet = {
10175
11605
  published_at: "0x23e0b5ab4aa63d0e6fd98fa5e247bcf9b36ad716b479d39e56b2ba9ff631e09d",
10176
11606
  config: SDKConfig2.clmmConfig
10177
11607
  },
11608
+ dlmm_pool: {
11609
+ package_id: "",
11610
+ published_at: "",
11611
+ config: SDKConfig2.dlmmConfig
11612
+ },
10178
11613
  distribution: {
10179
11614
  package_id: "0x45ac2371c33ca0df8dc784d62c8ce5126d42edd8c56820396524dff2ae0619b1",
10180
11615
  published_at: "0x45ac2371c33ca0df8dc784d62c8ce5126d42edd8c56820396524dff2ae0619b1"
@@ -10222,6 +11657,7 @@ var src_default = MagmaClmmSDK;
10222
11657
  export {
10223
11658
  AMM_SWAP_MODULE,
10224
11659
  AmountSpecified,
11660
+ BinMath,
10225
11661
  CLOCK_ADDRESS,
10226
11662
  CachedContent,
10227
11663
  ClmmExpectSwapModule,
@@ -10249,6 +11685,7 @@ export {
10249
11685
  DeepbookCustodianV2Moudle,
10250
11686
  DeepbookEndpointsV2Moudle,
10251
11687
  DeepbookUtils,
11688
+ DlmmScript,
10252
11689
  FEE_RATE_DENOMINATOR,
10253
11690
  GAS_SYMBOL,
10254
11691
  GAS_TYPE_ARG,
@@ -10276,6 +11713,7 @@ export {
10276
11713
  SUI_SYSTEM_STATE_OBJECT_ID,
10277
11714
  SplitSwap,
10278
11715
  SplitUnit,
11716
+ StrategyType,
10279
11717
  SwapDirection,
10280
11718
  SwapModule,
10281
11719
  SwapUtils,
@@ -10297,6 +11735,10 @@ export {
10297
11735
  adjustForSlippage,
10298
11736
  asIntN,
10299
11737
  asUintN,
11738
+ autoFillXByStrategy,
11739
+ autoFillXByWeight,
11740
+ autoFillYByStrategy,
11741
+ autoFillYByWeight,
10300
11742
  bufferToHex,
10301
11743
  buildClmmPositionName,
10302
11744
  buildNFT,
@@ -10335,12 +11777,14 @@ export {
10335
11777
  getAmountUnfixedDelta,
10336
11778
  getCoinAFromLiquidity,
10337
11779
  getCoinBFromLiquidity,
11780
+ getCoinXYForLiquidity,
10338
11781
  getDefaultSuiInputType,
10339
11782
  getDeltaA,
10340
11783
  getDeltaB,
10341
11784
  getDeltaDownFromOutput,
10342
11785
  getDeltaUpFromInput,
10343
11786
  getFutureTime,
11787
+ getLiquidityAndCoinYByCoinX,
10344
11788
  getLiquidityFromCoinA,
10345
11789
  getLiquidityFromCoinB,
10346
11790
  getLowerSqrtPriceFromCoinA,
@@ -10364,6 +11808,7 @@ export {
10364
11808
  getObjectType,
10365
11809
  getObjectVersion,
10366
11810
  getPackagerConfigs,
11811
+ getPriceOfBinByBinId,
10367
11812
  getRewardInTickRange,
10368
11813
  getSuiObjectData,
10369
11814
  getTickDataFromUrlData,
@@ -10387,10 +11832,15 @@ export {
10387
11832
  shortAddress,
10388
11833
  shortString,
10389
11834
  tickScore,
11835
+ toAmountAskSide,
11836
+ toAmountBidSide,
11837
+ toAmountBothSide,
11838
+ toAmountsBothSideByStrategy,
10390
11839
  toBuffer,
10391
11840
  toCoinAmount,
10392
11841
  toDecimalsAmount,
10393
11842
  transClmmpoolDataWithoutTicks,
10394
- utf8to16
11843
+ utf8to16,
11844
+ withLiquiditySlippage
10395
11845
  };
10396
11846
  //# sourceMappingURL=index.mjs.map