@perpbrain/sdk 0.0.0-stage → 0.1.0

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.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +16 -2
  3. package/dist/cjs/card.d.ts +2 -0
  4. package/dist/cjs/card.js +311 -0
  5. package/dist/cjs/cli.d.ts +3 -0
  6. package/dist/cjs/cli.js +33 -0
  7. package/dist/cjs/guarded.d.ts +12 -0
  8. package/dist/cjs/guarded.js +52 -0
  9. package/dist/cjs/guards.d.ts +154 -0
  10. package/dist/cjs/guards.js +855 -0
  11. package/dist/cjs/index.d.ts +15 -0
  12. package/dist/cjs/index.js +56 -0
  13. package/dist/cjs/package.json +1 -0
  14. package/dist/cjs/receipt.d.ts +13 -0
  15. package/dist/cjs/receipt.js +660 -0
  16. package/dist/cjs/study.d.ts +29 -0
  17. package/dist/cjs/study.js +259 -0
  18. package/dist/cjs/vendor/costs.d.ts +64 -0
  19. package/dist/cjs/vendor/costs.js +247 -0
  20. package/dist/cjs/vendor/execution.d.ts +44 -0
  21. package/dist/cjs/vendor/execution.js +132 -0
  22. package/dist/cjs/vendor/fees.d.ts +17 -0
  23. package/dist/cjs/vendor/fees.js +82 -0
  24. package/dist/cjs/vendor/funding_adapter.d.ts +11 -0
  25. package/dist/cjs/vendor/funding_adapter.js +33 -0
  26. package/dist/cjs/vendor/info.d.ts +24 -0
  27. package/dist/cjs/vendor/info.js +55 -0
  28. package/dist/cjs/vendor/queries.d.ts +69 -0
  29. package/dist/cjs/vendor/queries.js +210 -0
  30. package/dist/cjs/vendor/rateLimit.d.ts +14 -0
  31. package/dist/cjs/vendor/rateLimit.js +57 -0
  32. package/dist/cjs/vendor/simDefaults.d.ts +31 -0
  33. package/dist/cjs/vendor/simDefaults.js +49 -0
  34. package/dist/cjs/vendor/simulate.d.ts +130 -0
  35. package/dist/cjs/vendor/simulate.js +610 -0
  36. package/dist/esm/card.d.ts +2 -0
  37. package/dist/esm/card.js +308 -0
  38. package/dist/esm/cli.d.ts +3 -0
  39. package/dist/esm/cli.js +31 -0
  40. package/dist/esm/guarded.d.ts +12 -0
  41. package/dist/esm/guarded.js +49 -0
  42. package/dist/esm/guards.d.ts +154 -0
  43. package/dist/esm/guards.js +841 -0
  44. package/dist/esm/index.d.ts +15 -0
  45. package/dist/esm/index.js +20 -0
  46. package/dist/esm/receipt.d.ts +13 -0
  47. package/dist/esm/receipt.js +653 -0
  48. package/dist/esm/study.d.ts +29 -0
  49. package/dist/esm/study.js +249 -0
  50. package/dist/esm/vendor/costs.d.ts +64 -0
  51. package/dist/esm/vendor/costs.js +240 -0
  52. package/dist/esm/vendor/execution.d.ts +44 -0
  53. package/dist/esm/vendor/execution.js +122 -0
  54. package/dist/esm/vendor/fees.d.ts +17 -0
  55. package/dist/esm/vendor/fees.js +74 -0
  56. package/dist/esm/vendor/funding_adapter.d.ts +11 -0
  57. package/dist/esm/vendor/funding_adapter.js +30 -0
  58. package/dist/esm/vendor/info.d.ts +24 -0
  59. package/dist/esm/vendor/info.js +49 -0
  60. package/dist/esm/vendor/queries.d.ts +69 -0
  61. package/dist/esm/vendor/queries.js +196 -0
  62. package/dist/esm/vendor/rateLimit.d.ts +14 -0
  63. package/dist/esm/vendor/rateLimit.js +53 -0
  64. package/dist/esm/vendor/simDefaults.d.ts +31 -0
  65. package/dist/esm/vendor/simDefaults.js +44 -0
  66. package/dist/esm/vendor/simulate.d.ts +130 -0
  67. package/dist/esm/vendor/simulate.js +605 -0
  68. package/package.json +64 -4
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ /** Execution assumptions for book-based fills (slippage floors and book metadata). */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.NON_HISTORICAL_BOOK_LABEL = exports.DEFAULT_MIN_TAKER_SLIPPAGE_BPS = exports.DEFAULT_MIN_STOP_SLIPPAGE_BPS = void 0;
5
+ exports.normalizedExecution = normalizedExecution;
6
+ exports.minStopBps = minStopBps;
7
+ exports.minTakerBps = minTakerBps;
8
+ exports.volatilityScale = volatilityScale;
9
+ exports.bookLabels = bookLabels;
10
+ exports.checkBookTime = checkBookTime;
11
+ exports.applySlippageFloor = applySlippageFloor;
12
+ const fees_ts_1 = require("./fees.js");
13
+ exports.DEFAULT_MIN_STOP_SLIPPAGE_BPS = "10";
14
+ exports.DEFAULT_MIN_TAKER_SLIPPAGE_BPS = "0";
15
+ exports.NON_HISTORICAL_BOOK_LABEL = "non_historical_book";
16
+ function normalizedExecution(config) {
17
+ return config === null || config === undefined ? {} : { ...config };
18
+ }
19
+ /** Stop slippage floor in bps. "0" disables it; the default is version-pinned. */
20
+ function minStopBps(config, fallback = exports.DEFAULT_MIN_STOP_SLIPPAGE_BPS) {
21
+ const value = config.minStopSlippageBps ?? fallback;
22
+ if ((0, fees_ts_1.parseDecimal)(value) < 0n) {
23
+ throw new Error("min_stop_slippage_bps must be non-negative");
24
+ }
25
+ return value;
26
+ }
27
+ function minTakerBps(config) {
28
+ // Issue 3: the same validation as Python (_non_negative_bps).
29
+ return nonNegative(config.minTakerSlippageBps ?? exports.DEFAULT_MIN_TAKER_SLIPPAGE_BPS, "min_taker_slippage_bps");
30
+ }
31
+ function volatilityScale(config) {
32
+ const value = config.volatilitySlippageScale;
33
+ return value === undefined ? null : nonNegative(value, "volatility_slippage_scale");
34
+ }
35
+ function nonNegative(value, label) {
36
+ if (decimal(value, label) < 0n) {
37
+ throw new Error(`${label} must be non-negative`);
38
+ }
39
+ return value;
40
+ }
41
+ function bookLabels(book) {
42
+ if (book.historical === false) {
43
+ return [exports.NON_HISTORICAL_BOOK_LABEL];
44
+ }
45
+ return [];
46
+ }
47
+ function checkBookTime(book, bar, config, warnings) {
48
+ const barTime = bar.timeMs;
49
+ const bookTime = book.timeMs;
50
+ if (barTime === undefined || bookTime === undefined) {
51
+ return;
52
+ }
53
+ if (barTime === bookTime) {
54
+ return;
55
+ }
56
+ const message = `book time_ms ${bookTime} does not match bar time_ms ${barTime}`;
57
+ const mode = config.bookTimeMismatch ?? "warn";
58
+ if (mode === "fail") {
59
+ throw new Error(message);
60
+ }
61
+ if (mode !== "warn") {
62
+ throw new Error("book_time_mismatch must be warn or fail");
63
+ }
64
+ warnings.push(message);
65
+ }
66
+ function applySlippageFloor(side, anchor, legs, minBps, bar, volScale) {
67
+ const min = (0, fees_ts_1.parseDecimal)(minBps);
68
+ if (min <= 0n) {
69
+ return legs;
70
+ }
71
+ let filled = 0n;
72
+ let notional = 0n;
73
+ const scale = 10n ** 18n;
74
+ for (const leg of legs) {
75
+ filled += leg.qty;
76
+ notional += (leg.qty * leg.px) / scale;
77
+ }
78
+ if (filled <= 0n || notional <= 0n) {
79
+ return legs;
80
+ }
81
+ const bps = scaledBps(min, bar, volScale);
82
+ const minimum = (notional * bps) / (10000n * scale);
83
+ const current = slippageTotal(side, anchor, legs);
84
+ if (current >= minimum) {
85
+ return legs;
86
+ }
87
+ const shortfall = minimum - current;
88
+ const delta = (shortfall * scale) / filled;
89
+ return legs.map((leg) => ({
90
+ qty: leg.qty,
91
+ px: side === "buy" ? leg.px + delta : leg.px - delta,
92
+ }));
93
+ }
94
+ function scaledBps(minBps, bar, volScale) {
95
+ if (volScale === null || bar === null) {
96
+ return minBps;
97
+ }
98
+ const scale = (0, fees_ts_1.parseDecimal)(volScale);
99
+ if (scale <= 0n) {
100
+ return minBps;
101
+ }
102
+ const opened = decimal(bar.open, "open");
103
+ const high = decimal(bar.high, "high");
104
+ const low = decimal(bar.low, "low");
105
+ if (opened <= 0n) {
106
+ return minBps;
107
+ }
108
+ // All values are 10^18 fixed point. rangeBps = (high - low) / open * 10000, and
109
+ // factor = 1 + scale * rangeBps / 10000 (Python execution._scaled_bps). The product
110
+ // scale * rangeBps is 10^36 scaled, so divide by 10^18 as well as by 10000.
111
+ const one = 10n ** 18n;
112
+ const rangeBps = ((high - low) * 10000n * one) / opened;
113
+ const factor = one + (scale * rangeBps) / (10000n * one);
114
+ return (minBps * factor) / one;
115
+ }
116
+ function slippageTotal(side, anchor, legs) {
117
+ const scale = 10n ** 18n;
118
+ let total = 0n;
119
+ for (const leg of legs) {
120
+ total +=
121
+ side === "buy" ? ((leg.px - anchor) * leg.qty) / scale : ((anchor - leg.px) * leg.qty) / scale;
122
+ }
123
+ return total;
124
+ }
125
+ function decimal(value, label) {
126
+ try {
127
+ return (0, fees_ts_1.parseDecimal)(value);
128
+ }
129
+ catch {
130
+ throw new Error(`${label} must be a decimal`);
131
+ }
132
+ }
@@ -0,0 +1,17 @@
1
+ /** Versioned perp fee table. Tier-0 base rates from the public fee docs. */
2
+ export declare const DOCS_URL = "https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees";
3
+ export declare const DEFAULT_FEE_VERSION = "hl-perp-tier0-base-2026-10-16";
4
+ export declare const TIER1_FEE_VERSION = "hl-perp-tier1-base-2026-10-16";
5
+ export declare const LEGACY_TIER0_FEE_VERSION = "hl-perp-tier0-base-pre-2025-05-05";
6
+ export declare const HL_FEE_CUTOFF_MS = 1746414000000;
7
+ export interface FeeSchedule {
8
+ version: string;
9
+ takerBps: string;
10
+ makerBps: string;
11
+ docsUrl: string;
12
+ }
13
+ export declare function feeSchedule(version?: string | null): FeeSchedule;
14
+ export declare function feeScheduleAtTime(tradeTimeMs: number): FeeSchedule;
15
+ export declare function parseDecimal(text: string): bigint;
16
+ export declare function formatDecimal(value: bigint): string;
17
+ export declare function feeAmount(notional: bigint, bps: string): bigint;
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ /** Versioned perp fee table. Tier-0 base rates from the public fee docs. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.HL_FEE_CUTOFF_MS = exports.LEGACY_TIER0_FEE_VERSION = exports.TIER1_FEE_VERSION = exports.DEFAULT_FEE_VERSION = exports.DOCS_URL = void 0;
5
+ exports.feeSchedule = feeSchedule;
6
+ exports.feeScheduleAtTime = feeScheduleAtTime;
7
+ exports.parseDecimal = parseDecimal;
8
+ exports.formatDecimal = formatDecimal;
9
+ exports.feeAmount = feeAmount;
10
+ exports.DOCS_URL = "https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees";
11
+ exports.DEFAULT_FEE_VERSION = "hl-perp-tier0-base-2026-10-16";
12
+ exports.TIER1_FEE_VERSION = "hl-perp-tier1-base-2026-10-16";
13
+ exports.LEGACY_TIER0_FEE_VERSION = "hl-perp-tier0-base-pre-2025-05-05";
14
+ exports.HL_FEE_CUTOFF_MS = 1_746_414_000_000;
15
+ const SCHEDULES = [
16
+ {
17
+ version: exports.LEGACY_TIER0_FEE_VERSION,
18
+ takerBps: "3.5",
19
+ makerBps: "1",
20
+ docsUrl: exports.DOCS_URL,
21
+ },
22
+ {
23
+ version: exports.DEFAULT_FEE_VERSION,
24
+ takerBps: "4.5",
25
+ makerBps: "1.5",
26
+ docsUrl: exports.DOCS_URL,
27
+ },
28
+ {
29
+ version: exports.TIER1_FEE_VERSION,
30
+ takerBps: "4",
31
+ makerBps: "1.2",
32
+ docsUrl: exports.DOCS_URL,
33
+ },
34
+ ];
35
+ function feeSchedule(version = null) {
36
+ const chosen = version ?? exports.DEFAULT_FEE_VERSION;
37
+ return scheduleOf(chosen);
38
+ }
39
+ function feeScheduleAtTime(tradeTimeMs) {
40
+ if (!Number.isInteger(tradeTimeMs) || tradeTimeMs < 0) {
41
+ throw new Error("trade_time_ms must be a positive integer");
42
+ }
43
+ if (tradeTimeMs < exports.HL_FEE_CUTOFF_MS) {
44
+ return scheduleOf(exports.LEGACY_TIER0_FEE_VERSION);
45
+ }
46
+ return scheduleOf(exports.DEFAULT_FEE_VERSION);
47
+ }
48
+ function scheduleOf(version) {
49
+ const found = SCHEDULES.find((item) => item.version === version);
50
+ if (found === undefined) {
51
+ throw new Error("unknown fee schedule version");
52
+ }
53
+ return found;
54
+ }
55
+ const SCALE = 18n;
56
+ const SCALE_FACTOR = 10n ** SCALE;
57
+ function parseDecimal(text) {
58
+ if (!/^-?\d+(\.\d+)?$/.test(text)) {
59
+ throw new Error("decimal required");
60
+ }
61
+ const negative = text.startsWith("-");
62
+ const body = negative ? text.slice(1) : text;
63
+ const [whole, frac = ""] = body.split(".");
64
+ if (frac.length > Number(SCALE)) {
65
+ throw new Error("decimal scale exceeded");
66
+ }
67
+ const padded = frac + "0".repeat(Number(SCALE) - frac.length);
68
+ const value = BigInt(whole) * SCALE_FACTOR + BigInt(padded);
69
+ return negative ? -value : value;
70
+ }
71
+ function formatDecimal(value) {
72
+ const negative = value < 0n;
73
+ const abs = negative ? -value : value;
74
+ const whole = abs / SCALE_FACTOR;
75
+ const frac = (abs % SCALE_FACTOR).toString().padStart(Number(SCALE), "0").replace(/0+$/, "");
76
+ const text = frac.length === 0 ? whole.toString() : `${whole.toString()}.${frac}`;
77
+ return negative ? `-${text}` : text;
78
+ }
79
+ function feeAmount(notional, bps) {
80
+ const rate = parseDecimal(bps);
81
+ return (notional * rate) / (SCALE_FACTOR * 10000n);
82
+ }
@@ -0,0 +1,11 @@
1
+ /** Map Hyperliquid fundingHistory rows to simulator FundingSample values. */
2
+ import { type FundingSample } from "./simulate.ts";
3
+ export interface FundingHistoryRow {
4
+ coin?: string;
5
+ fundingRate: string;
6
+ time: number;
7
+ }
8
+ export declare function fundingSamplesFromHistory(rows: FundingHistoryRow[], oracleByGridTime: Record<number, string>, options?: {
9
+ coin?: string;
10
+ fundingIntervalMs?: number;
11
+ }): FundingSample[];
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ /** Map Hyperliquid fundingHistory rows to simulator FundingSample values. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.fundingSamplesFromHistory = fundingSamplesFromHistory;
5
+ const simulate_ts_1 = require("./simulate.js");
6
+ const fees_ts_1 = require("./fees.js");
7
+ function fundingSamplesFromHistory(rows, oracleByGridTime, options = {}) {
8
+ const interval = options.fundingIntervalMs ?? simulate_ts_1.HL_FUNDING_INTERVAL_MS;
9
+ if (!Number.isInteger(interval) || interval <= 0) {
10
+ throw new Error("funding_interval_ms must be a positive integer");
11
+ }
12
+ const samples = [];
13
+ for (const row of rows) {
14
+ if (options.coin !== undefined && row.coin !== options.coin) {
15
+ throw new Error("funding coin does not match the request");
16
+ }
17
+ if (!Number.isInteger(row.time) || row.time < 0) {
18
+ throw new Error("funding time must be a positive integer");
19
+ }
20
+ const grid = (0, simulate_ts_1.fundingGridTime)(row.time, interval);
21
+ const oracle = oracleByGridTime[grid];
22
+ if (oracle === undefined || oracle === "") {
23
+ throw new Error("oracle price missing for funding grid time");
24
+ }
25
+ samples.push({
26
+ timeMs: row.time,
27
+ ratePerHour: (0, fees_ts_1.formatDecimal)((0, fees_ts_1.parseDecimal)(row.fundingRate)),
28
+ oraclePxUsd: oracle,
29
+ });
30
+ }
31
+ samples.sort((left, right) => left.timeMs - right.timeMs);
32
+ return samples;
33
+ }
@@ -0,0 +1,24 @@
1
+ /** Public info endpoint client. POST types are an allowlist. No order endpoint. */
2
+ import { TokenBucket } from "./rateLimit.ts";
3
+ export declare const INFO_URL = "https://api.hyperliquid.xyz/info";
4
+ export declare const READ_TYPES: readonly ["meta", "metaAndAssetCtxs", "l2Book", "candleSnapshot", "clearinghouseState", "userFees", "fundingHistory"];
5
+ export type ReadType = (typeof READ_TYPES)[number];
6
+ export type Transport = (url: string, body: Readonly<Record<string, unknown>>) => unknown;
7
+ export declare function assertInfoUrl(url: string): void;
8
+ export declare class InfoClient {
9
+ readonly limiter: TokenBucket;
10
+ readonly url: string;
11
+ private readonly transport;
12
+ constructor(transport: Transport, limiter?: TokenBucket, url?: string);
13
+ post(body: Readonly<Record<string, unknown>>): unknown;
14
+ }
15
+ export interface FetchLike {
16
+ (url: string, init: {
17
+ method: string;
18
+ headers: Record<string, string>;
19
+ body: string;
20
+ }): Promise<{
21
+ json(): Promise<unknown>;
22
+ }>;
23
+ }
24
+ export declare function fetchInfoTransport(fetchImpl: FetchLike): (url: string, body: Readonly<Record<string, unknown>>) => Promise<unknown>;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ /** Public info endpoint client. POST types are an allowlist. No order endpoint. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.InfoClient = exports.READ_TYPES = exports.INFO_URL = void 0;
5
+ exports.assertInfoUrl = assertInfoUrl;
6
+ exports.fetchInfoTransport = fetchInfoTransport;
7
+ const rateLimit_ts_1 = require("./rateLimit.js");
8
+ exports.INFO_URL = "https://api.hyperliquid.xyz/info";
9
+ exports.READ_TYPES = [
10
+ "meta",
11
+ "metaAndAssetCtxs",
12
+ "l2Book",
13
+ "candleSnapshot",
14
+ "clearinghouseState",
15
+ "userFees",
16
+ "fundingHistory",
17
+ ];
18
+ function assertInfoUrl(url) {
19
+ if (!url.endsWith("/info") || url.includes("/exchange")) {
20
+ throw new Error("info url must be the public /info endpoint");
21
+ }
22
+ }
23
+ function isReadType(value) {
24
+ return exports.READ_TYPES.some((kind) => kind === value);
25
+ }
26
+ class InfoClient {
27
+ limiter;
28
+ url;
29
+ transport;
30
+ constructor(transport, limiter, url = exports.INFO_URL) {
31
+ assertInfoUrl(url);
32
+ this.transport = transport;
33
+ this.limiter = limiter ?? new rateLimit_ts_1.TokenBucket();
34
+ this.url = url;
35
+ }
36
+ post(body) {
37
+ if (!isReadType(body.type)) {
38
+ throw new Error("info type is not allowed");
39
+ }
40
+ assertInfoUrl(this.url);
41
+ this.limiter.acquire();
42
+ return this.transport(this.url, body);
43
+ }
44
+ }
45
+ exports.InfoClient = InfoClient;
46
+ function fetchInfoTransport(fetchImpl) {
47
+ return async (url, body) => {
48
+ const response = await fetchImpl(url, {
49
+ method: "POST",
50
+ headers: { "content-type": "application/json" },
51
+ body: JSON.stringify(body),
52
+ });
53
+ return response.json();
54
+ };
55
+ }
@@ -0,0 +1,69 @@
1
+ /** Read-only info queries. Every result carries data age. No order path. */
2
+ import { InfoClient } from "./info.ts";
3
+ export declare const STALE_AFTER_MS = 20000;
4
+ export declare const MAX_BOOK_LEVELS = 20;
5
+ export interface DataAge {
6
+ ageMs: number;
7
+ stale: boolean;
8
+ asOfMs: number;
9
+ }
10
+ export interface Level {
11
+ px: string;
12
+ sz: string;
13
+ n: number;
14
+ }
15
+ export interface Market {
16
+ name: string;
17
+ szDecimals: number;
18
+ maxLeverage: number;
19
+ }
20
+ export interface MarketsResult extends DataAge {
21
+ markets: Market[];
22
+ }
23
+ export interface BookResult extends DataAge {
24
+ coin: string;
25
+ bids: Level[];
26
+ asks: Level[];
27
+ }
28
+ export interface FundingResult extends DataAge {
29
+ coin: string;
30
+ funding: string;
31
+ openInterest: string;
32
+ markPx: string;
33
+ oraclePx: string;
34
+ midPx: string;
35
+ }
36
+ export interface Position {
37
+ coin: string;
38
+ size: string;
39
+ entryPx: string;
40
+ liquidationPx: string | null;
41
+ unrealizedPnl: string;
42
+ leverageType: string;
43
+ leverageValue: number;
44
+ }
45
+ export interface PositionsResult extends DataAge {
46
+ address: string;
47
+ positions: Position[];
48
+ }
49
+ export interface FeesResult extends DataAge {
50
+ address: string;
51
+ takerRate: string;
52
+ makerRate: string;
53
+ takerBps: string;
54
+ makerBps: string;
55
+ }
56
+ export declare function fractionToBps(fraction: string): string;
57
+ export declare function requireAddress(address: string): string;
58
+ export declare function messageTime(payload: unknown): number | null;
59
+ export declare function makeAge(asOfMs: number, nowMs: number): DataAge;
60
+ export declare function clampDepth(depth: number): number;
61
+ export declare function parseL2Levels(value: unknown, depth: number): {
62
+ bids: Level[];
63
+ asks: Level[];
64
+ };
65
+ export declare function markets(client: InfoClient, nowMs: number, receivedMs?: number): MarketsResult;
66
+ export declare function orderBook(client: InfoClient, coin: string, nowMs: number, depth?: number, receivedMs?: number): BookResult;
67
+ export declare function funding(client: InfoClient, coin: string, nowMs: number, receivedMs?: number): FundingResult;
68
+ export declare function positions(client: InfoClient, address: string, nowMs: number, receivedMs?: number): PositionsResult;
69
+ export declare function fees(client: InfoClient, address: string, nowMs: number, receivedMs?: number): FeesResult;
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ /** Read-only info queries. Every result carries data age. No order path. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.MAX_BOOK_LEVELS = exports.STALE_AFTER_MS = void 0;
5
+ exports.fractionToBps = fractionToBps;
6
+ exports.requireAddress = requireAddress;
7
+ exports.messageTime = messageTime;
8
+ exports.makeAge = makeAge;
9
+ exports.clampDepth = clampDepth;
10
+ exports.parseL2Levels = parseL2Levels;
11
+ exports.markets = markets;
12
+ exports.orderBook = orderBook;
13
+ exports.funding = funding;
14
+ exports.positions = positions;
15
+ exports.fees = fees;
16
+ exports.STALE_AFTER_MS = 20_000;
17
+ exports.MAX_BOOK_LEVELS = 20;
18
+ const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
19
+ function fractionToBps(fraction) {
20
+ if (!/^\d+(\.\d+)?$/.test(fraction)) {
21
+ throw new Error("rate must be a decimal string");
22
+ }
23
+ const [whole, frac = ""] = fraction.split(".");
24
+ const digits = `${whole}${frac}`.replace(/^0+/, "") || "0";
25
+ const shift = 4 - frac.length;
26
+ let text;
27
+ if (shift >= 0) {
28
+ text = digits + "0".repeat(shift);
29
+ }
30
+ else {
31
+ const index = digits.length + shift;
32
+ text = index <= 0 ? `0.${"0".repeat(-index)}${digits}` : `${digits.slice(0, index)}.${digits.slice(index)}`;
33
+ }
34
+ if (!text.includes(".")) {
35
+ return text;
36
+ }
37
+ const trimmed = text.replace(/0+$/, "").replace(/\.$/, "");
38
+ return trimmed === "" ? "0" : trimmed;
39
+ }
40
+ function requireAddress(address) {
41
+ if (!ADDRESS.test(address)) {
42
+ throw new Error("address must be a 0x-prefixed 40 hex character string");
43
+ }
44
+ return address;
45
+ }
46
+ function isRecord(value) {
47
+ return typeof value === "object" && value !== null && !Array.isArray(value);
48
+ }
49
+ function expectRecord(value, label) {
50
+ if (!isRecord(value)) {
51
+ throw new Error(`${label} must be an object`);
52
+ }
53
+ return value;
54
+ }
55
+ function expectList(value, label) {
56
+ if (!Array.isArray(value)) {
57
+ throw new Error(`${label} must be a list`);
58
+ }
59
+ return value;
60
+ }
61
+ function expectString(value, label) {
62
+ if (typeof value !== "string") {
63
+ throw new Error(`${label} must be a string`);
64
+ }
65
+ return value;
66
+ }
67
+ function expectInt(value, label) {
68
+ if (typeof value !== "number" || !Number.isInteger(value)) {
69
+ throw new Error(`${label} must be an integer`);
70
+ }
71
+ return value;
72
+ }
73
+ function messageTime(payload) {
74
+ if (!isRecord(payload)) {
75
+ return null;
76
+ }
77
+ const raw = payload.time;
78
+ if (typeof raw !== "number" || !Number.isInteger(raw)) {
79
+ return null;
80
+ }
81
+ return raw;
82
+ }
83
+ function makeAge(asOfMs, nowMs) {
84
+ const elapsed = Math.max(0, nowMs - asOfMs);
85
+ return { ageMs: elapsed, stale: elapsed >= exports.STALE_AFTER_MS, asOfMs };
86
+ }
87
+ function aged(payload, nowMs, receivedMs) {
88
+ return makeAge(messageTime(payload) ?? receivedMs, nowMs);
89
+ }
90
+ function clampDepth(depth) {
91
+ if (depth < 1) {
92
+ throw new Error("depth must be at least 1");
93
+ }
94
+ return Math.min(depth, exports.MAX_BOOK_LEVELS);
95
+ }
96
+ function parseLevel(value) {
97
+ const body = expectRecord(value, "level");
98
+ return {
99
+ px: expectString(body.px, "px"),
100
+ sz: expectString(body.sz, "sz"),
101
+ n: expectInt(body.n, "n"),
102
+ };
103
+ }
104
+ function parseL2Levels(value, depth) {
105
+ const limit = clampDepth(depth);
106
+ const sides = expectList(value, "levels");
107
+ if (sides.length !== 2) {
108
+ throw new Error("levels must have a bid side and an ask side");
109
+ }
110
+ const bids = expectList(sides[0], "bids").map(parseLevel).slice(0, limit);
111
+ const asks = expectList(sides[1], "asks").map(parseLevel).slice(0, limit);
112
+ return { bids, asks };
113
+ }
114
+ function markets(client, nowMs, receivedMs = nowMs) {
115
+ const payload = expectRecord(client.post({ type: "meta" }), "meta");
116
+ const rows = expectList(payload.universe, "universe").map((item) => {
117
+ const body = expectRecord(item, "market");
118
+ return {
119
+ name: expectString(body.name, "name"),
120
+ szDecimals: expectInt(body.szDecimals, "szDecimals"),
121
+ maxLeverage: expectInt(body.maxLeverage, "maxLeverage"),
122
+ };
123
+ });
124
+ return { markets: rows, ...aged(payload, nowMs, receivedMs) };
125
+ }
126
+ function orderBook(client, coin, nowMs, depth = 20, receivedMs = nowMs) {
127
+ if (coin === "") {
128
+ throw new Error("market is required");
129
+ }
130
+ const payload = expectRecord(client.post({ type: "l2Book", coin }), "l2 book");
131
+ if (payload.coin !== coin) {
132
+ throw new Error("order book coin does not match the request");
133
+ }
134
+ const levels = parseL2Levels(payload.levels, depth);
135
+ return { coin, ...levels, ...aged(payload, nowMs, receivedMs) };
136
+ }
137
+ function funding(client, coin, nowMs, receivedMs = nowMs) {
138
+ if (coin === "") {
139
+ throw new Error("market is required");
140
+ }
141
+ const payload = client.post({ type: "metaAndAssetCtxs" });
142
+ const sides = expectList(payload, "metaAndAssetCtxs");
143
+ if (sides.length !== 2) {
144
+ throw new Error("metaAndAssetCtxs must contain meta and contexts");
145
+ }
146
+ const meta = expectRecord(sides[0], "meta");
147
+ const contexts = expectList(sides[1], "contexts");
148
+ const universe = expectList(meta.universe, "universe");
149
+ const index = universe.findIndex((item) => expectRecord(item, "market").name === coin);
150
+ if (index < 0) {
151
+ throw new Error("coin is not in the universe");
152
+ }
153
+ if (index >= contexts.length) {
154
+ throw new Error("asset context is missing");
155
+ }
156
+ const ctx = expectRecord(contexts[index], "asset context");
157
+ return {
158
+ coin,
159
+ funding: expectString(ctx.funding, "funding"),
160
+ openInterest: expectString(ctx.openInterest, "openInterest"),
161
+ markPx: expectString(ctx.markPx, "markPx"),
162
+ oraclePx: expectString(ctx.oraclePx, "oraclePx"),
163
+ midPx: expectString(ctx.midPx, "midPx"),
164
+ ...aged(payload, nowMs, receivedMs),
165
+ };
166
+ }
167
+ function positions(client, address, nowMs, receivedMs = nowMs) {
168
+ const user = requireAddress(address);
169
+ const payload = expectRecord(client.post({ type: "clearinghouseState", user }), "clearinghouse state");
170
+ const rows = expectList(payload.assetPositions, "assetPositions").map(parsePosition);
171
+ return { address: user, positions: rows, ...aged(payload, nowMs, receivedMs) };
172
+ }
173
+ function fees(client, address, nowMs, receivedMs = nowMs) {
174
+ const user = requireAddress(address);
175
+ const payload = expectRecord(client.post({ type: "userFees", user }), "user fees");
176
+ const [takerRate, makerRate] = feeRates(payload);
177
+ return {
178
+ address: user,
179
+ takerRate,
180
+ makerRate,
181
+ takerBps: fractionToBps(takerRate),
182
+ makerBps: fractionToBps(makerRate),
183
+ ...aged(payload, nowMs, receivedMs),
184
+ };
185
+ }
186
+ function parsePosition(value) {
187
+ const wrapper = expectRecord(value, "asset position");
188
+ if (wrapper.type !== "oneWay") {
189
+ throw new Error("only one-way positions are supported");
190
+ }
191
+ const body = expectRecord(wrapper.position, "position");
192
+ const leverage = expectRecord(body.leverage, "leverage");
193
+ const liquidation = body.liquidationPx;
194
+ return {
195
+ coin: expectString(body.coin, "coin"),
196
+ size: expectString(body.szi, "szi"),
197
+ entryPx: expectString(body.entryPx, "entryPx"),
198
+ liquidationPx: liquidation === null ? null : expectString(liquidation, "liquidationPx"),
199
+ unrealizedPnl: expectString(body.unrealizedPnl, "unrealizedPnl"),
200
+ leverageType: expectString(leverage.type, "leverage type"),
201
+ leverageValue: expectInt(leverage.value, "leverage value"),
202
+ };
203
+ }
204
+ function feeRates(payload) {
205
+ if (typeof payload.userCrossRate === "string" && typeof payload.userAddRate === "string") {
206
+ return [payload.userCrossRate, payload.userAddRate];
207
+ }
208
+ const schedule = expectRecord(payload.feeSchedule, "feeSchedule");
209
+ return [expectString(schedule.cross, "cross"), expectString(schedule.add, "add")];
210
+ }
@@ -0,0 +1,14 @@
1
+ /** Process-wide token bucket: 8 requests per second, burst 10. */
2
+ export declare const RATE_PER_SEC = 8;
3
+ export declare const BURST = 10;
4
+ export declare class TokenBucket {
5
+ readonly ratePerSec: number;
6
+ readonly burst: number;
7
+ private milliTokens;
8
+ private updatedMs;
9
+ private readonly clockMs;
10
+ private readonly sleepFn;
11
+ constructor(ratePerSec?: number, burst?: number, clockMs?: () => number, sleepFn?: (durationMs: number) => void);
12
+ acquire(tokens?: number): number;
13
+ private refill;
14
+ }