@magmaprotocol/magma-clmm-sdk 0.5.77 → 0.5.79

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,512 @@ 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 || amountX.isZero()) {
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 || amountY.isZero()) {
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 toWeightDecendingOrder(minBinId, maxBinId) {
1884
+ const distributions = [];
1885
+ for (let i = minBinId; i <= maxBinId; i++) {
1886
+ distributions.push({
1887
+ binId: i,
1888
+ weight: maxBinId - i + 1
1889
+ });
1890
+ }
1891
+ return distributions;
1892
+ }
1893
+ function toWeightAscendingOrder(minBinId, maxBinId) {
1894
+ const distributions = [];
1895
+ for (let i = minBinId; i <= maxBinId; i++) {
1896
+ distributions.push({
1897
+ binId: i,
1898
+ weight: i - minBinId + 1
1899
+ });
1900
+ }
1901
+ return distributions;
1902
+ }
1903
+ function toWeightSpotBalanced(minBinId, maxBinId) {
1904
+ const distributions = [];
1905
+ for (let i = minBinId; i <= maxBinId; i++) {
1906
+ distributions.push({
1907
+ binId: i,
1908
+ weight: 1
1909
+ });
1910
+ }
1911
+ return distributions;
1912
+ }
1913
+ var DEFAULT_MAX_WEIGHT = 2e3;
1914
+ var DEFAULT_MIN_WEIGHT = 200;
1915
+ function toWeightCurve(minBinId, maxBinId, activeId) {
1916
+ if (activeId < minBinId || activeId > maxBinId) {
1917
+ throw new ClmmpoolsError("Invalid strategy params", "InvalidParams" /* InvalidParams */);
1918
+ }
1919
+ const maxWeight = DEFAULT_MAX_WEIGHT;
1920
+ const minWeight = DEFAULT_MIN_WEIGHT;
1921
+ const diffWeight = maxWeight - minWeight;
1922
+ const diffMinWeight = activeId > minBinId ? Math.floor(diffWeight / (activeId - minBinId)) : 0;
1923
+ const diffMaxWeight = maxBinId > activeId ? Math.floor(diffWeight / (maxBinId - activeId)) : 0;
1924
+ const distributions = [];
1925
+ for (let i = minBinId; i <= maxBinId; i++) {
1926
+ if (i < activeId) {
1927
+ distributions.push({
1928
+ binId: i,
1929
+ weight: maxWeight - (activeId - i) * diffMinWeight
1930
+ });
1931
+ } else if (i > activeId) {
1932
+ distributions.push({
1933
+ binId: i,
1934
+ weight: maxWeight - (i - activeId) * diffMaxWeight
1935
+ });
1936
+ } else {
1937
+ distributions.push({
1938
+ binId: i,
1939
+ weight: maxWeight
1940
+ });
1941
+ }
1942
+ }
1943
+ return distributions;
1944
+ }
1945
+ function toWeightBidAsk(minBinId, maxBinId, activeId) {
1946
+ if (activeId < minBinId || activeId > maxBinId) {
1947
+ throw new ClmmpoolsError("Invalid strategy params", "InvalidParams" /* InvalidParams */);
1948
+ }
1949
+ const maxWeight = DEFAULT_MAX_WEIGHT;
1950
+ const minWeight = DEFAULT_MIN_WEIGHT;
1951
+ const diffWeight = maxWeight - minWeight;
1952
+ const diffMinWeight = activeId > minBinId ? Math.floor(diffWeight / (activeId - minBinId)) : 0;
1953
+ const diffMaxWeight = maxBinId > activeId ? Math.floor(diffWeight / (maxBinId - activeId)) : 0;
1954
+ const distributions = [];
1955
+ for (let i = minBinId; i <= maxBinId; i++) {
1956
+ if (i < activeId) {
1957
+ distributions.push({
1958
+ binId: i,
1959
+ weight: minWeight + (activeId - i) * diffMinWeight
1960
+ });
1961
+ } else if (i > activeId) {
1962
+ distributions.push({
1963
+ binId: i,
1964
+ weight: minWeight + (i - activeId) * diffMaxWeight
1965
+ });
1966
+ } else {
1967
+ distributions.push({
1968
+ binId: i,
1969
+ weight: minWeight
1970
+ });
1971
+ }
1972
+ }
1973
+ return distributions;
1974
+ }
1975
+ function autoFillYByStrategy(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, minBinId, maxBinId, strategyType) {
1976
+ switch (strategyType) {
1977
+ case 1 /* Spot */: {
1978
+ const weights = toWeightSpotBalanced(minBinId, maxBinId);
1979
+ return autoFillYByWeight(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, weights);
1980
+ }
1981
+ case 2 /* Curve */: {
1982
+ const weights = toWeightCurve(minBinId, maxBinId, activeId);
1983
+ return autoFillYByWeight(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, weights);
1984
+ }
1985
+ case 3 /* BidAsk */: {
1986
+ const weights = toWeightBidAsk(minBinId, maxBinId, activeId);
1987
+ return autoFillYByWeight(activeId, binStep, amountX, amountXInActiveBin, amountYInActiveBin, weights);
1988
+ }
1989
+ default:
1990
+ throw new Error(`Unsupported strategy type: ${strategyType}`);
1991
+ }
1992
+ }
1993
+ function autoFillXByStrategy(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, minBinId, maxBinId, strategyType) {
1994
+ switch (strategyType) {
1995
+ case 1 /* Spot */: {
1996
+ const weights = toWeightSpotBalanced(minBinId, maxBinId);
1997
+ return autoFillXByWeight(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, weights);
1998
+ }
1999
+ case 2 /* Curve */: {
2000
+ const weights = toWeightCurve(minBinId, maxBinId, activeId);
2001
+ return autoFillXByWeight(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2002
+ }
2003
+ case 3 /* BidAsk */: {
2004
+ const weights = toWeightBidAsk(minBinId, maxBinId, activeId);
2005
+ return autoFillXByWeight(activeId, binStep, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2006
+ }
2007
+ default:
2008
+ throw new Error(`Unsupported strategy type: ${strategyType}`);
2009
+ }
2010
+ }
2011
+ function toAmountsBothSideByStrategy(activeId, binStep, minBinId, maxBinId, amountX, amountY, amountXInActiveBin, amountYInActiveBin, strategyType) {
2012
+ const isSingleSideX = amountY.isZero();
2013
+ switch (strategyType) {
2014
+ case 1 /* Spot */: {
2015
+ const weights = toWeightSpotBalanced(minBinId, maxBinId);
2016
+ return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2017
+ }
2018
+ case 2 /* Curve */: {
2019
+ if (activeId < minBinId) {
2020
+ const weights2 = toWeightDecendingOrder(minBinId, maxBinId);
2021
+ return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights2);
2022
+ }
2023
+ if (activeId > maxBinId) {
2024
+ const weights2 = toWeightAscendingOrder(minBinId, maxBinId);
2025
+ return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights2);
2026
+ }
2027
+ const weights = toWeightCurve(minBinId, maxBinId, activeId);
2028
+ return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2029
+ }
2030
+ case 3 /* BidAsk */: {
2031
+ if (activeId < minBinId) {
2032
+ const weights2 = toWeightAscendingOrder(minBinId, maxBinId);
2033
+ return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights2);
2034
+ }
2035
+ if (activeId > maxBinId) {
2036
+ const weights2 = toWeightDecendingOrder(minBinId, maxBinId);
2037
+ return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights2);
2038
+ }
2039
+ const weights = toWeightBidAsk(minBinId, maxBinId, activeId);
2040
+ return toAmountBothSide(activeId, binStep, amountX, amountY, amountXInActiveBin, amountYInActiveBin, weights);
2041
+ }
2042
+ default:
2043
+ throw new Error(`Unsupported strategy type: ${strategyType}`);
2044
+ }
2045
+ }
2046
+
2047
+ // src/math/LiquidityHelper.ts
2048
+ import Decimal5 from "decimal.js";
2049
+
2050
+ // src/utils/numbers.ts
2051
+ import Decimal4 from "decimal.js";
2052
+ function d(value) {
2053
+ if (Decimal4.isDecimal(value)) {
2054
+ return value;
2055
+ }
2056
+ return new Decimal4(value === void 0 ? 0 : value);
2057
+ }
2058
+ function decimalsMultiplier(decimals) {
2059
+ return d(10).pow(d(decimals).abs());
2060
+ }
2061
+
2062
+ // src/math/LiquidityHelper.ts
2063
+ function withLiquiditySlippage(value, slippage, mode) {
2064
+ return d(value)[mode](d(value).mul(slippage)).toDP(0);
2065
+ }
2066
+ function getLiquidityAndCoinYByCoinX(coinInVal, reserveInSize, reserveOutSize, lpSupply) {
2067
+ if (coinInVal.lessThanOrEqualTo(0)) {
2068
+ throw new ClmmpoolsError("coinInVal is less than zero", "InvalidCoinAmount" /* InvalidCoinAmount */);
2069
+ }
2070
+ if (reserveInSize.lessThanOrEqualTo(0) || reserveOutSize.lessThanOrEqualTo(0)) {
2071
+ return -1;
2072
+ }
2073
+ const coinYAmount = coinInVal.mul(reserveOutSize).div(reserveInSize);
2074
+ const sqrtSupply = lpSupply;
2075
+ const lpX = coinInVal.div(reserveInSize).mul(sqrtSupply);
2076
+ const lpY = coinYAmount.div(reserveOutSize).mul(sqrtSupply);
2077
+ const lpAmount = Decimal5.min(lpX, lpY);
2078
+ return {
2079
+ coinYAmount,
2080
+ lpAmount
2081
+ };
2082
+ }
2083
+ function getCoinXYForLiquidity(liquidity, reserveInSize, reserveOutSize, lpSuply) {
2084
+ if (liquidity.lessThanOrEqualTo(0)) {
2085
+ throw new ClmmpoolsError("liquidity can't be equal or less than zero", "InvalidLiquidityAmount" /* InvalidLiquidityAmount */);
2086
+ }
2087
+ if (reserveInSize.lessThanOrEqualTo(0) || reserveOutSize.lessThanOrEqualTo(0)) {
2088
+ throw new ClmmpoolsError("reserveInSize or reserveOutSize can not be equal or less than zero", "InvalidReserveAmount" /* InvalidReserveAmount */);
2089
+ }
2090
+ const sqrtSupply = lpSuply;
2091
+ const coinXAmount = liquidity.div(sqrtSupply).mul(reserveInSize);
2092
+ const coinYAmount = liquidity.div(sqrtSupply).mul(reserveOutSize);
2093
+ return {
2094
+ coinXAmount,
2095
+ coinYAmount
2096
+ };
2097
+ }
2098
+
2099
+ // src/math/percentage.ts
2100
+ import BN10 from "bn.js";
1596
2101
  var Percentage = class {
1597
2102
  numerator;
1598
2103
  denominator;
@@ -1620,8 +2125,8 @@ var Percentage = class {
1620
2125
  * @returns
1621
2126
  */
1622
2127
  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;
2128
+ const num = typeof numerator === "number" ? new BN10(numerator.toString()) : numerator;
2129
+ const denom = typeof denominator === "number" ? new BN10(denominator.toString()) : denominator;
1625
2130
  return new Percentage(num, denom);
1626
2131
  }
1627
2132
  };
@@ -1721,7 +2226,7 @@ function adjustForCoinSlippage(tokenAmount, slippage, adjustUp) {
1721
2226
  }
1722
2227
 
1723
2228
  // src/math/SplitSwap.ts
1724
- import BN10 from "bn.js";
2229
+ import BN11 from "bn.js";
1725
2230
  var SplitUnit = /* @__PURE__ */ ((SplitUnit2) => {
1726
2231
  SplitUnit2[SplitUnit2["FIVE"] = 5] = "FIVE";
1727
2232
  SplitUnit2[SplitUnit2["TEN"] = 10] = "TEN";
@@ -1779,7 +2284,7 @@ function updateSplitSwapResult(maxIndex, currentIndex, splitSwapResult, stepResu
1779
2284
  return splitSwapResult;
1780
2285
  }
1781
2286
  function computeSplitSwap(a2b, byAmountIn, amounts, poolData, swapTicks) {
1782
- let currentLiquidity = new BN10(poolData.liquidity);
2287
+ let currentLiquidity = new BN11(poolData.liquidity);
1783
2288
  let { currentSqrtPrice } = poolData;
1784
2289
  let splitSwapResult = {
1785
2290
  amountInArray: [],
@@ -1842,7 +2347,7 @@ function computeSplitSwap(a2b, byAmountIn, amounts, poolData, swapTicks) {
1842
2347
  targetSqrtPrice,
1843
2348
  currentLiquidity,
1844
2349
  remainerAmount,
1845
- new BN10(poolData.feeRate),
2350
+ new BN11(poolData.feeRate),
1846
2351
  byAmountIn
1847
2352
  );
1848
2353
  tempStepResult = stepResult;
@@ -1854,7 +2359,7 @@ function computeSplitSwap(a2b, byAmountIn, amounts, poolData, swapTicks) {
1854
2359
  splitSwapResult.amountOutArray[i] = splitSwapResult.amountOutArray[i].add(stepResult.amountOut);
1855
2360
  splitSwapResult.feeAmountArray[i] = splitSwapResult.feeAmountArray[i].add(stepResult.feeAmount);
1856
2361
  if (stepResult.nextSqrtPrice.eq(tick.sqrtPrice)) {
1857
- signedLiquidityChange = a2b ? tick.liquidityNet.mul(new BN10(-1)) : tick.liquidityNet;
2362
+ signedLiquidityChange = a2b ? tick.liquidityNet.mul(new BN11(-1)) : tick.liquidityNet;
1858
2363
  currentLiquidity = signedLiquidityChange.gt(ZERO) ? currentLiquidity.add(signedLiquidityChange) : currentLiquidity.sub(signedLiquidityChange.abs());
1859
2364
  currentSqrtPrice = tick.sqrtPrice;
1860
2365
  } else {
@@ -1879,7 +2384,7 @@ function computeSplitSwap(a2b, byAmountIn, amounts, poolData, swapTicks) {
1879
2384
  break;
1880
2385
  }
1881
2386
  if (tempStepResult.nextSqrtPrice.eq(tick.sqrtPrice)) {
1882
- signedLiquidityChange = a2b ? tick.liquidityNet.mul(new BN10(-1)) : tick.liquidityNet;
2387
+ signedLiquidityChange = a2b ? tick.liquidityNet.mul(new BN11(-1)) : tick.liquidityNet;
1883
2388
  currentLiquidity = signedLiquidityChange.gt(ZERO) ? currentLiquidity.add(signedLiquidityChange) : currentLiquidity.sub(signedLiquidityChange.abs());
1884
2389
  currentSqrtPrice = tick.sqrtPrice;
1885
2390
  } else {
@@ -1934,17 +2439,22 @@ var SplitSwap = class {
1934
2439
  }
1935
2440
  };
1936
2441
 
1937
- // src/utils/numbers.ts
1938
- import Decimal3 from "decimal.js";
1939
- function d(value) {
1940
- if (Decimal3.isDecimal(value)) {
1941
- return value;
2442
+ // src/math/bin.ts
2443
+ import Decimal6 from "decimal.js";
2444
+ import { get_price_x128_from_real_id as get_price_x128_from_real_id2, get_real_id_from_price_x128 } from "@magmaprotocol/calc_dlmm";
2445
+ var BinMath = class {
2446
+ static getPriceOfBinByBinId(binId, binStep, decimalsA, decimalsB) {
2447
+ const twoDec = new Decimal6(2);
2448
+ const price = new Decimal6(get_price_x128_from_real_id2(binId, binStep));
2449
+ return price.div(twoDec.pow(128)).mul(Decimal6.pow(10, decimalsA - decimalsB));
2450
+ }
2451
+ static getBinIdFromPrice(price, binStep, decimalsA, decimalsB) {
2452
+ const twoDec = new Decimal6(2);
2453
+ const tenDec = new Decimal6(10);
2454
+ const realid = get_real_id_from_price_x128(new Decimal6(price).mul(tenDec.pow(decimalsB - decimalsA)).mul(twoDec.pow(128)).toDecimalPlaces(0).toString(), binStep);
2455
+ return realid;
1942
2456
  }
1943
- return new Decimal3(value === void 0 ? 0 : value);
1944
- }
1945
- function decimalsMultiplier(decimals) {
1946
- return d(10).pow(d(decimals).abs());
1947
- }
2457
+ };
1948
2458
 
1949
2459
  // src/utils/objects.ts
1950
2460
  function getSuiObjectData(resp) {
@@ -2099,7 +2609,7 @@ function buildPool(objects) {
2099
2609
  const rewarders = [];
2100
2610
  fields.rewarder_manager.fields.rewarders.forEach((item) => {
2101
2611
  const { emissions_per_second } = item.fields;
2102
- const emissionSeconds = MathUtil.fromX64(new BN11(emissions_per_second));
2612
+ const emissionSeconds = MathUtil.fromX64(new BN12(emissions_per_second));
2103
2613
  const emissionsEveryDay = Math.floor(emissionSeconds.toNumber() * 60 * 60 * 24);
2104
2614
  rewarders.push({
2105
2615
  emissions_per_second,
@@ -2291,11 +2801,11 @@ function buildTickData(objects) {
2291
2801
  const possition = {
2292
2802
  objectId: getObjectId(objects),
2293
2803
  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),
2804
+ sqrtPrice: new BN12(valueItem.sqrt_price),
2805
+ liquidityNet: new BN12(valueItem.liquidity_net.fields.bits),
2806
+ liquidityGross: new BN12(valueItem.liquidity_gross),
2807
+ feeGrowthOutsideA: new BN12(valueItem.fee_growth_outside_a),
2808
+ feeGrowthOutsideB: new BN12(valueItem.fee_growth_outside_b),
2299
2809
  rewardersGrowthOutside: valueItem.rewards_growth_outside
2300
2810
  };
2301
2811
  return possition;
@@ -2305,11 +2815,11 @@ function buildTickDataByEvent(fields) {
2305
2815
  throw new ClmmpoolsError(`Invalid tick fields.`, "InvalidTickFields" /* InvalidTickFields */);
2306
2816
  }
2307
2817
  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);
2818
+ const sqrtPrice = new BN12(fields.sqrt_price);
2819
+ const liquidityNet = new BN12(fields.liquidity_net.bits);
2820
+ const liquidityGross = new BN12(fields.liquidity_gross);
2821
+ const feeGrowthOutsideA = new BN12(fields.fee_growth_outside_a);
2822
+ const feeGrowthOutsideB = new BN12(fields.fee_growth_outside_b);
2313
2823
  const rewardersGrowthOutside = fields.rewards_growth_outside || [];
2314
2824
  const tick = {
2315
2825
  objectId: "",
@@ -2328,7 +2838,7 @@ function buildClmmPositionName(pool_index, position_index) {
2328
2838
  }
2329
2839
 
2330
2840
  // src/utils/tick.ts
2331
- import BN12 from "bn.js";
2841
+ import BN13 from "bn.js";
2332
2842
  var TickUtil = class {
2333
2843
  /**
2334
2844
  * Get min tick index.
@@ -2368,22 +2878,22 @@ function getRewardInTickRange(pool, tickLower, tickUpper, tickLowerIndex, tickUp
2368
2878
  let rewarder_growth_below = growthGlobal[i];
2369
2879
  if (tickLower !== null) {
2370
2880
  if (pool.current_tick_index < tickLowerIndex) {
2371
- rewarder_growth_below = growthGlobal[i].sub(new BN12(tickLower.rewardersGrowthOutside[i]));
2881
+ rewarder_growth_below = growthGlobal[i].sub(new BN13(tickLower.rewardersGrowthOutside[i]));
2372
2882
  } else {
2373
2883
  rewarder_growth_below = tickLower.rewardersGrowthOutside[i];
2374
2884
  }
2375
2885
  }
2376
- let rewarder_growth_above = new BN12(0);
2886
+ let rewarder_growth_above = new BN13(0);
2377
2887
  if (tickUpper !== null) {
2378
2888
  if (pool.current_tick_index >= tickUpperIndex) {
2379
- rewarder_growth_above = growthGlobal[i].sub(new BN12(tickUpper.rewardersGrowthOutside[i]));
2889
+ rewarder_growth_above = growthGlobal[i].sub(new BN13(tickUpper.rewardersGrowthOutside[i]));
2380
2890
  } else {
2381
2891
  rewarder_growth_above = tickUpper.rewardersGrowthOutside[i];
2382
2892
  }
2383
2893
  }
2384
2894
  const rewGrowthInside = MathUtil.subUnderflowU128(
2385
- MathUtil.subUnderflowU128(new BN12(growthGlobal[i]), new BN12(rewarder_growth_below)),
2386
- new BN12(rewarder_growth_above)
2895
+ MathUtil.subUnderflowU128(new BN13(growthGlobal[i]), new BN13(rewarder_growth_below)),
2896
+ new BN13(rewarder_growth_above)
2387
2897
  );
2388
2898
  rewarderGrowthInside.push(rewGrowthInside);
2389
2899
  }
@@ -2391,8 +2901,8 @@ function getRewardInTickRange(pool, tickLower, tickUpper, tickLowerIndex, tickUp
2391
2901
  }
2392
2902
 
2393
2903
  // src/utils/transaction-util.ts
2394
- import BN13 from "bn.js";
2395
- import Decimal4 from "decimal.js";
2904
+ import BN14 from "bn.js";
2905
+ import Decimal7 from "decimal.js";
2396
2906
  import { Transaction } from "@mysten/sui/transactions";
2397
2907
  function findAdjustCoin(coinPair) {
2398
2908
  const isAdjustCoinA = CoinAssist.isSuiCoin(coinPair.coinTypeA);
@@ -2400,7 +2910,7 @@ function findAdjustCoin(coinPair) {
2400
2910
  return { isAdjustCoinA, isAdjustCoinB };
2401
2911
  }
2402
2912
  function reverSlippageAmount(slippageAmount, slippage) {
2403
- return Decimal4.ceil(d(slippageAmount).div(1 + slippage)).toString();
2913
+ return Decimal7.ceil(d(slippageAmount).div(1 + slippage)).toString();
2404
2914
  }
2405
2915
  async function printTransaction(tx, isPrint = true) {
2406
2916
  console.log(`inputs`, tx.blockData.inputs);
@@ -2700,7 +3210,7 @@ var _TransactionUtil = class {
2700
3210
  const liquidityInput = ClmmPoolUtil.estLiquidityAndcoinAmountFromOneAmounts(
2701
3211
  Number(params.tick_lower),
2702
3212
  Number(params.tick_upper),
2703
- new BN13(coinAmount),
3213
+ new BN14(coinAmount),
2704
3214
  params.fix_amount_a,
2705
3215
  true,
2706
3216
  slippage,
@@ -2774,12 +3284,12 @@ var _TransactionUtil = class {
2774
3284
  max_amount_a = params.amount_a;
2775
3285
  min_amount_a = params.amount_a;
2776
3286
  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();
3287
+ 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
3288
  } else {
2779
3289
  max_amount_b = params.amount_b;
2780
3290
  min_amount_b = params.amount_b;
2781
3291
  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();
3292
+ 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
3293
  }
2784
3294
  const args = params.is_open ? [
2785
3295
  tx.object(clmmConfig.global_config_id),
@@ -3768,7 +4278,7 @@ var _TransactionUtil = class {
3768
4278
  const basePath = splitPath.basePaths[i];
3769
4279
  a2b.push(basePath.direction);
3770
4280
  poolAddress.push(basePath.poolAddress);
3771
- rawAmountLimit.push(new BN13(basePath.inputAmount.toString()));
4281
+ rawAmountLimit.push(new BN14(basePath.inputAmount.toString()));
3772
4282
  if (i === 0) {
3773
4283
  coinType.push(basePath.fromCoin, basePath.toCoin);
3774
4284
  } else {
@@ -3776,8 +4286,8 @@ var _TransactionUtil = class {
3776
4286
  }
3777
4287
  }
3778
4288
  const onePath = {
3779
- amountIn: new BN13(splitPath.inputAmount.toString()),
3780
- amountOut: new BN13(splitPath.outputAmount.toString()),
4289
+ amountIn: new BN14(splitPath.inputAmount.toString()),
4290
+ amountOut: new BN14(splitPath.outputAmount.toString()),
3781
4291
  poolAddress,
3782
4292
  a2b,
3783
4293
  rawAmountLimit,
@@ -4134,9 +4644,9 @@ var TxBlock = class {
4134
4644
  };
4135
4645
 
4136
4646
  // src/utils/deepbook-utils.ts
4137
- import BN14 from "bn.js";
4647
+ import BN15 from "bn.js";
4138
4648
  import { Transaction as Transaction3 } from "@mysten/sui/transactions";
4139
- var FLOAT_SCALING = new BN14(1e9);
4649
+ var FLOAT_SCALING = new BN15(1e9);
4140
4650
  var DeepbookUtils = class {
4141
4651
  static createAccountCap(senderAddress, sdkOptions, tx, isTransfer = false) {
4142
4652
  if (senderAddress.length === 0) {
@@ -4282,9 +4792,9 @@ var DeepbookUtils = class {
4282
4792
  static async preSwap(sdk, pool, a2b, amountIn) {
4283
4793
  let isExceed = false;
4284
4794
  let amountOut = ZERO;
4285
- let remainAmount = new BN14(amountIn);
4795
+ let remainAmount = new BN15(amountIn);
4286
4796
  let feeAmount = ZERO;
4287
- const initAmountIn = new BN14(amountIn);
4797
+ const initAmountIn = new BN15(amountIn);
4288
4798
  if (a2b) {
4289
4799
  let bids = await this.getPoolBids(sdk, pool.poolID, pool.baseAsset, pool.quoteAsset);
4290
4800
  if (bids === null) {
@@ -4294,16 +4804,16 @@ var DeepbookUtils = class {
4294
4804
  return b.price - a.price;
4295
4805
  });
4296
4806
  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);
4807
+ const curBidAmount = new BN15(bids[i].quantity);
4808
+ const curBidPrice = new BN15(bids[i].price);
4809
+ const fee = curBidAmount.mul(new BN15(curBidPrice)).mul(new BN15(pool.takerFeeRate)).div(FLOAT_SCALING).div(FLOAT_SCALING);
4300
4810
  if (remainAmount.gt(curBidAmount)) {
4301
4811
  remainAmount = remainAmount.sub(curBidAmount);
4302
4812
  amountOut = amountOut.add(curBidAmount.mul(curBidPrice).div(FLOAT_SCALING).sub(fee));
4303
4813
  feeAmount = feeAmount.add(fee);
4304
4814
  } 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);
4815
+ const curOut = remainAmount.mul(new BN15(bids[i].price)).div(FLOAT_SCALING);
4816
+ const curFee = curOut.mul(new BN15(pool.takerFeeRate)).div(FLOAT_SCALING);
4307
4817
  amountOut = amountOut.add(curOut.sub(curFee));
4308
4818
  remainAmount = remainAmount.sub(remainAmount);
4309
4819
  feeAmount = feeAmount.add(curFee);
@@ -4318,15 +4828,15 @@ var DeepbookUtils = class {
4318
4828
  isExceed = true;
4319
4829
  }
4320
4830
  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);
4831
+ const curAskAmount = new BN15(asks[i].price).mul(new BN15(asks[i].quantity)).div(new BN15(1e9));
4832
+ const fee = curAskAmount.mul(new BN15(pool.takerFeeRate)).div(FLOAT_SCALING);
4323
4833
  const curAskAmountWithFee = curAskAmount.add(fee);
4324
4834
  if (remainAmount.gt(curAskAmount)) {
4325
- amountOut = amountOut.add(new BN14(asks[i].quantity));
4835
+ amountOut = amountOut.add(new BN15(asks[i].quantity));
4326
4836
  remainAmount = remainAmount.sub(curAskAmountWithFee);
4327
4837
  feeAmount = feeAmount.add(fee);
4328
4838
  } else {
4329
- const splitNums = new BN14(asks[i].quantity).div(new BN14(pool.lotSize));
4839
+ const splitNums = new BN15(asks[i].quantity).div(new BN15(pool.lotSize));
4330
4840
  const splitAmount = curAskAmountWithFee.div(splitNums);
4331
4841
  const swapSplitNum = remainAmount.div(splitAmount);
4332
4842
  amountOut = amountOut.add(swapSplitNum.muln(pool.lotSize));
@@ -5187,7 +5697,7 @@ var PoolModule = class {
5187
5697
  };
5188
5698
 
5189
5699
  // src/modules/positionModule.ts
5190
- import BN15 from "bn.js";
5700
+ import BN16 from "bn.js";
5191
5701
  import { Transaction as Transaction5 } from "@mysten/sui/transactions";
5192
5702
  import { isValidSuiObjectId } from "@mysten/sui/utils";
5193
5703
  var PositionModule = class {
@@ -5409,8 +5919,8 @@ var PositionModule = class {
5409
5919
  for (let i = 0; i < valueData.length; i += 1) {
5410
5920
  const { parsedJson } = valueData[i];
5411
5921
  const posRrewarderResult = {
5412
- feeOwedA: new BN15(parsedJson.fee_owned_a),
5413
- feeOwedB: new BN15(parsedJson.fee_owned_b),
5922
+ feeOwedA: new BN16(parsedJson.fee_owned_a),
5923
+ feeOwedB: new BN16(parsedJson.fee_owned_b),
5414
5924
  position_id: parsedJson.position_id
5415
5925
  };
5416
5926
  result.push(posRrewarderResult);
@@ -5786,7 +6296,7 @@ var PositionModule = class {
5786
6296
  };
5787
6297
 
5788
6298
  // src/modules/rewarderModule.ts
5789
- import BN16 from "bn.js";
6299
+ import BN17 from "bn.js";
5790
6300
  import { Transaction as Transaction6 } from "@mysten/sui/transactions";
5791
6301
  var RewarderModule = class {
5792
6302
  _sdk;
@@ -5812,7 +6322,7 @@ var RewarderModule = class {
5812
6322
  }
5813
6323
  const emissionsEveryDay = [];
5814
6324
  for (const rewarderInfo of rewarderInfos) {
5815
- const emissionSeconds = MathUtil.fromX64(new BN16(rewarderInfo.emissions_per_second));
6325
+ const emissionSeconds = MathUtil.fromX64(new BN17(rewarderInfo.emissions_per_second));
5816
6326
  emissionsEveryDay.push({
5817
6327
  emissions: Math.floor(emissionSeconds.toNumber() * 60 * 60 * 24),
5818
6328
  coin_address: rewarderInfo.coinAddress
@@ -5831,20 +6341,20 @@ var RewarderModule = class {
5831
6341
  const currentPool = await this.sdk.Pool.getPool(poolID);
5832
6342
  const lastTime = currentPool.rewarder_last_updated_time;
5833
6343
  currentPool.rewarder_last_updated_time = currentTime.toString();
5834
- if (Number(currentPool.liquidity) === 0 || currentTime.eq(new BN16(lastTime))) {
6344
+ if (Number(currentPool.liquidity) === 0 || currentTime.eq(new BN17(lastTime))) {
5835
6345
  return currentPool;
5836
6346
  }
5837
- const timeDelta = currentTime.div(new BN16(1e3)).sub(new BN16(lastTime)).add(new BN16(15));
6347
+ const timeDelta = currentTime.div(new BN17(1e3)).sub(new BN17(lastTime)).add(new BN17(15));
5838
6348
  const rewarderInfos = currentPool.rewarder_infos;
5839
6349
  for (let i = 0; i < rewarderInfos.length; i += 1) {
5840
6350
  const rewarderInfo = rewarderInfos[i];
5841
6351
  const rewarderGrowthDelta = MathUtil.checkMulDivFloor(
5842
6352
  timeDelta,
5843
- new BN16(rewarderInfo.emissions_per_second),
5844
- new BN16(currentPool.liquidity),
6353
+ new BN17(rewarderInfo.emissions_per_second),
6354
+ new BN17(currentPool.liquidity),
5845
6355
  128
5846
6356
  );
5847
- this.growthGlobal[i] = new BN16(rewarderInfo.growth_global).add(new BN16(rewarderGrowthDelta));
6357
+ this.growthGlobal[i] = new BN17(rewarderInfo.growth_global).add(new BN17(rewarderGrowthDelta));
5848
6358
  }
5849
6359
  return currentPool;
5850
6360
  }
@@ -5859,7 +6369,7 @@ var RewarderModule = class {
5859
6369
  */
5860
6370
  async posRewardersAmount(poolID, positionHandle, positionID) {
5861
6371
  const currentTime = Date.parse((/* @__PURE__ */ new Date()).toString());
5862
- const pool = await this.updatePoolRewarder(poolID, new BN16(currentTime));
6372
+ const pool = await this.updatePoolRewarder(poolID, new BN17(currentTime));
5863
6373
  const position = await this.sdk.Position.getPositionRewarders(positionHandle, positionID);
5864
6374
  if (position === void 0) {
5865
6375
  return [];
@@ -5880,7 +6390,7 @@ var RewarderModule = class {
5880
6390
  */
5881
6391
  async poolRewardersAmount(accountAddress, poolID) {
5882
6392
  const currentTime = Date.parse((/* @__PURE__ */ new Date()).toString());
5883
- const pool = await this.updatePoolRewarder(poolID, new BN16(currentTime));
6393
+ const pool = await this.updatePoolRewarder(poolID, new BN17(currentTime));
5884
6394
  const positions = await this.sdk.Position.getPositionList(accountAddress, [poolID]);
5885
6395
  const tickDatas = await this.getPoolLowerAndUpperTicks(pool.ticks_handle, positions);
5886
6396
  const rewarderAmount = [ZERO, ZERO, ZERO];
@@ -5907,38 +6417,38 @@ var RewarderModule = class {
5907
6417
  const growthInside = [];
5908
6418
  const AmountOwed = [];
5909
6419
  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"))) {
6420
+ let growthDelta0 = MathUtil.subUnderflowU128(rewardersInside[0], new BN17(position.reward_growth_inside_0));
6421
+ if (growthDelta0.gt(new BN17("3402823669209384634633745948738404"))) {
5912
6422
  growthDelta0 = ONE;
5913
6423
  }
5914
- const amountOwed_0 = MathUtil.checkMulShiftRight(new BN16(position.liquidity), growthDelta0, 64, 128);
6424
+ const amountOwed_0 = MathUtil.checkMulShiftRight(new BN17(position.liquidity), growthDelta0, 64, 128);
5915
6425
  growthInside.push(rewardersInside[0]);
5916
6426
  AmountOwed.push({
5917
- amount_owed: new BN16(position.reward_amount_owed_0).add(amountOwed_0),
6427
+ amount_owed: new BN17(position.reward_amount_owed_0).add(amountOwed_0),
5918
6428
  coin_address: pool.rewarder_infos[0].coinAddress
5919
6429
  });
5920
6430
  }
5921
6431
  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"))) {
6432
+ let growthDelta_1 = MathUtil.subUnderflowU128(rewardersInside[1], new BN17(position.reward_growth_inside_1));
6433
+ if (growthDelta_1.gt(new BN17("3402823669209384634633745948738404"))) {
5924
6434
  growthDelta_1 = ONE;
5925
6435
  }
5926
- const amountOwed_1 = MathUtil.checkMulShiftRight(new BN16(position.liquidity), growthDelta_1, 64, 128);
6436
+ const amountOwed_1 = MathUtil.checkMulShiftRight(new BN17(position.liquidity), growthDelta_1, 64, 128);
5927
6437
  growthInside.push(rewardersInside[1]);
5928
6438
  AmountOwed.push({
5929
- amount_owed: new BN16(position.reward_amount_owed_1).add(amountOwed_1),
6439
+ amount_owed: new BN17(position.reward_amount_owed_1).add(amountOwed_1),
5930
6440
  coin_address: pool.rewarder_infos[1].coinAddress
5931
6441
  });
5932
6442
  }
5933
6443
  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"))) {
6444
+ let growthDelta_2 = MathUtil.subUnderflowU128(rewardersInside[2], new BN17(position.reward_growth_inside_2));
6445
+ if (growthDelta_2.gt(new BN17("3402823669209384634633745948738404"))) {
5936
6446
  growthDelta_2 = ONE;
5937
6447
  }
5938
- const amountOwed_2 = MathUtil.checkMulShiftRight(new BN16(position.liquidity), growthDelta_2, 64, 128);
6448
+ const amountOwed_2 = MathUtil.checkMulShiftRight(new BN17(position.liquidity), growthDelta_2, 64, 128);
5939
6449
  growthInside.push(rewardersInside[2]);
5940
6450
  AmountOwed.push({
5941
- amount_owed: new BN16(position.reward_amount_owed_2).add(amountOwed_2),
6451
+ amount_owed: new BN17(position.reward_amount_owed_2).add(amountOwed_2),
5942
6452
  coin_address: pool.rewarder_infos[2].coinAddress
5943
6453
  });
5944
6454
  }
@@ -6052,8 +6562,8 @@ var RewarderModule = class {
6052
6562
  for (let i = 0; i < valueData.length; i += 1) {
6053
6563
  const { parsedJson } = valueData[i];
6054
6564
  const posRrewarderResult = {
6055
- feeOwedA: new BN16(parsedJson.fee_owned_a),
6056
- feeOwedB: new BN16(parsedJson.fee_owned_b),
6565
+ feeOwedA: new BN17(parsedJson.fee_owned_a),
6566
+ feeOwedB: new BN17(parsedJson.fee_owned_b),
6057
6567
  position_id: parsedJson.position_id
6058
6568
  };
6059
6569
  result.push(posRrewarderResult);
@@ -6116,7 +6626,7 @@ var RewarderModule = class {
6116
6626
  };
6117
6627
  for (let j = 0; j < params[i].rewarderInfo.length; j += 1) {
6118
6628
  posRrewarderResult.rewarderAmountOwed.push({
6119
- amount_owed: new BN16(valueData[i].parsedJson.data[j]),
6629
+ amount_owed: new BN17(valueData[i].parsedJson.data[j]),
6120
6630
  coin_address: params[i].rewarderInfo[j].coinAddress
6121
6631
  });
6122
6632
  }
@@ -6275,7 +6785,7 @@ var RewarderModule = class {
6275
6785
  };
6276
6786
 
6277
6787
  // src/modules/routerModule.ts
6278
- import BN17 from "bn.js";
6788
+ import BN18 from "bn.js";
6279
6789
  import { Graph, GraphEdge, GraphVertex } from "@syntsugar/cc-graph";
6280
6790
  import { Transaction as Transaction7 } from "@mysten/sui/transactions";
6281
6791
  function _pairSymbol(base, quote) {
@@ -6557,8 +7067,8 @@ var RouterModule = class {
6557
7067
  if (swapWithMultiPoolParams != null) {
6558
7068
  const preSwapResult2 = await this.sdk.Swap.preSwapWithMultiPool(swapWithMultiPoolParams);
6559
7069
  const onePath2 = {
6560
- amountIn: new BN17(preSwapResult2.estimatedAmountIn),
6561
- amountOut: new BN17(preSwapResult2.estimatedAmountOut),
7070
+ amountIn: new BN18(preSwapResult2.estimatedAmountIn),
7071
+ amountOut: new BN18(preSwapResult2.estimatedAmountOut),
6562
7072
  poolAddress: [preSwapResult2.poolAddress],
6563
7073
  a2b: [preSwapResult2.aToB],
6564
7074
  rawAmountLimit: byAmountIn ? [preSwapResult2.estimatedAmountOut] : [preSwapResult2.estimatedAmountIn],
@@ -6571,8 +7081,8 @@ var RouterModule = class {
6571
7081
  priceSlippagePoint
6572
7082
  };
6573
7083
  const result2 = {
6574
- amountIn: new BN17(preSwapResult2.estimatedAmountIn),
6575
- amountOut: new BN17(preSwapResult2.estimatedAmountOut),
7084
+ amountIn: new BN18(preSwapResult2.estimatedAmountIn),
7085
+ amountOut: new BN18(preSwapResult2.estimatedAmountOut),
6576
7086
  paths: [onePath2],
6577
7087
  a2b: preSwapResult2.aToB,
6578
7088
  b2c: void 0,
@@ -6594,8 +7104,8 @@ var RouterModule = class {
6594
7104
  if (swapWithMultiPoolParams != null) {
6595
7105
  const preSwapResult2 = await this.sdk.Swap.preSwapWithMultiPool(swapWithMultiPoolParams);
6596
7106
  const onePath2 = {
6597
- amountIn: new BN17(preSwapResult2.estimatedAmountIn),
6598
- amountOut: new BN17(preSwapResult2.estimatedAmountOut),
7107
+ amountIn: new BN18(preSwapResult2.estimatedAmountIn),
7108
+ amountOut: new BN18(preSwapResult2.estimatedAmountOut),
6599
7109
  poolAddress: [preSwapResult2.poolAddress],
6600
7110
  a2b: [preSwapResult2.aToB],
6601
7111
  rawAmountLimit: byAmountIn ? [preSwapResult2.estimatedAmountOut] : [preSwapResult2.estimatedAmountIn],
@@ -6608,8 +7118,8 @@ var RouterModule = class {
6608
7118
  priceSlippagePoint
6609
7119
  };
6610
7120
  const result3 = {
6611
- amountIn: new BN17(preSwapResult2.estimatedAmountIn),
6612
- amountOut: new BN17(preSwapResult2.estimatedAmountOut),
7121
+ amountIn: new BN18(preSwapResult2.estimatedAmountIn),
7122
+ amountOut: new BN18(preSwapResult2.estimatedAmountOut),
6613
7123
  paths: [onePath2],
6614
7124
  a2b: preSwapResult2.aToB,
6615
7125
  b2c: void 0,
@@ -6690,8 +7200,8 @@ var RouterModule = class {
6690
7200
  if (swapWithMultiPoolParams != null) {
6691
7201
  const preSwapResult = await this.sdk.Swap.preSwapWithMultiPool(swapWithMultiPoolParams);
6692
7202
  const onePath = {
6693
- amountIn: new BN17(preSwapResult.estimatedAmountIn),
6694
- amountOut: new BN17(preSwapResult.estimatedAmountOut),
7203
+ amountIn: new BN18(preSwapResult.estimatedAmountIn),
7204
+ amountOut: new BN18(preSwapResult.estimatedAmountOut),
6695
7205
  poolAddress: [preSwapResult.poolAddress],
6696
7206
  a2b: [preSwapResult.aToB],
6697
7207
  rawAmountLimit: byAmountIn ? [preSwapResult.estimatedAmountOut] : [preSwapResult.estimatedAmountIn],
@@ -6704,8 +7214,8 @@ var RouterModule = class {
6704
7214
  priceSlippagePoint
6705
7215
  };
6706
7216
  const result = {
6707
- amountIn: new BN17(preSwapResult.estimatedAmountIn),
6708
- amountOut: new BN17(preSwapResult.estimatedAmountOut),
7217
+ amountIn: new BN18(preSwapResult.estimatedAmountIn),
7218
+ amountOut: new BN18(preSwapResult.estimatedAmountOut),
6709
7219
  paths: [onePath],
6710
7220
  a2b: preSwapResult.aToB,
6711
7221
  b2c: void 0,
@@ -6789,13 +7299,13 @@ var RouterModule = class {
6789
7299
  continue;
6790
7300
  }
6791
7301
  if (params[0].byAmountIn) {
6792
- const amount = new BN17(valueData[i].parsedJson.data.amount_out);
7302
+ const amount = new BN18(valueData[i].parsedJson.data.amount_out);
6793
7303
  if (amount.gt(tempMaxAmount)) {
6794
7304
  tempIndex = i;
6795
7305
  tempMaxAmount = amount;
6796
7306
  }
6797
7307
  } 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));
7308
+ 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
7309
  if (amount.lt(tempMaxAmount)) {
6800
7310
  tempIndex = i;
6801
7311
  tempMaxAmount = amount;
@@ -6865,8 +7375,8 @@ var RouterModule = class {
6865
7375
  };
6866
7376
 
6867
7377
  // src/modules/swapModule.ts
6868
- import BN18 from "bn.js";
6869
- import Decimal5 from "decimal.js";
7378
+ import BN19 from "bn.js";
7379
+ import Decimal8 from "decimal.js";
6870
7380
  import { Transaction as Transaction8 } from "@mysten/sui/transactions";
6871
7381
  var AMM_SWAP_MODULE = "amm_swap";
6872
7382
  var POOL_STRUCT = "Pool";
@@ -6884,14 +7394,14 @@ var SwapModule = class {
6884
7394
  const pathCount = item.basePaths.length;
6885
7395
  if (pathCount > 0) {
6886
7396
  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);
7397
+ const feeRate = path.label === "Magma" ? new Decimal8(path.feeRate).div(10 ** 6) : new Decimal8(path.feeRate).div(10 ** 9);
6888
7398
  const feeAmount = d(path.inputAmount).div(10 ** path.fromDecimal).mul(feeRate);
6889
7399
  fee = fee.add(feeAmount);
6890
7400
  if (pathCount > 1) {
6891
7401
  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);
7402
+ const price1 = path.direction ? path.currentPrice : new Decimal8(1).div(path.currentPrice);
7403
+ const price2 = path2.direction ? path2.currentPrice : new Decimal8(1).div(path2.currentPrice);
7404
+ const feeRate2 = path2.label === "Magma" ? new Decimal8(path2.feeRate).div(10 ** 6) : new Decimal8(path2.feeRate).div(10 ** 9);
6895
7405
  const feeAmount2 = d(path2.outputAmount).div(10 ** path2.toDecimal).mul(feeRate2);
6896
7406
  const fee2 = feeAmount2.div(price1.mul(price2));
6897
7407
  fee = fee.add(fee2);
@@ -6909,17 +7419,17 @@ var SwapModule = class {
6909
7419
  const outputAmount = d(path.outputAmount).div(10 ** path.toDecimal);
6910
7420
  const inputAmount = d(path.inputAmount).div(10 ** path.fromDecimal);
6911
7421
  const rate = outputAmount.div(inputAmount);
6912
- const cprice = path.direction ? new Decimal5(path.currentPrice) : new Decimal5(1).div(path.currentPrice);
7422
+ const cprice = path.direction ? new Decimal8(path.currentPrice) : new Decimal8(1).div(path.currentPrice);
6913
7423
  impactValue = impactValue.add(this.calculateSingleImpact(rate, cprice));
6914
7424
  }
6915
7425
  if (pathCount === 2) {
6916
7426
  const path = item.basePaths[0];
6917
7427
  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);
7428
+ const cprice1 = path.direction ? new Decimal8(path.currentPrice) : new Decimal8(1).div(path.currentPrice);
7429
+ const cprice2 = path2.direction ? new Decimal8(path2.currentPrice) : new Decimal8(1).div(path2.currentPrice);
6920
7430
  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);
7431
+ const outputAmount = new Decimal8(path2.outputAmount).div(10 ** path2.toDecimal);
7432
+ const inputAmount = new Decimal8(path.inputAmount).div(10 ** path.fromDecimal);
6923
7433
  const rate = outputAmount.div(inputAmount);
6924
7434
  impactValue = impactValue.add(this.calculateSingleImpact(rate, cprice));
6925
7435
  }
@@ -6981,13 +7491,13 @@ var SwapModule = class {
6981
7491
  continue;
6982
7492
  }
6983
7493
  if (params.byAmountIn) {
6984
- const amount = new BN18(valueData[i].parsedJson.data.amount_out);
7494
+ const amount = new BN19(valueData[i].parsedJson.data.amount_out);
6985
7495
  if (amount.gt(tempMaxAmount)) {
6986
7496
  tempIndex = i;
6987
7497
  tempMaxAmount = amount;
6988
7498
  }
6989
7499
  } else {
6990
- const amount = new BN18(valueData[i].parsedJson.data.amount_out);
7500
+ const amount = new BN19(valueData[i].parsedJson.data.amount_out);
6991
7501
  if (amount.lt(tempMaxAmount)) {
6992
7502
  tempIndex = i;
6993
7503
  tempMaxAmount = amount;
@@ -7051,7 +7561,7 @@ var SwapModule = class {
7051
7561
  return this.transformSwapData(params, valueData[0].parsedJson.data);
7052
7562
  }
7053
7563
  transformSwapData(params, data) {
7054
- const estimatedAmountIn = data.amount_in && data.fee_amount ? new BN18(data.amount_in).add(new BN18(data.fee_amount)).toString() : "";
7564
+ const estimatedAmountIn = data.amount_in && data.fee_amount ? new BN19(data.amount_in).add(new BN19(data.fee_amount)).toString() : "";
7055
7565
  return {
7056
7566
  poolAddress: params.pool.poolAddress,
7057
7567
  currentSqrtPrice: params.currentSqrtPrice,
@@ -7068,7 +7578,7 @@ var SwapModule = class {
7068
7578
  transformSwapWithMultiPoolData(params, jsonData) {
7069
7579
  const { data } = jsonData;
7070
7580
  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() : "";
7581
+ const estimatedAmountIn = data.amount_in && data.fee_amount ? new BN19(data.amount_in).add(new BN19(data.fee_amount)).toString() : "";
7072
7582
  return {
7073
7583
  poolAddress: params.poolAddress,
7074
7584
  estimatedAmountIn,
@@ -8581,8 +9091,8 @@ var TokenModule = class {
8581
9091
  };
8582
9092
 
8583
9093
  // src/modules/routerModuleV2.ts
8584
- import BN19 from "bn.js";
8585
- import Decimal6 from "decimal.js";
9094
+ import BN20 from "bn.js";
9095
+ import Decimal9 from "decimal.js";
8586
9096
  import { v4 as uuidv4 } from "uuid";
8587
9097
  import axios from "axios";
8588
9098
  var RouterModuleV2 = class {
@@ -8599,7 +9109,7 @@ var RouterModuleV2 = class {
8599
9109
  if (label === "Magma") {
8600
9110
  return TickMath.sqrtPriceX64ToPrice(currentSqrtPrice, decimalA, decimalB);
8601
9111
  }
8602
- return new Decimal6(currentSqrtPrice.toString()).div(new Decimal6(10).pow(new Decimal6(decimalB + 9 - decimalA)));
9112
+ return new Decimal9(currentSqrtPrice.toString()).div(new Decimal9(10).pow(new Decimal9(decimalB + 9 - decimalA)));
8603
9113
  }
8604
9114
  parseJsonResult(data) {
8605
9115
  const result = {
@@ -8625,12 +9135,12 @@ var RouterModuleV2 = class {
8625
9135
  outputAmount: basePath.output_amount,
8626
9136
  inputAmount: basePath.input_amount,
8627
9137
  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,
9138
+ currentSqrtPrice: new BN20(basePath.current_sqrt_price.toString()),
9139
+ afterSqrtPrice: basePath.label === "Magma" ? new BN20(basePath.after_sqrt_price.toString()) : ZERO,
8630
9140
  fromDecimal: basePath.from_decimal,
8631
9141
  toDecimal: basePath.to_decimal,
8632
9142
  currentPrice: this.calculatePrice(
8633
- new BN19(basePath.current_sqrt_price.toString()),
9143
+ new BN20(basePath.current_sqrt_price.toString()),
8634
9144
  basePath.from_decimal,
8635
9145
  basePath.to_decimal,
8636
9146
  basePath.direction,
@@ -8713,7 +9223,7 @@ var RouterModuleV2 = class {
8713
9223
  const priceResult = await this.sdk.Router.priceUseV1(
8714
9224
  from,
8715
9225
  to,
8716
- new BN19(amount),
9226
+ new BN20(amount),
8717
9227
  byAmountIn,
8718
9228
  priceSplitPoint,
8719
9229
  partner,
@@ -8725,7 +9235,7 @@ var RouterModuleV2 = class {
8725
9235
  if (path.poolAddress.length > 1) {
8726
9236
  const fromDecimal0 = this.sdk.Router.tokenInfo(path.coinType[0]).decimals;
8727
9237
  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);
9238
+ const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), fromDecimal0, toDecimal0) : TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), toDecimal0, fromDecimal0);
8729
9239
  const path0 = {
8730
9240
  direction: path.a2b[0],
8731
9241
  label: "Magma",
@@ -8742,7 +9252,7 @@ var RouterModuleV2 = class {
8742
9252
  };
8743
9253
  const fromDecimal1 = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
8744
9254
  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);
9255
+ const currentPrice1 = path.a2b[1] ? TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[1]), fromDecimal1, toDecimal1) : TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[1]), toDecimal1, fromDecimal1);
8746
9256
  const path1 = {
8747
9257
  direction: path.a2b[1],
8748
9258
  label: "Magma",
@@ -8761,7 +9271,7 @@ var RouterModuleV2 = class {
8761
9271
  } else {
8762
9272
  const fromDecimal = this.sdk.Router.tokenInfo(path.coinType[0]).decimals;
8763
9273
  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);
9274
+ const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), fromDecimal, toDecimal) : TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), toDecimal, fromDecimal);
8765
9275
  const path0 = {
8766
9276
  direction: path.a2b[0],
8767
9277
  label: "Magma",
@@ -8846,7 +9356,7 @@ var RouterModuleV2 = class {
8846
9356
  const priceResult = await this.sdk.Router.priceUseV1(
8847
9357
  from,
8848
9358
  to,
8849
- new BN19(amount),
9359
+ new BN20(amount),
8850
9360
  byAmountIn,
8851
9361
  priceSplitPoint,
8852
9362
  partner,
@@ -8858,7 +9368,7 @@ var RouterModuleV2 = class {
8858
9368
  if (path.poolAddress.length > 1) {
8859
9369
  const fromDecimal0 = this.sdk.Router.tokenInfo(path.coinType[0]).decimals;
8860
9370
  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);
9371
+ const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), fromDecimal0, toDecimal0) : TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), toDecimal0, fromDecimal0);
8862
9372
  const path0 = {
8863
9373
  direction: path.a2b[0],
8864
9374
  label: "Magma",
@@ -8875,7 +9385,7 @@ var RouterModuleV2 = class {
8875
9385
  };
8876
9386
  const fromDecimal1 = this.sdk.Router.tokenInfo(path.coinType[1]).decimals;
8877
9387
  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);
9388
+ const currentPrice1 = path.a2b[1] ? TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[1]), fromDecimal1, toDecimal1) : TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[1]), toDecimal1, fromDecimal1);
8879
9389
  const path1 = {
8880
9390
  direction: path.a2b[1],
8881
9391
  label: "Magma",
@@ -8894,7 +9404,7 @@ var RouterModuleV2 = class {
8894
9404
  } else {
8895
9405
  const fromDecimal = this.sdk.Router.tokenInfo(path.coinType[0]).decimals;
8896
9406
  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);
9407
+ const currentPrice = path.a2b[0] ? TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), fromDecimal, toDecimal) : TickMath.sqrtPriceX64ToPrice(new BN20(priceResult.currentSqrtPrice[0]), toDecimal, fromDecimal);
8898
9408
  const path0 = {
8899
9409
  direction: path.a2b[0],
8900
9410
  label: "Magma",
@@ -9769,6 +10279,21 @@ var GaugeModule = class {
9769
10279
  });
9770
10280
  return tx;
9771
10281
  }
10282
+ async getAllRewardByPositions(paramsList) {
10283
+ const tx = new Transaction11();
10284
+ const { integrate } = this.sdk.sdkOptions;
10285
+ const { magma_token } = getPackagerConfigs(this.sdk.sdkOptions.magma_config);
10286
+ paramsList.forEach((params) => {
10287
+ const typeArguments = [params.coinTypeA, params.coinTypeB, magma_token];
10288
+ const args = [tx.object(params.gaugeId), tx.object(params.poolId), tx.object(params.positionId), tx.object(CLOCK_ADDRESS)];
10289
+ tx.moveCall({
10290
+ target: `${integrate.published_at}::${Gauge}::get_reward_by_position`,
10291
+ arguments: args,
10292
+ typeArguments
10293
+ });
10294
+ });
10295
+ return tx;
10296
+ }
9772
10297
  async getEpochRewardByPool(pool, incentive_tokens) {
9773
10298
  const tx = new Transaction11();
9774
10299
  const { integrate, simulationAccount } = this.sdk.sdkOptions;
@@ -9801,67 +10326,964 @@ var GaugeModule = class {
9801
10326
  }
9802
10327
  };
9803
10328
 
9804
- // src/sdk.ts
9805
- var MagmaClmmSDK = class {
10329
+ // src/modules/dlmm.ts
10330
+ import { Transaction as Transaction12 } from "@mysten/sui/transactions";
10331
+ import {
10332
+ get_price_x128_from_real_id as get_price_x128_from_real_id3,
10333
+ get_real_id,
10334
+ get_real_id_from_price_x128 as get_real_id_from_price_x1282,
10335
+ get_storage_id_from_real_id
10336
+ } from "@magmaprotocol/calc_dlmm";
10337
+ import Decimal10 from "decimal.js";
10338
+ var DlmmModule = class {
10339
+ _sdk;
9806
10340
  _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
- });
10341
+ constructor(sdk) {
10342
+ this._sdk = sdk;
10343
+ }
10344
+ get sdk() {
10345
+ return this._sdk;
10346
+ }
10347
+ async getPoolInfo(pools) {
10348
+ const objects = await this._sdk.fullClient.batchGetObjects(pools, { showContent: true });
10349
+ const poolList = [];
10350
+ objects.forEach((obj) => {
10351
+ if (obj.error != null || obj.data?.content?.dataType !== "moveObject") {
10352
+ throw new ClmmpoolsError(`Invalid objects. error: ${obj.error}`, "InvalidType" /* InvalidType */);
10353
+ }
10354
+ const fields = getObjectFields(obj);
10355
+ poolList.push({
10356
+ pool_id: fields.id.id,
10357
+ bin_step: fields.bin_step,
10358
+ coin_a: fields.x.fields.name,
10359
+ coin_b: fields.y.fields.name,
10360
+ base_factor: fields.params.fields.base_factor,
10361
+ base_fee: fields.params.fields.base_factor / 1e4 * (fields.bin_step / 1e4),
10362
+ active_index: fields.params.fields.active_index,
10363
+ real_bin_id: get_real_id(fields.params.fields.active_index),
10364
+ coinAmountA: fields.reserve_x,
10365
+ coinAmountB: fields.reserve_y
10366
+ });
10367
+ });
10368
+ return poolList;
10369
+ }
10370
+ // eg: fetch pool active_index
10371
+ async fetchPairParams(params) {
10372
+ const tx = new Transaction12();
10373
+ const { integrate, simulationAccount } = this.sdk.sdkOptions;
10374
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10375
+ const args = [tx.object(params.pair)];
10376
+ tx.moveCall({
10377
+ target: `${integrate.published_at}::${DlmmScript}::fetch_pair_params`,
10378
+ arguments: args,
10379
+ typeArguments
10380
+ });
10381
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
10382
+ transactionBlock: tx,
10383
+ sender: simulationAccount.address
10384
+ });
10385
+ if (simulateRes.error != null) {
10386
+ throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
10387
+ }
10388
+ let res = {
10389
+ base_factor: 0,
10390
+ filter_period: 0,
10391
+ decay_period: 0,
10392
+ reduction_factor: 0,
10393
+ variable_fee_control: 0,
10394
+ protocol_share: 0,
10395
+ max_volatility_accumulator: 0,
10396
+ volatility_accumulator: 0,
10397
+ volatility_reference: 0,
10398
+ index_reference: 0,
10399
+ time_of_last_update: 0,
10400
+ oracle_index: 0,
10401
+ active_index: 0
10402
+ };
10403
+ simulateRes.events?.forEach((item) => {
10404
+ console.log(extractStructTagFromType(item.type).name);
10405
+ if (extractStructTagFromType(item.type).name === `EventPairParams`) {
10406
+ res = item.parsedJson.params;
10407
+ }
10408
+ });
10409
+ return res;
10410
+ }
10411
+ // NOTE: x, y should be sorted
10412
+ async createPairPayload(params) {
10413
+ const storage_id = get_storage_id_from_real_id(
10414
+ BinMath.getBinIdFromPrice(params.priceTokenBPerTokenA, params.bin_step, params.coinADecimal, params.coinBDecimal)
10415
+ );
10416
+ const tx = new Transaction12();
10417
+ tx.setSender(this.sdk.senderAddress);
10418
+ const { clmm_pool, dlmm_pool, integrate } = this.sdk.sdkOptions;
10419
+ const { global_config_id } = getPackagerConfigs(clmm_pool);
10420
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10421
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10422
+ const args = [
10423
+ tx.object(dlmmConfig.factory),
10424
+ tx.object(global_config_id),
10425
+ tx.pure.u64(params.base_fee),
10426
+ tx.pure.u16(params.bin_step),
10427
+ tx.pure.u32(storage_id)
10428
+ ];
10429
+ tx.moveCall({
10430
+ target: `${integrate.published_at}::${DlmmScript}::create_pair`,
10431
+ typeArguments,
10432
+ arguments: args
10433
+ });
10434
+ return tx;
10435
+ }
10436
+ // async mintByStrategySingle(params: MintByStrategySingleParams): Promise<Transaction> {}
10437
+ async mintByStrategy(params) {
10438
+ const tx = new Transaction12();
10439
+ const slippage = new Decimal10(params.slippage);
10440
+ const lower_slippage = new Decimal10(1).sub(slippage.div(new Decimal10(1e4)));
10441
+ const upper_slippage = new Decimal10(1).plus(slippage.div(new Decimal10(1e4)));
10442
+ tx.setSender(this.sdk.senderAddress);
10443
+ const { dlmm_pool, integrate } = this.sdk.sdkOptions;
10444
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10445
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10446
+ const price = get_price_x128_from_real_id3(params.active_bin, params.bin_step);
10447
+ const min_price = new Decimal10(price).mul(lower_slippage);
10448
+ const max_price = new Decimal10(price).mul(upper_slippage);
10449
+ const active_min = get_storage_id_from_real_id(get_real_id_from_price_x1282(min_price.toDecimalPlaces(0).toString(), params.bin_step));
10450
+ const active_max = get_storage_id_from_real_id(get_real_id_from_price_x1282(max_price.toDecimalPlaces(0).toString(), params.bin_step));
10451
+ const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10452
+ let primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountATotal), params.coinTypeA, false, true);
10453
+ let primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountBTotal), params.coinTypeB, false, true);
10454
+ let amount_min = 0;
10455
+ let amount_max = 0;
10456
+ if (params.fixCoinA && params.fixCoinB) {
10457
+ primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountATotal), params.coinTypeB, false, true);
10458
+ primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountBTotal), params.coinTypeB, false, true);
10459
+ } else if (params.fixCoinA) {
10460
+ amount_min = new Decimal10(params.amountBTotal).mul(lower_slippage).toDecimalPlaces(0).toNumber();
10461
+ amount_max = new Decimal10(params.amountBTotal).mul(upper_slippage).toDecimalPlaces(0).toNumber();
10462
+ primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amount_max), params.coinTypeB, false, true);
10463
+ } else if (params.fixCoinB) {
10464
+ amount_min = new Decimal10(params.amountATotal).mul(lower_slippage).toDecimalPlaces(0).toNumber();
10465
+ amount_max = new Decimal10(params.amountATotal).mul(upper_slippage).toDecimalPlaces(0).toNumber();
10466
+ primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amount_max), params.coinTypeB, false, true);
10467
+ }
10468
+ if (params.fixCoinA && params.fixCoinB) {
10469
+ } else if (params.fixCoinA) {
10470
+ params.amountBTotal = 0;
10471
+ } else if (params.fixCoinB) {
10472
+ params.amountATotal = 0;
10473
+ }
10474
+ const args = [
10475
+ tx.object(params.pair),
10476
+ tx.object(dlmmConfig.factory),
10477
+ primaryCoinAInputs.targetCoin,
10478
+ primaryCoinBInputs.targetCoin,
10479
+ tx.pure.u64(params.amountATotal),
10480
+ tx.pure.u64(params.amountBTotal),
10481
+ tx.pure.u8(params.strategy),
10482
+ tx.pure.u32(get_storage_id_from_real_id(params.min_bin)),
10483
+ tx.pure.u32(get_storage_id_from_real_id(params.max_bin)),
10484
+ tx.pure.u32(active_min),
10485
+ tx.pure.u32(active_max),
10486
+ tx.pure.u64(amount_min),
10487
+ tx.pure.u64(amount_max),
10488
+ tx.object(CLOCK_ADDRESS)
10489
+ ];
10490
+ tx.moveCall({
10491
+ target: `${integrate.published_at}::${DlmmScript}::mint_by_strategy`,
10492
+ typeArguments,
10493
+ arguments: args
10494
+ });
10495
+ return tx;
10496
+ }
10497
+ // Create a position by percent
10498
+ async mintPercent(params) {
10499
+ const tx = new Transaction12();
10500
+ tx.setSender(this.sdk.senderAddress);
10501
+ const { dlmm_pool, integrate } = this.sdk.sdkOptions;
10502
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10503
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10504
+ const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10505
+ const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountATotal), params.coinTypeA, false, true);
10506
+ const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountBTotal), params.coinTypeB, false, true);
10507
+ const args = [
10508
+ tx.object(params.pair),
10509
+ tx.object(dlmmConfig.factory),
10510
+ primaryCoinAInputs.targetCoin,
10511
+ primaryCoinBInputs.targetCoin,
10512
+ tx.pure.u64(params.amountATotal),
10513
+ tx.pure.u64(params.amountBTotal),
10514
+ tx.pure.vector("u32", params.storageIds),
10515
+ tx.pure.vector("u64", params.binsAPercent),
10516
+ tx.pure.vector("u64", params.binsBPercent),
10517
+ tx.pure.address(params.to),
10518
+ tx.object(CLOCK_ADDRESS)
10519
+ ];
10520
+ tx.moveCall({
10521
+ target: `${integrate.published_at}::${DlmmScript}::mint_percent`,
10522
+ typeArguments,
10523
+ arguments: args
10524
+ });
10525
+ return tx;
10526
+ }
10527
+ // Create a position by amount
10528
+ async createPositionByAmount(params) {
10529
+ const tx = new Transaction12();
10530
+ tx.setSender(this.sdk.senderAddress);
10531
+ const { dlmm_pool, integrate } = this.sdk.sdkOptions;
10532
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10533
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10534
+ const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10535
+ const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountATotal), params.coinTypeA, false, true);
10536
+ const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(params.amountBTotal), params.coinTypeB, false, true);
10537
+ const args = [
10538
+ tx.object(params.pair),
10539
+ tx.object(dlmmConfig.factory),
10540
+ primaryCoinAInputs.targetCoin,
10541
+ primaryCoinBInputs.targetCoin,
10542
+ tx.pure.vector("u32", params.storageIds),
10543
+ tx.pure.vector("u64", params.amountsA),
10544
+ tx.pure.vector("u64", params.amountsB),
10545
+ tx.pure.address(params.to),
10546
+ tx.object(CLOCK_ADDRESS)
10547
+ ];
10548
+ tx.moveCall({
10549
+ target: `${integrate.published_at}::${DlmmScript}::mint_amounts`,
10550
+ typeArguments,
10551
+ arguments: args
10552
+ });
10553
+ return tx;
10554
+ }
10555
+ async addLiquidity(params) {
10556
+ if (params.rewards_token.length === 0) {
10557
+ return this._raisePositionByAmounts(params);
10558
+ }
10559
+ return this._raisePositionByAmountsReward(params);
10560
+ }
10561
+ async _raisePositionByAmounts(params) {
10562
+ const tx = new Transaction12();
10563
+ tx.setSender(this.sdk.senderAddress);
10564
+ const { dlmm_pool, integrate } = this.sdk.sdkOptions;
10565
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10566
+ const typeArguments = [params.coin_a, params.coin_b];
10567
+ const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10568
+ const amountATotal = params.amounts_a.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10569
+ const amountBTotal = params.amounts_b.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10570
+ const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountATotal), params.coin_a, false, true);
10571
+ const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountBTotal), params.coin_b, false, true);
10572
+ const args = [
10573
+ tx.object(params.pool_id),
10574
+ tx.object(dlmmConfig.factory),
10575
+ tx.object(params.position_id),
10576
+ primaryCoinAInputs.targetCoin,
10577
+ primaryCoinBInputs.targetCoin,
10578
+ tx.pure.vector("u64", params.amounts_a),
10579
+ tx.pure.vector("u64", params.amounts_b),
10580
+ tx.pure.address(params.receiver),
10581
+ tx.object(CLOCK_ADDRESS)
10582
+ ];
10583
+ tx.moveCall({
10584
+ target: `${integrate.published_at}::${DlmmScript}::raise_position_by_amounts`,
10585
+ typeArguments,
10586
+ arguments: args
10587
+ });
10588
+ return tx;
10589
+ }
10590
+ async _raisePositionByAmountsReward(params) {
10591
+ const tx = new Transaction12();
10592
+ tx.setSender(this.sdk.senderAddress);
10593
+ const { dlmm_pool, integrate, clmm_pool } = this.sdk.sdkOptions;
10594
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10595
+ const clmmConfigs = getPackagerConfigs(clmm_pool);
10596
+ const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
10597
+ const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10598
+ const amountATotal = params.amounts_a.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10599
+ const amountBTotal = params.amounts_b.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10600
+ const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountATotal), params.coin_a, false, true);
10601
+ const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountBTotal), params.coin_b, false, true);
10602
+ const args = [
10603
+ tx.object(params.pool_id),
10604
+ tx.object(dlmmConfig.factory),
10605
+ tx.object(clmmConfigs.global_vault_id),
10606
+ tx.object(params.position_id),
10607
+ primaryCoinAInputs.targetCoin,
10608
+ primaryCoinBInputs.targetCoin,
10609
+ tx.pure.vector("u64", params.amounts_a),
10610
+ tx.pure.vector("u64", params.amounts_b),
10611
+ tx.pure.address(params.receiver),
10612
+ tx.object(CLOCK_ADDRESS)
10613
+ ];
10614
+ tx.moveCall({
10615
+ target: `${integrate.published_at}::${DlmmScript}::raise_position_by_amounts_reward${params.rewards_token.length}`,
10616
+ typeArguments,
10617
+ arguments: args
10618
+ });
10619
+ return tx;
10620
+ }
10621
+ async burnPosition(params) {
10622
+ const tx = new Transaction12();
10623
+ tx.setSender(this.sdk.senderAddress);
10624
+ const { integrate, clmm_pool } = this.sdk.sdkOptions;
10625
+ const clmmConfigs = getPackagerConfigs(clmm_pool);
10626
+ const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
10627
+ let args = [tx.object(params.pool_id), tx.object(params.position_id), tx.object(CLOCK_ADDRESS)];
10628
+ let target = `${integrate.published_at}::${DlmmScript}::burn_position`;
10629
+ if (params.rewards_token.length > 0) {
10630
+ args = [tx.object(params.pool_id), tx.object(clmmConfigs.global_vault_id), tx.object(params.position_id), tx.object(CLOCK_ADDRESS)];
10631
+ target = `${integrate.published_at}::${DlmmScript}::burn_position_reward${params.rewards_token.length}`;
10632
+ }
10633
+ tx.moveCall({
10634
+ target,
10635
+ typeArguments,
10636
+ arguments: args
10637
+ });
10638
+ return tx;
10639
+ }
10640
+ async shrinkPosition(params) {
10641
+ const tx = new Transaction12();
10642
+ tx.setSender(this.sdk.senderAddress);
10643
+ const { integrate, clmm_pool } = this.sdk.sdkOptions;
10644
+ const clmmConfigs = getPackagerConfigs(clmm_pool);
10645
+ const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
10646
+ let args = [tx.object(params.pool_id), tx.object(params.position_id), tx.pure.u64(params.delta_percentage), tx.object(CLOCK_ADDRESS)];
10647
+ let target = `${integrate.published_at}::${DlmmScript}::shrink_position`;
10648
+ if (params.rewards_token.length > 0) {
10649
+ args = [
10650
+ tx.object(params.pool_id),
10651
+ tx.object(clmmConfigs.global_vault_id),
10652
+ tx.object(params.position_id),
10653
+ tx.pure.u64(params.delta_percentage),
10654
+ tx.object(CLOCK_ADDRESS)
10655
+ ];
10656
+ target = `${integrate.published_at}::${DlmmScript}::shrink_position_reward${params.rewards_token.length}`;
10657
+ }
10658
+ tx.moveCall({
10659
+ target,
10660
+ typeArguments,
10661
+ arguments: args
10662
+ });
10663
+ return tx;
10664
+ }
10665
+ async collectFeeAndReward(params) {
10666
+ let tx = new Transaction12();
10667
+ tx = await this.collectFees(params);
10668
+ if (params.rewards_token.length > 0) {
10669
+ tx = await this.collectReward(params);
10670
+ }
10671
+ return tx;
10672
+ }
10673
+ async collectReward(params, transaction) {
10674
+ const tx = transaction || new Transaction12();
10675
+ tx.setSender(this.sdk.senderAddress);
10676
+ const { integrate, clmm_pool } = this.sdk.sdkOptions;
10677
+ const clmmConfigs = getPackagerConfigs(clmm_pool);
10678
+ const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
10679
+ const args = [
10680
+ tx.object(params.pool_id),
10681
+ tx.object(clmmConfigs.global_vault_id),
10682
+ tx.object(params.position_id),
10683
+ tx.object(CLOCK_ADDRESS)
10684
+ ];
10685
+ let target = `${integrate.published_at}::${DlmmScript}::collect_reward`;
10686
+ if (params.rewards_token.length > 1) {
10687
+ target = `${integrate.published_at}::${DlmmScript}::collect_reward${params.rewards_token.length}`;
10688
+ }
10689
+ tx.moveCall({
10690
+ target,
10691
+ typeArguments,
10692
+ arguments: args
10693
+ });
10694
+ return tx;
10695
+ }
10696
+ async collectFees(params, transaction) {
10697
+ const tx = transaction || new Transaction12();
10698
+ tx.setSender(this.sdk.senderAddress);
10699
+ const { integrate } = this.sdk.sdkOptions;
10700
+ const typeArguments = [params.coin_a, params.coin_b];
10701
+ const args = [tx.object(params.pool_id), tx.object(params.position_id), tx.object(CLOCK_ADDRESS)];
10702
+ const target = `${integrate.published_at}::${DlmmScript}::collect_fees`;
10703
+ tx.moveCall({
10704
+ target,
10705
+ typeArguments,
10706
+ arguments: args
10707
+ });
10708
+ return tx;
10709
+ }
10710
+ async createPairAddLiquidity(params) {
10711
+ const tx = new Transaction12();
10712
+ tx.setSender(this.sdk.senderAddress);
10713
+ const { clmm_pool, dlmm_pool, integrate } = this.sdk.sdkOptions;
10714
+ const { global_config_id } = getPackagerConfigs(clmm_pool);
10715
+ const dlmmConfig = getPackagerConfigs(dlmm_pool);
10716
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10717
+ const allCoins = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10718
+ const amountATotal = params.amountsX.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10719
+ const amountBTotal = params.amountsY.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
10720
+ const primaryCoinAInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountATotal), params.coinTypeA, false, true);
10721
+ const primaryCoinBInputs = TransactionUtil.buildCoinForAmount(tx, allCoins, BigInt(amountBTotal), params.coinTypeB, false, true);
10722
+ const storageIds = [];
10723
+ params.realIds.forEach((i) => {
10724
+ storageIds.push(get_storage_id_from_real_id(i));
10725
+ });
10726
+ const args = [
10727
+ tx.object(dlmmConfig.factory),
10728
+ tx.object(global_config_id),
10729
+ tx.pure.u64(params.baseFee),
10730
+ tx.pure.u16(params.binStep),
10731
+ tx.pure.u32(get_storage_id_from_real_id(params.activeId)),
10732
+ primaryCoinAInputs.targetCoin,
10733
+ primaryCoinBInputs.targetCoin,
10734
+ tx.pure.vector("u32", storageIds),
10735
+ tx.pure.vector("u64", params.amountsX),
10736
+ tx.pure.vector("u64", params.amountsY),
10737
+ tx.pure.address(params.to),
10738
+ tx.object(CLOCK_ADDRESS)
10739
+ ];
10740
+ const target = `${integrate.published_at}::${DlmmScript}::create_pair_add_liquidity`;
10741
+ tx.moveCall({
10742
+ target,
10743
+ typeArguments,
10744
+ arguments: args
10745
+ });
10746
+ return tx;
10747
+ }
10748
+ async swap(params) {
10749
+ const tx = new Transaction12();
10750
+ tx.setSender(this.sdk.senderAddress);
10751
+ const { clmm_pool, integrate } = this.sdk.sdkOptions;
10752
+ const { global_config_id } = getPackagerConfigs(clmm_pool);
10753
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10754
+ const allCoinAsset = await this._sdk.getOwnerCoinAssets(this._sdk.senderAddress);
10755
+ const primaryCoinInputA = TransactionUtil.buildCoinForAmount(
10756
+ tx,
10757
+ allCoinAsset,
10758
+ params.swapForY ? BigInt(params.amountIn) : BigInt(0),
10759
+ params.coinTypeA,
10760
+ false,
10761
+ true
10762
+ );
10763
+ const primaryCoinInputB = TransactionUtil.buildCoinForAmount(
10764
+ tx,
10765
+ allCoinAsset,
10766
+ params.swapForY ? BigInt(0) : BigInt(params.amountIn),
10767
+ params.coinTypeB,
10768
+ false,
10769
+ true
10770
+ );
10771
+ const args = [
10772
+ tx.object(params.pair),
10773
+ tx.object(global_config_id),
10774
+ primaryCoinInputA.targetCoin,
10775
+ primaryCoinInputB.targetCoin,
10776
+ tx.pure.u64(params.amountIn),
10777
+ tx.pure.u64(params.minAmountOut),
10778
+ tx.pure.bool(params.swapForY),
10779
+ tx.pure.address(params.to),
10780
+ tx.object(CLOCK_ADDRESS)
10781
+ ];
10782
+ tx.moveCall({
10783
+ target: `${integrate.published_at}::${DlmmScript}::swap`,
10784
+ typeArguments,
10785
+ arguments: args
10786
+ });
10787
+ return tx;
10788
+ }
10789
+ async fetchBins(params) {
10790
+ const tx = new Transaction12();
10791
+ const { integrate, simulationAccount } = this.sdk.sdkOptions;
10792
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10793
+ const args = [tx.object(params.pair), tx.pure.u64(params.offset), tx.pure.u64(params.limit)];
10794
+ tx.moveCall({
10795
+ target: `${integrate.published_at}::${DlmmScript}::fetch_bins`,
10796
+ arguments: args,
10797
+ typeArguments
10798
+ });
10799
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
10800
+ transactionBlock: tx,
10801
+ sender: simulationAccount.address
10802
+ });
10803
+ if (simulateRes.error != null) {
10804
+ throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
10805
+ }
10806
+ let res = [];
10807
+ simulateRes.events?.forEach((item) => {
10808
+ if (extractStructTagFromType(item.type).name === `EventFetchBins`) {
10809
+ const { bins } = item.parsedJson;
10810
+ res = bins;
10811
+ }
10812
+ });
10813
+ return res;
10814
+ }
10815
+ /**
10816
+ * Gets a list of positions for the given account address.
10817
+ * @param accountAddress The account address to get positions for.
10818
+ * @param assignPoolIds An array of pool IDs to filter the positions by.
10819
+ * @returns array of Position objects.
10820
+ */
10821
+ async getUserPositionById(positionId, showDisplay = true) {
10822
+ let position;
10823
+ const ownerRes = await this._sdk.fullClient.getObject({
10824
+ id: positionId,
10825
+ options: { showContent: true, showType: true, showDisplay, showOwner: true }
10826
+ });
10827
+ const type = extractStructTagFromType(ownerRes.data.type);
10828
+ if (type.full_address === this.buildPositionType()) {
10829
+ position = this.buildPosition(ownerRes);
10830
+ } else {
10831
+ throw new ClmmpoolsError(`Dlmm Position not exists. Get Position error:${ownerRes.error}`, "InvalidPositionObject" /* InvalidPositionObject */);
10832
+ }
10833
+ const poolMap = /* @__PURE__ */ new Set();
10834
+ poolMap.add(position.pool);
10835
+ const pool = (await this.getPoolInfo(Array.from(poolMap)))[0];
10836
+ const _params = [];
10837
+ _params.push({
10838
+ pool_id: pool.pool_id,
10839
+ coin_a: pool.coin_a,
10840
+ coin_b: pool.coin_b
10841
+ });
10842
+ const pool_reward_coins = await this.getPairRewarders(_params);
10843
+ const positionLiquidity = await this.getPositionLiquidity({
10844
+ pair: position.pool,
10845
+ positionId: position.pos_object_id,
10846
+ coinTypeA: pool.coin_a,
10847
+ coinTypeB: pool.coin_b
10848
+ });
10849
+ const rewards_token = pool_reward_coins.get(position.pool) || [];
10850
+ let positionRewards = { position_id: position.pos_object_id, reward: [], amount: [] };
10851
+ if (rewards_token.length > 0) {
10852
+ positionRewards = await this.getEarnedRewards({
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
+ rewards_token: pool_reward_coins.get(position.pool) || []
10858
+ });
10859
+ }
10860
+ const positionFees = await this.getEarnedFees({
10861
+ pool_id: position.pool,
10862
+ position_id: position.pos_object_id,
10863
+ coin_a: pool.coin_a,
10864
+ coin_b: pool.coin_b
10865
+ });
10866
+ return {
10867
+ position,
10868
+ liquidity: positionLiquidity,
10869
+ rewards: positionRewards,
10870
+ fees: positionFees,
10871
+ contractPool: pool
10872
+ };
10873
+ }
10874
+ /**
10875
+ * Gets a list of positions for the given account address.
10876
+ * @param accountAddress The account address to get positions for.
10877
+ * @param assignPoolIds An array of pool IDs to filter the positions by.
10878
+ * @returns array of Position objects.
10879
+ */
10880
+ async getUserPositions(accountAddress, assignPoolIds = [], showDisplay = true) {
10881
+ const allPosition = [];
10882
+ const ownerRes = await this._sdk.fullClient.getOwnedObjectsByPage(accountAddress, {
10883
+ options: { showType: true, showContent: true, showDisplay, showOwner: true },
10884
+ filter: { Package: this._sdk.sdkOptions.dlmm_pool.package_id }
10885
+ });
10886
+ const hasAssignPoolIds = assignPoolIds.length > 0;
10887
+ for (const item of ownerRes.data) {
10888
+ const type = extractStructTagFromType(item.data.type);
10889
+ if (type.full_address === this.buildPositionType()) {
10890
+ const position = this.buildPosition(item);
10891
+ const cacheKey = `${position.pos_object_id}_getPositionList`;
10892
+ this.updateCache(cacheKey, position, cacheTime24h);
10893
+ if (hasAssignPoolIds) {
10894
+ if (assignPoolIds.includes(position.pool)) {
10895
+ allPosition.push(position);
10896
+ }
10897
+ } else {
10898
+ allPosition.push(position);
10899
+ }
10900
+ }
10901
+ }
10902
+ const poolMap = /* @__PURE__ */ new Set();
10903
+ for (const item of allPosition) {
10904
+ poolMap.add(item.pool);
10905
+ }
10906
+ const poolList = await this.getPoolInfo(Array.from(poolMap));
10907
+ this.updateCache(`${DlmmScript}_positionList_poolList`, poolList, cacheTime24h);
10908
+ const _params = [];
10909
+ for (const pool of poolList) {
10910
+ _params.push({
10911
+ pool_id: pool.pool_id,
10912
+ coin_a: pool.coin_a,
10913
+ coin_b: pool.coin_b
10914
+ });
10915
+ }
10916
+ const pool_reward_coins = await this.getPairRewarders(_params);
10917
+ const out = [];
10918
+ for (const item of allPosition) {
10919
+ const pool = poolList.find((pool2) => pool2.pool_id === item.pool);
10920
+ const positionLiquidity = await this.getPositionLiquidity({
10921
+ pair: item.pool,
10922
+ positionId: item.pos_object_id,
10923
+ coinTypeA: pool.coin_a,
10924
+ coinTypeB: pool.coin_b
10925
+ });
10926
+ const rewards_token = pool_reward_coins.get(item.pool) || [];
10927
+ let positionRewards = { position_id: item.pos_object_id, reward: [], amount: [] };
10928
+ if (rewards_token.length > 0) {
10929
+ positionRewards = await this.getEarnedRewards({
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
+ rewards_token: pool_reward_coins.get(item.pool) || []
10935
+ });
10936
+ }
10937
+ const positionFees = await this.getEarnedFees({
10938
+ pool_id: item.pool,
10939
+ position_id: item.pos_object_id,
10940
+ coin_a: pool.coin_a,
10941
+ coin_b: pool.coin_b
10942
+ });
10943
+ out.push({
10944
+ position: item,
10945
+ liquidity: positionLiquidity,
10946
+ rewards: positionRewards,
10947
+ fees: positionFees,
10948
+ contractPool: pool
10949
+ });
10950
+ }
10951
+ return out;
10952
+ }
10953
+ buildPosition(object) {
10954
+ if (object.error != null || object.data?.content?.dataType !== "moveObject") {
10955
+ throw new ClmmpoolsError(`Dlmm Position not exists. Get Position error:${object.error}`, "InvalidPositionObject" /* InvalidPositionObject */);
10956
+ }
10957
+ const fields = getObjectFields(object);
10958
+ const ownerWarp = getObjectOwner(object);
10959
+ return {
10960
+ pos_object_id: fields.id.id,
10961
+ owner: ownerWarp.AddressOwner,
10962
+ pool: fields.pair_id,
10963
+ bin_real_ids: fields.bin_ids.map((id) => get_real_id(id)),
10964
+ type: ""
10965
+ };
10966
+ }
10967
+ // return [coin_a, coin_b]
10968
+ async getPoolCoins(pools) {
10969
+ const res = await this._sdk.fullClient.multiGetObjects({ ids: pools, options: { showContent: true } });
10970
+ const poolCoins = /* @__PURE__ */ new Map();
10971
+ res.forEach((item) => {
10972
+ if (item.error != null || item.data?.content?.dataType !== "moveObject") {
10973
+ throw new Error(`Failed to get poolCoins with err: ${item.error}`);
10974
+ }
10975
+ const type = getObjectType(item);
10976
+ const poolTypeFields = extractStructTagFromType(type);
10977
+ poolCoins.set(item.data.objectId, poolTypeFields.type_arguments);
10978
+ });
10979
+ return poolCoins;
10980
+ }
10981
+ buildPositionType() {
10982
+ return `${this._sdk.sdkOptions.dlmm_pool.package_id}::dlmm_position::Position`;
10983
+ }
10984
+ async getPositionLiquidity(params) {
10985
+ const tx = new Transaction12();
10986
+ const { integrate, simulationAccount } = this.sdk.sdkOptions;
10987
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
10988
+ const args = [tx.object(params.pair), tx.object(params.positionId)];
10989
+ tx.moveCall({
10990
+ target: `${integrate.published_at}::${DlmmScript}::position_liquidity`,
10991
+ arguments: args,
10992
+ typeArguments
10993
+ });
10994
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
10995
+ transactionBlock: tx,
10996
+ sender: simulationAccount.address
10997
+ });
10998
+ if (simulateRes.error != null) {
10999
+ throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
11000
+ }
11001
+ const out = {
11002
+ shares: 0,
11003
+ liquidity: 0,
11004
+ x_equivalent: 0,
11005
+ y_equivalent: 0,
11006
+ bin_real_ids: [],
11007
+ bin_x_eq: [],
11008
+ bin_y_eq: [],
11009
+ bin_liquidity: []
11010
+ };
11011
+ simulateRes.events?.forEach((item) => {
11012
+ if (extractStructTagFromType(item.type).name === `EventPositionLiquidity`) {
11013
+ out.shares = item.parsedJson.shares;
11014
+ out.liquidity = item.parsedJson.liquidity;
11015
+ out.x_equivalent = item.parsedJson.x_equivalent;
11016
+ out.y_equivalent = item.parsedJson.y_equivalent;
11017
+ out.bin_real_ids = item.parsedJson.bin_ids.map((id) => get_real_id(id));
11018
+ out.bin_x_eq = item.parsedJson.bin_x_eq;
11019
+ out.bin_y_eq = item.parsedJson.bin_y_eq;
11020
+ out.bin_liquidity = item.parsedJson.bin_liquidity;
11021
+ }
11022
+ });
11023
+ return out;
11024
+ }
11025
+ async getPairLiquidity(params) {
11026
+ const tx = new Transaction12();
11027
+ const { integrate, simulationAccount } = this.sdk.sdkOptions;
11028
+ const typeArguments = [params.coinTypeA, params.coinTypeB];
11029
+ const args = [tx.object(params.pair)];
11030
+ tx.moveCall({
11031
+ target: `${integrate.published_at}::${DlmmScript}::pair_liquidity`,
11032
+ arguments: args,
11033
+ typeArguments
11034
+ });
11035
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11036
+ transactionBlock: tx,
11037
+ sender: simulationAccount.address
11038
+ });
11039
+ if (simulateRes.error != null) {
11040
+ throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
11041
+ }
11042
+ const out = {
11043
+ shares: 0,
11044
+ liquidity: 0,
11045
+ x: 0,
11046
+ y: 0,
11047
+ bin_ids: [],
11048
+ bin_x: [],
11049
+ bin_y: []
11050
+ };
11051
+ simulateRes.events?.forEach((item) => {
11052
+ if (extractStructTagFromType(item.type).name === `EventPositionLiquidity`) {
11053
+ out.shares = item.parsedJson.shares;
11054
+ out.liquidity = item.parsedJson.liquidity;
11055
+ out.x = item.parsedJson.x;
11056
+ out.y = item.parsedJson.y;
11057
+ out.bin_ids = item.bin_ids;
11058
+ out.bin_x = item.bin_x;
11059
+ out.bin_y = item.bin_y;
11060
+ }
11061
+ });
11062
+ return out;
11063
+ }
11064
+ async getEarnedFees(params) {
11065
+ const tx = new Transaction12();
11066
+ const { integrate, simulationAccount } = this.sdk.sdkOptions;
11067
+ const typeArguments = [params.coin_a, params.coin_b];
11068
+ const args = [tx.object(params.pool_id), tx.object(params.position_id)];
11069
+ tx.moveCall({
11070
+ target: `${integrate.published_at}::${DlmmScript}::earned_fees`,
11071
+ arguments: args,
11072
+ typeArguments
11073
+ });
11074
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11075
+ transactionBlock: tx,
11076
+ sender: simulationAccount.address
11077
+ });
11078
+ const out = {
11079
+ position_id: "",
11080
+ x: "",
11081
+ y: "",
11082
+ fee_x: 0,
11083
+ fee_y: 0
11084
+ };
11085
+ if (simulateRes.error != null) {
11086
+ throw new Error(`fetchPairRewards error code: ${simulateRes.error ?? "unknown error"}`);
11087
+ }
11088
+ simulateRes.events?.forEach((item) => {
11089
+ if (extractStructTagFromType(item.type).name === `EventPositionLiquidity`) {
11090
+ out.position_id = item.parsedJson.position_id;
11091
+ out.x = item.parsedJson.x;
11092
+ out.y = item.parsedJson.y;
11093
+ out.fee_x = item.parsedJson.fee_x;
11094
+ out.fee_y = item.parsedJson.fee_y;
11095
+ }
11096
+ });
11097
+ return out;
11098
+ }
11099
+ async getEarnedRewards(params) {
11100
+ const tx = new Transaction12();
11101
+ const { integrate, simulationAccount } = this.sdk.sdkOptions;
11102
+ const typeArguments = [params.coin_a, params.coin_b, ...params.rewards_token];
11103
+ const args = [tx.object(params.pool_id), tx.object(params.position_id), tx.object(CLOCK_ADDRESS)];
11104
+ let target = `${integrate.published_at}::${DlmmScript}::earned_rewards`;
11105
+ if (params.rewards_token.length > 1) {
11106
+ target = `${integrate.published_at}::${DlmmScript}::earned_rewards${params.rewards_token.length}`;
11107
+ }
11108
+ tx.moveCall({
11109
+ target,
11110
+ arguments: args,
11111
+ typeArguments
11112
+ });
11113
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11114
+ transactionBlock: tx,
11115
+ sender: simulationAccount.address
11116
+ });
11117
+ const out = {
11118
+ position_id: "",
11119
+ reward: [],
11120
+ amount: []
11121
+ };
11122
+ if (simulateRes.error != null) {
11123
+ throw new Error(`getEarnedRewards error code: ${simulateRes.error ?? "unknown error"}`);
11124
+ }
11125
+ simulateRes.events?.forEach((item) => {
11126
+ if (extractStructTagFromType(item.type).name === `DlmmEventEarnedRewards`) {
11127
+ out.position_id = item.parsedJson.position_id;
11128
+ out.reward = [item.parsedJson.reward];
11129
+ out.amount = [item.parsedJson.amount];
11130
+ } else if (extractStructTagFromType(item.type).name === `DlmmEventEarnedRewards2`) {
11131
+ out.position_id = item.parsedJson.position_id;
11132
+ out.reward = [item.parsedJson.reward1, item.parsedJson.reward2];
11133
+ out.amount = [item.parsedJson.amount1, item.parsedJson.amount2];
11134
+ } else if (extractStructTagFromType(item.type).name === `EventEarnedRewards3`) {
11135
+ out.position_id = item.parsedJson.position_id;
11136
+ out.reward = [item.parsedJson.reward1, item.parsedJson.reward2, item.parsedJson.reward3];
11137
+ out.amount = [item.parsedJson.amount1, item.parsedJson.amount2, item.parsedJson.amount3];
11138
+ }
11139
+ });
11140
+ return out;
11141
+ }
11142
+ // return pool_id => reward_tokens
11143
+ async getPairRewarders(params) {
11144
+ let tx = new Transaction12();
11145
+ for (const param of params) {
11146
+ tx = await this._getPairRewarders(param, tx);
11147
+ }
11148
+ return this._parsePairRewarders(tx);
11149
+ }
11150
+ async _getPairRewarders(params, tx) {
11151
+ tx = tx || new Transaction12();
11152
+ const { integrate } = this.sdk.sdkOptions;
11153
+ const typeArguments = [params.coin_a, params.coin_b];
11154
+ const args = [tx.object(params.pool_id)];
11155
+ tx.moveCall({
11156
+ target: `${integrate.published_at}::${DlmmScript}::get_pair_rewarders`,
11157
+ arguments: args,
11158
+ typeArguments
11159
+ });
11160
+ return tx;
11161
+ }
11162
+ async _parsePairRewarders(tx) {
11163
+ const { simulationAccount } = this.sdk.sdkOptions;
11164
+ const simulateRes = await this.sdk.fullClient.devInspectTransactionBlock({
11165
+ transactionBlock: tx,
11166
+ sender: simulationAccount.address
11167
+ });
11168
+ const out = /* @__PURE__ */ new Map();
11169
+ if (simulateRes.error != null) {
11170
+ throw new Error(`fetchBins error code: ${simulateRes.error ?? "unknown error"}`);
11171
+ }
11172
+ simulateRes.events?.forEach((item) => {
11173
+ if (extractStructTagFromType(item.type).name === `EventPairRewardTypes`) {
11174
+ const pairRewards = {
11175
+ pair_id: "",
11176
+ tokens: []
11177
+ };
11178
+ pairRewards.pair_id = item.parsedJson.pair_id;
11179
+ item.parsedJson.tokens.forEach((token) => {
11180
+ pairRewards.tokens.push(token.name);
11181
+ });
11182
+ out.set(pairRewards.pair_id, pairRewards.tokens);
11183
+ }
11184
+ });
11185
+ return out;
11186
+ }
11187
+ /**
11188
+ * Updates the cache for the given key.
11189
+ *
11190
+ * @param key The key of the cache entry to update.
11191
+ * @param data The data to store in the cache.
11192
+ * @param time The time in minutes after which the cache entry should expire.
11193
+ */
11194
+ updateCache(key, data, time = cacheTime5min) {
11195
+ let cacheData = this._cache[key];
11196
+ if (cacheData) {
11197
+ cacheData.overdueTime = getFutureTime(time);
11198
+ cacheData.value = data;
11199
+ } else {
11200
+ cacheData = new CachedContent(data, getFutureTime(time));
11201
+ }
11202
+ this._cache[key] = cacheData;
11203
+ }
11204
+ /**
11205
+ * Gets the cache entry for the given key.
11206
+ *
11207
+ * @param key The key of the cache entry to get.
11208
+ * @param forceRefresh Whether to force a refresh of the cache entry.
11209
+ * @returns The cache entry for the given key, or undefined if the cache entry does not exist or is expired.
11210
+ */
11211
+ getCache(key, forceRefresh = false) {
11212
+ const cacheData = this._cache[key];
11213
+ const isValid = cacheData?.isValid();
11214
+ if (!forceRefresh && isValid) {
11215
+ return cacheData.value;
11216
+ }
11217
+ if (!isValid) {
11218
+ delete this._cache[key];
11219
+ }
11220
+ return void 0;
11221
+ }
11222
+ };
11223
+
11224
+ // src/sdk.ts
11225
+ var MagmaClmmSDK = class {
11226
+ _cache = {};
11227
+ /**
11228
+ * RPC provider on the SUI chain
11229
+ */
11230
+ _rpcModule;
11231
+ /**
11232
+ * Provide interact with clmm pools with a pool router interface.
11233
+ */
11234
+ _pool;
11235
+ /**
11236
+ * Provide interact with clmm position with a position router interface.
11237
+ */
11238
+ _position;
11239
+ /**
11240
+ * Provide interact with a pool swap router interface.
11241
+ */
11242
+ _swap;
11243
+ /**
11244
+ * Provide interact with a lock interface.
11245
+ */
11246
+ _lock;
11247
+ _gauge;
11248
+ _dlmm;
11249
+ /**
11250
+ * Provide interact with a position rewarder interface.
11251
+ */
11252
+ _rewarder;
11253
+ /**
11254
+ * Provide interact with a pool router interface.
11255
+ */
11256
+ _router;
11257
+ /**
11258
+ * Provide interact with a pool routerV2 interface.
11259
+ */
11260
+ _router_v2;
11261
+ /**
11262
+ * Provide interact with pool and token config (contain token base info for metadat).
11263
+ * @deprecated Please use MagmaConfig instead
11264
+ */
11265
+ _token;
11266
+ /**
11267
+ * Provide interact with clmm pool and coin and launchpad pool config
11268
+ */
11269
+ _config;
11270
+ /**
11271
+ * Provide sdk options
11272
+ */
11273
+ _sdkOptions;
11274
+ /**
11275
+ * After connecting the wallet, set the current wallet address to senderAddress.
11276
+ */
11277
+ _senderAddress = "";
11278
+ constructor(options) {
11279
+ this._sdkOptions = options;
11280
+ this._rpcModule = new RpcModule({
11281
+ url: options.fullRpcUrl
11282
+ });
9862
11283
  this._swap = new SwapModule(this);
9863
11284
  this._lock = new LockModule(this);
9864
11285
  this._gauge = new GaugeModule(this);
11286
+ this._dlmm = new DlmmModule(this);
9865
11287
  this._pool = new PoolModule(this);
9866
11288
  this._position = new PositionModule(this);
9867
11289
  this._rewarder = new RewarderModule(this);
@@ -9899,6 +11321,9 @@ var MagmaClmmSDK = class {
9899
11321
  get Gauge() {
9900
11322
  return this._gauge;
9901
11323
  }
11324
+ get Dlmm() {
11325
+ return this._dlmm;
11326
+ }
9902
11327
  /**
9903
11328
  * Getter for the fullClient property.
9904
11329
  * @returns {RpcModule} The fullClient property value.
@@ -10072,6 +11497,7 @@ var main_default = MagmaClmmSDK;
10072
11497
  var SDKConfig = {
10073
11498
  clmmConfig: {
10074
11499
  pools_id: "0xfa145b9de10fe858be81edd1c6cdffcf27be9d016de02a1345eb1009a68ba8b2",
11500
+ // clmm and dlmm both use this global_config
10075
11501
  global_config_id: "0x4c4e1402401f72c7d8533d0ed8d5f8949da363c7a3319ccef261ffe153d32f8a",
10076
11502
  global_vault_id: "0xa7e1102f222b6eb81ccc8a126e7feb2353342be9df6f6646a77c4519da29c071",
10077
11503
  admin_cap_id: "0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75"
@@ -10091,7 +11517,11 @@ var SDKConfig = {
10091
11517
  distribution_cfg: "0xaff8d151ac29317201151f97d28c546b3c5923d8cfc5499f40dea61c4022c949",
10092
11518
  magma_token: "0x7161c6c6bb65f852797c8f7f5c4f8d57adaf796e1b840921f9e23fabeadfd54e::magma::MAGMA",
10093
11519
  minter_id: "0x4fa5766cd83b33b215b139fec27ac344040f3bbd84fcbee7b61fc671aadc51fa"
10094
- }
11520
+ },
11521
+ dlmmConfig: {
11522
+ factory: ""
11523
+ },
11524
+ gaugeConfig: {}
10095
11525
  };
10096
11526
  var clmmMainnet = {
10097
11527
  fullRpcUrl: getFullnodeUrl("mainnet"),
@@ -10108,6 +11538,11 @@ var clmmMainnet = {
10108
11538
  published_at: "0x4a35d3dfef55ed3631b7158544c6322a23bc434fe4fca1234cb680ce0505f82d",
10109
11539
  config: SDKConfig.clmmConfig
10110
11540
  },
11541
+ dlmm_pool: {
11542
+ package_id: "",
11543
+ published_at: "",
11544
+ config: SDKConfig.dlmmConfig
11545
+ },
10111
11546
  distribution: {
10112
11547
  package_id: "0xee4a1f231dc45a303389998fe26c4e39278cf68b404b32e4f0b9769129b8267b",
10113
11548
  published_at: "0xee4a1f231dc45a303389998fe26c4e39278cf68b404b32e4f0b9769129b8267b"
@@ -10161,6 +11596,9 @@ var SDKConfig2 = {
10161
11596
  distribution_cfg: "0x94e23846c975e2faf89a61bfc2b10ad64decab9069eb1f9fc39752b010868c74",
10162
11597
  magma_token: "0x45ac2371c33ca0df8dc784d62c8ce5126d42edd8c56820396524dff2ae0619b1::magma_token::MAGMA_TOKEN",
10163
11598
  minter_id: "0x89435d6b2a510ba50ca23303f10e91ec058f138a88f69a43fe03cd22edb214c5"
11599
+ },
11600
+ dlmmConfig: {
11601
+ factory: ""
10164
11602
  }
10165
11603
  };
10166
11604
  var clmmTestnet = {
@@ -10175,6 +11613,11 @@ var clmmTestnet = {
10175
11613
  published_at: "0x23e0b5ab4aa63d0e6fd98fa5e247bcf9b36ad716b479d39e56b2ba9ff631e09d",
10176
11614
  config: SDKConfig2.clmmConfig
10177
11615
  },
11616
+ dlmm_pool: {
11617
+ package_id: "",
11618
+ published_at: "",
11619
+ config: SDKConfig2.dlmmConfig
11620
+ },
10178
11621
  distribution: {
10179
11622
  package_id: "0x45ac2371c33ca0df8dc784d62c8ce5126d42edd8c56820396524dff2ae0619b1",
10180
11623
  published_at: "0x45ac2371c33ca0df8dc784d62c8ce5126d42edd8c56820396524dff2ae0619b1"
@@ -10222,6 +11665,7 @@ var src_default = MagmaClmmSDK;
10222
11665
  export {
10223
11666
  AMM_SWAP_MODULE,
10224
11667
  AmountSpecified,
11668
+ BinMath,
10225
11669
  CLOCK_ADDRESS,
10226
11670
  CachedContent,
10227
11671
  ClmmExpectSwapModule,
@@ -10249,6 +11693,7 @@ export {
10249
11693
  DeepbookCustodianV2Moudle,
10250
11694
  DeepbookEndpointsV2Moudle,
10251
11695
  DeepbookUtils,
11696
+ DlmmScript,
10252
11697
  FEE_RATE_DENOMINATOR,
10253
11698
  GAS_SYMBOL,
10254
11699
  GAS_TYPE_ARG,
@@ -10276,6 +11721,7 @@ export {
10276
11721
  SUI_SYSTEM_STATE_OBJECT_ID,
10277
11722
  SplitSwap,
10278
11723
  SplitUnit,
11724
+ StrategyType,
10279
11725
  SwapDirection,
10280
11726
  SwapModule,
10281
11727
  SwapUtils,
@@ -10297,6 +11743,10 @@ export {
10297
11743
  adjustForSlippage,
10298
11744
  asIntN,
10299
11745
  asUintN,
11746
+ autoFillXByStrategy,
11747
+ autoFillXByWeight,
11748
+ autoFillYByStrategy,
11749
+ autoFillYByWeight,
10300
11750
  bufferToHex,
10301
11751
  buildClmmPositionName,
10302
11752
  buildNFT,
@@ -10335,12 +11785,14 @@ export {
10335
11785
  getAmountUnfixedDelta,
10336
11786
  getCoinAFromLiquidity,
10337
11787
  getCoinBFromLiquidity,
11788
+ getCoinXYForLiquidity,
10338
11789
  getDefaultSuiInputType,
10339
11790
  getDeltaA,
10340
11791
  getDeltaB,
10341
11792
  getDeltaDownFromOutput,
10342
11793
  getDeltaUpFromInput,
10343
11794
  getFutureTime,
11795
+ getLiquidityAndCoinYByCoinX,
10344
11796
  getLiquidityFromCoinA,
10345
11797
  getLiquidityFromCoinB,
10346
11798
  getLowerSqrtPriceFromCoinA,
@@ -10364,6 +11816,7 @@ export {
10364
11816
  getObjectType,
10365
11817
  getObjectVersion,
10366
11818
  getPackagerConfigs,
11819
+ getPriceOfBinByBinId,
10367
11820
  getRewardInTickRange,
10368
11821
  getSuiObjectData,
10369
11822
  getTickDataFromUrlData,
@@ -10387,10 +11840,15 @@ export {
10387
11840
  shortAddress,
10388
11841
  shortString,
10389
11842
  tickScore,
11843
+ toAmountAskSide,
11844
+ toAmountBidSide,
11845
+ toAmountBothSide,
11846
+ toAmountsBothSideByStrategy,
10390
11847
  toBuffer,
10391
11848
  toCoinAmount,
10392
11849
  toDecimalsAmount,
10393
11850
  transClmmpoolDataWithoutTicks,
10394
- utf8to16
11851
+ utf8to16,
11852
+ withLiquiditySlippage
10395
11853
  };
10396
11854
  //# sourceMappingURL=index.mjs.map