opentool 0.8.24 → 0.8.27

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.
@@ -578,12 +578,29 @@ function toApiDecimal(value) {
578
578
  }
579
579
  return asString;
580
580
  }
581
+ var NORMALIZED_HEX_PATTERN = /^0x[0-9a-f]+$/;
582
+ var ADDRESS_HEX_LENGTH = 42;
583
+ var CLOID_HEX_LENGTH = 34;
581
584
  function normalizeHex(value) {
582
- const lower = value.toLowerCase();
583
- return lower.replace(/^0x0+/, "0x") || "0x0";
585
+ const lower = value.trim().toLowerCase();
586
+ if (!NORMALIZED_HEX_PATTERN.test(lower)) {
587
+ throw new Error(`Invalid hex value: ${value}`);
588
+ }
589
+ return lower;
584
590
  }
585
591
  function normalizeAddress(value) {
586
- return normalizeHex(value);
592
+ const normalized = normalizeHex(value);
593
+ if (normalized.length !== ADDRESS_HEX_LENGTH) {
594
+ throw new Error(`Invalid address length: ${normalized}`);
595
+ }
596
+ return normalized;
597
+ }
598
+ function normalizeCloid(value) {
599
+ const normalized = normalizeHex(value);
600
+ if (normalized.length !== CLOID_HEX_LENGTH) {
601
+ throw new Error(`Invalid cloid length: ${normalized}`);
602
+ }
603
+ return normalized;
587
604
  }
588
605
  async function signL1Action(args) {
589
606
  const { wallet, action, nonce, vaultAddress, expiresAfter, isTestnet } = args;
@@ -1326,8 +1343,8 @@ async function cancelHyperliquidOrdersByCloid(options) {
1326
1343
  options,
1327
1344
  options.cancels,
1328
1345
  (idx, entry) => ({
1329
- a: idx,
1330
- c: normalizeAddress(entry.cloid)
1346
+ asset: idx,
1347
+ cloid: normalizeCloid(entry.cloid)
1331
1348
  })
1332
1349
  )
1333
1350
  };
@@ -1338,10 +1355,10 @@ async function cancelAllHyperliquidOrders(options) {
1338
1355
  return submitExchangeAction(options, action);
1339
1356
  }
1340
1357
  async function scheduleHyperliquidCancel(options) {
1341
- if (options.time !== null) {
1358
+ if (options.time != null) {
1342
1359
  assertPositiveNumber(options.time, "time");
1343
1360
  }
1344
- const action = { type: "scheduleCancel", time: options.time };
1361
+ const action = options.time == null ? { type: "scheduleCancel" } : { type: "scheduleCancel", time: options.time };
1345
1362
  return submitExchangeAction(options, action);
1346
1363
  }
1347
1364
  async function modifyHyperliquidOrder(options) {
@@ -1575,7 +1592,7 @@ async function buildOrder(intent, options) {
1575
1592
  r: intent.reduceOnly ?? false,
1576
1593
  t: limitOrTrigger,
1577
1594
  ...intent.clientId ? {
1578
- c: normalizeAddress(intent.clientId)
1595
+ c: normalizeCloid(intent.clientId)
1579
1596
  } : {}
1580
1597
  };
1581
1598
  }
@@ -1622,6 +1639,32 @@ function assertPositiveDecimal(value, label) {
1622
1639
  return;
1623
1640
  }
1624
1641
  assertString(value, label);
1642
+ if (!/^(?:\d+\.?\d*|\.\d+)$/.test(value.trim())) {
1643
+ throw new Error(`${label} must be a positive decimal string.`);
1644
+ }
1645
+ const numeric = Number(value);
1646
+ if (!Number.isFinite(numeric) || numeric <= 0) {
1647
+ throw new Error(`${label} must be positive.`);
1648
+ }
1649
+ }
1650
+ function collectExchangeErrorMessages(payload) {
1651
+ if (!payload || typeof payload !== "object") return [];
1652
+ const root = payload;
1653
+ const messages = [];
1654
+ const statuses = root.response?.data?.statuses;
1655
+ if (Array.isArray(statuses)) {
1656
+ statuses.forEach((status, index) => {
1657
+ if (status && typeof status === "object" && "error" in status && typeof status.error === "string") {
1658
+ const errorText = status.error;
1659
+ messages.push(`status[${index}]: ${errorText}`);
1660
+ }
1661
+ });
1662
+ }
1663
+ const singleStatus = root.response?.data?.status;
1664
+ if (singleStatus && typeof singleStatus === "object" && "error" in singleStatus && typeof singleStatus.error === "string") {
1665
+ messages.push(singleStatus.error);
1666
+ }
1667
+ return messages;
1625
1668
  }
1626
1669
  async function postExchange(env, body) {
1627
1670
  const response = await fetch(`${API_BASES[env]}/exchange`, {
@@ -1659,10 +1702,909 @@ async function postExchange(env, body) {
1659
1702
  body: json
1660
1703
  });
1661
1704
  }
1705
+ const nestedErrors = collectExchangeErrorMessages(json);
1706
+ if (nestedErrors.length > 0) {
1707
+ throw new HyperliquidApiError("Hyperliquid exchange returned action errors.", {
1708
+ status: response.status,
1709
+ statusText: response.statusText,
1710
+ body: json,
1711
+ errors: nestedErrors
1712
+ });
1713
+ }
1714
+ return json;
1715
+ }
1716
+
1717
+ // src/adapters/hyperliquid/env.ts
1718
+ function resolveHyperliquidChain(environment) {
1719
+ return environment === "mainnet" ? "arbitrum" : "arbitrum-sepolia";
1720
+ }
1721
+ function resolveHyperliquidRpcEnvVar(environment) {
1722
+ return environment === "mainnet" ? "ARBITRUM_RPC_URL" : "ARBITRUM_SEPOLIA_RPC_URL";
1723
+ }
1724
+ function resolveHyperliquidChainConfig(environment, env = process.env) {
1725
+ const rpcVar = resolveHyperliquidRpcEnvVar(environment);
1726
+ const rpcUrl = env[rpcVar];
1727
+ return {
1728
+ chain: resolveHyperliquidChain(environment),
1729
+ ...rpcUrl ? { rpcUrl } : {}
1730
+ };
1731
+ }
1732
+ function resolveHyperliquidStoreNetwork(environment) {
1733
+ return environment === "mainnet" ? "hyperliquid" : "hyperliquid-testnet";
1734
+ }
1735
+
1736
+ // src/adapters/hyperliquid/symbols.ts
1737
+ var UNKNOWN_SYMBOL2 = "UNKNOWN";
1738
+ function extractHyperliquidDex(symbol) {
1739
+ const idx = symbol.indexOf(":");
1740
+ if (idx <= 0) return null;
1741
+ const dex = symbol.slice(0, idx).trim().toLowerCase();
1742
+ return dex || null;
1743
+ }
1744
+ function normalizeSpotTokenName2(value) {
1745
+ const raw = (value ?? "").trim();
1746
+ if (!raw) return "";
1747
+ if (raw.endsWith("0") && raw.length > 1) {
1748
+ return raw.slice(0, -1);
1749
+ }
1750
+ return raw;
1751
+ }
1752
+ function normalizeHyperliquidBaseSymbol(value) {
1753
+ if (!value) return null;
1754
+ const trimmed = value.trim();
1755
+ if (!trimmed) return null;
1756
+ const withoutDex = trimmed.includes(":") ? trimmed.split(":").slice(1).join(":") : trimmed;
1757
+ const base = withoutDex.split("-")[0] ?? withoutDex;
1758
+ const baseNoPair = base.split("/")[0] ?? base;
1759
+ const normalized = baseNoPair.trim().toUpperCase();
1760
+ if (!normalized || normalized === UNKNOWN_SYMBOL2) return null;
1761
+ return normalized;
1762
+ }
1763
+ function normalizeHyperliquidMetaSymbol(symbol) {
1764
+ const trimmed = symbol.trim();
1765
+ const noDex = trimmed.includes(":") ? trimmed.split(":").slice(1).join(":") : trimmed;
1766
+ const noPair = noDex.split("-")[0] ?? noDex;
1767
+ return (noPair.split("/")[0] ?? noPair).trim();
1768
+ }
1769
+ function resolveHyperliquidPair(value) {
1770
+ if (!value) return null;
1771
+ const trimmed = value.trim();
1772
+ if (!trimmed) return null;
1773
+ const withoutDex = trimmed.includes(":") ? trimmed.split(":").slice(1).join(":") : trimmed;
1774
+ if (withoutDex.includes("/")) {
1775
+ return withoutDex.toUpperCase();
1776
+ }
1777
+ if (withoutDex.includes("-")) {
1778
+ const [base, ...rest] = withoutDex.split("-");
1779
+ const quote = rest.join("-").trim();
1780
+ if (!base || !quote) return null;
1781
+ return `${base.toUpperCase()}/${quote.toUpperCase()}`;
1782
+ }
1783
+ return null;
1784
+ }
1785
+ function resolveHyperliquidProfileChain(environment) {
1786
+ return environment === "testnet" ? "hyperliquid-testnet" : "hyperliquid";
1787
+ }
1788
+ function buildHyperliquidProfileAssets(params) {
1789
+ const chain = resolveHyperliquidProfileChain(params.environment);
1790
+ return params.assets.map((asset) => {
1791
+ const symbols = asset.assetSymbols.map((symbol) => normalizeHyperliquidBaseSymbol(symbol)).filter((symbol) => Boolean(symbol));
1792
+ if (symbols.length === 0) return null;
1793
+ const explicitPair = typeof asset.pair === "string" ? resolveHyperliquidPair(asset.pair) : null;
1794
+ const derivedPair = symbols.length === 1 ? resolveHyperliquidPair(asset.assetSymbols[0] ?? symbols[0]) : null;
1795
+ const pair = explicitPair ?? derivedPair ?? void 0;
1796
+ const leverage = typeof asset.leverage === "number" && Number.isFinite(asset.leverage) && asset.leverage > 0 ? asset.leverage : void 0;
1797
+ const walletAddress = typeof asset.walletAddress === "string" && asset.walletAddress.trim().length > 0 ? asset.walletAddress.trim() : void 0;
1798
+ return {
1799
+ venue: "hyperliquid",
1800
+ chain,
1801
+ assetSymbols: symbols,
1802
+ ...pair ? { pair } : {},
1803
+ ...leverage ? { leverage } : {},
1804
+ ...walletAddress ? { walletAddress } : {}
1805
+ };
1806
+ }).filter((asset) => asset !== null);
1807
+ }
1808
+ function parseSpotPairSymbol(symbol) {
1809
+ const trimmed = symbol.trim();
1810
+ if (!trimmed.includes("/")) return null;
1811
+ const [rawBase, rawQuote] = trimmed.split("/");
1812
+ const base = rawBase?.trim().toUpperCase() ?? "";
1813
+ const quote = rawQuote?.trim().toUpperCase() ?? "";
1814
+ if (!base || !quote) return null;
1815
+ return { base, quote };
1816
+ }
1817
+ function isHyperliquidSpotSymbol(symbol) {
1818
+ return symbol.startsWith("@") || symbol.includes("/");
1819
+ }
1820
+ function resolveSpotMidCandidates(baseSymbol) {
1821
+ const base = baseSymbol.trim().toUpperCase();
1822
+ if (!base) return [];
1823
+ const candidates = [base];
1824
+ if (base.startsWith("U") && base.length > 1) {
1825
+ candidates.push(base.slice(1));
1826
+ }
1827
+ return Array.from(new Set(candidates));
1828
+ }
1829
+ function resolveSpotTokenCandidates(value) {
1830
+ const normalized = normalizeSpotTokenName2(value).toUpperCase();
1831
+ if (!normalized) return [];
1832
+ const candidates = [normalized];
1833
+ if (normalized.startsWith("U") && normalized.length > 1) {
1834
+ candidates.push(normalized.slice(1));
1835
+ }
1836
+ return Array.from(new Set(candidates));
1837
+ }
1838
+ function resolveHyperliquidOrderSymbol(value) {
1839
+ if (!value) return null;
1840
+ const trimmed = value.trim();
1841
+ if (!trimmed) return null;
1842
+ if (trimmed.startsWith("@")) return trimmed;
1843
+ if (trimmed.includes(":")) {
1844
+ const [rawDex, ...restParts] = trimmed.split(":");
1845
+ const dex = rawDex.trim().toLowerCase();
1846
+ const rest = restParts.join(":");
1847
+ const base = rest.split("/")[0]?.split("-")[0] ?? rest;
1848
+ const normalizedBase = base.trim().toUpperCase();
1849
+ if (!dex || !normalizedBase || normalizedBase === UNKNOWN_SYMBOL2) {
1850
+ return null;
1851
+ }
1852
+ return `${dex}:${normalizedBase}`;
1853
+ }
1854
+ const pair = resolveHyperliquidPair(trimmed);
1855
+ if (pair) return pair;
1856
+ return normalizeHyperliquidBaseSymbol(trimmed);
1857
+ }
1858
+ function resolveHyperliquidSymbol(asset, override) {
1859
+ const raw = override && override.trim().length > 0 ? override.trim() : asset.trim();
1860
+ if (!raw) return raw;
1861
+ if (raw.startsWith("@")) return raw;
1862
+ if (raw.includes(":")) {
1863
+ const [dexRaw, ...restParts] = raw.split(":");
1864
+ const dex = dexRaw.trim().toLowerCase();
1865
+ const rest = restParts.join(":");
1866
+ const base2 = rest.split("/")[0]?.split("-")[0] ?? rest;
1867
+ const normalizedBase = base2.trim().toUpperCase();
1868
+ if (!dex) return normalizedBase;
1869
+ return `${dex}:${normalizedBase}`;
1870
+ }
1871
+ if (raw.includes("/")) {
1872
+ return raw.toUpperCase();
1873
+ }
1874
+ if (raw.includes("-")) {
1875
+ const [base2, ...rest] = raw.split("-");
1876
+ const quote = rest.join("-").trim();
1877
+ if (base2 && quote) {
1878
+ return `${base2.toUpperCase()}/${quote.toUpperCase()}`;
1879
+ }
1880
+ }
1881
+ const base = raw.split("-")[0] ?? raw;
1882
+ const baseNoPair = base.split("/")[0] ?? base;
1883
+ return baseNoPair.trim().toUpperCase();
1884
+ }
1885
+
1886
+ // src/adapters/hyperliquid/order-utils.ts
1887
+ var MAX_HYPERLIQUID_PRICE_DECIMALS = 8;
1888
+ function countDecimals(value) {
1889
+ if (!Number.isFinite(value)) return 0;
1890
+ const s = value.toString();
1891
+ const [, dec = ""] = s.split(".");
1892
+ return dec.length;
1893
+ }
1894
+ function clampPriceDecimals(value) {
1895
+ if (!Number.isFinite(value) || value <= 0) {
1896
+ throw new Error("Price must be positive.");
1897
+ }
1898
+ const fixed = value.toFixed(MAX_HYPERLIQUID_PRICE_DECIMALS);
1899
+ return fixed.replace(/\.?0+$/, "");
1900
+ }
1901
+ function assertNumberString(value) {
1902
+ if (!/^-?(?:\d+\.?\d*|\.\d+)$/.test(value)) {
1903
+ throw new TypeError("Invalid decimal number string.");
1904
+ }
1905
+ }
1906
+ function normalizeDecimalString(value) {
1907
+ return value.trim().replace(/^(-?)0+(?=\d)/, "$1").replace(/\.0*$|(\.\d+?)0+$/, "$1").replace(/^(-?)\./, "$10.").replace(/^-?$/, "0").replace(/^-0$/, "0");
1908
+ }
1909
+ var StringMath = {
1910
+ log10Floor(value) {
1911
+ const abs = value.startsWith("-") ? value.slice(1) : value;
1912
+ const num = Number(abs);
1913
+ if (!Number.isFinite(num) || num === 0) return -Infinity;
1914
+ const [intPart, fracPart = ""] = abs.split(".");
1915
+ if (Number(intPart) !== 0) {
1916
+ return intPart.replace(/^0+/, "").length - 1;
1917
+ }
1918
+ const leadingZeros = fracPart.match(/^0*/)?.[0]?.length ?? 0;
1919
+ return -(leadingZeros + 1);
1920
+ },
1921
+ multiplyByPow10(value, exp) {
1922
+ if (!Number.isInteger(exp)) {
1923
+ throw new RangeError("Exponent must be an integer.");
1924
+ }
1925
+ if (exp === 0) return normalizeDecimalString(value);
1926
+ const negative = value.startsWith("-");
1927
+ const abs = negative ? value.slice(1) : value;
1928
+ const [intRaw, fracRaw = ""] = abs.split(".");
1929
+ const intPart = intRaw || "0";
1930
+ let output;
1931
+ if (exp > 0) {
1932
+ if (exp >= fracRaw.length) {
1933
+ output = intPart + fracRaw + "0".repeat(exp - fracRaw.length);
1934
+ } else {
1935
+ output = `${intPart}${fracRaw.slice(0, exp)}.${fracRaw.slice(exp)}`;
1936
+ }
1937
+ } else {
1938
+ const absExp = -exp;
1939
+ if (absExp >= intPart.length) {
1940
+ output = `0.${"0".repeat(absExp - intPart.length)}${intPart}${fracRaw}`;
1941
+ } else {
1942
+ output = `${intPart.slice(0, -absExp)}.${intPart.slice(-absExp)}${fracRaw}`;
1943
+ }
1944
+ }
1945
+ return normalizeDecimalString((negative ? "-" : "") + output);
1946
+ },
1947
+ trunc(value) {
1948
+ const index = value.indexOf(".");
1949
+ return index === -1 ? value : value.slice(0, index) || "0";
1950
+ },
1951
+ toPrecisionTruncate(value, precision) {
1952
+ if (!Number.isInteger(precision) || precision < 1) {
1953
+ throw new RangeError("Precision must be a positive integer.");
1954
+ }
1955
+ if (/^-?0+(\.0*)?$/.test(value)) return "0";
1956
+ const negative = value.startsWith("-");
1957
+ const abs = negative ? value.slice(1) : value;
1958
+ const magnitude = StringMath.log10Floor(abs);
1959
+ const shiftAmount = precision - magnitude - 1;
1960
+ const shifted = StringMath.multiplyByPow10(abs, shiftAmount);
1961
+ const truncated = StringMath.trunc(shifted);
1962
+ const shiftedBack = StringMath.multiplyByPow10(truncated, -shiftAmount);
1963
+ return normalizeDecimalString(negative ? `-${shiftedBack}` : shiftedBack);
1964
+ },
1965
+ toFixedTruncate(value, decimals) {
1966
+ if (!Number.isInteger(decimals) || decimals < 0) {
1967
+ throw new RangeError("Decimals must be a non-negative integer.");
1968
+ }
1969
+ const matcher = new RegExp(`^-?(?:\\d+)?(?:\\.\\d{0,${decimals}})?`);
1970
+ const result = value.match(matcher)?.[0];
1971
+ if (!result) {
1972
+ throw new TypeError("Invalid number format.");
1973
+ }
1974
+ return normalizeDecimalString(result);
1975
+ }
1976
+ };
1977
+ function formatHyperliquidPrice(price, szDecimals, marketType = "perp") {
1978
+ const normalized = price.toString().trim();
1979
+ assertNumberString(normalized);
1980
+ if (/^-?\d+$/.test(normalized)) {
1981
+ return normalizeDecimalString(normalized);
1982
+ }
1983
+ const maxDecimals2 = Math.max((marketType === "perp" ? 6 : 8) - szDecimals, 0);
1984
+ const decimalsTrimmed = StringMath.toFixedTruncate(normalized, maxDecimals2);
1985
+ const sigFigTrimmed = StringMath.toPrecisionTruncate(decimalsTrimmed, 5);
1986
+ if (sigFigTrimmed === "0") {
1987
+ throw new RangeError("Price is too small and was truncated to 0.");
1988
+ }
1989
+ return sigFigTrimmed;
1990
+ }
1991
+ function formatHyperliquidSize(size, szDecimals) {
1992
+ const normalized = size.toString().trim();
1993
+ assertNumberString(normalized);
1994
+ const truncated = StringMath.toFixedTruncate(normalized, szDecimals);
1995
+ if (truncated === "0") {
1996
+ throw new RangeError("Size is too small and was truncated to 0.");
1997
+ }
1998
+ return truncated;
1999
+ }
2000
+ function formatHyperliquidOrderSize(value, szDecimals) {
2001
+ if (!Number.isFinite(value) || value <= 0) return "0";
2002
+ try {
2003
+ return formatHyperliquidSize(value, szDecimals);
2004
+ } catch {
2005
+ return "0";
2006
+ }
2007
+ }
2008
+ function roundHyperliquidPriceToTick(price, tick, side) {
2009
+ if (!Number.isFinite(price) || price <= 0) {
2010
+ throw new Error("Price must be positive.");
2011
+ }
2012
+ if (!Number.isFinite(tick.tickDecimals) || tick.tickDecimals < 0) {
2013
+ throw new Error("tick.tickDecimals must be a non-negative number.");
2014
+ }
2015
+ if (tick.tickSizeInt <= 0n) {
2016
+ throw new Error("tick.tickSizeInt must be positive.");
2017
+ }
2018
+ const scale = 10 ** tick.tickDecimals;
2019
+ const scaled = BigInt(Math.round(price * scale));
2020
+ const tickSize = tick.tickSizeInt;
2021
+ const rounded = side === "sell" ? scaled / tickSize * tickSize : (scaled + tickSize - 1n) / tickSize * tickSize;
2022
+ const integer = Number(rounded) / scale;
2023
+ return clampPriceDecimals(integer);
2024
+ }
2025
+ function formatHyperliquidMarketablePrice(params) {
2026
+ const { mid, side, slippageBps, tick } = params;
2027
+ const decimals = countDecimals(mid);
2028
+ const factor = 10 ** decimals;
2029
+ const adjusted = mid * (side === "buy" ? 1 + slippageBps / 1e4 : 1 - slippageBps / 1e4);
2030
+ if (tick) {
2031
+ return roundHyperliquidPriceToTick(adjusted, tick, side);
2032
+ }
2033
+ const scaled = adjusted * factor;
2034
+ const rounded = side === "buy" ? Math.ceil(scaled) / factor : Math.floor(scaled) / factor;
2035
+ return clampPriceDecimals(rounded);
2036
+ }
2037
+ function extractHyperliquidOrderIds(responses) {
2038
+ const cloids = /* @__PURE__ */ new Set();
2039
+ const oids = /* @__PURE__ */ new Set();
2040
+ const push = (val, target) => {
2041
+ if (val === null || val === void 0) return;
2042
+ const str = String(val);
2043
+ if (str.length) target.add(str);
2044
+ };
2045
+ for (const res of responses) {
2046
+ const statuses = res?.response?.data?.statuses;
2047
+ if (!Array.isArray(statuses)) continue;
2048
+ for (const status of statuses) {
2049
+ const resting = status.resting;
2050
+ const filled = status.filled;
2051
+ push(resting?.cloid, cloids);
2052
+ push(resting?.oid, oids);
2053
+ push(filled?.cloid, cloids);
2054
+ push(filled?.oid, oids);
2055
+ }
2056
+ }
2057
+ return {
2058
+ cloids: Array.from(cloids),
2059
+ oids: Array.from(oids)
2060
+ };
2061
+ }
2062
+ function resolveHyperliquidOrderRef(params) {
2063
+ const { response, fallbackCloid, fallbackOid, prefix = "hl-order", index = 0 } = params;
2064
+ const statuses = response?.response?.data?.statuses ?? [];
2065
+ if (Array.isArray(statuses)) {
2066
+ for (const status of statuses) {
2067
+ const filled = status && typeof status.filled === "object" ? status.filled : null;
2068
+ if (filled) {
2069
+ if (typeof filled.cloid === "string" && filled.cloid.trim().length > 0) {
2070
+ return filled.cloid;
2071
+ }
2072
+ if (typeof filled.oid === "number" || typeof filled.oid === "string" && filled.oid.trim().length > 0) {
2073
+ return String(filled.oid);
2074
+ }
2075
+ }
2076
+ const resting = status && typeof status.resting === "object" ? status.resting : null;
2077
+ if (resting) {
2078
+ if (typeof resting.cloid === "string" && resting.cloid.trim().length > 0) {
2079
+ return resting.cloid;
2080
+ }
2081
+ if (typeof resting.oid === "number" || typeof resting.oid === "string" && resting.oid.trim().length > 0) {
2082
+ return String(resting.oid);
2083
+ }
2084
+ }
2085
+ }
2086
+ }
2087
+ if (fallbackCloid && fallbackCloid.trim().length > 0) {
2088
+ return fallbackCloid;
2089
+ }
2090
+ if (fallbackOid && fallbackOid.trim().length > 0) {
2091
+ return fallbackOid;
2092
+ }
2093
+ return `${prefix}-${Date.now()}-${index}`;
2094
+ }
2095
+ function resolveHyperliquidErrorDetail(error) {
2096
+ if (error instanceof HyperliquidApiError) {
2097
+ return error.response ?? null;
2098
+ }
2099
+ if (error && typeof error === "object" && "response" in error) {
2100
+ return error.response ?? null;
2101
+ }
2102
+ return null;
2103
+ }
2104
+
2105
+ // src/adapters/hyperliquid/state-readers.ts
2106
+ function unwrapData(payload) {
2107
+ if (!payload || typeof payload !== "object") return null;
2108
+ if ("data" in payload) {
2109
+ const data = payload.data;
2110
+ if (data && typeof data === "object") {
2111
+ return data;
2112
+ }
2113
+ }
2114
+ return payload;
2115
+ }
2116
+ function readHyperliquidNumber(value) {
2117
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2118
+ if (typeof value === "string" && value.trim().length > 0) {
2119
+ const parsed = Number(value);
2120
+ return Number.isFinite(parsed) ? parsed : null;
2121
+ }
2122
+ return null;
2123
+ }
2124
+ function readHyperliquidAccountValue(payload) {
2125
+ const data = unwrapData(payload);
2126
+ if (!data) return null;
2127
+ const candidates = [
2128
+ data?.marginSummary?.accountValue,
2129
+ data?.crossMarginSummary?.accountValue,
2130
+ data?.accountValue,
2131
+ data?.equity,
2132
+ data?.totalAccountValue,
2133
+ data?.marginSummary?.totalAccountValue
2134
+ ];
2135
+ for (const value of candidates) {
2136
+ const parsed = readHyperliquidNumber(value);
2137
+ if (parsed !== null) return parsed;
2138
+ }
2139
+ return null;
2140
+ }
2141
+ function matchPerpCoin(params) {
2142
+ const coin = params.coin.toUpperCase();
2143
+ const target = params.target.toUpperCase();
2144
+ if (params.prefixMatch) return coin.startsWith(target);
2145
+ return coin === target;
2146
+ }
2147
+ function readHyperliquidPerpPositionSize(payload, symbol, options) {
2148
+ const data = unwrapData(payload);
2149
+ const rows = Array.isArray(data?.assetPositions) ? data.assetPositions : [];
2150
+ const base = symbol.split("-")[0]?.toUpperCase() ?? symbol.toUpperCase();
2151
+ const prefixMatch = options?.prefixMatch ?? false;
2152
+ for (const row of rows) {
2153
+ const position = row.position ?? row;
2154
+ const coin = typeof position?.coin === "string" ? position.coin : typeof row.coin === "string" ? row.coin : "";
2155
+ if (!matchPerpCoin({ coin, target: base, prefixMatch })) continue;
2156
+ const size = position.szi ?? row.szi;
2157
+ const parsed = readHyperliquidNumber(size);
2158
+ return parsed ?? 0;
2159
+ }
2160
+ return 0;
2161
+ }
2162
+ function readHyperliquidPerpPosition(payload, symbol, options) {
2163
+ const data = unwrapData(payload);
2164
+ const rows = Array.isArray(data?.assetPositions) ? data.assetPositions : [];
2165
+ const target = symbol.split("-")[0]?.toUpperCase() ?? symbol.toUpperCase();
2166
+ const prefixMatch = options?.prefixMatch ?? false;
2167
+ for (const row of rows) {
2168
+ const position = row?.position ?? row;
2169
+ const coin = typeof position?.coin === "string" ? position.coin : typeof row?.coin === "string" ? row.coin : "";
2170
+ if (!matchPerpCoin({ coin, target, prefixMatch })) continue;
2171
+ const size = readHyperliquidNumber(position?.szi ?? row.szi) ?? 0;
2172
+ const positionValue = Math.abs(
2173
+ readHyperliquidNumber(position?.positionValue ?? row.positionValue) ?? 0
2174
+ );
2175
+ const unrealizedPnl = readHyperliquidNumber(
2176
+ position?.unrealizedPnl ?? row.unrealizedPnl
2177
+ );
2178
+ return { size, positionValue, unrealizedPnl };
2179
+ }
2180
+ return { size: 0, positionValue: 0, unrealizedPnl: null };
2181
+ }
2182
+ function readHyperliquidSpotBalanceSize(payload, symbol) {
2183
+ const data = unwrapData(payload);
2184
+ const rows = Array.isArray(data?.balances) ? data.balances : [];
2185
+ const base = symbol.split("/")[0]?.split("-")[0]?.toUpperCase() ?? symbol.toUpperCase();
2186
+ for (const row of rows) {
2187
+ const coin = typeof row?.coin === "string" ? row.coin : typeof row?.asset === "string" ? row.asset : "";
2188
+ if (coin.toUpperCase() !== base) continue;
2189
+ const total = row.total ?? row.balance ?? row.szi;
2190
+ const parsed = readHyperliquidNumber(total);
2191
+ return parsed ?? 0;
2192
+ }
2193
+ return 0;
2194
+ }
2195
+ function readHyperliquidSpotBalance(payload, base) {
2196
+ const data = unwrapData(payload);
2197
+ const balances = Array.isArray(data?.balances) ? data.balances : [];
2198
+ const target = base.toUpperCase();
2199
+ for (const row of balances) {
2200
+ const coin = typeof row?.coin === "string" ? row.coin : "";
2201
+ if (coin.toUpperCase() !== target) continue;
2202
+ const total = readHyperliquidNumber(row?.total) ?? 0;
2203
+ const entryNtl = readHyperliquidNumber(row?.entryNtl);
2204
+ return { total, entryNtl };
2205
+ }
2206
+ return { total: 0, entryNtl: null };
2207
+ }
2208
+ function readHyperliquidSpotAccountValue(params) {
2209
+ const rows = Array.isArray(params.balances) ? params.balances : [];
2210
+ if (rows.length === 0) return null;
2211
+ let total = 0;
2212
+ let hasValue = false;
2213
+ for (const row of rows) {
2214
+ const coin = typeof row?.coin === "string" ? row.coin : typeof row?.asset === "string" ? row.asset : "";
2215
+ if (!coin) continue;
2216
+ const amount = readHyperliquidNumber(
2217
+ row.total ?? row.balance ?? row.szi
2218
+ );
2219
+ if (amount == null || amount === 0) continue;
2220
+ const price = params.pricesUsd.get(coin.toUpperCase());
2221
+ if (price == null || !Number.isFinite(price) || price <= 0) continue;
2222
+ total += amount * price;
2223
+ hasValue = true;
2224
+ }
2225
+ return hasValue ? total : null;
2226
+ }
2227
+
2228
+ // src/adapters/hyperliquid/market-data.ts
2229
+ var META_CACHE_TTL_MS = 5 * 60 * 1e3;
2230
+ var allMidsCache = /* @__PURE__ */ new Map();
2231
+ function gcd(a, b) {
2232
+ let left = a < 0n ? -a : a;
2233
+ let right = b < 0n ? -b : b;
2234
+ while (right !== 0n) {
2235
+ const next = left % right;
2236
+ left = right;
2237
+ right = next;
2238
+ }
2239
+ return left;
2240
+ }
2241
+ function pow10(decimals) {
2242
+ let result = 1n;
2243
+ for (let i = 0; i < decimals; i += 1) {
2244
+ result *= 10n;
2245
+ }
2246
+ return result;
2247
+ }
2248
+ function maxDecimals(values) {
2249
+ let max = 0;
2250
+ for (const value of values) {
2251
+ const dot = value.indexOf(".");
2252
+ if (dot === -1) continue;
2253
+ const decimals = value.length - dot - 1;
2254
+ if (decimals > max) max = decimals;
2255
+ }
2256
+ return max;
2257
+ }
2258
+ function toScaledInt(value, decimals) {
2259
+ const trimmed = value.trim();
2260
+ const negative = trimmed.startsWith("-");
2261
+ const unsigned = negative ? trimmed.slice(1) : trimmed;
2262
+ const [intPart, fracPart = ""] = unsigned.split(".");
2263
+ const padded = fracPart.padEnd(decimals, "0").slice(0, decimals);
2264
+ const combined = `${intPart || "0"}${padded}`;
2265
+ const asInt = BigInt(combined || "0");
2266
+ return negative ? -asInt : asInt;
2267
+ }
2268
+ function formatScaledInt(value, decimals) {
2269
+ const negative = value < 0n;
2270
+ const absValue = negative ? -value : value;
2271
+ const scale = pow10(decimals);
2272
+ const integer = absValue / scale;
2273
+ const fraction = absValue % scale;
2274
+ if (decimals === 0) {
2275
+ return `${negative ? "-" : ""}${integer.toString()}`;
2276
+ }
2277
+ const fractionStr = fraction.toString().padStart(decimals, "0");
2278
+ return `${negative ? "-" : ""}${integer.toString()}.${fractionStr}`.replace(
2279
+ /\.?0+$/,
2280
+ ""
2281
+ );
2282
+ }
2283
+ function resolveSpotSizeDecimals(meta, symbol) {
2284
+ const universe = meta.universe ?? [];
2285
+ const tokens = meta.tokens ?? [];
2286
+ if (!universe.length || !tokens.length) {
2287
+ throw new Error(`Spot metadata unavailable for ${symbol}.`);
2288
+ }
2289
+ const tokenMap = /* @__PURE__ */ new Map();
2290
+ for (const token of tokens) {
2291
+ const index = token?.index;
2292
+ const szDecimals = typeof token?.szDecimals === "number" ? token.szDecimals : null;
2293
+ if (typeof index !== "number" || szDecimals == null) continue;
2294
+ tokenMap.set(index, {
2295
+ name: normalizeSpotTokenName2(token?.name),
2296
+ szDecimals
2297
+ });
2298
+ }
2299
+ if (symbol.startsWith("@")) {
2300
+ const targetIndex = Number.parseInt(symbol.slice(1), 10);
2301
+ if (!Number.isFinite(targetIndex)) {
2302
+ throw new Error(`Invalid spot pair id: ${symbol}`);
2303
+ }
2304
+ for (let idx = 0; idx < universe.length; idx += 1) {
2305
+ const market = universe[idx];
2306
+ const marketIndex = typeof market?.index === "number" ? market.index : idx;
2307
+ if (marketIndex !== targetIndex) continue;
2308
+ const [baseIndex] = Array.isArray(market?.tokens) ? market.tokens : [];
2309
+ const baseToken = tokenMap.get(baseIndex ?? -1);
2310
+ if (!baseToken) break;
2311
+ return baseToken.szDecimals;
2312
+ }
2313
+ throw new Error(`Unknown spot pair id: ${symbol}`);
2314
+ }
2315
+ const pair = parseSpotPairSymbol(symbol);
2316
+ if (!pair) {
2317
+ throw new Error(`Invalid spot symbol: ${symbol}`);
2318
+ }
2319
+ const normalizedBase = normalizeSpotTokenName2(pair.base).toUpperCase();
2320
+ const normalizedQuote = normalizeSpotTokenName2(pair.quote).toUpperCase();
2321
+ for (const market of universe) {
2322
+ const [baseIndex, quoteIndex] = Array.isArray(market?.tokens) ? market.tokens : [];
2323
+ const baseToken = tokenMap.get(baseIndex ?? -1);
2324
+ const quoteToken = tokenMap.get(quoteIndex ?? -1);
2325
+ if (!baseToken || !quoteToken) continue;
2326
+ if (baseToken.name.toUpperCase() === normalizedBase && quoteToken.name.toUpperCase() === normalizedQuote) {
2327
+ return baseToken.szDecimals;
2328
+ }
2329
+ }
2330
+ throw new Error(`No size decimals found for ${symbol}.`);
2331
+ }
2332
+ async function fetchHyperliquidAllMids(environment) {
2333
+ const cacheKey = environment;
2334
+ const cached = allMidsCache.get(cacheKey);
2335
+ if (cached && Date.now() - cached.fetchedAt < META_CACHE_TTL_MS) {
2336
+ return cached.mids;
2337
+ }
2338
+ const baseUrl = API_BASES[environment];
2339
+ const res = await fetch(`${baseUrl}/info`, {
2340
+ method: "POST",
2341
+ headers: { "content-type": "application/json" },
2342
+ body: JSON.stringify({ type: "allMids" })
2343
+ });
2344
+ const json = await res.json().catch(() => null);
2345
+ if (!res.ok || !json || typeof json !== "object") {
2346
+ throw new Error(`Failed to load Hyperliquid mid prices (${res.status}).`);
2347
+ }
2348
+ allMidsCache.set(cacheKey, { fetchedAt: Date.now(), mids: json });
1662
2349
  return json;
1663
2350
  }
2351
+ async function fetchHyperliquidTickSize(params) {
2352
+ return fetchHyperliquidTickSizeForCoin(params.environment, params.symbol);
2353
+ }
2354
+ async function fetchHyperliquidSpotTickSize(params) {
2355
+ if (!Number.isFinite(params.marketIndex)) {
2356
+ throw new Error("Hyperliquid spot market index is invalid.");
2357
+ }
2358
+ return fetchHyperliquidTickSizeForCoin(
2359
+ params.environment,
2360
+ `@${params.marketIndex}`
2361
+ );
2362
+ }
2363
+ async function fetchHyperliquidTickSizeForCoin(environment, coin) {
2364
+ const base = API_BASES[environment];
2365
+ const res = await fetch(`${base}/info`, {
2366
+ method: "POST",
2367
+ headers: { "content-type": "application/json" },
2368
+ body: JSON.stringify({ type: "l2Book", coin })
2369
+ });
2370
+ if (!res.ok) {
2371
+ throw new Error(`Hyperliquid l2Book failed for ${coin}`);
2372
+ }
2373
+ const data = await res.json().catch(() => null);
2374
+ const levels = Array.isArray(data?.levels) ? data?.levels ?? [] : [];
2375
+ const prices = levels.flatMap(
2376
+ (side) => Array.isArray(side) ? side.map((entry) => String(entry?.px ?? "")) : []
2377
+ ).filter((px) => px.length > 0);
2378
+ if (prices.length < 2) {
2379
+ throw new Error(`Hyperliquid l2Book missing price levels for ${coin}`);
2380
+ }
2381
+ const decimals = maxDecimals(prices);
2382
+ const scaled = prices.map((px) => toScaledInt(px, decimals));
2383
+ const unique = Array.from(new Set(scaled.map((v) => v.toString()))).map((v) => BigInt(v)).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
2384
+ let tick = 0n;
2385
+ for (let i = 1; i < unique.length; i += 1) {
2386
+ const diff = unique[i] - unique[i - 1];
2387
+ if (diff <= 0n) continue;
2388
+ tick = tick === 0n ? diff : gcd(tick, diff);
2389
+ }
2390
+ if (tick === 0n) {
2391
+ tick = 1n;
2392
+ }
2393
+ return { tickSizeInt: tick, tickDecimals: decimals };
2394
+ }
2395
+ async function fetchHyperliquidPerpMarketInfo(params) {
2396
+ const data = await fetchHyperliquidMetaAndAssetCtxs(params.environment);
2397
+ const universe = data?.[0]?.universe ?? [];
2398
+ const contexts = data?.[1] ?? [];
2399
+ const target = normalizeHyperliquidMetaSymbol(params.symbol).toUpperCase();
2400
+ const idx = universe.findIndex(
2401
+ (entry) => normalizeHyperliquidMetaSymbol(entry?.name ?? "").toUpperCase() === target
2402
+ );
2403
+ if (idx < 0) {
2404
+ throw new Error(`Unknown Hyperliquid perp asset: ${params.symbol}`);
2405
+ }
2406
+ const ctx = contexts[idx] ?? null;
2407
+ const price = readHyperliquidNumber(ctx?.markPx ?? ctx?.midPx ?? ctx?.oraclePx);
2408
+ if (!price || price <= 0) {
2409
+ throw new Error(`No perp price available for ${params.symbol}`);
2410
+ }
2411
+ const fundingRate = readHyperliquidNumber(ctx?.funding);
2412
+ const szDecimals = readHyperliquidNumber(universe[idx]?.szDecimals);
2413
+ if (szDecimals == null) {
2414
+ throw new Error(`No size decimals available for ${params.symbol}`);
2415
+ }
2416
+ return {
2417
+ symbol: params.symbol,
2418
+ price,
2419
+ fundingRate,
2420
+ szDecimals
2421
+ };
2422
+ }
2423
+ async function fetchHyperliquidSpotMarketInfo(params) {
2424
+ const mids = params.mids === void 0 ? await fetchHyperliquidAllMids(params.environment).catch(() => null) : params.mids;
2425
+ const data = await fetchHyperliquidSpotMetaAndAssetCtxs(params.environment);
2426
+ const universe = data?.[0]?.universe ?? [];
2427
+ const tokens = data?.[0]?.tokens ?? [];
2428
+ const contexts = data?.[1] ?? [];
2429
+ const tokenMap = /* @__PURE__ */ new Map();
2430
+ for (const token of tokens) {
2431
+ const index = token?.index;
2432
+ const szDecimals = readHyperliquidNumber(token?.szDecimals);
2433
+ if (typeof index !== "number" || szDecimals == null) continue;
2434
+ tokenMap.set(index, {
2435
+ name: normalizeSpotTokenName2(token?.name),
2436
+ szDecimals
2437
+ });
2438
+ }
2439
+ const baseCandidates = resolveSpotTokenCandidates(params.base);
2440
+ const quoteCandidates = resolveSpotTokenCandidates(params.quote);
2441
+ const normalizedBase = normalizeSpotTokenName2(params.base).toUpperCase();
2442
+ const normalizedQuote = normalizeSpotTokenName2(params.quote).toUpperCase();
2443
+ for (let idx = 0; idx < universe.length; idx += 1) {
2444
+ const market = universe[idx];
2445
+ const [baseIndex, quoteIndex] = Array.isArray(market?.tokens) ? market.tokens : [];
2446
+ const baseToken = tokenMap.get(baseIndex ?? -1);
2447
+ const quoteToken = tokenMap.get(quoteIndex ?? -1);
2448
+ if (!baseToken || !quoteToken) continue;
2449
+ const marketBaseCandidates = resolveSpotTokenCandidates(baseToken.name);
2450
+ const marketQuoteCandidates = resolveSpotTokenCandidates(quoteToken.name);
2451
+ if (baseCandidates.some((candidate) => marketBaseCandidates.includes(candidate)) && quoteCandidates.some((candidate) => marketQuoteCandidates.includes(candidate))) {
2452
+ const contextIndex = typeof market?.index === "number" ? market.index : idx;
2453
+ const ctx = (contextIndex >= 0 && contextIndex < contexts.length ? contexts[contextIndex] : null) ?? contexts[idx] ?? null;
2454
+ let price = null;
2455
+ if (mids) {
2456
+ for (const candidate of resolveSpotMidCandidates(baseToken.name)) {
2457
+ const mid = readHyperliquidNumber(mids[candidate]);
2458
+ if (mid != null && mid > 0) {
2459
+ price = mid;
2460
+ break;
2461
+ }
2462
+ }
2463
+ }
2464
+ if (!price || price <= 0) {
2465
+ price = readHyperliquidNumber(ctx?.markPx ?? ctx?.midPx ?? ctx?.oraclePx);
2466
+ }
2467
+ if (!price || price <= 0) {
2468
+ throw new Error(
2469
+ `No spot price available for ${normalizedBase}/${normalizedQuote}`
2470
+ );
2471
+ }
2472
+ const marketIndex = typeof market?.index === "number" ? market.index : idx;
2473
+ return {
2474
+ symbol: `${baseToken.name.toUpperCase()}/${quoteToken.name.toUpperCase()}`,
2475
+ base: baseToken.name.toUpperCase(),
2476
+ quote: quoteToken.name.toUpperCase(),
2477
+ assetId: 1e4 + marketIndex,
2478
+ marketIndex,
2479
+ price,
2480
+ szDecimals: baseToken.szDecimals
2481
+ };
2482
+ }
2483
+ }
2484
+ throw new Error(`Unknown Hyperliquid spot market: ${normalizedBase}/${normalizedQuote}`);
2485
+ }
2486
+ async function fetchHyperliquidSizeDecimals(params) {
2487
+ const { symbol, environment } = params;
2488
+ if (isHyperliquidSpotSymbol(symbol)) {
2489
+ const meta2 = await fetchHyperliquidSpotMeta(environment);
2490
+ return resolveSpotSizeDecimals(meta2, symbol);
2491
+ }
2492
+ const meta = await fetchHyperliquidMeta(environment);
2493
+ const universe = Array.isArray(meta?.universe) ? meta.universe : [];
2494
+ const normalized = normalizeHyperliquidMetaSymbol(symbol).toUpperCase();
2495
+ const match = universe.find(
2496
+ (entry) => normalizeHyperliquidMetaSymbol(entry?.name ?? "").toUpperCase() === normalized
2497
+ );
2498
+ if (!match || typeof match.szDecimals !== "number") {
2499
+ throw new Error(`No size decimals found for ${symbol}.`);
2500
+ }
2501
+ return match.szDecimals;
2502
+ }
2503
+ function buildHyperliquidSpotUsdPriceMap(params) {
2504
+ const universe = params.meta.universe ?? [];
2505
+ const tokens = params.meta.tokens ?? [];
2506
+ const tokenMap = /* @__PURE__ */ new Map();
2507
+ for (const token of tokens) {
2508
+ const index = token?.index;
2509
+ if (typeof index !== "number") continue;
2510
+ tokenMap.set(index, normalizeSpotTokenName2(token?.name).toUpperCase());
2511
+ }
2512
+ const prices = /* @__PURE__ */ new Map();
2513
+ prices.set("USDC", 1);
2514
+ for (let idx = 0; idx < universe.length; idx += 1) {
2515
+ const market = universe[idx];
2516
+ const [baseIndex, quoteIndex] = Array.isArray(market?.tokens) ? market.tokens : [];
2517
+ const base = tokenMap.get(baseIndex ?? -1);
2518
+ const quote = tokenMap.get(quoteIndex ?? -1);
2519
+ if (!base || !quote) continue;
2520
+ if (quote !== "USDC") continue;
2521
+ const contextIndex = typeof market?.index === "number" ? market.index : idx;
2522
+ const ctx = (contextIndex >= 0 && contextIndex < params.ctxs.length ? params.ctxs[contextIndex] : null) ?? params.ctxs[idx] ?? null;
2523
+ let price = null;
2524
+ if (params.mids) {
2525
+ for (const candidate of resolveSpotMidCandidates(base)) {
2526
+ const mid = readHyperliquidNumber(params.mids[candidate]);
2527
+ if (mid != null && mid > 0) {
2528
+ price = mid;
2529
+ break;
2530
+ }
2531
+ }
2532
+ }
2533
+ if (!price || price <= 0) {
2534
+ price = readHyperliquidNumber(ctx?.markPx ?? ctx?.midPx ?? ctx?.oraclePx);
2535
+ }
2536
+ if (!price || price <= 0) continue;
2537
+ prices.set(base, price);
2538
+ }
2539
+ return prices;
2540
+ }
2541
+ async function fetchHyperliquidSpotUsdPriceMap(environment) {
2542
+ const [spotMetaAndCtxs, mids] = await Promise.all([
2543
+ fetchHyperliquidSpotMetaAndAssetCtxs(environment),
2544
+ fetchHyperliquidAllMids(environment).catch(() => null)
2545
+ ]);
2546
+ const [metaRaw, ctxsRaw] = spotMetaAndCtxs;
2547
+ const meta = {
2548
+ universe: Array.isArray(metaRaw?.universe) ? metaRaw.universe : [],
2549
+ tokens: Array.isArray(metaRaw?.tokens) ? metaRaw.tokens : []
2550
+ };
2551
+ const ctxs = Array.isArray(ctxsRaw) ? ctxsRaw : [];
2552
+ return buildHyperliquidSpotUsdPriceMap({ meta, ctxs, mids });
2553
+ }
2554
+ async function fetchHyperliquidSpotAccountValue(params) {
2555
+ const pricesUsd = await fetchHyperliquidSpotUsdPriceMap(params.environment);
2556
+ return readHyperliquidSpotAccountValue({
2557
+ balances: params.balances,
2558
+ pricesUsd
2559
+ });
2560
+ }
2561
+ var __hyperliquidMarketDataInternals = {
2562
+ maxDecimals,
2563
+ toScaledInt,
2564
+ formatScaledInt
2565
+ };
1664
2566
 
1665
2567
  // src/adapters/hyperliquid/index.ts
2568
+ function assertPositiveDecimalInput(value, label) {
2569
+ if (typeof value === "number") {
2570
+ if (!Number.isFinite(value) || value <= 0) {
2571
+ throw new Error(`${label} must be a positive number.`);
2572
+ }
2573
+ return;
2574
+ }
2575
+ if (typeof value === "bigint") {
2576
+ if (value <= 0n) {
2577
+ throw new Error(`${label} must be positive.`);
2578
+ }
2579
+ return;
2580
+ }
2581
+ const trimmed = value.trim();
2582
+ if (!trimmed.length) {
2583
+ throw new Error(`${label} must be a non-empty string.`);
2584
+ }
2585
+ if (!/^(?:\d+\.?\d*|\.\d+)$/.test(trimmed)) {
2586
+ throw new Error(`${label} must be a positive decimal string.`);
2587
+ }
2588
+ const numeric = Number(trimmed);
2589
+ if (!Number.isFinite(numeric) || numeric <= 0) {
2590
+ throw new Error(`${label} must be positive.`);
2591
+ }
2592
+ }
2593
+ function normalizePositiveDecimalString(raw, label) {
2594
+ const trimmed = raw.trim();
2595
+ if (!trimmed.length) {
2596
+ throw new Error(`${label} must be a non-empty decimal string.`);
2597
+ }
2598
+ if (!/^(?:\d+\.?\d*|\.\d+)$/.test(trimmed)) {
2599
+ throw new Error(`${label} must be a positive decimal string.`);
2600
+ }
2601
+ const normalized = trimmed.replace(/^0+(?=\d)/, "").replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "");
2602
+ const numeric = Number(normalized);
2603
+ if (!Number.isFinite(numeric) || numeric <= 0) {
2604
+ throw new Error(`${label} must be positive.`);
2605
+ }
2606
+ return normalized;
2607
+ }
1666
2608
  async function placeHyperliquidOrder(options) {
1667
2609
  const {
1668
2610
  wallet,
@@ -1686,6 +2628,11 @@ async function placeHyperliquidOrder(options) {
1686
2628
  const resolvedBaseUrl = API_BASES[inferredEnvironment];
1687
2629
  const preparedOrders = await Promise.all(
1688
2630
  orders.map(async (intent) => {
2631
+ assertPositiveDecimalInput(intent.price, "price");
2632
+ assertPositiveDecimalInput(intent.size, "size");
2633
+ if (intent.trigger) {
2634
+ assertPositiveDecimalInput(intent.trigger.triggerPx, "triggerPx");
2635
+ }
1689
2636
  const assetIndex = await resolveHyperliquidAssetIndex({
1690
2637
  symbol: intent.symbol,
1691
2638
  baseUrl: resolvedBaseUrl,
@@ -1711,7 +2658,7 @@ async function placeHyperliquidOrder(options) {
1711
2658
  r: intent.reduceOnly ?? false,
1712
2659
  t: limitOrTrigger,
1713
2660
  ...intent.clientId ? {
1714
- c: normalizeHex(intent.clientId)
2661
+ c: normalizeCloid(intent.clientId)
1715
2662
  } : {}
1716
2663
  };
1717
2664
  return order;
@@ -1780,7 +2727,9 @@ async function placeHyperliquidOrder(options) {
1780
2727
  }
1781
2728
  const statuses = json.response?.data?.statuses ?? [];
1782
2729
  const errorStatuses = statuses.filter(
1783
- (entry) => "error" in entry
2730
+ (entry) => Boolean(
2731
+ entry && typeof entry === "object" && "error" in entry && typeof entry.error === "string"
2732
+ )
1784
2733
  );
1785
2734
  if (errorStatuses.length) {
1786
2735
  const message = errorStatuses.map((entry) => entry.error).join(", ");
@@ -1834,10 +2783,11 @@ async function depositToHyperliquidBridge(options) {
1834
2783
  }
1835
2784
  async function withdrawFromHyperliquid(options) {
1836
2785
  const { environment, amount, destination, wallet } = options;
1837
- const parsedAmount = Number(amount);
1838
- if (!Number.isFinite(parsedAmount) || parsedAmount <= 0) {
1839
- throw new Error("Withdraw amount must be a positive number.");
1840
- }
2786
+ const normalizedAmount = normalizePositiveDecimalString(
2787
+ amount,
2788
+ "Withdraw amount"
2789
+ );
2790
+ const parsedAmount = Number.parseFloat(normalizedAmount);
1841
2791
  if (!wallet.account || !wallet.walletClient || !wallet.publicClient) {
1842
2792
  throw new Error(
1843
2793
  "Wallet client and public client are required for withdraw."
@@ -1857,7 +2807,7 @@ async function withdrawFromHyperliquid(options) {
1857
2807
  const message = {
1858
2808
  hyperliquidChain,
1859
2809
  destination: normalizedDestination,
1860
- amount: parsedAmount.toString(),
2810
+ amount: normalizedAmount,
1861
2811
  time
1862
2812
  };
1863
2813
  const types = {
@@ -1882,7 +2832,7 @@ async function withdrawFromHyperliquid(options) {
1882
2832
  signatureChainId,
1883
2833
  hyperliquidChain,
1884
2834
  destination: normalizedDestination,
1885
- amount: parsedAmount.toString(),
2835
+ amount: normalizedAmount,
1886
2836
  time: nonce
1887
2837
  },
1888
2838
  nonce,
@@ -2052,6 +3002,6 @@ var __hyperliquidInternals = {
2052
3002
  splitSignature
2053
3003
  };
2054
3004
 
2055
- export { DEFAULT_HYPERLIQUID_MARKET_SLIPPAGE_BPS, HyperliquidApiError, HyperliquidBuilderApprovalError, HyperliquidExchangeClient, HyperliquidGuardError, HyperliquidInfoClient, HyperliquidTermsError, __hyperliquidInternals, approveHyperliquidBuilderFee, batchModifyHyperliquidOrders, buildHyperliquidMarketIdentity, cancelAllHyperliquidOrders, cancelHyperliquidOrders, cancelHyperliquidOrdersByCloid, cancelHyperliquidTwapOrder, computeHyperliquidMarketIocLimitPrice, createHyperliquidSubAccount, createMonotonicNonceFactory, depositToHyperliquidBridge, fetchHyperliquidAssetCtxs, fetchHyperliquidClearinghouseState, fetchHyperliquidFrontendOpenOrders, fetchHyperliquidHistoricalOrders, fetchHyperliquidMeta, fetchHyperliquidMetaAndAssetCtxs, fetchHyperliquidOpenOrders, fetchHyperliquidOrderStatus, fetchHyperliquidPreTransferCheck, fetchHyperliquidSpotAssetCtxs, fetchHyperliquidSpotClearinghouseState, fetchHyperliquidSpotMeta, fetchHyperliquidSpotMetaAndAssetCtxs, fetchHyperliquidUserFills, fetchHyperliquidUserFillsByTime, fetchHyperliquidUserRateLimit, getHyperliquidMaxBuilderFee, modifyHyperliquidOrder, placeHyperliquidOrder, placeHyperliquidTwapOrder, recordHyperliquidBuilderApproval, recordHyperliquidTermsAcceptance, reserveHyperliquidRequestWeight, resolveHyperliquidAbstractionFromMode, scheduleHyperliquidCancel, sendHyperliquidSpot, setHyperliquidAccountAbstractionMode, setHyperliquidDexAbstraction, setHyperliquidPortfolioMargin, transferHyperliquidSubAccount, updateHyperliquidIsolatedMargin, updateHyperliquidLeverage, withdrawFromHyperliquid };
3005
+ export { DEFAULT_HYPERLIQUID_MARKET_SLIPPAGE_BPS, HyperliquidApiError, HyperliquidBuilderApprovalError, HyperliquidExchangeClient, HyperliquidGuardError, HyperliquidInfoClient, HyperliquidTermsError, __hyperliquidInternals, __hyperliquidMarketDataInternals, approveHyperliquidBuilderFee, batchModifyHyperliquidOrders, buildHyperliquidMarketIdentity, buildHyperliquidProfileAssets, buildHyperliquidSpotUsdPriceMap, cancelAllHyperliquidOrders, cancelHyperliquidOrders, cancelHyperliquidOrdersByCloid, cancelHyperliquidTwapOrder, computeHyperliquidMarketIocLimitPrice, createHyperliquidSubAccount, createMonotonicNonceFactory, depositToHyperliquidBridge, extractHyperliquidDex, extractHyperliquidOrderIds, fetchHyperliquidAllMids, fetchHyperliquidAssetCtxs, fetchHyperliquidClearinghouseState, fetchHyperliquidFrontendOpenOrders, fetchHyperliquidHistoricalOrders, fetchHyperliquidMeta, fetchHyperliquidMetaAndAssetCtxs, fetchHyperliquidOpenOrders, fetchHyperliquidOrderStatus, fetchHyperliquidPerpMarketInfo, fetchHyperliquidPreTransferCheck, fetchHyperliquidSizeDecimals, fetchHyperliquidSpotAccountValue, fetchHyperliquidSpotAssetCtxs, fetchHyperliquidSpotClearinghouseState, fetchHyperliquidSpotMarketInfo, fetchHyperliquidSpotMeta, fetchHyperliquidSpotMetaAndAssetCtxs, fetchHyperliquidSpotTickSize, fetchHyperliquidSpotUsdPriceMap, fetchHyperliquidTickSize, fetchHyperliquidUserFills, fetchHyperliquidUserFillsByTime, fetchHyperliquidUserRateLimit, formatHyperliquidMarketablePrice, formatHyperliquidOrderSize, formatHyperliquidPrice, formatHyperliquidSize, getHyperliquidMaxBuilderFee, isHyperliquidSpotSymbol, modifyHyperliquidOrder, normalizeHyperliquidBaseSymbol, normalizeHyperliquidMetaSymbol, normalizeSpotTokenName2 as normalizeSpotTokenName, parseSpotPairSymbol, placeHyperliquidOrder, placeHyperliquidTwapOrder, readHyperliquidAccountValue, readHyperliquidNumber, readHyperliquidPerpPosition, readHyperliquidPerpPositionSize, readHyperliquidSpotAccountValue, readHyperliquidSpotBalance, readHyperliquidSpotBalanceSize, recordHyperliquidBuilderApproval, recordHyperliquidTermsAcceptance, reserveHyperliquidRequestWeight, resolveHyperliquidAbstractionFromMode, resolveHyperliquidChain, resolveHyperliquidChainConfig, resolveHyperliquidErrorDetail, resolveHyperliquidOrderRef, resolveHyperliquidOrderSymbol, resolveHyperliquidPair, resolveHyperliquidProfileChain, resolveHyperliquidRpcEnvVar, resolveHyperliquidStoreNetwork, resolveHyperliquidSymbol, resolveSpotMidCandidates, resolveSpotTokenCandidates, roundHyperliquidPriceToTick, scheduleHyperliquidCancel, sendHyperliquidSpot, setHyperliquidAccountAbstractionMode, setHyperliquidDexAbstraction, setHyperliquidPortfolioMargin, transferHyperliquidSubAccount, updateHyperliquidIsolatedMargin, updateHyperliquidLeverage, withdrawFromHyperliquid };
2056
3006
  //# sourceMappingURL=index.js.map
2057
3007
  //# sourceMappingURL=index.js.map