@swapkit/helpers 1.0.0-rc.103 → 1.0.0-rc.105

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1280,7 +1280,7 @@ var MemoType;
1280
1280
  MemoType2["BOND"] = "BOND";
1281
1281
  MemoType2["DEPOSIT"] = "+";
1282
1282
  MemoType2["LEAVE"] = "LEAVE";
1283
- MemoType2["THORNAME_REGISTER"] = "~";
1283
+ MemoType2["NAME_REGISTER"] = "~";
1284
1284
  MemoType2["UNBOND"] = "UNBOND";
1285
1285
  MemoType2["WITHDRAW"] = "-";
1286
1286
  MemoType2["OPEN_LOAN"] = "$+";
@@ -1627,1108 +1627,1126 @@ var QuoteResponseSchema = z2.object({
1627
1627
  description: "Error message"
1628
1628
  }))
1629
1629
  });
1630
- // src/modules/requestClient.ts
1631
- import ky from "ky";
1632
- function setRequestClientConfig({ apiKey, ...config }) {
1633
- kyClient = ky.create({
1634
- ...config,
1635
- headers: { ...defaultRequestHeaders, ...config.headers, "x-api-key": apiKey }
1636
- });
1630
+ // src/helpers/validators.ts
1631
+ function validateIdentifier(identifier = "") {
1632
+ const uppercasedIdentifier = identifier.toUpperCase();
1633
+ const [chain] = uppercasedIdentifier.split(".");
1634
+ if (supportedChains.includes(chain))
1635
+ return true;
1636
+ const [synthChain] = uppercasedIdentifier.split("/");
1637
+ if (supportedChains.includes(synthChain))
1638
+ return true;
1639
+ throw new Error(`Invalid identifier: ${identifier}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`);
1637
1640
  }
1638
- var getKyClient = function() {
1639
- if (kyClient)
1640
- return kyClient;
1641
- kyClient = ky.create({ headers: defaultRequestHeaders });
1642
- return kyClient;
1643
- };
1644
- var kyClient;
1645
- var defaultRequestHeaders = typeof window !== "undefined" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" };
1646
- var getTypedBaseRequestClient = (ky2) => ({
1647
- get: (url, options) => ky2.get(url, options).json(),
1648
- post: (url, options) => ky2.post(url, options).json()
1649
- });
1650
- var RequestClient = {
1651
- ...getTypedBaseRequestClient(getKyClient()),
1652
- extend: (options) => {
1653
- const extendedClient = getKyClient().extend(options);
1654
- return {
1655
- ...getTypedBaseRequestClient(extendedClient),
1656
- extend: RequestClient.extend
1657
- };
1658
- }
1659
- };
1641
+ function validateTNS(name) {
1642
+ if (name.length > 30)
1643
+ return false;
1644
+ const regex = /^[a-zA-Z0-9+_-]+$/g;
1645
+ return !!name.match(regex);
1646
+ }
1647
+ var supportedChains = [...Object.values(Chain), "TERRA"];
1660
1648
 
1661
- // src/helpers/asset.ts
1662
- async function findAssetBy(params) {
1663
- const tokenPackages = await import("@swapkit/tokens");
1664
- for (const tokenList of Object.values(tokenPackages)) {
1665
- for (const { identifier, chain: tokenChain, ...rest } of tokenList.tokens) {
1666
- if ("identifier" in params && identifier === params.identifier) {
1667
- return identifier;
1668
- }
1669
- if ("address" in rest && "chain" in params && tokenChain === params.chain && rest.address.toLowerCase() === params.contract.toLowerCase())
1670
- return identifier;
1671
- }
1649
+ // src/modules/bigIntArithmetics.ts
1650
+ function formatBigIntToSafeValue({
1651
+ value,
1652
+ bigIntDecimal = DEFAULT_DECIMAL,
1653
+ decimal = DEFAULT_DECIMAL
1654
+ }) {
1655
+ if (decimal === 0)
1656
+ return value.toString();
1657
+ const isNegative = value < 0n;
1658
+ let valueString = value.toString().substring(isNegative ? 1 : 0);
1659
+ const padLength = decimal - (valueString.length - 1);
1660
+ if (padLength > 0) {
1661
+ valueString = "0".repeat(padLength) + valueString;
1672
1662
  }
1673
- return;
1674
- }
1675
- var getDecimalMethodHex = "0x313ce567";
1676
- var getContractDecimals = async ({ chain, to }) => {
1677
- try {
1678
- const { result } = await RequestClient.post(ChainToRPC[chain], {
1679
- headers: {
1680
- accept: "*/*",
1681
- "content-type": "application/json",
1682
- "cache-control": "no-cache"
1683
- },
1684
- body: JSON.stringify({
1685
- id: 44,
1686
- jsonrpc: "2.0",
1687
- method: "eth_call",
1688
- params: [{ to: to.toLowerCase(), data: getDecimalMethodHex }, "latest"]
1689
- })
1690
- });
1691
- return Number.parseInt(BigInt(result || BaseDecimal[chain]).toString());
1692
- } catch (error) {
1693
- console.error(error);
1694
- return BaseDecimal[chain];
1663
+ const decimalIndex = valueString.length - decimal;
1664
+ let decimalString = valueString.slice(-decimal);
1665
+ if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) {
1666
+ decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1).toString()}`;
1667
+ } else {
1668
+ decimalString = decimalString.substring(0, bigIntDecimal);
1695
1669
  }
1670
+ return `${isNegative ? "-" : ""}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace(/\.?0*$/, "");
1671
+ }
1672
+ var toSafeValue = function(value) {
1673
+ const parsedValue = typeof value === "number" ? numberFormatter.format(value) : getStringValue(value);
1674
+ const splitValue = `${parsedValue}`.replaceAll(",", ".").split(".");
1675
+ return splitValue.length > 1 ? `${splitValue.slice(0, -1).join("")}.${splitValue.at(-1)}` : splitValue[0] || "0";
1696
1676
  };
1697
- var getETHAssetDecimal = (symbol) => {
1698
- if (symbol === Chain.Ethereum)
1699
- return BaseDecimal.ETH;
1700
- const splitSymbol = symbol.split("-");
1701
- const address = splitSymbol.length === 1 ? undefined : splitSymbol[splitSymbol.length - 1];
1702
- return address?.startsWith("0x") ? getContractDecimals({ chain: Chain.Ethereum, to: address }) : BaseDecimal.ETH;
1703
- };
1704
- var getAVAXAssetDecimal = (symbol) => {
1705
- const splitSymbol = symbol.split("-");
1706
- const address = splitSymbol.length === 1 ? undefined : splitSymbol[splitSymbol.length - 1];
1707
- return address?.startsWith("0x") ? getContractDecimals({ chain: Chain.Avalanche, to: address.toLowerCase() }) : BaseDecimal.AVAX;
1677
+ var getFloatDecimals = function(value) {
1678
+ const decimals = value.split(".")[1]?.length || 0;
1679
+ return Math.max(decimals, DEFAULT_DECIMAL);
1708
1680
  };
1709
- var getBSCAssetDecimal = (symbol) => {
1710
- if (symbol === Chain.BinanceSmartChain)
1711
- return BaseDecimal.BSC;
1712
- return BaseDecimal.BSC;
1681
+ var getStringValue = function(param) {
1682
+ return typeof param === "object" ? "getValue" in param ? param.getValue("string") : param.value : param;
1713
1683
  };
1714
- var getDecimal = ({ chain, symbol }) => {
1715
- switch (chain) {
1716
- case Chain.Ethereum:
1717
- return getETHAssetDecimal(symbol);
1718
- case Chain.Avalanche:
1719
- return getAVAXAssetDecimal(symbol);
1720
- case Chain.BinanceSmartChain:
1721
- return getBSCAssetDecimal(symbol);
1722
- default:
1723
- return BaseDecimal[chain];
1684
+ var DEFAULT_DECIMAL = 8;
1685
+ var toMultiplier = (decimal) => 10n ** BigInt(decimal);
1686
+ var decimalFromMultiplier = (multiplier) => Math.log10(Number.parseFloat(multiplier.toString()));
1687
+
1688
+ class BigIntArithmetics {
1689
+ decimalMultiplier = 10n ** 8n;
1690
+ bigIntValue = 0n;
1691
+ decimal;
1692
+ static fromBigInt(value, decimal) {
1693
+ return new BigIntArithmetics({
1694
+ decimal,
1695
+ value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })
1696
+ });
1724
1697
  }
1725
- };
1726
- var isGasAsset = ({ chain, symbol }) => {
1727
- switch (chain) {
1728
- case Chain.Arbitrum:
1729
- case Chain.Optimism:
1730
- return symbol === "ETH";
1731
- case Chain.Maya:
1732
- return symbol === "CACAO";
1733
- case Chain.Kujira:
1734
- return symbol === "KUJI";
1735
- case Chain.Cosmos:
1736
- return symbol === "ATOM";
1737
- case Chain.Polygon:
1738
- return symbol === "MATIC";
1739
- case Chain.BinanceSmartChain:
1740
- return symbol === "BNB";
1741
- case Chain.THORChain:
1742
- return symbol === "RUNE";
1743
- default:
1744
- return symbol === chain;
1698
+ static shiftDecimals({
1699
+ value,
1700
+ from,
1701
+ to
1702
+ }) {
1703
+ return BigIntArithmetics.fromBigInt(value.getBaseValue("bigint") * toMultiplier(to) / toMultiplier(from), to);
1745
1704
  }
1746
- };
1747
- var getCommonAssetInfo = (assetString) => {
1748
- switch (assetString) {
1749
- case `${Chain.Ethereum}.THOR`:
1750
- return { identifier: "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044", decimal: 18 };
1751
- case `${Chain.Ethereum}.vTHOR`:
1752
- return { identifier: "ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", decimal: 18 };
1753
- case Chain.Arbitrum:
1754
- return { identifier: `${Chain.Arbitrum}.ETH`, decimal: BaseDecimal[assetString] };
1755
- case Chain.Optimism:
1756
- return { identifier: `${Chain.Optimism}.ETH`, decimal: BaseDecimal[assetString] };
1757
- case Chain.Cosmos:
1758
- return { identifier: "GAIA.ATOM", decimal: BaseDecimal[assetString] };
1759
- case Chain.THORChain:
1760
- return { identifier: "THOR.RUNE", decimal: BaseDecimal[assetString] };
1761
- case Chain.BinanceSmartChain:
1762
- return { identifier: "BSC.BNB", decimal: BaseDecimal[assetString] };
1763
- case Chain.Maya:
1764
- return { identifier: "MAYA.CACAO", decimal: BaseDecimal.MAYA };
1765
- case `${Chain.Maya}.MAYA`:
1766
- return { identifier: "MAYA.MAYA", decimal: 4 };
1767
- case `${Chain.Kujira}.USK`:
1768
- return { identifier: `${Chain.Kujira}.USK`, decimal: 6 };
1769
- default:
1770
- return { identifier: `${assetString}.${assetString}`, decimal: BaseDecimal[assetString] };
1705
+ constructor(params) {
1706
+ const value = getStringValue(params);
1707
+ const isComplex = typeof params === "object";
1708
+ this.decimal = isComplex ? params.decimal : undefined;
1709
+ this.decimalMultiplier = isComplex && "decimalMultiplier" in params ? params.decimalMultiplier : toMultiplier(Math.max(getFloatDecimals(toSafeValue(value)), this.decimal || 0));
1710
+ this.#setValue(value);
1771
1711
  }
1772
- };
1773
- var getAssetType = ({ chain, symbol }) => {
1774
- if (symbol.includes("/"))
1775
- return "Synth";
1776
- switch (chain) {
1777
- case Chain.Cosmos:
1778
- return symbol === "ATOM" ? "Native" : Chain.Cosmos;
1779
- case Chain.Kujira:
1780
- return symbol === Chain.Kujira ? "Native" : Chain.Kujira;
1781
- case Chain.Binance:
1782
- return symbol === Chain.Binance ? "Native" : "BEP2";
1783
- case Chain.BinanceSmartChain:
1784
- return symbol === Chain.Binance ? "Native" : "BEP20";
1785
- case Chain.Ethereum:
1786
- return symbol === Chain.Ethereum ? "Native" : "ERC20";
1787
- case Chain.Avalanche:
1788
- return symbol === Chain.Avalanche ? "Native" : Chain.Avalanche;
1789
- case Chain.Polygon:
1790
- return symbol === Chain.Polygon ? "Native" : "POLYGON";
1791
- case Chain.Arbitrum:
1792
- return [Chain.Ethereum, Chain.Arbitrum].includes(symbol) ? "Native" : "ARBITRUM";
1793
- case Chain.Optimism:
1794
- return [Chain.Ethereum, Chain.Optimism].includes(symbol) ? "Native" : "OPTIMISM";
1795
- default:
1796
- return "Native";
1712
+ set(value) {
1713
+ return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() });
1797
1714
  }
1798
- };
1799
- var assetFromString = (assetString) => {
1800
- const [chain, ...symbolArray] = assetString.split(".");
1801
- const synth = assetString.includes("/");
1802
- const symbol = symbolArray.join(".");
1803
- const splitSymbol = symbol?.split("-");
1804
- const ticker = splitSymbol?.length ? splitSymbol.length === 1 ? splitSymbol[0] : splitSymbol.slice(0, -1).join("-") : undefined;
1805
- return { chain, symbol, ticker, synth };
1806
- };
1807
- var potentialScamRegex = new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/, "gmi");
1808
- var evmAssetHasAddress = (assetString) => {
1809
- const [chain, symbol] = assetString.split(".");
1810
- if (!EVMChains.includes(chain))
1811
- return true;
1812
- const splitSymbol = symbol.split("-");
1813
- const address = splitSymbol.length === 1 ? undefined : splitSymbol[splitSymbol.length - 1];
1814
- return isGasAsset({ chain, symbol }) || !!address;
1815
- };
1816
- var filterAssets = (tokens2) => tokens2.filter(({ chain, value, symbol }) => {
1817
- const assetString = `${chain}.${symbol}`;
1818
- return !potentialScamRegex.test(assetString) && evmAssetHasAddress(assetString) && value !== "0";
1819
- });
1820
- // src/helpers/derivationPath.ts
1821
- function getDerivationPathFor({ chain, index, addressIndex = 0, type }) {
1822
- if (EVMChains.includes(chain)) {
1823
- if (type === "legacy")
1824
- return [44, 60, 0, index];
1825
- if (type === "ledgerLive")
1826
- return [44, 60, index, 0, addressIndex];
1827
- return updatedLastIndex(NetworkDerivationPath[chain], index);
1715
+ add(...args) {
1716
+ return this.#arithmetics("add", ...args);
1828
1717
  }
1829
- if ([Chain.Bitcoin, Chain.Litecoin].includes(chain)) {
1830
- const chainId = chain === Chain.Bitcoin ? 0 : 2;
1831
- if (type === "nativeSegwitMiddleAccount")
1832
- return [84, chainId, index, 0, addressIndex];
1833
- if (type === "segwit")
1834
- return [49, chainId, 0, 0, index];
1835
- if (type === "legacy")
1836
- return [44, chainId, 0, 0, index];
1837
- return updatedLastIndex(NetworkDerivationPath[chain], index);
1718
+ sub(...args) {
1719
+ return this.#arithmetics("sub", ...args);
1838
1720
  }
1839
- return updatedLastIndex(NetworkDerivationPath[chain], index);
1840
- }
1841
- function getWalletFormatFor(path) {
1842
- const [_, purpose, chainId] = path.split("/").map((p) => Number.parseInt(p, 10));
1843
- if (chainId === 145)
1844
- ;
1845
- switch (purpose) {
1846
- case 44:
1847
- return "legacy";
1848
- case 49:
1849
- return "p2sh";
1850
- default:
1851
- return "bech32";
1721
+ mul(...args) {
1722
+ return this.#arithmetics("mul", ...args);
1852
1723
  }
1853
- }
1854
- var updatedLastIndex = (path, index) => [
1855
- ...path.slice(0, path.length - 1),
1856
- index
1857
- ];
1858
- // src/helpers/liquidity.ts
1859
- function getAsymmetricRuneShare({
1860
- liquidityUnits,
1861
- poolUnits,
1862
- runeDepth
1863
- }) {
1864
- const s = toTCSwapKitNumber(liquidityUnits);
1865
- const T = toTCSwapKitNumber(poolUnits);
1866
- const A = toTCSwapKitNumber(runeDepth);
1867
- const part1 = s.mul(A);
1868
- const part2 = T.mul(T).mul(2);
1869
- const part3 = T.mul(s).mul(2);
1870
- const part4 = s.mul(s);
1871
- const part5 = T.mul(T).mul(T);
1872
- const numerator = part1.mul(part2.sub(part3).add(part4));
1873
- return numerator.div(part5);
1874
- }
1875
- function getAsymmetricAssetShare({
1876
- liquidityUnits,
1877
- poolUnits,
1878
- assetDepth
1879
- }) {
1880
- const s = toTCSwapKitNumber(liquidityUnits);
1881
- const T = toTCSwapKitNumber(poolUnits);
1882
- const A = toTCSwapKitNumber(assetDepth);
1883
- const part1 = s.mul(A);
1884
- const part2 = T.mul(T).mul(2);
1885
- const part3 = T.mul(s).mul(2);
1886
- const part4 = s.mul(s);
1887
- const numerator = part1.mul(part2.sub(part3).add(part4));
1888
- const part5 = T.mul(T).mul(T);
1889
- return numerator.div(part5);
1890
- }
1891
- function getAsymmetricRuneWithdrawAmount({
1892
- percent,
1893
- runeDepth,
1894
- liquidityUnits,
1895
- poolUnits
1896
- }) {
1897
- return getAsymmetricRuneShare({ runeDepth, liquidityUnits, poolUnits }).mul(percent);
1898
- }
1899
- function getAsymmetricAssetWithdrawAmount({
1900
- percent,
1901
- assetDepth,
1902
- liquidityUnits,
1903
- poolUnits
1904
- }) {
1905
- return getAsymmetricAssetShare({ assetDepth, liquidityUnits, poolUnits }).mul(percent);
1906
- }
1907
- var toTCSwapKitNumber = function(value) {
1908
- return SwapKitNumber.fromBigInt(BigInt(value), BaseDecimal.THOR);
1909
- };
1910
- function getSymmetricPoolShare({
1911
- liquidityUnits,
1912
- poolUnits,
1913
- runeDepth,
1914
- assetDepth
1915
- }) {
1916
- return {
1917
- assetAmount: toTCSwapKitNumber(assetDepth).mul(liquidityUnits).div(poolUnits),
1918
- runeAmount: toTCSwapKitNumber(runeDepth).mul(liquidityUnits).div(poolUnits)
1919
- };
1920
- }
1921
- function getSymmetricWithdraw({
1922
- liquidityUnits,
1923
- poolUnits,
1924
- runeDepth,
1925
- assetDepth,
1926
- percent
1927
- }) {
1928
- return Object.fromEntries(Object.entries(getSymmetricPoolShare({ liquidityUnits, poolUnits, runeDepth, assetDepth })).map(([name, value]) => [name, value.mul(percent)]));
1929
- }
1930
- function getEstimatedPoolShare({
1931
- runeDepth,
1932
- poolUnits,
1933
- assetDepth,
1934
- liquidityUnits,
1935
- runeAmount,
1936
- assetAmount
1937
- }) {
1938
- const R = new SwapKitNumber({ value: runeDepth, decimal: 8 });
1939
- const A = new SwapKitNumber({ value: assetDepth, decimal: 8 });
1940
- const P = new SwapKitNumber({ value: poolUnits, decimal: 8 });
1941
- const runeAddAmount = new SwapKitNumber({ value: runeAmount, decimal: 8 });
1942
- const assetAddAmount = new SwapKitNumber({ value: assetAmount, decimal: 8 });
1943
- const rA = runeAddAmount.mul(A);
1944
- const aR = assetAddAmount.mul(R);
1945
- const ra = runeAddAmount.mul(assetAddAmount);
1946
- const RA = R.mul(A);
1947
- const numerator = P.mul(rA.add(aR.add(ra.mul(2))));
1948
- const denominator = rA.add(aR.add(RA.mul(2)));
1949
- const liquidityUnitsAfterAdd = numerator.div(denominator);
1950
- const estimatedLiquidityUnits = toTCSwapKitNumber(liquidityUnits).add(liquidityUnitsAfterAdd);
1951
- if (liquidityUnitsAfterAdd.getBaseValue("number") === 0) {
1952
- return estimatedLiquidityUnits.div(P).getBaseValue("number");
1724
+ div(...args) {
1725
+ return this.#arithmetics("div", ...args);
1953
1726
  }
1954
- const newPoolUnits = P.add(estimatedLiquidityUnits);
1955
- return estimatedLiquidityUnits.div(newPoolUnits).getBaseValue("number");
1956
- }
1957
- function getLiquiditySlippage({
1958
- runeAmount,
1959
- assetAmount,
1960
- runeDepth,
1961
- assetDepth
1962
- }) {
1963
- if (runeAmount === "0" || assetAmount === "0" || runeDepth === "0" || assetDepth === "0")
1964
- return 0;
1965
- const R = toTCSwapKitNumber(runeDepth);
1966
- const T = toTCSwapKitNumber(assetDepth);
1967
- const assetAddAmount = toTCSwapKitNumber(assetAmount);
1968
- const runeAddAmount = toTCSwapKitNumber(runeAmount);
1969
- const numerator = assetAddAmount.mul(R).sub(T.mul(runeAddAmount));
1970
- const denominator = T.mul(runeAddAmount).add(R.mul(T));
1971
- return Math.abs(numerator.div(denominator).getBaseValue("number"));
1972
- }
1973
- // src/helpers/memo.ts
1974
- var getMemoFor = (memoType, options) => {
1975
- switch (memoType) {
1976
- case MemoType.LEAVE:
1977
- case MemoType.BOND: {
1978
- const { address } = options;
1979
- return `${memoType}:${address}`;
1980
- }
1981
- case MemoType.UNBOND: {
1982
- const { address, unbondAmount } = options;
1983
- return `${memoType}:${address}:${unbondAmount}`;
1727
+ gt(value) {
1728
+ return this.#comparison("gt", value);
1729
+ }
1730
+ gte(value) {
1731
+ return this.#comparison("gte", value);
1732
+ }
1733
+ lt(value) {
1734
+ return this.#comparison("lt", value);
1735
+ }
1736
+ lte(value) {
1737
+ return this.#comparison("lte", value);
1738
+ }
1739
+ eqValue(value) {
1740
+ return this.#comparison("eqValue", value);
1741
+ }
1742
+ getValue(type) {
1743
+ const value = this.formatBigIntToSafeValue(this.bigIntValue, this.decimal || decimalFromMultiplier(this.decimalMultiplier));
1744
+ switch (type) {
1745
+ case "number":
1746
+ return Number(value);
1747
+ case "string":
1748
+ return value;
1749
+ case "bigint":
1750
+ return this.bigIntValue * 10n ** BigInt(this.decimal || 8n) / this.decimalMultiplier;
1984
1751
  }
1985
- case MemoType.THORNAME_REGISTER: {
1986
- const { name, chain, address, owner } = options;
1987
- return `${memoType}:${name}:${chain}:${address}${owner ? `:${owner}` : ""}`;
1752
+ }
1753
+ getBaseValue(type) {
1754
+ const divisor = this.decimalMultiplier / toMultiplier(this.decimal || BaseDecimal.THOR);
1755
+ const baseValue = this.bigIntValue / divisor;
1756
+ switch (type) {
1757
+ case "number":
1758
+ return Number(baseValue);
1759
+ case "string":
1760
+ return baseValue.toString();
1761
+ case "bigint":
1762
+ return baseValue;
1988
1763
  }
1989
- case MemoType.DEPOSIT: {
1990
- const { chain, symbol, address, singleSide } = options;
1991
- const getPoolIdentifier = (chain2, symbol2) => {
1992
- switch (chain2) {
1993
- case Chain.Litecoin:
1994
- return "l";
1995
- case Chain.Dogecoin:
1996
- return "d";
1997
- case Chain.BitcoinCash:
1998
- return "c";
1999
- default:
2000
- return `${chain2}.${symbol2}`;
2001
- }
2002
- };
2003
- return singleSide ? `${memoType}:${chain}/${symbol}` : `${memoType}:${getPoolIdentifier(chain, symbol)}:${address || ""}`;
1764
+ }
1765
+ getBigIntValue(value, decimal) {
1766
+ if (!decimal && typeof value === "object")
1767
+ return value.bigIntValue;
1768
+ const stringValue = getStringValue(value);
1769
+ const safeValue = toSafeValue(stringValue);
1770
+ if (safeValue === "0" || safeValue === "undefined")
1771
+ return 0n;
1772
+ return this.#toBigInt(safeValue, decimal);
1773
+ }
1774
+ toSignificant(significantDigits = 6) {
1775
+ const [int, dec] = this.getValue("string").split(".");
1776
+ const integer = int || "";
1777
+ const decimal = dec || "";
1778
+ const valueLength = Number.parseInt(integer) ? integer.length + decimal.length : decimal.length;
1779
+ if (valueLength <= significantDigits) {
1780
+ return this.getValue("string");
2004
1781
  }
2005
- case MemoType.WITHDRAW: {
2006
- const { chain, ticker, symbol, basisPoints, targetAssetString, singleSide } = options;
2007
- const shortenedSymbol = chain === "ETH" && ticker !== "ETH" ? `${ticker}-${symbol.slice(-3)}` : symbol;
2008
- const target = !singleSide && targetAssetString ? `:${targetAssetString}` : "";
2009
- const assetDivider = singleSide ? "/" : ".";
2010
- return `${memoType}:${chain}${assetDivider}${shortenedSymbol}:${basisPoints}${target}`;
1782
+ if (integer.length >= significantDigits) {
1783
+ return integer.slice(0, significantDigits).padEnd(integer.length, "0");
2011
1784
  }
2012
- case MemoType.OPEN_LOAN:
2013
- case MemoType.CLOSE_LOAN: {
2014
- const { asset, address } = options;
2015
- return `${memoType}:${asset}:${address}`;
1785
+ if (Number.parseInt(integer)) {
1786
+ return `${integer}.${decimal.slice(0, significantDigits - integer.length)}`.padEnd(significantDigits - integer.length, "0");
2016
1787
  }
2017
- default:
2018
- return "";
1788
+ const trimmedDecimal = Number.parseInt(decimal);
1789
+ const slicedDecimal = `${trimmedDecimal}`.slice(0, significantDigits);
1790
+ return `0.${slicedDecimal.padStart(decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length, "0")}`;
2019
1791
  }
2020
- };
2021
- // src/modules/swapKitError.ts
2022
- var errorMessages = {
2023
- core_wallet_connection_not_found: 10001,
2024
- core_estimated_max_spendable_chain_not_supported: 10002,
2025
- core_extend_error: 10003,
2026
- core_inbound_data_not_found: 10004,
2027
- core_approve_asset_address_or_from_not_found: 10005,
2028
- core_plugin_not_found: 10006,
2029
- core_plugin_swap_not_found: 10007,
2030
- core_approve_asset_target_invalid: 10008,
2031
- core_chain_halted: 10099,
2032
- core_wallet_xdefi_not_installed: 10101,
2033
- core_wallet_evmwallet_not_installed: 10102,
2034
- core_wallet_walletconnect_not_installed: 10103,
2035
- core_wallet_keystore_not_installed: 10104,
2036
- core_wallet_ledger_not_installed: 10105,
2037
- core_wallet_trezor_not_installed: 10106,
2038
- core_wallet_keplr_not_installed: 10107,
2039
- core_wallet_okx_not_installed: 10108,
2040
- core_wallet_keepkey_not_installed: 10109,
2041
- core_swap_invalid_params: 10200,
2042
- core_swap_route_not_complete: 10201,
2043
- core_swap_asset_not_recognized: 10202,
2044
- core_swap_contract_not_found: 10203,
2045
- core_swap_route_transaction_not_found: 10204,
2046
- core_swap_contract_not_supported: 10205,
2047
- core_swap_transaction_error: 10206,
2048
- core_swap_quote_mode_not_supported: 10207,
2049
- core_transaction_deposit_error: 10301,
2050
- core_transaction_create_liquidity_rune_error: 10302,
2051
- core_transaction_create_liquidity_asset_error: 10303,
2052
- core_transaction_create_liquidity_invalid_params: 10304,
2053
- core_transaction_add_liquidity_invalid_params: 10305,
2054
- core_transaction_add_liquidity_no_rune_address: 10306,
2055
- core_transaction_add_liquidity_rune_error: 10307,
2056
- core_transaction_add_liquidity_asset_error: 10308,
2057
- core_transaction_withdraw_error: 10309,
2058
- core_transaction_deposit_to_pool_error: 10310,
2059
- core_transaction_deposit_insufficient_funds_error: 10311,
2060
- core_transaction_deposit_gas_error: 10312,
2061
- core_transaction_invalid_sender_address: 10313,
2062
- core_transaction_deposit_server_error: 10314,
2063
- core_transaction_user_rejected: 10315,
2064
- wallet_ledger_connection_error: 20001,
2065
- wallet_ledger_connection_claimed: 20002,
2066
- wallet_ledger_get_address_error: 20003,
2067
- wallet_ledger_device_not_found: 20004,
2068
- wallet_ledger_device_locked: 20005,
2069
- chainflip_channel_error: 30001,
2070
- chainflip_broker_recipient_error: 30002,
2071
- api_v2_invalid_response: 40001,
2072
- helpers_number_different_decimals: 99101
2073
- };
2074
-
2075
- class SwapKitError extends Error {
2076
- constructor(errorKey, sourceError) {
2077
- if (sourceError) {
2078
- console.error(sourceError, {
2079
- stack: sourceError?.stack,
2080
- message: sourceError?.message
2081
- });
1792
+ toFixed(fixedDigits = 6) {
1793
+ const [int, dec] = this.getValue("string").split(".");
1794
+ const integer = int || "";
1795
+ const decimal = dec || "";
1796
+ if (Number.parseInt(integer)) {
1797
+ return `${integer}.${decimal.slice(0, fixedDigits)}`.padEnd(fixedDigits, "0");
2082
1798
  }
2083
- super(errorKey, {
2084
- cause: { code: errorMessages[errorKey], message: errorKey }
1799
+ const trimmedDecimal = Number.parseInt(decimal);
1800
+ const slicedDecimal = `${trimmedDecimal}`.slice(0, fixedDigits);
1801
+ return `0.${slicedDecimal.padStart(decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length, "0")}`;
1802
+ }
1803
+ toAbbreviation(digits = 2) {
1804
+ const value = this.getValue("number");
1805
+ const abbreviations = ["", "K", "M", "B", "T", "Q", "Qi", "S"];
1806
+ const tier = Math.floor(Math.log10(Math.abs(value)) / 3);
1807
+ const suffix = abbreviations[tier];
1808
+ if (!suffix)
1809
+ return this.getValue("string");
1810
+ const scale = 10 ** (tier * 3);
1811
+ const scaled = value / scale;
1812
+ return `${scaled.toFixed(digits)}${suffix}`;
1813
+ }
1814
+ toCurrency(currency = "$", {
1815
+ currencyPosition = "start",
1816
+ decimal = 2,
1817
+ decimalSeparator = ".",
1818
+ thousandSeparator = ","
1819
+ } = {}) {
1820
+ const value = this.getValue("number");
1821
+ const [int = "", dec = ""] = value.toFixed(6).split(".");
1822
+ const integer = int.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
1823
+ const parsedValue = int || dec ? int === "0" ? `${Number.parseFloat(`0.${dec}`)}`.replace(".", decimalSeparator) : `${integer}${Number.parseInt(dec) ? `${decimalSeparator}${dec.slice(0, decimal)}` : ""}` : "0.00";
1824
+ return `${currencyPosition === "start" ? currency : ""}${parsedValue}${currencyPosition === "end" ? currency : ""}`;
1825
+ }
1826
+ formatBigIntToSafeValue(value, decimal) {
1827
+ const bigIntDecimal = decimal || this.decimal || DEFAULT_DECIMAL;
1828
+ const decimalToUseForConversion = Math.max(bigIntDecimal, decimalFromMultiplier(this.decimalMultiplier));
1829
+ const isNegative = value < 0n;
1830
+ const valueString = value.toString().substring(isNegative ? 1 : 0);
1831
+ const padLength = decimalToUseForConversion - (valueString.length - 1);
1832
+ const parsedValueString = padLength > 0 ? "0".repeat(padLength) + valueString : valueString;
1833
+ const decimalIndex = parsedValueString.length - decimalToUseForConversion;
1834
+ let decimalString = parsedValueString.slice(-decimalToUseForConversion);
1835
+ if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) {
1836
+ decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1).toString()}`;
1837
+ } else {
1838
+ decimalString = decimalString.substring(0, bigIntDecimal);
1839
+ }
1840
+ return `${isNegative ? "-" : ""}${parsedValueString.slice(0, decimalIndex)}.${decimalString}`.replace(/\.?0*$/, "");
1841
+ }
1842
+ #arithmetics(method, ...args) {
1843
+ const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args);
1844
+ const decimal = Math.max(precisionDecimal, decimalFromMultiplier(this.decimalMultiplier));
1845
+ const precisionDecimalMultiplier = toMultiplier(decimal);
1846
+ const result = args.reduce((acc, arg) => {
1847
+ const value2 = this.getBigIntValue(arg, decimal);
1848
+ switch (method) {
1849
+ case "add":
1850
+ return acc + value2;
1851
+ case "sub":
1852
+ return acc - value2;
1853
+ case "mul":
1854
+ return acc * value2 / precisionDecimalMultiplier;
1855
+ case "div": {
1856
+ if (value2 === 0n)
1857
+ throw new RangeError("Division by zero");
1858
+ return acc * precisionDecimalMultiplier / value2;
1859
+ }
1860
+ default:
1861
+ return acc;
1862
+ }
1863
+ }, this.bigIntValue * precisionDecimalMultiplier / this.decimalMultiplier);
1864
+ const value = formatBigIntToSafeValue({
1865
+ bigIntDecimal: decimal,
1866
+ decimal,
1867
+ value: result
1868
+ });
1869
+ return new this.constructor({
1870
+ decimalMultiplier: toMultiplier(decimal),
1871
+ decimal: this.decimal,
1872
+ value,
1873
+ identifier: this.toString()
2085
1874
  });
2086
- Object.setPrototypeOf(this, SwapKitError.prototype);
2087
1875
  }
2088
- }
2089
-
2090
- // src/helpers/others.ts
2091
- function getTHORNameCost(numberOfYears) {
2092
- if (numberOfYears < 0)
2093
- throw new Error("Invalid number of years");
2094
- return 10 + numberOfYears;
2095
- }
2096
- function getMAYANameCost(numberOfYears) {
2097
- if (numberOfYears < 0)
2098
- throw new Error("Invalid number of year");
2099
- return Math.round((10 + numberOfYears * 1.0512) * 10000000000) / 10000000000;
2100
- }
2101
- function derivationPathToString([network3, chainId, account, change, index]) {
2102
- const shortPath = typeof index !== "number";
2103
- return `m/${network3}'/${chainId}'/${account}'/${change}${shortPath ? "" : `/${index}`}`;
2104
- }
2105
- function wrapWithThrow(fn, errorKey) {
2106
- try {
2107
- return fn();
2108
- } catch (error) {
2109
- if (errorKey) {
2110
- throw new SwapKitError(errorKey, error);
1876
+ #comparison(method, ...args) {
1877
+ const decimal = this.#retrievePrecisionDecimal(this, ...args);
1878
+ const value = this.getBigIntValue(args[0] || "0", decimal);
1879
+ const compareToValue = this.getBigIntValue(this, decimal);
1880
+ switch (method) {
1881
+ case "gt":
1882
+ return compareToValue > value;
1883
+ case "gte":
1884
+ return compareToValue >= value;
1885
+ case "lt":
1886
+ return compareToValue < value;
1887
+ case "lte":
1888
+ return compareToValue <= value;
1889
+ case "eqValue":
1890
+ return compareToValue === value;
2111
1891
  }
2112
- return console.error(error);
2113
1892
  }
2114
- }
2115
- // src/helpers/validators.ts
2116
- function validateIdentifier(identifier = "") {
2117
- const uppercasedIdentifier = identifier.toUpperCase();
2118
- const [chain] = uppercasedIdentifier.split(".");
2119
- if (supportedChains.includes(chain))
2120
- return true;
2121
- const [synthChain] = uppercasedIdentifier.split("/");
2122
- if (supportedChains.includes(synthChain))
2123
- return true;
2124
- throw new Error(`Invalid identifier: ${identifier}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`);
2125
- }
2126
- function validateTNS(name) {
2127
- if (name.length > 30)
2128
- return false;
2129
- const regex = /^[a-zA-Z0-9+_-]+$/g;
2130
- return !!name.match(regex);
2131
- }
2132
- var supportedChains = [...Object.values(Chain), "TERRA"];
2133
- // src/helpers/web3wallets.ts
2134
- function getEIP6963Wallets() {
2135
- const providers = [];
2136
- function onAnnouncement(event) {
2137
- if (providers.map((p) => p.info.uuid).includes(event.detail.info.uuid))
2138
- return;
2139
- providers.push(event.detail);
1893
+ #setValue(value) {
1894
+ const safeValue = toSafeValue(value) || "0";
1895
+ this.bigIntValue = this.#toBigInt(safeValue);
2140
1896
  }
2141
- window.addEventListener("eip6963:announceProvider", onAnnouncement);
2142
- window.dispatchEvent(new Event("eip6963:requestProvider"));
2143
- function removeEIP6963EventListener() {
2144
- window.removeEventListener("eip6963:announceProvider", onAnnouncement);
1897
+ #retrievePrecisionDecimal(...args) {
1898
+ const decimals = args.map((arg) => {
1899
+ const isObject = typeof arg === "object";
1900
+ const value = isObject ? arg.decimal || decimalFromMultiplier(arg.decimalMultiplier) : getFloatDecimals(toSafeValue(arg));
1901
+ return value;
1902
+ }).filter(Boolean);
1903
+ return Math.max(...decimals, DEFAULT_DECIMAL);
1904
+ }
1905
+ #toBigInt(value, decimal) {
1906
+ const multiplier = decimal ? toMultiplier(decimal) : this.decimalMultiplier;
1907
+ const padDecimal = decimalFromMultiplier(multiplier);
1908
+ const [integerPart = "", decimalPart = ""] = value.split(".");
1909
+ return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, "0")}`);
2145
1910
  }
2146
- return { providers, removeEIP6963EventListener };
2147
1911
  }
2148
- var methodsToWrap = [
2149
- "approve",
2150
- "approvedAmount",
2151
- "call",
2152
- "sendTransaction",
2153
- "transfer",
2154
- "isApproved",
2155
- "approvedAmount",
2156
- "EIP1193SendTransaction",
2157
- "getFeeData",
2158
- "broadcastTransaction",
2159
- "estimateCall",
2160
- "estimateGasLimit",
2161
- "estimateGasPrices",
2162
- "createContractTxObject"
2163
- ];
2164
- var wrapMethodWithNetworkSwitch = (func, provider, chainId) => async (...args) => {
2165
- try {
2166
- await switchEVMWalletNetwork(provider, chainId);
2167
- } catch (error) {
2168
- throw new Error(`Failed to switch network: ${error}`);
1912
+ var numberFormatter = Intl.NumberFormat("fullwide", {
1913
+ useGrouping: false,
1914
+ maximumFractionDigits: 20
1915
+ });
1916
+
1917
+ // src/modules/swapKitNumber.ts
1918
+ class SwapKitNumber extends BigIntArithmetics {
1919
+ constructor() {
1920
+ super(...arguments);
2169
1921
  }
2170
- return func(...args);
2171
- };
2172
- var providerRequest = ({ provider, params, method }) => {
2173
- if (!provider?.send)
2174
- throw new Error("Provider not found");
2175
- const providerParams = params ? Array.isArray(params) ? params : [params] : [];
2176
- return provider.send(method, providerParams);
2177
- };
2178
- var prepareNetworkSwitch = ({
2179
- toolbox,
2180
- chainId,
2181
- provider = window.ethereum
2182
- }) => {
2183
- const wrappedMethods = methodsToWrap.reduce((object, methodName) => {
2184
- if (!toolbox[methodName])
2185
- return object;
2186
- const method = toolbox[methodName];
2187
- if (typeof method !== "function")
2188
- return object;
2189
- return {
2190
- ...object,
2191
- [methodName]: wrapMethodWithNetworkSwitch(method, provider, chainId)
2192
- };
2193
- }, {});
2194
- return { ...toolbox, ...wrappedMethods };
2195
- };
2196
- var addEVMWalletNetwork = (provider, networkParams) => providerRequest({ provider, method: "wallet_addEthereumChain", params: [networkParams] });
2197
- var switchEVMWalletNetwork = (provider, chainId = ChainId.EthereumHex) => providerRequest({ provider, method: "wallet_switchEthereumChain", params: [{ chainId }] });
2198
- var addAccountsChangedCallback = (callback) => {
2199
- window.ethereum?.on("accountsChanged", () => callback());
2200
- window.xfi?.ethereum.on("accountsChanged", () => callback());
2201
- };
2202
- var getETHDefaultWallet = () => {
2203
- const { isTrust, isBraveWallet, __XDEFI, overrideIsMetaMask, selectedProvider } = window?.ethereum || {};
2204
- if (isTrust)
2205
- return WalletOption.TRUSTWALLET_WEB;
2206
- if (isBraveWallet)
2207
- return WalletOption.BRAVE;
2208
- if (overrideIsMetaMask && selectedProvider?.isCoinbaseWallet)
2209
- return WalletOption.COINBASE_WEB;
2210
- if (__XDEFI)
2211
- WalletOption.XDEFI;
2212
- return WalletOption.METAMASK;
2213
- };
2214
- var isDetected = (walletOption) => {
2215
- return listWeb3EVMWallets().includes(walletOption);
2216
- };
2217
- var listWeb3EVMWallets = () => {
2218
- const metamaskEnabled = window?.ethereum && !window.ethereum?.isBraveWallet;
2219
- const xdefiEnabled = window?.xfi || window?.ethereum?.__XDEFI;
2220
- const braveEnabled = window?.ethereum?.isBraveWallet;
2221
- const trustEnabled = window?.ethereum?.isTrust || window?.trustwallet;
2222
- const coinbaseEnabled = window?.ethereum?.overrideIsMetaMask && window?.ethereum?.selectedProvider?.isCoinbaseWallet || window?.coinbaseWalletExtension;
2223
- const wallets = [];
2224
- if (metamaskEnabled)
2225
- wallets.push(WalletOption.METAMASK);
2226
- if (xdefiEnabled)
2227
- wallets.push(WalletOption.XDEFI);
2228
- if (braveEnabled)
2229
- wallets.push(WalletOption.BRAVE);
2230
- if (trustEnabled)
2231
- wallets.push(WalletOption.TRUSTWALLET_WEB);
2232
- if (coinbaseEnabled)
2233
- wallets.push(WalletOption.COINBASE_WEB);
2234
- if (okxMobileEnabled())
2235
- wallets.push(WalletOption.OKX_MOBILE);
2236
- return wallets;
2237
- };
2238
- var okxMobileEnabled = () => {
2239
- const ua = navigator.userAgent;
2240
- const isIOS = /iphone|ipad|ipod|ios/i.test(ua);
2241
- const isAndroid = /android|XiaoMi|MiuiBrowser/i.test(ua);
2242
- const isMobile = isIOS || isAndroid;
2243
- const isOKApp = /OKApp/i.test(ua);
2244
- return isMobile && isOKApp;
2245
- };
2246
- var isWeb3Detected = () => typeof window.ethereum !== "undefined";
2247
- // src/modules/bigIntArithmetics.ts
2248
- function formatBigIntToSafeValue({
2249
- value,
2250
- bigIntDecimal = DEFAULT_DECIMAL,
2251
- decimal = DEFAULT_DECIMAL
2252
- }) {
2253
- if (decimal === 0)
2254
- return value.toString();
2255
- const isNegative = value < 0n;
2256
- let valueString = value.toString().substring(isNegative ? 1 : 0);
2257
- const padLength = decimal - (valueString.length - 1);
2258
- if (padLength > 0) {
2259
- valueString = "0".repeat(padLength) + valueString;
1922
+ eq(value) {
1923
+ return this.eqValue(value);
2260
1924
  }
2261
- const decimalIndex = valueString.length - decimal;
2262
- let decimalString = valueString.slice(-decimal);
2263
- if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) {
2264
- decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1).toString()}`;
2265
- } else {
2266
- decimalString = decimalString.substring(0, bigIntDecimal);
1925
+ static fromBigInt(value, decimal) {
1926
+ return new SwapKitNumber({
1927
+ decimal,
1928
+ value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })
1929
+ });
2267
1930
  }
2268
- return `${isNegative ? "-" : ""}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace(/\.?0*$/, "");
2269
1931
  }
2270
- var toSafeValue = function(value) {
2271
- const parsedValue = typeof value === "number" ? numberFormatter.format(value) : getStringValue(value);
2272
- const splitValue = `${parsedValue}`.replaceAll(",", ".").split(".");
2273
- return splitValue.length > 1 ? `${splitValue.slice(0, -1).join("")}.${splitValue.at(-1)}` : splitValue[0] || "0";
1932
+
1933
+ // src/modules/assetValue.ts
1934
+ function getMinAmountByChain(chain) {
1935
+ const asset2 = AssetValue.fromChainOrSignature(chain);
1936
+ switch (chain) {
1937
+ case Chain.Bitcoin:
1938
+ case Chain.Litecoin:
1939
+ case Chain.BitcoinCash:
1940
+ return asset2.set(0.00010001);
1941
+ case Chain.Dogecoin:
1942
+ return asset2.set(1.00000001);
1943
+ case Chain.Avalanche:
1944
+ case Chain.Ethereum:
1945
+ return asset2.set(0.00000001);
1946
+ case Chain.THORChain:
1947
+ case Chain.Maya:
1948
+ return asset2.set(0);
1949
+ case Chain.Cosmos:
1950
+ return asset2.set(0.000001);
1951
+ default:
1952
+ return asset2.set(0.00000001);
1953
+ }
1954
+ }
1955
+ async function createAssetValue(identifier, value = 0) {
1956
+ validateIdentifier(identifier);
1957
+ const staticToken = staticTokensMap.get(identifier.toUpperCase());
1958
+ const decimal = staticToken?.decimal || await getDecimal(getAssetInfo(identifier));
1959
+ if (!staticToken) {
1960
+ staticTokensMap.set(identifier.toUpperCase(), { identifier, decimal });
1961
+ }
1962
+ return new AssetValue({ decimal, value: safeValue(value, decimal), identifier });
1963
+ }
1964
+ var createSyntheticAssetValue = function(identifier, value = 0) {
1965
+ const [synthChain, symbol] = identifier.split(".")?.[0]?.toUpperCase() === Chain.THORChain ? identifier.split(".").slice(1).join().split("/") : identifier.split("/");
1966
+ if (!(synthChain && symbol))
1967
+ throw new Error("Invalid asset identifier");
1968
+ return new AssetValue({
1969
+ decimal: 8,
1970
+ value: safeValue(value, 8),
1971
+ identifier: `${Chain.THORChain}.${synthChain}/${symbol}`
1972
+ });
2274
1973
  };
2275
- var getFloatDecimals = function(value) {
2276
- const decimals = value.split(".")[1]?.length || 0;
2277
- return Math.max(decimals, DEFAULT_DECIMAL);
1974
+ var safeValue = function(value, decimal) {
1975
+ return typeof value === "bigint" ? formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }) : value;
2278
1976
  };
2279
- var getStringValue = function(param) {
2280
- return typeof param === "object" ? "getValue" in param ? param.getValue("string") : param.value : param;
1977
+ var getAssetInfo = function(identifier) {
1978
+ const isSynthetic = identifier.slice(0, 14).includes("/");
1979
+ const isThorchain = identifier.split(".")?.[0]?.toUpperCase() === Chain.THORChain;
1980
+ const isMaya = identifier.split(".")?.[0]?.toUpperCase() === Chain.Maya;
1981
+ const [synthChain, synthSymbol = ""] = isThorchain || isMaya ? identifier.split(".").slice(1).join().split("/") : identifier.split("/");
1982
+ if (isSynthetic && !(synthChain && synthSymbol))
1983
+ throw new Error("Invalid asset identifier");
1984
+ const adjustedIdentifier = identifier.includes(".") && !isSynthetic ? identifier : `${isMaya ? Chain.Maya : Chain.THORChain}.${synthSymbol}`;
1985
+ const [chain, ...rest] = adjustedIdentifier.split(".");
1986
+ const symbol = isSynthetic ? synthSymbol : rest.join(".");
1987
+ const splitSymbol = symbol.split("-");
1988
+ const ticker = splitSymbol.length === 1 ? splitSymbol[0] : splitSymbol.slice(0, -1).join("-");
1989
+ const address = splitSymbol.length === 1 ? undefined : splitSymbol[splitSymbol.length - 1];
1990
+ return {
1991
+ address: address?.toLowerCase(),
1992
+ chain,
1993
+ isGasAsset: isGasAsset({ chain, symbol }),
1994
+ isSynthetic,
1995
+ symbol: (isSynthetic ? `${synthChain}/` : "") + (address ? `${ticker}-${address?.toLowerCase() ?? ""}` : symbol),
1996
+ ticker
1997
+ };
2281
1998
  };
2282
- var DEFAULT_DECIMAL = 8;
2283
- var toMultiplier = (decimal) => 10n ** BigInt(decimal);
2284
- var decimalFromMultiplier = (multiplier) => Math.log10(Number.parseFloat(multiplier.toString()));
1999
+ var staticTokensMap = new Map;
2285
2000
 
2286
- class BigIntArithmetics {
2287
- decimalMultiplier = 10n ** 8n;
2288
- bigIntValue = 0n;
2289
- decimal;
2290
- static fromBigInt(value, decimal) {
2291
- return new BigIntArithmetics({
2292
- decimal,
2293
- value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })
2294
- });
2295
- }
2296
- static shiftDecimals({
2001
+ class AssetValue extends BigIntArithmetics {
2002
+ address;
2003
+ chain;
2004
+ isGasAsset = false;
2005
+ isSynthetic = false;
2006
+ symbol;
2007
+ tax;
2008
+ ticker;
2009
+ type;
2010
+ chainId;
2011
+ constructor({
2297
2012
  value,
2298
- from,
2299
- to
2013
+ decimal,
2014
+ tax,
2015
+ chain,
2016
+ symbol,
2017
+ identifier
2300
2018
  }) {
2301
- return BigIntArithmetics.fromBigInt(value.getBaseValue("bigint") * toMultiplier(to) / toMultiplier(from), to);
2302
- }
2303
- constructor(params) {
2304
- const value = getStringValue(params);
2305
- const isComplex = typeof params === "object";
2306
- this.decimal = isComplex ? params.decimal : undefined;
2307
- this.decimalMultiplier = isComplex && "decimalMultiplier" in params ? params.decimalMultiplier : toMultiplier(Math.max(getFloatDecimals(toSafeValue(value)), this.decimal || 0));
2308
- this.#setValue(value);
2019
+ super(typeof value === "object" ? value : { decimal, value });
2020
+ const assetInfo = getAssetInfo(identifier || `${chain}.${symbol}`);
2021
+ this.type = getAssetType(assetInfo);
2022
+ this.tax = tax;
2023
+ this.chain = assetInfo.chain;
2024
+ this.ticker = assetInfo.ticker;
2025
+ this.symbol = assetInfo.symbol;
2026
+ this.address = assetInfo.address;
2027
+ this.isSynthetic = assetInfo.isSynthetic;
2028
+ this.isGasAsset = assetInfo.isGasAsset;
2029
+ this.chainId = ChainToChainId[assetInfo.chain];
2309
2030
  }
2310
- set(value) {
2311
- return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() });
2031
+ toString() {
2032
+ return this.isSynthetic ? this.symbol : `${this.chain}.${this.symbol}`;
2312
2033
  }
2313
- add(...args) {
2314
- return this.#arithmetics("add", ...args);
2034
+ toUrl() {
2035
+ return this.isSynthetic ? `${this.chain}.${this.symbol.replace("/", ".")}` : this.toString();
2315
2036
  }
2316
- sub(...args) {
2317
- return this.#arithmetics("sub", ...args);
2037
+ eq({ chain, symbol }) {
2038
+ return this.chain === chain && this.symbol === symbol;
2318
2039
  }
2319
- mul(...args) {
2320
- return this.#arithmetics("mul", ...args);
2040
+ static fromUrl(urlAsset, value = 0) {
2041
+ const [chain, ticker, symbol] = urlAsset.split(".");
2042
+ if (!(chain && ticker))
2043
+ throw new Error("Invalid asset url");
2044
+ const assetString = chain === Chain.THORChain && symbol ? `${chain}.${ticker}/${symbol}` : urlAsset;
2045
+ return createAssetValue(assetString, value);
2321
2046
  }
2322
- div(...args) {
2323
- return this.#arithmetics("div", ...args);
2047
+ static fromString(assetString, value = 0) {
2048
+ return createAssetValue(assetString, value);
2324
2049
  }
2325
- gt(value) {
2326
- return this.#comparison("gt", value);
2050
+ static fromIdentifier(assetString, value = 0) {
2051
+ return createAssetValue(assetString, value);
2327
2052
  }
2328
- gte(value) {
2329
- return this.#comparison("gte", value);
2330
- }
2331
- lt(value) {
2332
- return this.#comparison("lt", value);
2053
+ static fromStringSync(assetString, value = 0) {
2054
+ const { chain, isSynthetic } = getAssetInfo(assetString);
2055
+ const tokenInfo = staticTokensMap.get(assetString.toUpperCase());
2056
+ if (isSynthetic)
2057
+ return createSyntheticAssetValue(assetString, value);
2058
+ const { tax, decimal, identifier } = tokenInfo || {
2059
+ decimal: BaseDecimal[chain],
2060
+ identifier: assetString
2061
+ };
2062
+ return new AssetValue({
2063
+ tax,
2064
+ value: safeValue(value, decimal),
2065
+ identifier: isSynthetic ? assetString : identifier,
2066
+ decimal: isSynthetic ? 8 : decimal
2067
+ });
2333
2068
  }
2334
- lte(value) {
2335
- return this.#comparison("lte", value);
2069
+ static async fromStringWithBase(assetString, value = 0, baseDecimal = BaseDecimal.THOR) {
2070
+ const shiftedAmount = BigIntArithmetics.shiftDecimals({
2071
+ value: SwapKitNumber.fromBigInt(BigInt(value)),
2072
+ from: 0,
2073
+ to: baseDecimal
2074
+ }).getBaseValue("string");
2075
+ const assetValue = await AssetValue.fromString(assetString, value);
2076
+ return assetValue.set(shiftedAmount);
2336
2077
  }
2337
- eqValue(value) {
2338
- return this.#comparison("eqValue", value);
2078
+ static fromStringWithBaseSync(assetString, value = 0, baseDecimal = BaseDecimal.THOR) {
2079
+ const { chain, isSynthetic } = getAssetInfo(assetString);
2080
+ const tokenInfo = staticTokensMap.get(assetString.toUpperCase());
2081
+ if (isSynthetic)
2082
+ return createSyntheticAssetValue(assetString, value);
2083
+ const { tax, decimal, identifier } = tokenInfo || {
2084
+ decimal: BaseDecimal[chain],
2085
+ identifier: assetString
2086
+ };
2087
+ return new AssetValue({
2088
+ tax,
2089
+ value: safeValue(BigInt(value), baseDecimal),
2090
+ identifier,
2091
+ decimal
2092
+ });
2339
2093
  }
2340
- getValue(type) {
2341
- const value = this.formatBigIntToSafeValue(this.bigIntValue, this.decimal || decimalFromMultiplier(this.decimalMultiplier));
2342
- switch (type) {
2343
- case "number":
2344
- return Number(value);
2345
- case "string":
2346
- return value;
2347
- case "bigint":
2348
- return this.bigIntValue * 10n ** BigInt(this.decimal || 8n) / this.decimalMultiplier;
2349
- }
2094
+ static fromIdentifierSync(assetString, value = 0) {
2095
+ const { chain, isSynthetic } = getAssetInfo(assetString);
2096
+ const tokenInfo = staticTokensMap.get(assetString);
2097
+ if (isSynthetic)
2098
+ return createSyntheticAssetValue(assetString, value);
2099
+ const { tax, decimal, identifier } = tokenInfo || {
2100
+ decimal: BaseDecimal[chain],
2101
+ identifier: assetString
2102
+ };
2103
+ return new AssetValue({ tax, decimal, identifier, value: safeValue(value, decimal) });
2350
2104
  }
2351
- getBaseValue(type) {
2352
- const divisor = this.decimalMultiplier / toMultiplier(this.decimal || BaseDecimal.THOR);
2353
- const baseValue = this.bigIntValue / divisor;
2354
- switch (type) {
2355
- case "number":
2356
- return Number(baseValue);
2357
- case "string":
2358
- return baseValue.toString();
2359
- case "bigint":
2360
- return baseValue;
2361
- }
2105
+ static fromChainOrSignature(assetString, value = 0) {
2106
+ const { decimal, identifier } = getCommonAssetInfo(assetString);
2107
+ return new AssetValue({ value: safeValue(value, decimal), decimal, identifier });
2362
2108
  }
2363
- getBigIntValue(value, decimal) {
2364
- if (!decimal && typeof value === "object")
2365
- return value.bigIntValue;
2366
- const stringValue = getStringValue(value);
2367
- const safeValue = toSafeValue(stringValue);
2368
- if (safeValue === "0" || safeValue === "undefined")
2369
- return 0n;
2370
- return this.#toBigInt(safeValue, decimal);
2109
+ static loadStaticAssets() {
2110
+ return new Promise((resolve, reject) => {
2111
+ try {
2112
+ import("@swapkit/tokens").then((tokenPackages) => {
2113
+ for (const tokenList of Object.values(tokenPackages)) {
2114
+ for (const { identifier, chain, ...rest } of tokenList.tokens) {
2115
+ staticTokensMap.set(identifier.toUpperCase(), {
2116
+ identifier,
2117
+ decimal: "decimals" in rest ? rest.decimals : BaseDecimal[chain]
2118
+ });
2119
+ }
2120
+ }
2121
+ resolve({ ok: true });
2122
+ });
2123
+ } catch (error) {
2124
+ console.error(error);
2125
+ reject({
2126
+ ok: false,
2127
+ error,
2128
+ message: "Couldn't load static assets. Ensure you have installed @swapkit/tokens package"
2129
+ });
2130
+ }
2131
+ });
2371
2132
  }
2372
- toSignificant(significantDigits = 6) {
2373
- const [int, dec] = this.getValue("string").split(".");
2374
- const integer = int || "";
2375
- const decimal = dec || "";
2376
- const valueLength = Number.parseInt(integer) ? integer.length + decimal.length : decimal.length;
2377
- if (valueLength <= significantDigits) {
2378
- return this.getValue("string");
2379
- }
2380
- if (integer.length >= significantDigits) {
2381
- return integer.slice(0, significantDigits).padEnd(integer.length, "0");
2382
- }
2383
- if (Number.parseInt(integer)) {
2384
- return `${integer}.${decimal.slice(0, significantDigits - integer.length)}`.padEnd(significantDigits - integer.length, "0");
2385
- }
2386
- const trimmedDecimal = Number.parseInt(decimal);
2387
- const slicedDecimal = `${trimmedDecimal}`.slice(0, significantDigits);
2388
- return `0.${slicedDecimal.padStart(decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length, "0")}`;
2133
+ }
2134
+
2135
+ // src/modules/requestClient.ts
2136
+ import ky from "ky";
2137
+ function setRequestClientConfig({ apiKey, ...config }) {
2138
+ kyClient = ky.create({
2139
+ ...config,
2140
+ headers: { ...defaultRequestHeaders, ...config.headers, "x-api-key": apiKey }
2141
+ });
2142
+ }
2143
+ var getKyClient = function() {
2144
+ if (kyClient)
2145
+ return kyClient;
2146
+ kyClient = ky.create({ headers: defaultRequestHeaders });
2147
+ return kyClient;
2148
+ };
2149
+ var kyClient;
2150
+ var defaultRequestHeaders = typeof window !== "undefined" ? {} : { referrer: "https://sk.thorswap.net", referer: "https://sk.thorswap.net" };
2151
+ var getTypedBaseRequestClient = (ky2) => ({
2152
+ get: (url, options) => ky2.get(url, options).json(),
2153
+ post: (url, options) => ky2.post(url, options).json()
2154
+ });
2155
+ var RequestClient = {
2156
+ ...getTypedBaseRequestClient(getKyClient()),
2157
+ extend: (options) => {
2158
+ const extendedClient = getKyClient().extend(options);
2159
+ return {
2160
+ ...getTypedBaseRequestClient(extendedClient),
2161
+ extend: RequestClient.extend
2162
+ };
2389
2163
  }
2390
- toFixed(fixedDigits = 6) {
2391
- const [int, dec] = this.getValue("string").split(".");
2392
- const integer = int || "";
2393
- const decimal = dec || "";
2394
- if (Number.parseInt(integer)) {
2395
- return `${integer}.${decimal.slice(0, fixedDigits)}`.padEnd(fixedDigits, "0");
2164
+ };
2165
+
2166
+ // src/helpers/asset.ts
2167
+ async function findAssetBy(params) {
2168
+ const tokenPackages = await import("@swapkit/tokens");
2169
+ for (const tokenList of Object.values(tokenPackages)) {
2170
+ for (const { identifier, chain: tokenChain, ...rest } of tokenList.tokens) {
2171
+ if ("identifier" in params && identifier === params.identifier) {
2172
+ return identifier;
2173
+ }
2174
+ if ("address" in rest && "chain" in params && tokenChain === params.chain && rest.address.toLowerCase() === params.contract.toLowerCase())
2175
+ return identifier;
2396
2176
  }
2397
- const trimmedDecimal = Number.parseInt(decimal);
2398
- const slicedDecimal = `${trimmedDecimal}`.slice(0, fixedDigits);
2399
- return `0.${slicedDecimal.padStart(decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length, "0")}`;
2400
2177
  }
2401
- toAbbreviation(digits = 2) {
2402
- const value = this.getValue("number");
2403
- const abbreviations = ["", "K", "M", "B", "T", "Q", "Qi", "S"];
2404
- const tier = Math.floor(Math.log10(Math.abs(value)) / 3);
2405
- const suffix = abbreviations[tier];
2406
- if (!suffix)
2407
- return this.getValue("string");
2408
- const scale = 10 ** (tier * 3);
2409
- const scaled = value / scale;
2410
- return `${scaled.toFixed(digits)}${suffix}`;
2178
+ return;
2179
+ }
2180
+ var getDecimalMethodHex = "0x313ce567";
2181
+ var getContractDecimals = async ({ chain, to }) => {
2182
+ try {
2183
+ const { result } = await RequestClient.post(ChainToRPC[chain], {
2184
+ headers: {
2185
+ accept: "*/*",
2186
+ "content-type": "application/json",
2187
+ "cache-control": "no-cache"
2188
+ },
2189
+ body: JSON.stringify({
2190
+ id: 44,
2191
+ jsonrpc: "2.0",
2192
+ method: "eth_call",
2193
+ params: [{ to: to.toLowerCase(), data: getDecimalMethodHex }, "latest"]
2194
+ })
2195
+ });
2196
+ return Number.parseInt(BigInt(result || BaseDecimal[chain]).toString());
2197
+ } catch (error) {
2198
+ console.error(error);
2199
+ return BaseDecimal[chain];
2411
2200
  }
2412
- toCurrency(currency = "$", {
2413
- currencyPosition = "start",
2414
- decimal = 2,
2415
- decimalSeparator = ".",
2416
- thousandSeparator = ","
2417
- } = {}) {
2418
- const value = this.getValue("number");
2419
- const [int = "", dec = ""] = value.toFixed(6).split(".");
2420
- const integer = int.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
2421
- const parsedValue = int || dec ? int === "0" ? `${Number.parseFloat(`0.${dec}`)}`.replace(".", decimalSeparator) : `${integer}${Number.parseInt(dec) ? `${decimalSeparator}${dec.slice(0, decimal)}` : ""}` : "0.00";
2422
- return `${currencyPosition === "start" ? currency : ""}${parsedValue}${currencyPosition === "end" ? currency : ""}`;
2201
+ };
2202
+ var getETHAssetDecimal = (symbol) => {
2203
+ if (symbol === Chain.Ethereum)
2204
+ return BaseDecimal.ETH;
2205
+ const splitSymbol = symbol.split("-");
2206
+ const address = splitSymbol.length === 1 ? undefined : splitSymbol[splitSymbol.length - 1];
2207
+ return address?.startsWith("0x") ? getContractDecimals({ chain: Chain.Ethereum, to: address }) : BaseDecimal.ETH;
2208
+ };
2209
+ var getAVAXAssetDecimal = (symbol) => {
2210
+ const splitSymbol = symbol.split("-");
2211
+ const address = splitSymbol.length === 1 ? undefined : splitSymbol[splitSymbol.length - 1];
2212
+ return address?.startsWith("0x") ? getContractDecimals({ chain: Chain.Avalanche, to: address.toLowerCase() }) : BaseDecimal.AVAX;
2213
+ };
2214
+ var getBSCAssetDecimal = (symbol) => {
2215
+ if (symbol === Chain.BinanceSmartChain)
2216
+ return BaseDecimal.BSC;
2217
+ return BaseDecimal.BSC;
2218
+ };
2219
+ var getDecimal = ({ chain, symbol }) => {
2220
+ switch (chain) {
2221
+ case Chain.Ethereum:
2222
+ return getETHAssetDecimal(symbol);
2223
+ case Chain.Avalanche:
2224
+ return getAVAXAssetDecimal(symbol);
2225
+ case Chain.BinanceSmartChain:
2226
+ return getBSCAssetDecimal(symbol);
2227
+ default:
2228
+ return BaseDecimal[chain];
2423
2229
  }
2424
- formatBigIntToSafeValue(value, decimal) {
2425
- const bigIntDecimal = decimal || this.decimal || DEFAULT_DECIMAL;
2426
- const decimalToUseForConversion = Math.max(bigIntDecimal, decimalFromMultiplier(this.decimalMultiplier));
2427
- const isNegative = value < 0n;
2428
- const valueString = value.toString().substring(isNegative ? 1 : 0);
2429
- const padLength = decimalToUseForConversion - (valueString.length - 1);
2430
- const parsedValueString = padLength > 0 ? "0".repeat(padLength) + valueString : valueString;
2431
- const decimalIndex = parsedValueString.length - decimalToUseForConversion;
2432
- let decimalString = parsedValueString.slice(-decimalToUseForConversion);
2433
- if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) {
2434
- decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1).toString()}`;
2435
- } else {
2436
- decimalString = decimalString.substring(0, bigIntDecimal);
2437
- }
2438
- return `${isNegative ? "-" : ""}${parsedValueString.slice(0, decimalIndex)}.${decimalString}`.replace(/\.?0*$/, "");
2439
- }
2440
- #arithmetics(method, ...args) {
2441
- const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args);
2442
- const decimal = Math.max(precisionDecimal, decimalFromMultiplier(this.decimalMultiplier));
2443
- const precisionDecimalMultiplier = toMultiplier(decimal);
2444
- const result = args.reduce((acc, arg) => {
2445
- const value2 = this.getBigIntValue(arg, decimal);
2446
- switch (method) {
2447
- case "add":
2448
- return acc + value2;
2449
- case "sub":
2450
- return acc - value2;
2451
- case "mul":
2452
- return acc * value2 / precisionDecimalMultiplier;
2453
- case "div": {
2454
- if (value2 === 0n)
2455
- throw new RangeError("Division by zero");
2456
- return acc * precisionDecimalMultiplier / value2;
2457
- }
2458
- default:
2459
- return acc;
2460
- }
2461
- }, this.bigIntValue * precisionDecimalMultiplier / this.decimalMultiplier);
2462
- const value = formatBigIntToSafeValue({
2463
- bigIntDecimal: decimal,
2464
- decimal,
2465
- value: result
2466
- });
2467
- return new this.constructor({
2468
- decimalMultiplier: toMultiplier(decimal),
2469
- decimal: this.decimal,
2470
- value,
2471
- identifier: this.toString()
2472
- });
2473
- }
2474
- #comparison(method, ...args) {
2475
- const decimal = this.#retrievePrecisionDecimal(this, ...args);
2476
- const value = this.getBigIntValue(args[0] || "0", decimal);
2477
- const compareToValue = this.getBigIntValue(this, decimal);
2478
- switch (method) {
2479
- case "gt":
2480
- return compareToValue > value;
2481
- case "gte":
2482
- return compareToValue >= value;
2483
- case "lt":
2484
- return compareToValue < value;
2485
- case "lte":
2486
- return compareToValue <= value;
2487
- case "eqValue":
2488
- return compareToValue === value;
2489
- }
2490
- }
2491
- #setValue(value) {
2492
- const safeValue = toSafeValue(value) || "0";
2493
- this.bigIntValue = this.#toBigInt(safeValue);
2494
- }
2495
- #retrievePrecisionDecimal(...args) {
2496
- const decimals = args.map((arg) => {
2497
- const isObject = typeof arg === "object";
2498
- const value = isObject ? arg.decimal || decimalFromMultiplier(arg.decimalMultiplier) : getFloatDecimals(toSafeValue(arg));
2499
- return value;
2500
- }).filter(Boolean);
2501
- return Math.max(...decimals, DEFAULT_DECIMAL);
2502
- }
2503
- #toBigInt(value, decimal) {
2504
- const multiplier = decimal ? toMultiplier(decimal) : this.decimalMultiplier;
2505
- const padDecimal = decimalFromMultiplier(multiplier);
2506
- const [integerPart = "", decimalPart = ""] = value.split(".");
2507
- return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, "0")}`);
2508
- }
2509
- }
2510
- var numberFormatter = Intl.NumberFormat("fullwide", {
2511
- useGrouping: false,
2512
- maximumFractionDigits: 20
2513
- });
2514
-
2515
- // src/modules/swapKitNumber.ts
2516
- class SwapKitNumber extends BigIntArithmetics {
2517
- constructor() {
2518
- super(...arguments);
2519
- }
2520
- eq(value) {
2521
- return this.eqValue(value);
2522
- }
2523
- static fromBigInt(value, decimal) {
2524
- return new SwapKitNumber({
2525
- decimal,
2526
- value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })
2527
- });
2528
- }
2529
- }
2530
-
2531
- // src/modules/assetValue.ts
2532
- function getMinAmountByChain(chain) {
2533
- const asset2 = AssetValue.fromChainOrSignature(chain);
2230
+ };
2231
+ var getGasAsset = ({ chain }) => {
2534
2232
  switch (chain) {
2535
- case Chain.Bitcoin:
2536
- case Chain.Litecoin:
2537
- case Chain.BitcoinCash:
2538
- return asset2.set(0.00010001);
2539
- case Chain.Dogecoin:
2540
- return asset2.set(1.00000001);
2541
- case Chain.Avalanche:
2542
- case Chain.Ethereum:
2543
- return asset2.set(0.00000001);
2233
+ case Chain.Arbitrum:
2234
+ case Chain.Optimism:
2235
+ return AssetValue.fromStringSync(`${chain}.ETH`);
2236
+ case Chain.Maya:
2237
+ return AssetValue.fromStringSync(`${chain}.CACAO`);
2238
+ case Chain.Cosmos:
2239
+ return AssetValue.fromStringSync(`${chain}.ATOM`);
2240
+ case Chain.BinanceSmartChain:
2241
+ return AssetValue.fromStringSync(`${chain}.BNB`);
2544
2242
  case Chain.THORChain:
2243
+ return AssetValue.fromStringSync(`${chain}.RUNE`);
2244
+ default:
2245
+ return AssetValue.fromStringSync(`${chain}.${chain}`);
2246
+ }
2247
+ };
2248
+ var isGasAsset = ({ chain, symbol }) => {
2249
+ switch (chain) {
2250
+ case Chain.Arbitrum:
2251
+ case Chain.Optimism:
2252
+ return symbol === "ETH";
2545
2253
  case Chain.Maya:
2546
- return asset2.set(0);
2254
+ return symbol === "CACAO";
2547
2255
  case Chain.Cosmos:
2548
- return asset2.set(0.000001);
2256
+ return symbol === "ATOM";
2257
+ case Chain.BinanceSmartChain:
2258
+ return symbol === "BNB";
2259
+ case Chain.THORChain:
2260
+ return symbol === "RUNE";
2549
2261
  default:
2550
- return asset2.set(0.00000001);
2262
+ return symbol === chain;
2551
2263
  }
2552
- }
2553
- async function createAssetValue(identifier, value = 0) {
2554
- validateIdentifier(identifier);
2555
- const staticToken = staticTokensMap.get(identifier.toUpperCase());
2556
- const decimal = staticToken?.decimal || await getDecimal(getAssetInfo(identifier));
2557
- if (!staticToken) {
2558
- staticTokensMap.set(identifier.toUpperCase(), { identifier, decimal });
2264
+ };
2265
+ var getCommonAssetInfo = (assetString) => {
2266
+ switch (assetString) {
2267
+ case `${Chain.Ethereum}.THOR`:
2268
+ return { identifier: "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044", decimal: 18 };
2269
+ case `${Chain.Ethereum}.vTHOR`:
2270
+ return { identifier: "ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", decimal: 18 };
2271
+ case Chain.Arbitrum:
2272
+ return { identifier: `${Chain.Arbitrum}.ETH`, decimal: BaseDecimal[assetString] };
2273
+ case Chain.Optimism:
2274
+ return { identifier: `${Chain.Optimism}.ETH`, decimal: BaseDecimal[assetString] };
2275
+ case Chain.Cosmos:
2276
+ return { identifier: "GAIA.ATOM", decimal: BaseDecimal[assetString] };
2277
+ case Chain.THORChain:
2278
+ return { identifier: "THOR.RUNE", decimal: BaseDecimal[assetString] };
2279
+ case Chain.BinanceSmartChain:
2280
+ return { identifier: "BSC.BNB", decimal: BaseDecimal[assetString] };
2281
+ case Chain.Maya:
2282
+ return { identifier: "MAYA.CACAO", decimal: BaseDecimal.MAYA };
2283
+ case `${Chain.Maya}.MAYA`:
2284
+ return { identifier: "MAYA.MAYA", decimal: 4 };
2285
+ case `${Chain.Kujira}.USK`:
2286
+ return { identifier: `${Chain.Kujira}.USK`, decimal: 6 };
2287
+ default:
2288
+ return { identifier: `${assetString}.${assetString}`, decimal: BaseDecimal[assetString] };
2559
2289
  }
2560
- return new AssetValue({ decimal, value: safeValue(value, decimal), identifier });
2561
- }
2562
- var createSyntheticAssetValue = function(identifier, value = 0) {
2563
- const [synthChain, symbol] = identifier.split(".")?.[0]?.toUpperCase() === Chain.THORChain ? identifier.split(".").slice(1).join().split("/") : identifier.split("/");
2564
- if (!(synthChain && symbol))
2565
- throw new Error("Invalid asset identifier");
2566
- return new AssetValue({
2567
- decimal: 8,
2568
- value: safeValue(value, 8),
2569
- identifier: `${Chain.THORChain}.${synthChain}/${symbol}`
2570
- });
2571
2290
  };
2572
- var safeValue = function(value, decimal) {
2573
- return typeof value === "bigint" ? formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }) : value;
2291
+ var getAssetType = ({ chain, symbol }) => {
2292
+ if (symbol.includes("/"))
2293
+ return "Synth";
2294
+ switch (chain) {
2295
+ case Chain.Cosmos:
2296
+ return symbol === "ATOM" ? "Native" : Chain.Cosmos;
2297
+ case Chain.Kujira:
2298
+ return symbol === Chain.Kujira ? "Native" : Chain.Kujira;
2299
+ case Chain.Binance:
2300
+ return symbol === Chain.Binance ? "Native" : "BEP2";
2301
+ case Chain.BinanceSmartChain:
2302
+ return symbol === Chain.Binance ? "Native" : "BEP20";
2303
+ case Chain.Ethereum:
2304
+ return symbol === Chain.Ethereum ? "Native" : "ERC20";
2305
+ case Chain.Avalanche:
2306
+ return symbol === Chain.Avalanche ? "Native" : Chain.Avalanche;
2307
+ case Chain.Polygon:
2308
+ return symbol === Chain.Polygon ? "Native" : "POLYGON";
2309
+ case Chain.Arbitrum:
2310
+ return [Chain.Ethereum, Chain.Arbitrum].includes(symbol) ? "Native" : "ARBITRUM";
2311
+ case Chain.Optimism:
2312
+ return [Chain.Ethereum, Chain.Optimism].includes(symbol) ? "Native" : "OPTIMISM";
2313
+ default:
2314
+ return "Native";
2315
+ }
2574
2316
  };
2575
- var getAssetInfo = function(identifier) {
2576
- const isSynthetic = identifier.slice(0, 14).includes("/");
2577
- const isThorchain = identifier.split(".")?.[0]?.toUpperCase() === Chain.THORChain;
2578
- const isMaya = identifier.split(".")?.[0]?.toUpperCase() === Chain.Maya;
2579
- const [synthChain, synthSymbol = ""] = isThorchain || isMaya ? identifier.split(".").slice(1).join().split("/") : identifier.split("/");
2580
- if (isSynthetic && !(synthChain && synthSymbol))
2581
- throw new Error("Invalid asset identifier");
2582
- const adjustedIdentifier = identifier.includes(".") && !isSynthetic ? identifier : `${isMaya ? Chain.Maya : Chain.THORChain}.${synthSymbol}`;
2583
- const [chain, ...rest] = adjustedIdentifier.split(".");
2584
- const symbol = isSynthetic ? synthSymbol : rest.join(".");
2317
+ var assetFromString = (assetString) => {
2318
+ const [chain, ...symbolArray] = assetString.split(".");
2319
+ const synth = assetString.includes("/");
2320
+ const symbol = symbolArray.join(".");
2321
+ const splitSymbol = symbol?.split("-");
2322
+ const ticker = splitSymbol?.length ? splitSymbol.length === 1 ? splitSymbol[0] : splitSymbol.slice(0, -1).join("-") : undefined;
2323
+ return { chain, symbol, ticker, synth };
2324
+ };
2325
+ var potentialScamRegex = new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/, "gmi");
2326
+ var evmAssetHasAddress = (assetString) => {
2327
+ const [chain, symbol] = assetString.split(".");
2328
+ if (!EVMChains.includes(chain))
2329
+ return true;
2585
2330
  const splitSymbol = symbol.split("-");
2586
- const ticker = splitSymbol.length === 1 ? splitSymbol[0] : splitSymbol.slice(0, -1).join("-");
2587
2331
  const address = splitSymbol.length === 1 ? undefined : splitSymbol[splitSymbol.length - 1];
2588
- return {
2589
- address: address?.toLowerCase(),
2590
- chain,
2591
- isGasAsset: isGasAsset({ chain, symbol }),
2592
- isSynthetic,
2593
- symbol: (isSynthetic ? `${synthChain}/` : "") + (address ? `${ticker}-${address?.toLowerCase() ?? ""}` : symbol),
2594
- ticker
2595
- };
2332
+ return isGasAsset({ chain, symbol }) || !!address;
2596
2333
  };
2597
- var staticTokensMap = new Map;
2598
-
2599
- class AssetValue extends BigIntArithmetics {
2600
- address;
2601
- chain;
2602
- isGasAsset = false;
2603
- isSynthetic = false;
2604
- symbol;
2605
- tax;
2606
- ticker;
2607
- type;
2608
- chainId;
2609
- constructor({
2610
- value,
2611
- decimal,
2612
- tax,
2613
- chain,
2614
- symbol,
2615
- identifier
2616
- }) {
2617
- super(typeof value === "object" ? value : { decimal, value });
2618
- const assetInfo = getAssetInfo(identifier || `${chain}.${symbol}`);
2619
- this.type = getAssetType(assetInfo);
2620
- this.tax = tax;
2621
- this.chain = assetInfo.chain;
2622
- this.ticker = assetInfo.ticker;
2623
- this.symbol = assetInfo.symbol;
2624
- this.address = assetInfo.address;
2625
- this.isSynthetic = assetInfo.isSynthetic;
2626
- this.isGasAsset = assetInfo.isGasAsset;
2627
- this.chainId = ChainToChainId[assetInfo.chain];
2628
- }
2629
- toString() {
2630
- return this.isSynthetic ? this.symbol : `${this.chain}.${this.symbol}`;
2631
- }
2632
- toUrl() {
2633
- return this.isSynthetic ? `${this.chain}.${this.symbol.replace("/", ".")}` : this.toString();
2634
- }
2635
- eq({ chain, symbol }) {
2636
- return this.chain === chain && this.symbol === symbol;
2637
- }
2638
- static fromUrl(urlAsset, value = 0) {
2639
- const [chain, ticker, symbol] = urlAsset.split(".");
2640
- if (!(chain && ticker))
2641
- throw new Error("Invalid asset url");
2642
- const assetString = chain === Chain.THORChain && symbol ? `${chain}.${ticker}/${symbol}` : urlAsset;
2643
- return createAssetValue(assetString, value);
2334
+ var filterAssets = (tokens2) => tokens2.filter(({ chain, value, symbol }) => {
2335
+ const assetString = `${chain}.${symbol}`;
2336
+ return !potentialScamRegex.test(assetString) && evmAssetHasAddress(assetString) && value !== "0";
2337
+ });
2338
+ // src/helpers/derivationPath.ts
2339
+ function getDerivationPathFor({ chain, index, addressIndex = 0, type }) {
2340
+ if (EVMChains.includes(chain)) {
2341
+ if (type === "legacy")
2342
+ return [44, 60, 0, index];
2343
+ if (type === "ledgerLive")
2344
+ return [44, 60, index, 0, addressIndex];
2345
+ return updatedLastIndex(NetworkDerivationPath[chain], index);
2644
2346
  }
2645
- static fromString(assetString, value = 0) {
2646
- return createAssetValue(assetString, value);
2347
+ if ([Chain.Bitcoin, Chain.Litecoin].includes(chain)) {
2348
+ const chainId = chain === Chain.Bitcoin ? 0 : 2;
2349
+ if (type === "nativeSegwitMiddleAccount")
2350
+ return [84, chainId, index, 0, addressIndex];
2351
+ if (type === "segwit")
2352
+ return [49, chainId, 0, 0, index];
2353
+ if (type === "legacy")
2354
+ return [44, chainId, 0, 0, index];
2355
+ return updatedLastIndex(NetworkDerivationPath[chain], index);
2647
2356
  }
2648
- static fromIdentifier(assetString, value = 0) {
2649
- return createAssetValue(assetString, value);
2357
+ return updatedLastIndex(NetworkDerivationPath[chain], index);
2358
+ }
2359
+ function getWalletFormatFor(path) {
2360
+ const [_, purpose, chainId] = path.split("/").map((p) => Number.parseInt(p, 10));
2361
+ if (chainId === 145)
2362
+ ;
2363
+ switch (purpose) {
2364
+ case 44:
2365
+ return "legacy";
2366
+ case 49:
2367
+ return "p2sh";
2368
+ default:
2369
+ return "bech32";
2650
2370
  }
2651
- static fromStringSync(assetString, value = 0) {
2652
- const { chain, isSynthetic } = getAssetInfo(assetString);
2653
- const tokenInfo = staticTokensMap.get(assetString.toUpperCase());
2654
- if (isSynthetic)
2655
- return createSyntheticAssetValue(assetString, value);
2656
- const { tax, decimal, identifier } = tokenInfo || {
2657
- decimal: BaseDecimal[chain],
2658
- identifier: assetString
2659
- };
2660
- return new AssetValue({
2661
- tax,
2662
- value: safeValue(value, decimal),
2663
- identifier: isSynthetic ? assetString : identifier,
2664
- decimal: isSynthetic ? 8 : decimal
2665
- });
2371
+ }
2372
+ var updatedLastIndex = (path, index) => [
2373
+ ...path.slice(0, path.length - 1),
2374
+ index
2375
+ ];
2376
+ // src/helpers/liquidity.ts
2377
+ function getAsymmetricRuneShare({
2378
+ liquidityUnits,
2379
+ poolUnits,
2380
+ runeDepth
2381
+ }) {
2382
+ const s = toTCSwapKitNumber(liquidityUnits);
2383
+ const T = toTCSwapKitNumber(poolUnits);
2384
+ const A = toTCSwapKitNumber(runeDepth);
2385
+ const part1 = s.mul(A);
2386
+ const part2 = T.mul(T).mul(2);
2387
+ const part3 = T.mul(s).mul(2);
2388
+ const part4 = s.mul(s);
2389
+ const part5 = T.mul(T).mul(T);
2390
+ const numerator = part1.mul(part2.sub(part3).add(part4));
2391
+ return numerator.div(part5);
2392
+ }
2393
+ function getAsymmetricAssetShare({
2394
+ liquidityUnits,
2395
+ poolUnits,
2396
+ assetDepth
2397
+ }) {
2398
+ const s = toTCSwapKitNumber(liquidityUnits);
2399
+ const T = toTCSwapKitNumber(poolUnits);
2400
+ const A = toTCSwapKitNumber(assetDepth);
2401
+ const part1 = s.mul(A);
2402
+ const part2 = T.mul(T).mul(2);
2403
+ const part3 = T.mul(s).mul(2);
2404
+ const part4 = s.mul(s);
2405
+ const numerator = part1.mul(part2.sub(part3).add(part4));
2406
+ const part5 = T.mul(T).mul(T);
2407
+ return numerator.div(part5);
2408
+ }
2409
+ function getAsymmetricRuneWithdrawAmount({
2410
+ percent,
2411
+ runeDepth,
2412
+ liquidityUnits,
2413
+ poolUnits
2414
+ }) {
2415
+ return getAsymmetricRuneShare({ runeDepth, liquidityUnits, poolUnits }).mul(percent);
2416
+ }
2417
+ function getAsymmetricAssetWithdrawAmount({
2418
+ percent,
2419
+ assetDepth,
2420
+ liquidityUnits,
2421
+ poolUnits
2422
+ }) {
2423
+ return getAsymmetricAssetShare({ assetDepth, liquidityUnits, poolUnits }).mul(percent);
2424
+ }
2425
+ var toTCSwapKitNumber = function(value) {
2426
+ return SwapKitNumber.fromBigInt(BigInt(value), BaseDecimal.THOR);
2427
+ };
2428
+ function getSymmetricPoolShare({
2429
+ liquidityUnits,
2430
+ poolUnits,
2431
+ runeDepth,
2432
+ assetDepth
2433
+ }) {
2434
+ return {
2435
+ assetAmount: toTCSwapKitNumber(assetDepth).mul(liquidityUnits).div(poolUnits),
2436
+ runeAmount: toTCSwapKitNumber(runeDepth).mul(liquidityUnits).div(poolUnits)
2437
+ };
2438
+ }
2439
+ function getSymmetricWithdraw({
2440
+ liquidityUnits,
2441
+ poolUnits,
2442
+ runeDepth,
2443
+ assetDepth,
2444
+ percent
2445
+ }) {
2446
+ return Object.fromEntries(Object.entries(getSymmetricPoolShare({ liquidityUnits, poolUnits, runeDepth, assetDepth })).map(([name, value]) => [name, value.mul(percent)]));
2447
+ }
2448
+ function getEstimatedPoolShare({
2449
+ runeDepth,
2450
+ poolUnits,
2451
+ assetDepth,
2452
+ liquidityUnits,
2453
+ runeAmount,
2454
+ assetAmount
2455
+ }) {
2456
+ const R = new SwapKitNumber({ value: runeDepth, decimal: 8 });
2457
+ const A = new SwapKitNumber({ value: assetDepth, decimal: 8 });
2458
+ const P = new SwapKitNumber({ value: poolUnits, decimal: 8 });
2459
+ const runeAddAmount = new SwapKitNumber({ value: runeAmount, decimal: 8 });
2460
+ const assetAddAmount = new SwapKitNumber({ value: assetAmount, decimal: 8 });
2461
+ const rA = runeAddAmount.mul(A);
2462
+ const aR = assetAddAmount.mul(R);
2463
+ const ra = runeAddAmount.mul(assetAddAmount);
2464
+ const RA = R.mul(A);
2465
+ const numerator = P.mul(rA.add(aR.add(ra.mul(2))));
2466
+ const denominator = rA.add(aR.add(RA.mul(2)));
2467
+ const liquidityUnitsAfterAdd = numerator.div(denominator);
2468
+ const estimatedLiquidityUnits = toTCSwapKitNumber(liquidityUnits).add(liquidityUnitsAfterAdd);
2469
+ if (liquidityUnitsAfterAdd.getBaseValue("number") === 0) {
2470
+ return estimatedLiquidityUnits.div(P).getBaseValue("number");
2666
2471
  }
2667
- static async fromStringWithBase(assetString, value = 0, baseDecimal = BaseDecimal.THOR) {
2668
- const shiftedAmount = BigIntArithmetics.shiftDecimals({
2669
- value: SwapKitNumber.fromBigInt(BigInt(value)),
2670
- from: 0,
2671
- to: baseDecimal
2672
- }).getBaseValue("string");
2673
- const assetValue = await AssetValue.fromString(assetString, value);
2674
- return assetValue.set(shiftedAmount);
2472
+ const newPoolUnits = P.add(estimatedLiquidityUnits);
2473
+ return estimatedLiquidityUnits.div(newPoolUnits).getBaseValue("number");
2474
+ }
2475
+ function getLiquiditySlippage({
2476
+ runeAmount,
2477
+ assetAmount,
2478
+ runeDepth,
2479
+ assetDepth
2480
+ }) {
2481
+ if (runeAmount === "0" || assetAmount === "0" || runeDepth === "0" || assetDepth === "0")
2482
+ return 0;
2483
+ const R = toTCSwapKitNumber(runeDepth);
2484
+ const T = toTCSwapKitNumber(assetDepth);
2485
+ const assetAddAmount = toTCSwapKitNumber(assetAmount);
2486
+ const runeAddAmount = toTCSwapKitNumber(runeAmount);
2487
+ const numerator = assetAddAmount.mul(R).sub(T.mul(runeAddAmount));
2488
+ const denominator = T.mul(runeAddAmount).add(R.mul(T));
2489
+ return Math.abs(numerator.div(denominator).getBaseValue("number"));
2490
+ }
2491
+ // src/helpers/memo.ts
2492
+ var getMemoFor = (memoType, options) => {
2493
+ switch (memoType) {
2494
+ case MemoType.LEAVE:
2495
+ case MemoType.BOND: {
2496
+ const { address } = options;
2497
+ return `${memoType}:${address}`;
2498
+ }
2499
+ case MemoType.UNBOND: {
2500
+ const { address, unbondAmount } = options;
2501
+ return `${memoType}:${address}:${unbondAmount}`;
2502
+ }
2503
+ case MemoType.NAME_REGISTER: {
2504
+ const { name, chain, address, owner } = options;
2505
+ return `${memoType}:${name}:${chain}:${address}${owner ? `:${owner}` : ""}`;
2506
+ }
2507
+ case MemoType.DEPOSIT: {
2508
+ const { chain, symbol, address, singleSide } = options;
2509
+ const getPoolIdentifier = (chain2, symbol2) => {
2510
+ switch (chain2) {
2511
+ case Chain.Litecoin:
2512
+ return "l";
2513
+ case Chain.Dogecoin:
2514
+ return "d";
2515
+ case Chain.BitcoinCash:
2516
+ return "c";
2517
+ default:
2518
+ return `${chain2}.${symbol2}`;
2519
+ }
2520
+ };
2521
+ return singleSide ? `${memoType}:${chain}/${symbol}` : `${memoType}:${getPoolIdentifier(chain, symbol)}:${address || ""}`;
2522
+ }
2523
+ case MemoType.WITHDRAW: {
2524
+ const { chain, ticker, symbol, basisPoints, targetAssetString, singleSide } = options;
2525
+ const shortenedSymbol = chain === "ETH" && ticker !== "ETH" ? `${ticker}-${symbol.slice(-3)}` : symbol;
2526
+ const target = !singleSide && targetAssetString ? `:${targetAssetString}` : "";
2527
+ const assetDivider = singleSide ? "/" : ".";
2528
+ return `${memoType}:${chain}${assetDivider}${shortenedSymbol}:${basisPoints}${target}`;
2529
+ }
2530
+ case MemoType.OPEN_LOAN:
2531
+ case MemoType.CLOSE_LOAN: {
2532
+ const { asset: asset2, address } = options;
2533
+ return `${memoType}:${asset2}:${address}`;
2534
+ }
2535
+ default:
2536
+ return "";
2675
2537
  }
2676
- static fromStringWithBaseSync(assetString, value = 0, baseDecimal = BaseDecimal.THOR) {
2677
- const { chain, isSynthetic } = getAssetInfo(assetString);
2678
- const tokenInfo = staticTokensMap.get(assetString.toUpperCase());
2679
- if (isSynthetic)
2680
- return createSyntheticAssetValue(assetString, value);
2681
- const { tax, decimal, identifier } = tokenInfo || {
2682
- decimal: BaseDecimal[chain],
2683
- identifier: assetString
2684
- };
2685
- return new AssetValue({
2686
- tax,
2687
- value: safeValue(BigInt(value), baseDecimal),
2688
- identifier,
2689
- decimal
2538
+ };
2539
+ // src/modules/swapKitError.ts
2540
+ var errorMessages = {
2541
+ core_wallet_connection_not_found: 10001,
2542
+ core_estimated_max_spendable_chain_not_supported: 10002,
2543
+ core_extend_error: 10003,
2544
+ core_inbound_data_not_found: 10004,
2545
+ core_approve_asset_address_or_from_not_found: 10005,
2546
+ core_plugin_not_found: 10006,
2547
+ core_plugin_swap_not_found: 10007,
2548
+ core_approve_asset_target_invalid: 10008,
2549
+ core_chain_halted: 10099,
2550
+ core_wallet_xdefi_not_installed: 10101,
2551
+ core_wallet_evmwallet_not_installed: 10102,
2552
+ core_wallet_walletconnect_not_installed: 10103,
2553
+ core_wallet_keystore_not_installed: 10104,
2554
+ core_wallet_ledger_not_installed: 10105,
2555
+ core_wallet_trezor_not_installed: 10106,
2556
+ core_wallet_keplr_not_installed: 10107,
2557
+ core_wallet_okx_not_installed: 10108,
2558
+ core_wallet_keepkey_not_installed: 10109,
2559
+ core_swap_invalid_params: 10200,
2560
+ core_swap_route_not_complete: 10201,
2561
+ core_swap_asset_not_recognized: 10202,
2562
+ core_swap_contract_not_found: 10203,
2563
+ core_swap_route_transaction_not_found: 10204,
2564
+ core_swap_contract_not_supported: 10205,
2565
+ core_swap_transaction_error: 10206,
2566
+ core_swap_quote_mode_not_supported: 10207,
2567
+ core_transaction_deposit_error: 10301,
2568
+ core_transaction_create_liquidity_rune_error: 10302,
2569
+ core_transaction_create_liquidity_asset_error: 10303,
2570
+ core_transaction_create_liquidity_invalid_params: 10304,
2571
+ core_transaction_add_liquidity_invalid_params: 10305,
2572
+ core_transaction_add_liquidity_no_rune_address: 10306,
2573
+ core_transaction_add_liquidity_rune_error: 10307,
2574
+ core_transaction_add_liquidity_asset_error: 10308,
2575
+ core_transaction_withdraw_error: 10309,
2576
+ core_transaction_deposit_to_pool_error: 10310,
2577
+ core_transaction_deposit_insufficient_funds_error: 10311,
2578
+ core_transaction_deposit_gas_error: 10312,
2579
+ core_transaction_invalid_sender_address: 10313,
2580
+ core_transaction_deposit_server_error: 10314,
2581
+ core_transaction_user_rejected: 10315,
2582
+ core_transaction_create_liquidity_cacao_error: 10316,
2583
+ core_transaction_add_liquidity_no_cacao_address: 10306,
2584
+ core_transaction_add_liquidity_cacao_error: 10307,
2585
+ wallet_ledger_connection_error: 20001,
2586
+ wallet_ledger_connection_claimed: 20002,
2587
+ wallet_ledger_get_address_error: 20003,
2588
+ wallet_ledger_device_not_found: 20004,
2589
+ wallet_ledger_device_locked: 20005,
2590
+ chainflip_channel_error: 30001,
2591
+ chainflip_broker_recipient_error: 30002,
2592
+ api_v2_invalid_response: 40001,
2593
+ helpers_number_different_decimals: 99101
2594
+ };
2595
+
2596
+ class SwapKitError extends Error {
2597
+ constructor(errorKey, sourceError) {
2598
+ if (sourceError) {
2599
+ console.error(sourceError, {
2600
+ stack: sourceError?.stack,
2601
+ message: sourceError?.message
2602
+ });
2603
+ }
2604
+ super(errorKey, {
2605
+ cause: { code: errorMessages[errorKey], message: errorKey }
2690
2606
  });
2607
+ Object.setPrototypeOf(this, SwapKitError.prototype);
2691
2608
  }
2692
- static fromIdentifierSync(assetString, value = 0) {
2693
- const { chain, isSynthetic } = getAssetInfo(assetString);
2694
- const tokenInfo = staticTokensMap.get(assetString);
2695
- if (isSynthetic)
2696
- return createSyntheticAssetValue(assetString, value);
2697
- const { tax, decimal, identifier } = tokenInfo || {
2698
- decimal: BaseDecimal[chain],
2699
- identifier: assetString
2700
- };
2701
- return new AssetValue({ tax, decimal, identifier, value: safeValue(value, decimal) });
2609
+ }
2610
+
2611
+ // src/helpers/others.ts
2612
+ function getTHORNameCost(numberOfYears) {
2613
+ if (numberOfYears < 0)
2614
+ throw new Error("Invalid number of years");
2615
+ return 10 + numberOfYears;
2616
+ }
2617
+ function getMAYANameCost(numberOfYears) {
2618
+ if (numberOfYears < 0)
2619
+ throw new Error("Invalid number of year");
2620
+ return Math.round((10 + numberOfYears * 1.0512) * 10000000000) / 10000000000;
2621
+ }
2622
+ function derivationPathToString([network3, chainId, account, change, index]) {
2623
+ const shortPath = typeof index !== "number";
2624
+ return `m/${network3}'/${chainId}'/${account}'/${change}${shortPath ? "" : `/${index}`}`;
2625
+ }
2626
+ function wrapWithThrow(fn, errorKey) {
2627
+ try {
2628
+ return fn();
2629
+ } catch (error) {
2630
+ if (errorKey) {
2631
+ throw new SwapKitError(errorKey, error);
2632
+ }
2633
+ return console.error(error);
2702
2634
  }
2703
- static fromChainOrSignature(assetString, value = 0) {
2704
- const { decimal, identifier } = getCommonAssetInfo(assetString);
2705
- return new AssetValue({ value: safeValue(value, decimal), decimal, identifier });
2635
+ }
2636
+ // src/helpers/web3wallets.ts
2637
+ function getEIP6963Wallets() {
2638
+ const providers = [];
2639
+ function onAnnouncement(event) {
2640
+ if (providers.map((p) => p.info.uuid).includes(event.detail.info.uuid))
2641
+ return;
2642
+ providers.push(event.detail);
2706
2643
  }
2707
- static loadStaticAssets() {
2708
- return new Promise((resolve, reject) => {
2709
- try {
2710
- import("@swapkit/tokens").then((tokenPackages) => {
2711
- for (const tokenList of Object.values(tokenPackages)) {
2712
- for (const { identifier, chain, ...rest } of tokenList.tokens) {
2713
- staticTokensMap.set(identifier.toUpperCase(), {
2714
- identifier,
2715
- decimal: "decimals" in rest ? rest.decimals : BaseDecimal[chain]
2716
- });
2717
- }
2718
- }
2719
- resolve({ ok: true });
2720
- });
2721
- } catch (error) {
2722
- console.error(error);
2723
- reject({
2724
- ok: false,
2725
- error,
2726
- message: "Couldn't load static assets. Ensure you have installed @swapkit/tokens package"
2727
- });
2728
- }
2729
- });
2644
+ window.addEventListener("eip6963:announceProvider", onAnnouncement);
2645
+ window.dispatchEvent(new Event("eip6963:requestProvider"));
2646
+ function removeEIP6963EventListener() {
2647
+ window.removeEventListener("eip6963:announceProvider", onAnnouncement);
2730
2648
  }
2649
+ return { providers, removeEIP6963EventListener };
2731
2650
  }
2651
+ var methodsToWrap = [
2652
+ "approve",
2653
+ "approvedAmount",
2654
+ "call",
2655
+ "sendTransaction",
2656
+ "transfer",
2657
+ "isApproved",
2658
+ "approvedAmount",
2659
+ "EIP1193SendTransaction",
2660
+ "getFeeData",
2661
+ "broadcastTransaction",
2662
+ "estimateCall",
2663
+ "estimateGasLimit",
2664
+ "estimateGasPrices",
2665
+ "createContractTxObject"
2666
+ ];
2667
+ var wrapMethodWithNetworkSwitch = (func, provider, chainId) => async (...args) => {
2668
+ try {
2669
+ await switchEVMWalletNetwork(provider, chainId);
2670
+ } catch (error) {
2671
+ throw new Error(`Failed to switch network: ${error}`);
2672
+ }
2673
+ return func(...args);
2674
+ };
2675
+ var providerRequest = ({ provider, params, method }) => {
2676
+ if (!provider?.send)
2677
+ throw new Error("Provider not found");
2678
+ const providerParams = params ? Array.isArray(params) ? params : [params] : [];
2679
+ return provider.send(method, providerParams);
2680
+ };
2681
+ var prepareNetworkSwitch = ({
2682
+ toolbox,
2683
+ chainId,
2684
+ provider = window.ethereum
2685
+ }) => {
2686
+ const wrappedMethods = methodsToWrap.reduce((object, methodName) => {
2687
+ if (!toolbox[methodName])
2688
+ return object;
2689
+ const method = toolbox[methodName];
2690
+ if (typeof method !== "function")
2691
+ return object;
2692
+ return {
2693
+ ...object,
2694
+ [methodName]: wrapMethodWithNetworkSwitch(method, provider, chainId)
2695
+ };
2696
+ }, {});
2697
+ return { ...toolbox, ...wrappedMethods };
2698
+ };
2699
+ var addEVMWalletNetwork = (provider, networkParams) => providerRequest({ provider, method: "wallet_addEthereumChain", params: [networkParams] });
2700
+ var switchEVMWalletNetwork = (provider, chainId = ChainId.EthereumHex) => providerRequest({ provider, method: "wallet_switchEthereumChain", params: [{ chainId }] });
2701
+ var addAccountsChangedCallback = (callback) => {
2702
+ window.ethereum?.on("accountsChanged", () => callback());
2703
+ window.xfi?.ethereum.on("accountsChanged", () => callback());
2704
+ };
2705
+ var getETHDefaultWallet = () => {
2706
+ const { isTrust, isBraveWallet, __XDEFI, overrideIsMetaMask, selectedProvider } = window?.ethereum || {};
2707
+ if (isTrust)
2708
+ return WalletOption.TRUSTWALLET_WEB;
2709
+ if (isBraveWallet)
2710
+ return WalletOption.BRAVE;
2711
+ if (overrideIsMetaMask && selectedProvider?.isCoinbaseWallet)
2712
+ return WalletOption.COINBASE_WEB;
2713
+ if (__XDEFI)
2714
+ WalletOption.XDEFI;
2715
+ return WalletOption.METAMASK;
2716
+ };
2717
+ var isDetected = (walletOption) => {
2718
+ return listWeb3EVMWallets().includes(walletOption);
2719
+ };
2720
+ var listWeb3EVMWallets = () => {
2721
+ const metamaskEnabled = window?.ethereum && !window.ethereum?.isBraveWallet;
2722
+ const xdefiEnabled = window?.xfi || window?.ethereum?.__XDEFI;
2723
+ const braveEnabled = window?.ethereum?.isBraveWallet;
2724
+ const trustEnabled = window?.ethereum?.isTrust || window?.trustwallet;
2725
+ const coinbaseEnabled = window?.ethereum?.overrideIsMetaMask && window?.ethereum?.selectedProvider?.isCoinbaseWallet || window?.coinbaseWalletExtension;
2726
+ const wallets = [];
2727
+ if (metamaskEnabled)
2728
+ wallets.push(WalletOption.METAMASK);
2729
+ if (xdefiEnabled)
2730
+ wallets.push(WalletOption.XDEFI);
2731
+ if (braveEnabled)
2732
+ wallets.push(WalletOption.BRAVE);
2733
+ if (trustEnabled)
2734
+ wallets.push(WalletOption.TRUSTWALLET_WEB);
2735
+ if (coinbaseEnabled)
2736
+ wallets.push(WalletOption.COINBASE_WEB);
2737
+ if (okxMobileEnabled())
2738
+ wallets.push(WalletOption.OKX_MOBILE);
2739
+ return wallets;
2740
+ };
2741
+ var okxMobileEnabled = () => {
2742
+ const ua = navigator.userAgent;
2743
+ const isIOS = /iphone|ipad|ipod|ios/i.test(ua);
2744
+ const isAndroid = /android|XiaoMi|MiuiBrowser/i.test(ua);
2745
+ const isMobile = isIOS || isAndroid;
2746
+ const isOKApp = /OKApp/i.test(ua);
2747
+ return isMobile && isOKApp;
2748
+ };
2749
+ var isWeb3Detected = () => typeof window.ethereum !== "undefined";
2732
2750
  export {
2733
2751
  wrapWithThrow,
2734
2752
  wrapMethodWithNetworkSwitch,
@@ -2750,6 +2768,7 @@ export {
2750
2768
  getMemoFor,
2751
2769
  getMAYANameCost,
2752
2770
  getLiquiditySlippage,
2771
+ getGasAsset,
2753
2772
  getEstimatedPoolShare,
2754
2773
  getETHDefaultWallet,
2755
2774
  getEIP6963Wallets,
@@ -2826,4 +2845,4 @@ export {
2826
2845
  AGG_SWAP
2827
2846
  };
2828
2847
 
2829
- //# debugId=1AF616D9C1303CD064756e2164756e21
2848
+ //# debugId=DD0CB89ADAB3D33764756e2164756e21