@swapkit/helpers 1.0.0-rc.104 → 1.0.0-rc.106

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
@@ -1627,1111 +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.NAME_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
- core_transaction_create_liquidity_cacao_error: 10316,
2065
- core_transaction_add_liquidity_no_cacao_address: 10306,
2066
- core_transaction_add_liquidity_cacao_error: 10307,
2067
- wallet_ledger_connection_error: 20001,
2068
- wallet_ledger_connection_claimed: 20002,
2069
- wallet_ledger_get_address_error: 20003,
2070
- wallet_ledger_device_not_found: 20004,
2071
- wallet_ledger_device_locked: 20005,
2072
- chainflip_channel_error: 30001,
2073
- chainflip_broker_recipient_error: 30002,
2074
- api_v2_invalid_response: 40001,
2075
- helpers_number_different_decimals: 99101
2076
- };
2077
-
2078
- class SwapKitError extends Error {
2079
- constructor(errorKey, sourceError) {
2080
- if (sourceError) {
2081
- console.error(sourceError, {
2082
- stack: sourceError?.stack,
2083
- message: sourceError?.message
2084
- });
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");
2085
1798
  }
2086
- super(errorKey, {
2087
- 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()
2088
1874
  });
2089
- Object.setPrototypeOf(this, SwapKitError.prototype);
2090
1875
  }
2091
- }
2092
-
2093
- // src/helpers/others.ts
2094
- function getTHORNameCost(numberOfYears) {
2095
- if (numberOfYears < 0)
2096
- throw new Error("Invalid number of years");
2097
- return 10 + numberOfYears;
2098
- }
2099
- function getMAYANameCost(numberOfYears) {
2100
- if (numberOfYears < 0)
2101
- throw new Error("Invalid number of year");
2102
- return Math.round((10 + numberOfYears * 1.0512) * 10000000000) / 10000000000;
2103
- }
2104
- function derivationPathToString([network3, chainId, account, change, index]) {
2105
- const shortPath = typeof index !== "number";
2106
- return `m/${network3}'/${chainId}'/${account}'/${change}${shortPath ? "" : `/${index}`}`;
2107
- }
2108
- function wrapWithThrow(fn, errorKey) {
2109
- try {
2110
- return fn();
2111
- } catch (error) {
2112
- if (errorKey) {
2113
- 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;
2114
1891
  }
2115
- return console.error(error);
1892
+ }
1893
+ #setValue(value) {
1894
+ const safeValue = toSafeValue(value) || "0";
1895
+ this.bigIntValue = this.#toBigInt(safeValue);
1896
+ }
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")}`);
2116
1910
  }
2117
1911
  }
2118
- // src/helpers/validators.ts
2119
- function validateIdentifier(identifier = "") {
2120
- const uppercasedIdentifier = identifier.toUpperCase();
2121
- const [chain] = uppercasedIdentifier.split(".");
2122
- if (supportedChains.includes(chain))
2123
- return true;
2124
- const [synthChain] = uppercasedIdentifier.split("/");
2125
- if (supportedChains.includes(synthChain))
2126
- return true;
2127
- throw new Error(`Invalid identifier: ${identifier}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`);
2128
- }
2129
- function validateTNS(name) {
2130
- if (name.length > 30)
2131
- return false;
2132
- const regex = /^[a-zA-Z0-9+_-]+$/g;
2133
- return !!name.match(regex);
2134
- }
2135
- var supportedChains = [...Object.values(Chain), "TERRA"];
2136
- // src/helpers/web3wallets.ts
2137
- function getEIP6963Wallets() {
2138
- const providers = [];
2139
- function onAnnouncement(event) {
2140
- if (providers.map((p) => p.info.uuid).includes(event.detail.info.uuid))
2141
- return;
2142
- providers.push(event.detail);
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);
2143
1921
  }
2144
- window.addEventListener("eip6963:announceProvider", onAnnouncement);
2145
- window.dispatchEvent(new Event("eip6963:requestProvider"));
2146
- function removeEIP6963EventListener() {
2147
- window.removeEventListener("eip6963:announceProvider", onAnnouncement);
1922
+ eq(value) {
1923
+ return this.eqValue(value);
1924
+ }
1925
+ static fromBigInt(value, decimal) {
1926
+ return new SwapKitNumber({
1927
+ decimal,
1928
+ value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })
1929
+ });
2148
1930
  }
2149
- return { providers, removeEIP6963EventListener };
2150
1931
  }
2151
- var methodsToWrap = [
2152
- "approve",
2153
- "approvedAmount",
2154
- "call",
2155
- "sendTransaction",
2156
- "transfer",
2157
- "isApproved",
2158
- "approvedAmount",
2159
- "EIP1193SendTransaction",
2160
- "getFeeData",
2161
- "broadcastTransaction",
2162
- "estimateCall",
2163
- "estimateGasLimit",
2164
- "estimateGasPrices",
2165
- "createContractTxObject"
2166
- ];
2167
- var wrapMethodWithNetworkSwitch = (func, provider, chainId) => async (...args) => {
2168
- try {
2169
- await switchEVMWalletNetwork(provider, chainId);
2170
- } catch (error) {
2171
- throw new Error(`Failed to switch network: ${error}`);
2172
- }
2173
- return func(...args);
2174
- };
2175
- var providerRequest = ({ provider, params, method }) => {
2176
- if (!provider?.send)
2177
- throw new Error("Provider not found");
2178
- const providerParams = params ? Array.isArray(params) ? params : [params] : [];
2179
- return provider.send(method, providerParams);
2180
- };
2181
- var prepareNetworkSwitch = ({
2182
- toolbox,
2183
- chainId,
2184
- provider = window.ethereum
2185
- }) => {
2186
- const wrappedMethods = methodsToWrap.reduce((object, methodName) => {
2187
- if (!toolbox[methodName])
2188
- return object;
2189
- const method = toolbox[methodName];
2190
- if (typeof method !== "function")
2191
- return object;
2192
- return {
2193
- ...object,
2194
- [methodName]: wrapMethodWithNetworkSwitch(method, provider, chainId)
2195
- };
2196
- }, {});
2197
- return { ...toolbox, ...wrappedMethods };
2198
- };
2199
- var addEVMWalletNetwork = (provider, networkParams) => providerRequest({ provider, method: "wallet_addEthereumChain", params: [networkParams] });
2200
- var switchEVMWalletNetwork = (provider, chainId = ChainId.EthereumHex) => providerRequest({ provider, method: "wallet_switchEthereumChain", params: [{ chainId }] });
2201
- var addAccountsChangedCallback = (callback) => {
2202
- window.ethereum?.on("accountsChanged", () => callback());
2203
- window.xfi?.ethereum.on("accountsChanged", () => callback());
2204
- };
2205
- var getETHDefaultWallet = () => {
2206
- const { isTrust, isBraveWallet, __XDEFI, overrideIsMetaMask, selectedProvider } = window?.ethereum || {};
2207
- if (isTrust)
2208
- return WalletOption.TRUSTWALLET_WEB;
2209
- if (isBraveWallet)
2210
- return WalletOption.BRAVE;
2211
- if (overrideIsMetaMask && selectedProvider?.isCoinbaseWallet)
2212
- return WalletOption.COINBASE_WEB;
2213
- if (__XDEFI)
2214
- WalletOption.XDEFI;
2215
- return WalletOption.METAMASK;
2216
- };
2217
- var isDetected = (walletOption) => {
2218
- return listWeb3EVMWallets().includes(walletOption);
2219
- };
2220
- var listWeb3EVMWallets = () => {
2221
- const metamaskEnabled = window?.ethereum && !window.ethereum?.isBraveWallet;
2222
- const xdefiEnabled = window?.xfi || window?.ethereum?.__XDEFI;
2223
- const braveEnabled = window?.ethereum?.isBraveWallet;
2224
- const trustEnabled = window?.ethereum?.isTrust || window?.trustwallet;
2225
- const coinbaseEnabled = window?.ethereum?.overrideIsMetaMask && window?.ethereum?.selectedProvider?.isCoinbaseWallet || window?.coinbaseWalletExtension;
2226
- const wallets = [];
2227
- if (metamaskEnabled)
2228
- wallets.push(WalletOption.METAMASK);
2229
- if (xdefiEnabled)
2230
- wallets.push(WalletOption.XDEFI);
2231
- if (braveEnabled)
2232
- wallets.push(WalletOption.BRAVE);
2233
- if (trustEnabled)
2234
- wallets.push(WalletOption.TRUSTWALLET_WEB);
2235
- if (coinbaseEnabled)
2236
- wallets.push(WalletOption.COINBASE_WEB);
2237
- if (okxMobileEnabled())
2238
- wallets.push(WalletOption.OKX_MOBILE);
2239
- return wallets;
2240
- };
2241
- var okxMobileEnabled = () => {
2242
- const ua = navigator.userAgent;
2243
- const isIOS = /iphone|ipad|ipod|ios/i.test(ua);
2244
- const isAndroid = /android|XiaoMi|MiuiBrowser/i.test(ua);
2245
- const isMobile = isIOS || isAndroid;
2246
- const isOKApp = /OKApp/i.test(ua);
2247
- return isMobile && isOKApp;
2248
- };
2249
- var isWeb3Detected = () => typeof window.ethereum !== "undefined";
2250
- // src/modules/bigIntArithmetics.ts
2251
- function formatBigIntToSafeValue({
2252
- value,
2253
- bigIntDecimal = DEFAULT_DECIMAL,
2254
- decimal = DEFAULT_DECIMAL
2255
- }) {
2256
- if (decimal === 0)
2257
- return value.toString();
2258
- const isNegative = value < 0n;
2259
- let valueString = value.toString().substring(isNegative ? 1 : 0);
2260
- const padLength = decimal - (valueString.length - 1);
2261
- if (padLength > 0) {
2262
- valueString = "0".repeat(padLength) + valueString;
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);
2263
1953
  }
2264
- const decimalIndex = valueString.length - decimal;
2265
- let decimalString = valueString.slice(-decimal);
2266
- if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) {
2267
- decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1).toString()}`;
2268
- } else {
2269
- decimalString = decimalString.substring(0, bigIntDecimal);
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 });
2270
1961
  }
2271
- return `${isNegative ? "-" : ""}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace(/\.?0*$/, "");
1962
+ return new AssetValue({ decimal, value: safeValue(value, decimal), identifier });
2272
1963
  }
2273
- var toSafeValue = function(value) {
2274
- const parsedValue = typeof value === "number" ? numberFormatter.format(value) : getStringValue(value);
2275
- const splitValue = `${parsedValue}`.replaceAll(",", ".").split(".");
2276
- return splitValue.length > 1 ? `${splitValue.slice(0, -1).join("")}.${splitValue.at(-1)}` : splitValue[0] || "0";
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
+ });
2277
1973
  };
2278
- var getFloatDecimals = function(value) {
2279
- const decimals = value.split(".")[1]?.length || 0;
2280
- return Math.max(decimals, DEFAULT_DECIMAL);
1974
+ var safeValue = function(value, decimal) {
1975
+ return typeof value === "bigint" ? formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }) : value;
2281
1976
  };
2282
- var getStringValue = function(param) {
2283
- 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
+ };
2284
1998
  };
2285
- var DEFAULT_DECIMAL = 8;
2286
- var toMultiplier = (decimal) => 10n ** BigInt(decimal);
2287
- var decimalFromMultiplier = (multiplier) => Math.log10(Number.parseFloat(multiplier.toString()));
1999
+ var staticTokensMap = new Map;
2288
2000
 
2289
- class BigIntArithmetics {
2290
- decimalMultiplier = 10n ** 8n;
2291
- bigIntValue = 0n;
2292
- decimal;
2293
- static fromBigInt(value, decimal) {
2294
- return new BigIntArithmetics({
2295
- decimal,
2296
- value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })
2297
- });
2298
- }
2299
- 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({
2300
2012
  value,
2301
- from,
2302
- to
2013
+ decimal,
2014
+ tax,
2015
+ chain,
2016
+ symbol,
2017
+ identifier
2303
2018
  }) {
2304
- return BigIntArithmetics.fromBigInt(value.getBaseValue("bigint") * toMultiplier(to) / toMultiplier(from), to);
2305
- }
2306
- constructor(params) {
2307
- const value = getStringValue(params);
2308
- const isComplex = typeof params === "object";
2309
- this.decimal = isComplex ? params.decimal : undefined;
2310
- this.decimalMultiplier = isComplex && "decimalMultiplier" in params ? params.decimalMultiplier : toMultiplier(Math.max(getFloatDecimals(toSafeValue(value)), this.decimal || 0));
2311
- 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];
2312
2030
  }
2313
- set(value) {
2314
- return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() });
2031
+ toString() {
2032
+ return this.isSynthetic ? this.symbol : `${this.chain}.${this.symbol}`;
2315
2033
  }
2316
- add(...args) {
2317
- return this.#arithmetics("add", ...args);
2034
+ toUrl() {
2035
+ return this.isSynthetic ? `${this.chain}.${this.symbol.replace("/", ".")}` : this.toString();
2318
2036
  }
2319
- sub(...args) {
2320
- return this.#arithmetics("sub", ...args);
2037
+ eq({ chain, symbol }) {
2038
+ return this.chain === chain && this.symbol === symbol;
2321
2039
  }
2322
- mul(...args) {
2323
- 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);
2324
2046
  }
2325
- div(...args) {
2326
- return this.#arithmetics("div", ...args);
2047
+ static fromString(assetString, value = 0) {
2048
+ return createAssetValue(assetString, value);
2327
2049
  }
2328
- gt(value) {
2329
- return this.#comparison("gt", value);
2330
- }
2331
- gte(value) {
2332
- return this.#comparison("gte", value);
2050
+ static fromIdentifier(assetString, value = 0) {
2051
+ return createAssetValue(assetString, value);
2333
2052
  }
2334
- lt(value) {
2335
- 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
+ });
2336
2068
  }
2337
- lte(value) {
2338
- 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);
2339
2077
  }
2340
- eqValue(value) {
2341
- 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
+ });
2342
2093
  }
2343
- getValue(type) {
2344
- const value = this.formatBigIntToSafeValue(this.bigIntValue, this.decimal || decimalFromMultiplier(this.decimalMultiplier));
2345
- switch (type) {
2346
- case "number":
2347
- return Number(value);
2348
- case "string":
2349
- return value;
2350
- case "bigint":
2351
- return this.bigIntValue * 10n ** BigInt(this.decimal || 8n) / this.decimalMultiplier;
2352
- }
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) });
2353
2104
  }
2354
- getBaseValue(type) {
2355
- const divisor = this.decimalMultiplier / toMultiplier(this.decimal || BaseDecimal.THOR);
2356
- const baseValue = this.bigIntValue / divisor;
2357
- switch (type) {
2358
- case "number":
2359
- return Number(baseValue);
2360
- case "string":
2361
- return baseValue.toString();
2362
- case "bigint":
2363
- return baseValue;
2364
- }
2105
+ static fromChainOrSignature(assetString, value = 0) {
2106
+ const { decimal, identifier } = getCommonAssetInfo(assetString);
2107
+ return new AssetValue({ value: safeValue(value, decimal), decimal, identifier });
2365
2108
  }
2366
- getBigIntValue(value, decimal) {
2367
- if (!decimal && typeof value === "object")
2368
- return value.bigIntValue;
2369
- const stringValue = getStringValue(value);
2370
- const safeValue = toSafeValue(stringValue);
2371
- if (safeValue === "0" || safeValue === "undefined")
2372
- return 0n;
2373
- 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
+ });
2374
2132
  }
2375
- toSignificant(significantDigits = 6) {
2376
- const [int, dec] = this.getValue("string").split(".");
2377
- const integer = int || "";
2378
- const decimal = dec || "";
2379
- const valueLength = Number.parseInt(integer) ? integer.length + decimal.length : decimal.length;
2380
- if (valueLength <= significantDigits) {
2381
- return this.getValue("string");
2382
- }
2383
- if (integer.length >= significantDigits) {
2384
- return integer.slice(0, significantDigits).padEnd(integer.length, "0");
2385
- }
2386
- if (Number.parseInt(integer)) {
2387
- return `${integer}.${decimal.slice(0, significantDigits - integer.length)}`.padEnd(significantDigits - integer.length, "0");
2388
- }
2389
- const trimmedDecimal = Number.parseInt(decimal);
2390
- const slicedDecimal = `${trimmedDecimal}`.slice(0, significantDigits);
2391
- 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
+ };
2392
2163
  }
2393
- toFixed(fixedDigits = 6) {
2394
- const [int, dec] = this.getValue("string").split(".");
2395
- const integer = int || "";
2396
- const decimal = dec || "";
2397
- if (Number.parseInt(integer)) {
2398
- 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;
2399
2176
  }
2400
- const trimmedDecimal = Number.parseInt(decimal);
2401
- const slicedDecimal = `${trimmedDecimal}`.slice(0, fixedDigits);
2402
- return `0.${slicedDecimal.padStart(decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length, "0")}`;
2403
2177
  }
2404
- toAbbreviation(digits = 2) {
2405
- const value = this.getValue("number");
2406
- const abbreviations = ["", "K", "M", "B", "T", "Q", "Qi", "S"];
2407
- const tier = Math.floor(Math.log10(Math.abs(value)) / 3);
2408
- const suffix = abbreviations[tier];
2409
- if (!suffix)
2410
- return this.getValue("string");
2411
- const scale = 10 ** (tier * 3);
2412
- const scaled = value / scale;
2413
- 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];
2414
2200
  }
2415
- toCurrency(currency = "$", {
2416
- currencyPosition = "start",
2417
- decimal = 2,
2418
- decimalSeparator = ".",
2419
- thousandSeparator = ","
2420
- } = {}) {
2421
- const value = this.getValue("number");
2422
- const [int = "", dec = ""] = value.toFixed(6).split(".");
2423
- const integer = int.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
2424
- const parsedValue = int || dec ? int === "0" ? `${Number.parseFloat(`0.${dec}`)}`.replace(".", decimalSeparator) : `${integer}${Number.parseInt(dec) ? `${decimalSeparator}${dec.slice(0, decimal)}` : ""}` : "0.00";
2425
- 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];
2426
2229
  }
2427
- formatBigIntToSafeValue(value, decimal) {
2428
- const bigIntDecimal = decimal || this.decimal || DEFAULT_DECIMAL;
2429
- const decimalToUseForConversion = Math.max(bigIntDecimal, decimalFromMultiplier(this.decimalMultiplier));
2430
- const isNegative = value < 0n;
2431
- const valueString = value.toString().substring(isNegative ? 1 : 0);
2432
- const padLength = decimalToUseForConversion - (valueString.length - 1);
2433
- const parsedValueString = padLength > 0 ? "0".repeat(padLength) + valueString : valueString;
2434
- const decimalIndex = parsedValueString.length - decimalToUseForConversion;
2435
- let decimalString = parsedValueString.slice(-decimalToUseForConversion);
2436
- if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) {
2437
- decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1).toString()}`;
2438
- } else {
2439
- decimalString = decimalString.substring(0, bigIntDecimal);
2440
- }
2441
- return `${isNegative ? "-" : ""}${parsedValueString.slice(0, decimalIndex)}.${decimalString}`.replace(/\.?0*$/, "");
2442
- }
2443
- #arithmetics(method, ...args) {
2444
- const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args);
2445
- const decimal = Math.max(precisionDecimal, decimalFromMultiplier(this.decimalMultiplier));
2446
- const precisionDecimalMultiplier = toMultiplier(decimal);
2447
- const result = args.reduce((acc, arg) => {
2448
- const value2 = this.getBigIntValue(arg, decimal);
2449
- switch (method) {
2450
- case "add":
2451
- return acc + value2;
2452
- case "sub":
2453
- return acc - value2;
2454
- case "mul":
2455
- return acc * value2 / precisionDecimalMultiplier;
2456
- case "div": {
2457
- if (value2 === 0n)
2458
- throw new RangeError("Division by zero");
2459
- return acc * precisionDecimalMultiplier / value2;
2460
- }
2461
- default:
2462
- return acc;
2463
- }
2464
- }, this.bigIntValue * precisionDecimalMultiplier / this.decimalMultiplier);
2465
- const value = formatBigIntToSafeValue({
2466
- bigIntDecimal: decimal,
2467
- decimal,
2468
- value: result
2469
- });
2470
- return new this.constructor({
2471
- decimalMultiplier: toMultiplier(decimal),
2472
- decimal: this.decimal,
2473
- value,
2474
- identifier: this.toString()
2475
- });
2476
- }
2477
- #comparison(method, ...args) {
2478
- const decimal = this.#retrievePrecisionDecimal(this, ...args);
2479
- const value = this.getBigIntValue(args[0] || "0", decimal);
2480
- const compareToValue = this.getBigIntValue(this, decimal);
2481
- switch (method) {
2482
- case "gt":
2483
- return compareToValue > value;
2484
- case "gte":
2485
- return compareToValue >= value;
2486
- case "lt":
2487
- return compareToValue < value;
2488
- case "lte":
2489
- return compareToValue <= value;
2490
- case "eqValue":
2491
- return compareToValue === value;
2492
- }
2493
- }
2494
- #setValue(value) {
2495
- const safeValue = toSafeValue(value) || "0";
2496
- this.bigIntValue = this.#toBigInt(safeValue);
2497
- }
2498
- #retrievePrecisionDecimal(...args) {
2499
- const decimals = args.map((arg) => {
2500
- const isObject = typeof arg === "object";
2501
- const value = isObject ? arg.decimal || decimalFromMultiplier(arg.decimalMultiplier) : getFloatDecimals(toSafeValue(arg));
2502
- return value;
2503
- }).filter(Boolean);
2504
- return Math.max(...decimals, DEFAULT_DECIMAL);
2505
- }
2506
- #toBigInt(value, decimal) {
2507
- const multiplier = decimal ? toMultiplier(decimal) : this.decimalMultiplier;
2508
- const padDecimal = decimalFromMultiplier(multiplier);
2509
- const [integerPart = "", decimalPart = ""] = value.split(".");
2510
- return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, "0")}`);
2511
- }
2512
- }
2513
- var numberFormatter = Intl.NumberFormat("fullwide", {
2514
- useGrouping: false,
2515
- maximumFractionDigits: 20
2516
- });
2517
-
2518
- // src/modules/swapKitNumber.ts
2519
- class SwapKitNumber extends BigIntArithmetics {
2520
- constructor() {
2521
- super(...arguments);
2522
- }
2523
- eq(value) {
2524
- return this.eqValue(value);
2525
- }
2526
- static fromBigInt(value, decimal) {
2527
- return new SwapKitNumber({
2528
- decimal,
2529
- value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal })
2530
- });
2531
- }
2532
- }
2533
-
2534
- // src/modules/assetValue.ts
2535
- function getMinAmountByChain(chain) {
2536
- const asset2 = AssetValue.fromChainOrSignature(chain);
2230
+ };
2231
+ var getGasAsset = ({ chain }) => {
2537
2232
  switch (chain) {
2538
- case Chain.Bitcoin:
2539
- case Chain.Litecoin:
2540
- case Chain.BitcoinCash:
2541
- return asset2.set(0.00010001);
2542
- case Chain.Dogecoin:
2543
- return asset2.set(1.00000001);
2544
- case Chain.Avalanche:
2545
- case Chain.Ethereum:
2546
- 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`);
2547
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";
2548
2253
  case Chain.Maya:
2549
- return asset2.set(0);
2254
+ return symbol === "CACAO";
2550
2255
  case Chain.Cosmos:
2551
- 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";
2552
2261
  default:
2553
- return asset2.set(0.00000001);
2262
+ return symbol === chain;
2554
2263
  }
2555
- }
2556
- async function createAssetValue(identifier, value = 0) {
2557
- validateIdentifier(identifier);
2558
- const staticToken = staticTokensMap.get(identifier.toUpperCase());
2559
- const decimal = staticToken?.decimal || await getDecimal(getAssetInfo(identifier));
2560
- if (!staticToken) {
2561
- 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] };
2562
2289
  }
2563
- return new AssetValue({ decimal, value: safeValue(value, decimal), identifier });
2564
- }
2565
- var createSyntheticAssetValue = function(identifier, value = 0) {
2566
- const [synthChain, symbol] = identifier.split(".")?.[0]?.toUpperCase() === Chain.THORChain ? identifier.split(".").slice(1).join().split("/") : identifier.split("/");
2567
- if (!(synthChain && symbol))
2568
- throw new Error("Invalid asset identifier");
2569
- return new AssetValue({
2570
- decimal: 8,
2571
- value: safeValue(value, 8),
2572
- identifier: `${Chain.THORChain}.${synthChain}/${symbol}`
2573
- });
2574
2290
  };
2575
- var safeValue = function(value, decimal) {
2576
- 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
+ }
2577
2316
  };
2578
- var getAssetInfo = function(identifier) {
2579
- const isSynthetic = identifier.slice(0, 14).includes("/");
2580
- const isThorchain = identifier.split(".")?.[0]?.toUpperCase() === Chain.THORChain;
2581
- const isMaya = identifier.split(".")?.[0]?.toUpperCase() === Chain.Maya;
2582
- const [synthChain, synthSymbol = ""] = isThorchain || isMaya ? identifier.split(".").slice(1).join().split("/") : identifier.split("/");
2583
- if (isSynthetic && !(synthChain && synthSymbol))
2584
- throw new Error("Invalid asset identifier");
2585
- const adjustedIdentifier = identifier.includes(".") && !isSynthetic ? identifier : `${isMaya ? Chain.Maya : Chain.THORChain}.${synthSymbol}`;
2586
- const [chain, ...rest] = adjustedIdentifier.split(".");
2587
- 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;
2588
2330
  const splitSymbol = symbol.split("-");
2589
- const ticker = splitSymbol.length === 1 ? splitSymbol[0] : splitSymbol.slice(0, -1).join("-");
2590
2331
  const address = splitSymbol.length === 1 ? undefined : splitSymbol[splitSymbol.length - 1];
2591
- return {
2592
- address: address?.toLowerCase(),
2593
- chain,
2594
- isGasAsset: isGasAsset({ chain, symbol }),
2595
- isSynthetic,
2596
- symbol: (isSynthetic ? `${synthChain}/` : "") + (address ? `${ticker}-${address?.toLowerCase() ?? ""}` : symbol),
2597
- ticker
2598
- };
2332
+ return isGasAsset({ chain, symbol }) || !!address;
2599
2333
  };
2600
- var staticTokensMap = new Map;
2601
-
2602
- class AssetValue extends BigIntArithmetics {
2603
- address;
2604
- chain;
2605
- isGasAsset = false;
2606
- isSynthetic = false;
2607
- symbol;
2608
- tax;
2609
- ticker;
2610
- type;
2611
- chainId;
2612
- constructor({
2613
- value,
2614
- decimal,
2615
- tax,
2616
- chain,
2617
- symbol,
2618
- identifier
2619
- }) {
2620
- super(typeof value === "object" ? value : { decimal, value });
2621
- const assetInfo = getAssetInfo(identifier || `${chain}.${symbol}`);
2622
- this.type = getAssetType(assetInfo);
2623
- this.tax = tax;
2624
- this.chain = assetInfo.chain;
2625
- this.ticker = assetInfo.ticker;
2626
- this.symbol = assetInfo.symbol;
2627
- this.address = assetInfo.address;
2628
- this.isSynthetic = assetInfo.isSynthetic;
2629
- this.isGasAsset = assetInfo.isGasAsset;
2630
- this.chainId = ChainToChainId[assetInfo.chain];
2631
- }
2632
- toString() {
2633
- return this.isSynthetic ? this.symbol : `${this.chain}.${this.symbol}`;
2634
- }
2635
- toUrl() {
2636
- return this.isSynthetic ? `${this.chain}.${this.symbol.replace("/", ".")}` : this.toString();
2637
- }
2638
- eq({ chain, symbol }) {
2639
- return this.chain === chain && this.symbol === symbol;
2640
- }
2641
- static fromUrl(urlAsset, value = 0) {
2642
- const [chain, ticker, symbol] = urlAsset.split(".");
2643
- if (!(chain && ticker))
2644
- throw new Error("Invalid asset url");
2645
- const assetString = chain === Chain.THORChain && symbol ? `${chain}.${ticker}/${symbol}` : urlAsset;
2646
- 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);
2647
2346
  }
2648
- static fromString(assetString, value = 0) {
2649
- 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);
2650
2356
  }
2651
- static fromIdentifier(assetString, value = 0) {
2652
- 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";
2653
2370
  }
2654
- static fromStringSync(assetString, value = 0) {
2655
- const { chain, isSynthetic } = getAssetInfo(assetString);
2656
- const tokenInfo = staticTokensMap.get(assetString.toUpperCase());
2657
- if (isSynthetic)
2658
- return createSyntheticAssetValue(assetString, value);
2659
- const { tax, decimal, identifier } = tokenInfo || {
2660
- decimal: BaseDecimal[chain],
2661
- identifier: assetString
2662
- };
2663
- return new AssetValue({
2664
- tax,
2665
- value: safeValue(value, decimal),
2666
- identifier: isSynthetic ? assetString : identifier,
2667
- decimal: isSynthetic ? 8 : decimal
2668
- });
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");
2669
2471
  }
2670
- static async fromStringWithBase(assetString, value = 0, baseDecimal = BaseDecimal.THOR) {
2671
- const shiftedAmount = BigIntArithmetics.shiftDecimals({
2672
- value: SwapKitNumber.fromBigInt(BigInt(value)),
2673
- from: 0,
2674
- to: baseDecimal
2675
- }).getBaseValue("string");
2676
- const assetValue = await AssetValue.fromString(assetString, value);
2677
- 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 "";
2678
2537
  }
2679
- static fromStringWithBaseSync(assetString, value = 0, baseDecimal = BaseDecimal.THOR) {
2680
- const { chain, isSynthetic } = getAssetInfo(assetString);
2681
- const tokenInfo = staticTokensMap.get(assetString.toUpperCase());
2682
- if (isSynthetic)
2683
- return createSyntheticAssetValue(assetString, value);
2684
- const { tax, decimal, identifier } = tokenInfo || {
2685
- decimal: BaseDecimal[chain],
2686
- identifier: assetString
2687
- };
2688
- return new AssetValue({
2689
- tax,
2690
- value: safeValue(BigInt(value), baseDecimal),
2691
- identifier,
2692
- 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 }
2693
2606
  });
2607
+ Object.setPrototypeOf(this, SwapKitError.prototype);
2694
2608
  }
2695
- static fromIdentifierSync(assetString, value = 0) {
2696
- const { chain, isSynthetic } = getAssetInfo(assetString);
2697
- const tokenInfo = staticTokensMap.get(assetString);
2698
- if (isSynthetic)
2699
- return createSyntheticAssetValue(assetString, value);
2700
- const { tax, decimal, identifier } = tokenInfo || {
2701
- decimal: BaseDecimal[chain],
2702
- identifier: assetString
2703
- };
2704
- 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);
2705
2634
  }
2706
- static fromChainOrSignature(assetString, value = 0) {
2707
- const { decimal, identifier } = getCommonAssetInfo(assetString);
2708
- 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);
2709
2643
  }
2710
- static loadStaticAssets() {
2711
- return new Promise((resolve, reject) => {
2712
- try {
2713
- import("@swapkit/tokens").then((tokenPackages) => {
2714
- for (const tokenList of Object.values(tokenPackages)) {
2715
- for (const { identifier, chain, ...rest } of tokenList.tokens) {
2716
- staticTokensMap.set(identifier.toUpperCase(), {
2717
- identifier,
2718
- decimal: "decimals" in rest ? rest.decimals : BaseDecimal[chain]
2719
- });
2720
- }
2721
- }
2722
- resolve({ ok: true });
2723
- });
2724
- } catch (error) {
2725
- console.error(error);
2726
- reject({
2727
- ok: false,
2728
- error,
2729
- message: "Couldn't load static assets. Ensure you have installed @swapkit/tokens package"
2730
- });
2731
- }
2732
- });
2644
+ window.addEventListener("eip6963:announceProvider", onAnnouncement);
2645
+ window.dispatchEvent(new Event("eip6963:requestProvider"));
2646
+ function removeEIP6963EventListener() {
2647
+ window.removeEventListener("eip6963:announceProvider", onAnnouncement);
2733
2648
  }
2649
+ return { providers, removeEIP6963EventListener };
2734
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";
2735
2750
  export {
2736
2751
  wrapWithThrow,
2737
2752
  wrapMethodWithNetworkSwitch,
@@ -2753,6 +2768,7 @@ export {
2753
2768
  getMemoFor,
2754
2769
  getMAYANameCost,
2755
2770
  getLiquiditySlippage,
2771
+ getGasAsset,
2756
2772
  getEstimatedPoolShare,
2757
2773
  getETHDefaultWallet,
2758
2774
  getEIP6963Wallets,
@@ -2829,4 +2845,4 @@ export {
2829
2845
  AGG_SWAP
2830
2846
  };
2831
2847
 
2832
- //# debugId=98419242CC3C63F664756e2164756e21
2848
+ //# debugId=DD0CB89ADAB3D33764756e2164756e21