skewtape 0.0.1 → 0.1.4

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 (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +182 -0
  3. package/dist/cjs/backtest.d.ts +146 -0
  4. package/dist/cjs/backtest.js +410 -0
  5. package/dist/cjs/client.d.ts +255 -0
  6. package/dist/cjs/client.js +447 -0
  7. package/dist/cjs/download.d.ts +33 -0
  8. package/dist/cjs/download.js +160 -0
  9. package/dist/cjs/errors.d.ts +76 -0
  10. package/dist/cjs/errors.js +159 -0
  11. package/dist/cjs/exact.d.ts +36 -0
  12. package/dist/cjs/exact.js +168 -0
  13. package/dist/cjs/fees.d.ts +68 -0
  14. package/dist/cjs/fees.js +196 -0
  15. package/dist/cjs/geoblock.d.ts +48 -0
  16. package/dist/cjs/geoblock.js +78 -0
  17. package/dist/cjs/index.d.ts +31 -0
  18. package/dist/cjs/index.js +98 -0
  19. package/dist/cjs/kalshi.d.ts +261 -0
  20. package/dist/cjs/kalshi.js +416 -0
  21. package/dist/cjs/keccak.d.ts +10 -0
  22. package/dist/cjs/keccak.js +84 -0
  23. package/dist/cjs/msgpack.d.ts +15 -0
  24. package/dist/cjs/msgpack.js +112 -0
  25. package/dist/cjs/package.json +1 -0
  26. package/dist/cjs/paginated.d.ts +26 -0
  27. package/dist/cjs/paginated.js +51 -0
  28. package/dist/cjs/quote-math.d.ts +146 -0
  29. package/dist/cjs/quote-math.js +446 -0
  30. package/dist/cjs/quote.d.ts +108 -0
  31. package/dist/cjs/quote.js +307 -0
  32. package/dist/cjs/route-hyperliquid.d.ts +228 -0
  33. package/dist/cjs/route-hyperliquid.js +387 -0
  34. package/dist/cjs/route.d.ts +297 -0
  35. package/dist/cjs/route.js +516 -0
  36. package/dist/cjs/stream.d.ts +99 -0
  37. package/dist/cjs/stream.js +529 -0
  38. package/dist/cjs/version.d.ts +6 -0
  39. package/dist/cjs/version.js +9 -0
  40. package/dist/esm/backtest.d.ts +146 -0
  41. package/dist/esm/backtest.js +403 -0
  42. package/dist/esm/client.d.ts +255 -0
  43. package/dist/esm/client.js +441 -0
  44. package/dist/esm/download.d.ts +33 -0
  45. package/dist/esm/download.js +155 -0
  46. package/dist/esm/errors.d.ts +76 -0
  47. package/dist/esm/errors.js +142 -0
  48. package/dist/esm/exact.d.ts +36 -0
  49. package/dist/esm/exact.js +158 -0
  50. package/dist/esm/fees.d.ts +68 -0
  51. package/dist/esm/fees.js +185 -0
  52. package/dist/esm/geoblock.d.ts +48 -0
  53. package/dist/esm/geoblock.js +74 -0
  54. package/dist/esm/index.d.ts +31 -0
  55. package/dist/esm/index.js +30 -0
  56. package/dist/esm/kalshi.d.ts +261 -0
  57. package/dist/esm/kalshi.js +404 -0
  58. package/dist/esm/keccak.d.ts +10 -0
  59. package/dist/esm/keccak.js +80 -0
  60. package/dist/esm/msgpack.d.ts +15 -0
  61. package/dist/esm/msgpack.js +109 -0
  62. package/dist/esm/paginated.d.ts +26 -0
  63. package/dist/esm/paginated.js +47 -0
  64. package/dist/esm/quote-math.d.ts +146 -0
  65. package/dist/esm/quote-math.js +437 -0
  66. package/dist/esm/quote.d.ts +108 -0
  67. package/dist/esm/quote.js +297 -0
  68. package/dist/esm/route-hyperliquid.d.ts +228 -0
  69. package/dist/esm/route-hyperliquid.js +376 -0
  70. package/dist/esm/route.d.ts +297 -0
  71. package/dist/esm/route.js +507 -0
  72. package/dist/esm/stream.d.ts +99 -0
  73. package/dist/esm/stream.js +524 -0
  74. package/dist/esm/version.d.ts +6 -0
  75. package/dist/esm/version.js +6 -0
  76. package/package.json +48 -1
  77. package/src/backtest.ts +490 -0
  78. package/src/client.ts +595 -0
  79. package/src/download.ts +161 -0
  80. package/src/errors.ts +143 -0
  81. package/src/exact.ts +159 -0
  82. package/src/fees.ts +189 -0
  83. package/src/generated/schema.d.ts +2500 -0
  84. package/src/geoblock.ts +90 -0
  85. package/src/index.ts +146 -0
  86. package/src/kalshi.ts +563 -0
  87. package/src/keccak.ts +82 -0
  88. package/src/msgpack.ts +83 -0
  89. package/src/paginated.ts +51 -0
  90. package/src/quote-math.ts +555 -0
  91. package/src/quote.ts +324 -0
  92. package/src/route-hyperliquid.ts +457 -0
  93. package/src/route.ts +631 -0
  94. package/src/stream.ts +539 -0
  95. package/src/version.ts +6 -0
@@ -0,0 +1,108 @@
1
+ /**
2
+ * sk.quote(eventId, {outcome, side, size}): the best venue, or split across
3
+ * venues, to take a size of one outcome of a matched event once each venue's
4
+ * taker fee is counted. It places nothing.
5
+ *
6
+ * One call to Skewtape (GET /v1/quote-context/{event_id}, a metered data
7
+ * call) gives the members, their tokens, outcome maps and fee rows; the books
8
+ * are read from each venue, from this machine, with a plain fetch that never
9
+ * carries the Skewtape key. A venue that cannot be reached is left out and
10
+ * named (venue_unreachable); nothing routes around a block. The arithmetic is
11
+ * quote-math.ts, which passes tape's conformance vectors.
12
+ */
13
+ import type { components } from "./generated/schema.js";
14
+ import { MICRO, type Book, type QuoteResult } from "./quote-math.js";
15
+ export type QuoteContext = components["schemas"]["QuoteContext"];
16
+ export type QuoteContextMember = components["schemas"]["QuoteContextMember"];
17
+ export declare const POLYMARKET_CLOB_URL = "https://clob.polymarket.com";
18
+ /** Kalshi's smallest count where a market allows fractions: 0.01 contracts. */
19
+ export declare const KALSHI_FRACTION_MICRO = 10000;
20
+ /** A book reader could not read the book; message is the reason the quote names (venue_unreachable). */
21
+ export declare class BookUnavailable extends Error {
22
+ constructor(message: string);
23
+ }
24
+ /** What a book reader is asked for: the member's venue and market, the token of the outcome the quote takes, and the side (buy reads the asks, sell the bids). */
25
+ export interface BookRequest {
26
+ venue: string;
27
+ marketId: string;
28
+ tokenId: string;
29
+ side: "buy" | "sell";
30
+ }
31
+ /** Reads one book with fetchImpl, a plain fetch that carries no Skewtape key; throws BookUnavailable to leave the member out with a reason. */
32
+ export type BookReader = (request: BookRequest, fetchImpl: typeof fetch) => Promise<Book>;
33
+ export interface QuoteOptions {
34
+ /** The event's outcome to take, as the members' outcome maps name it ("yes", "no", ...). */
35
+ outcome: string;
36
+ side: "buy" | "sell";
37
+ /** Contracts, up to six decimals: a number or a decimal string. */
38
+ size: number | string;
39
+ /** Quote members that do not resolve alike, with a warning; refused by default. */
40
+ allowRuleMismatch?: boolean;
41
+ /** Readers by venue, used before the defaults (Polymarket's CLOB; Kalshi's public orderbook; kalshi_dflow through DFlow, not set up yet). */
42
+ bookReaders?: Record<string, BookReader>;
43
+ /** The fetch the books are read with; the global one by default. It must not carry the Skewtape key. */
44
+ venueFetch?: typeof fetch;
45
+ }
46
+ /**
47
+ * A decimal amount in millionths, exact when it has at most six decimals,
48
+ * otherwise rounded up or down. Strings are parsed exactly; a number goes
49
+ * through its shortest decimal form.
50
+ */
51
+ export declare function micros(value: number | string, up?: boolean): number;
52
+ /** How long a book read may take, the request and its body, in seconds. */
53
+ export declare const BOOK_TIMEOUT_SECONDS = 10;
54
+ /**
55
+ * The token's book from Polymarket's CLOB (GET /book?token_id=), the asks
56
+ * for a buy and the bids for a sell: levels as {"price", "size"} decimal
57
+ * strings, in dollars and contracts, as the CLOB's market channel sends them,
58
+ * and min_order_size in contracts. An ask's price rounds up and a bid's down
59
+ * past six decimals, and sizes down, so a quote never counts on more than the
60
+ * book holds.
61
+ *
62
+ * TODO(decision): the shape is the CLOB's book as the market channel's book
63
+ * event carries it (tape internal/venue/polymarket/live.go); the REST page
64
+ * could not be read on 14 Nov 2026 (docs.polymarket.com served an expired
65
+ * certificate). A staging recording of one /book reply confirms it, and shows
66
+ * whether the CLOB answers 404 for a token with no book (a closed market),
67
+ * which would then read as an empty book, not unreachable.
68
+ */
69
+ export declare const readPolymarketBook: BookReader;
70
+ /**
71
+ * A kalshi member's book from Kalshi's public orderbook (GET
72
+ * /markets/{ticker}/orderbook, through kalshi.ts with no key, one try).
73
+ * Kalshi lists bids only, yes and no: a no bid at p is a yes ask at 1 - p.
74
+ * So a buy of yes takes the no bids at 1 - p (rounded up past six decimals)
75
+ * and a buy of no the yes bids at 1 - p; a sell of yes takes the yes bids
76
+ * and a sell of no the no bids (rounded down). Counts are rounded down to
77
+ * millionths.
78
+ *
79
+ * The size step: Kalshi counts in hundredths of a contract where a market
80
+ * allows fractions and in whole contracts elsewhere (docs.kalshi.com,
81
+ * fixed-point migration, 5 Nov 2026), and names no field that says which. A
82
+ * book with a fractional count on either side is taken as fractional (0.01);
83
+ * any other as whole contracts, so a quote never counts on a size the market
84
+ * may refuse. Kalshi documents no minimum order beyond that.
85
+ */
86
+ export declare const readKalshiBook: BookReader;
87
+ /**
88
+ * A kalshi_dflow member trades through DFlow (ADR-0016), whose orderbook
89
+ * needs DFlow access, not set up yet, so the member is left out with that
90
+ * reason, plainly; nothing reads the book another way. (A kalshi member is
91
+ * read from Kalshi's own book: readKalshiBook.)
92
+ *
93
+ * TODO(decision): DFlow's orderbook endpoint, its shape and the key it needs
94
+ * (production access is by request). Until then a caller can pass its own
95
+ * reader in bookReaders.
96
+ */
97
+ export declare const readKalshiBookThroughDflow: BookReader;
98
+ export declare const DEFAULT_BOOK_READERS: Readonly<Record<string, BookReader>>;
99
+ /** The event's outcome names a quote can take, as the members' outcome maps name them. */
100
+ export declare function outcomesOf(context: QuoteContext): string[];
101
+ /**
102
+ * A quote on a context already read: each member's book read with its
103
+ * venue's reader (bookReaders first, then the defaults), then computeQuote.
104
+ * A member whose fee_status is blocked is left out without reading anything,
105
+ * and a rule mismatch is refused before any book is read.
106
+ */
107
+ export declare function quoteFromContext(context: QuoteContext, options: QuoteOptions): Promise<QuoteResult>;
108
+ export { MICRO };
@@ -0,0 +1,297 @@
1
+ /**
2
+ * sk.quote(eventId, {outcome, side, size}): the best venue, or split across
3
+ * venues, to take a size of one outcome of a matched event once each venue's
4
+ * taker fee is counted. It places nothing.
5
+ *
6
+ * One call to Skewtape (GET /v1/quote-context/{event_id}, a metered data
7
+ * call) gives the members, their tokens, outcome maps and fee rows; the books
8
+ * are read from each venue, from this machine, with a plain fetch that never
9
+ * carries the Skewtape key. A venue that cannot be reached is left out and
10
+ * named (venue_unreachable); nothing routes around a block. The arithmetic is
11
+ * quote-math.ts, which passes tape's conformance vectors.
12
+ */
13
+ import { Kalshi, KalshiError } from "./kalshi.js";
14
+ import { InvalidQuoteInputError, MICRO, RuleMismatchError, computeQuote, } from "./quote-math.js";
15
+ import { VERSION } from "./version.js";
16
+ export const POLYMARKET_CLOB_URL = "https://clob.polymarket.com";
17
+ /** Kalshi's smallest count where a market allows fractions: 0.01 contracts. */
18
+ export const KALSHI_FRACTION_MICRO = 10_000;
19
+ /** A book reader could not read the book; message is the reason the quote names (venue_unreachable). */
20
+ export class BookUnavailable extends Error {
21
+ constructor(message) {
22
+ super(message);
23
+ this.name = "BookUnavailable";
24
+ }
25
+ }
26
+ /**
27
+ * A decimal amount in millionths, exact when it has at most six decimals,
28
+ * otherwise rounded up or down. Strings are parsed exactly; a number goes
29
+ * through its shortest decimal form.
30
+ */
31
+ export function micros(value, up = false) {
32
+ const text = typeof value === "number" ? numberText(value) : value.trim();
33
+ const m = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(text);
34
+ if (!m || (m[2] === "" && (m[3] ?? "") === ""))
35
+ throw new Error(`not a number: ${JSON.stringify(value)}`);
36
+ const negative = m[1] === "-";
37
+ let digits = (m[2] ?? "") + (m[3] ?? "");
38
+ // The decimal point sits after point digits; exp moves it.
39
+ let point = (m[2] ?? "").length + Number(m[4] ?? 0) + 6;
40
+ if (point < 0) {
41
+ digits = "0".repeat(-point) + digits;
42
+ point = 0;
43
+ }
44
+ digits = digits.padEnd(point, "0");
45
+ const whole = BigInt(digits.slice(0, point) || "0");
46
+ const rest = digits.slice(point).replace(/0+$/, "");
47
+ let v = whole;
48
+ // Toward +infinity for up, -infinity otherwise.
49
+ if (rest !== "" && up !== negative)
50
+ v += 1n;
51
+ const out = Number(negative ? -v : v);
52
+ if (!Number.isSafeInteger(out))
53
+ throw new Error(`${JSON.stringify(value)} is past the safe integer range`);
54
+ return out;
55
+ }
56
+ function numberText(n) {
57
+ if (!Number.isFinite(n))
58
+ throw new Error(`not a finite number: ${n}`);
59
+ return String(n);
60
+ }
61
+ /** How long a book read may take, the request and its body, in seconds. */
62
+ export const BOOK_TIMEOUT_SECONDS = 10;
63
+ /** A failed book request or body read, as the reason the quote names: a timeout by its seconds, anything else by its error. */
64
+ function fetchFailure(err) {
65
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
66
+ return `clob.polymarket.com did not answer within ${BOOK_TIMEOUT_SECONDS} s`;
67
+ }
68
+ return err instanceof Error ? `${err.name}: ${err.message}` : String(err);
69
+ }
70
+ /**
71
+ * The token's book from Polymarket's CLOB (GET /book?token_id=), the asks
72
+ * for a buy and the bids for a sell: levels as {"price", "size"} decimal
73
+ * strings, in dollars and contracts, as the CLOB's market channel sends them,
74
+ * and min_order_size in contracts. An ask's price rounds up and a bid's down
75
+ * past six decimals, and sizes down, so a quote never counts on more than the
76
+ * book holds.
77
+ *
78
+ * TODO(decision): the shape is the CLOB's book as the market channel's book
79
+ * event carries it (tape internal/venue/polymarket/live.go); the REST page
80
+ * could not be read on 14 Nov 2026 (docs.polymarket.com served an expired
81
+ * certificate). A staging recording of one /book reply confirms it, and shows
82
+ * whether the CLOB answers 404 for a token with no book (a closed market),
83
+ * which would then read as an empty book, not unreachable.
84
+ */
85
+ export const readPolymarketBook = async (request, fetchImpl) => {
86
+ const url = `${POLYMARKET_CLOB_URL}/book?token_id=${encodeURIComponent(request.tokenId)}`;
87
+ let response;
88
+ try {
89
+ // A redirect is not followed: a block page reached through one is a
90
+ // status the check below names, as Python's client reports it.
91
+ response = await fetchImpl(url, {
92
+ method: "GET",
93
+ redirect: "manual",
94
+ headers: { "User-Agent": `skewtape-ts/${VERSION}` },
95
+ signal: AbortSignal.timeout(BOOK_TIMEOUT_SECONDS * 1000),
96
+ });
97
+ }
98
+ catch (err) {
99
+ throw new BookUnavailable(fetchFailure(err));
100
+ }
101
+ if (response.type === "opaqueredirect")
102
+ throw new BookUnavailable("clob.polymarket.com answered with a redirect");
103
+ if (response.status !== 200)
104
+ throw new BookUnavailable(`clob.polymarket.com answered HTTP ${response.status}`);
105
+ // The timeout covers the body read too, and is named as the request's is.
106
+ let text;
107
+ try {
108
+ text = await response.text();
109
+ }
110
+ catch (err) {
111
+ throw new BookUnavailable(fetchFailure(err));
112
+ }
113
+ try {
114
+ const body = JSON.parse(text);
115
+ const raw = (request.side === "buy" ? body.asks : body.bids) ?? [];
116
+ const levels = [];
117
+ for (const l of raw) {
118
+ const size = micros(l.size);
119
+ if (size > 0)
120
+ levels.push({ price_micros: micros(l.price, request.side === "buy"), size_micro: size });
121
+ }
122
+ const min = body.min_order_size;
123
+ return { levels, min_size_micro: min === undefined || min === null || min === "" ? 0 : micros(min, true) };
124
+ }
125
+ catch (err) {
126
+ throw new BookUnavailable(`clob.polymarket.com sent a book this version cannot read (${err instanceof Error ? err.message : String(err)})`);
127
+ }
128
+ };
129
+ /**
130
+ * A kalshi member's book from Kalshi's public orderbook (GET
131
+ * /markets/{ticker}/orderbook, through kalshi.ts with no key, one try).
132
+ * Kalshi lists bids only, yes and no: a no bid at p is a yes ask at 1 - p.
133
+ * So a buy of yes takes the no bids at 1 - p (rounded up past six decimals)
134
+ * and a buy of no the yes bids at 1 - p; a sell of yes takes the yes bids
135
+ * and a sell of no the no bids (rounded down). Counts are rounded down to
136
+ * millionths.
137
+ *
138
+ * The size step: Kalshi counts in hundredths of a contract where a market
139
+ * allows fractions and in whole contracts elsewhere (docs.kalshi.com,
140
+ * fixed-point migration, 5 Nov 2026), and names no field that says which. A
141
+ * book with a fractional count on either side is taken as fractional (0.01);
142
+ * any other as whole contracts, so a quote never counts on a size the market
143
+ * may refuse. Kalshi documents no minimum order beyond that.
144
+ */
145
+ export const readKalshiBook = async (request, fetchImpl) => {
146
+ if (request.tokenId !== "yes" && request.tokenId !== "no") {
147
+ throw new BookUnavailable(`Kalshi's book has a yes and a no side, and the token is ${JSON.stringify(request.tokenId)}`);
148
+ }
149
+ let book;
150
+ try {
151
+ book = await new Kalshi({ fetch: fetchImpl, maxRetries: 0, timeout: BOOK_TIMEOUT_SECONDS }).orderbook(request.marketId);
152
+ }
153
+ catch (err) {
154
+ if (err instanceof KalshiError)
155
+ throw new BookUnavailable(`Kalshi's orderbook for ${request.marketId}: ${err.message}`);
156
+ throw new BookUnavailable(err instanceof Error ? `${err.name}: ${err.message}` : String(err));
157
+ }
158
+ // kalshi.ts leaves out a row that is not [price, count]: here that is a
159
+ // book this version cannot read, not a thinner side, which would quietly
160
+ // move a quote to another venue.
161
+ const sides = book.raw.orderbook_fp;
162
+ for (const [side, parsed] of [
163
+ ["yes_dollars", book.yes],
164
+ ["no_dollars", book.no],
165
+ ]) {
166
+ const rows = sides?.[side];
167
+ if (rows !== undefined && rows !== null && (!Array.isArray(rows) || rows.length !== parsed.length)) {
168
+ throw new BookUnavailable(`Kalshi sent a book this version cannot read (a row of ${side} is not [price, count])`);
169
+ }
170
+ }
171
+ const [same, other] = request.tokenId === "yes" ? [book.yes, book.no] : [book.no, book.yes];
172
+ const buy = request.side === "buy";
173
+ try {
174
+ const levels = [];
175
+ for (const l of buy ? other : same) {
176
+ const size = micros(l.count_fp);
177
+ // floor and ceil of the price in millionths: 1 - p rounded up is
178
+ // MICRO - floor(p).
179
+ const lo = micros(l.price_dollars);
180
+ if (!(micros(l.price_dollars, true) > 0 && lo < MICRO))
181
+ throw new Error(`price ${l.price_dollars} is outside (0, 1)`);
182
+ if (size > 0)
183
+ levels.push({ price_micros: buy ? MICRO - lo : lo, size_micro: size });
184
+ }
185
+ const fractional = [...book.yes, ...book.no].some((l) => micros(l.count_fp) % MICRO !== 0);
186
+ return { levels, size_step_micro: fractional ? KALSHI_FRACTION_MICRO : MICRO };
187
+ }
188
+ catch (err) {
189
+ throw new BookUnavailable(`Kalshi sent a book this version cannot read (${err instanceof Error ? err.message : String(err)})`);
190
+ }
191
+ };
192
+ /**
193
+ * A kalshi_dflow member trades through DFlow (ADR-0016), whose orderbook
194
+ * needs DFlow access, not set up yet, so the member is left out with that
195
+ * reason, plainly; nothing reads the book another way. (A kalshi member is
196
+ * read from Kalshi's own book: readKalshiBook.)
197
+ *
198
+ * TODO(decision): DFlow's orderbook endpoint, its shape and the key it needs
199
+ * (production access is by request). Until then a caller can pass its own
200
+ * reader in bookReaders.
201
+ */
202
+ export const readKalshiBookThroughDflow = async () => {
203
+ throw new BookUnavailable("kalshi_dflow's book is read through DFlow's orderbook, and DFlow access is not set up yet");
204
+ };
205
+ export const DEFAULT_BOOK_READERS = {
206
+ polymarket: readPolymarketBook,
207
+ kalshi: readKalshiBook,
208
+ kalshi_dflow: readKalshiBookThroughDflow,
209
+ };
210
+ /** Each outcome's name (its label, or its token id when the market gives two outcomes the same label) to its token id. */
211
+ function names(member) {
212
+ const labels = member.tokens.map((o) => o.label);
213
+ const repeats = new Set(labels).size !== labels.length;
214
+ return new Map(member.tokens.map((o) => [repeats ? o.token_id : o.label, o.token_id]));
215
+ }
216
+ function tokenFor(member, outcome) {
217
+ const byName = names(member);
218
+ for (const [name, eventOutcome] of Object.entries(member.outcome_map)) {
219
+ if (eventOutcome === outcome && byName.has(name))
220
+ return byName.get(name);
221
+ }
222
+ return undefined;
223
+ }
224
+ function feeOf(member) {
225
+ const fee = member.fee;
226
+ if (!fee)
227
+ return null;
228
+ return { formula: fee.formula, rounding: fee.rounding, taker_params: { ...fee.taker_params }, min_fee_micros: fee.min_fee_micros ?? null };
229
+ }
230
+ /** The event's outcome names a quote can take, as the members' outcome maps name them. */
231
+ export function outcomesOf(context) {
232
+ const seen = [];
233
+ for (const m of context.members)
234
+ for (const v of Object.values(m.outcome_map))
235
+ if (!seen.includes(v))
236
+ seen.push(v);
237
+ return seen;
238
+ }
239
+ /**
240
+ * A quote on a context already read: each member's book read with its
241
+ * venue's reader (bookReaders first, then the defaults), then computeQuote.
242
+ * A member whose fee_status is blocked is left out without reading anything,
243
+ * and a rule mismatch is refused before any book is read.
244
+ */
245
+ export async function quoteFromContext(context, options) {
246
+ const { outcome, side } = options;
247
+ if (side !== "buy" && side !== "sell")
248
+ throw new InvalidQuoteInputError(`side ${JSON.stringify(side)} is neither buy nor sell`);
249
+ let size;
250
+ try {
251
+ size = micros(options.size);
252
+ if (micros(options.size, true) !== size)
253
+ throw new Error(`size ${options.size} has more than six decimals`);
254
+ }
255
+ catch (err) {
256
+ throw new InvalidQuoteInputError(err instanceof Error ? err.message : String(err));
257
+ }
258
+ const known = outcomesOf(context);
259
+ if (!known.includes(outcome))
260
+ throw new InvalidQuoteInputError(`outcome ${JSON.stringify(outcome)} is not one of the event's: ${known.join(", ") || "none"}`);
261
+ // Before any book is read (ARCHITECTURE 13.1, step 2).
262
+ if (!context.resolution_equal && !options.allowRuleMismatch)
263
+ throw new RuleMismatchError(context.rule_note);
264
+ const readers = { ...DEFAULT_BOOK_READERS, ...(options.bookReaders ?? {}) };
265
+ const fetchImpl = options.venueFetch ?? fetch;
266
+ const members = await Promise.all(context.members.map(async (m) => {
267
+ const member = { venue: m.venue, market_id: m.market_id, token_id: "", fee_status: m.fee_status, fee_per: m.fee_per, fee: feeOf(m), book: null };
268
+ if (m.fee_status === "blocked")
269
+ return { ...member, blocked: true };
270
+ const token = tokenFor(m, outcome);
271
+ if (token === undefined)
272
+ return { ...member, unreachable: `no token of the market maps to ${JSON.stringify(outcome)}` };
273
+ member.token_id = token;
274
+ const reader = readers[m.venue];
275
+ if (!reader)
276
+ return { ...member, unreachable: `sk.quote has no book reader for ${m.venue}; pass one in bookReaders` };
277
+ try {
278
+ member.book = await reader({ venue: m.venue, marketId: m.market_id, tokenId: token, side }, fetchImpl);
279
+ }
280
+ catch (err) {
281
+ if (!(err instanceof BookUnavailable))
282
+ throw err;
283
+ member.unreachable = err.message || "the book could not be read";
284
+ }
285
+ return member;
286
+ }));
287
+ return computeQuote({
288
+ event_id: context.event_id,
289
+ side,
290
+ size_micro: size,
291
+ resolution_equal: context.resolution_equal,
292
+ rule_note: context.rule_note,
293
+ allow_rule_mismatch: options.allowRuleMismatch ?? false,
294
+ members,
295
+ });
296
+ }
297
+ export { MICRO };
@@ -0,0 +1,228 @@
1
+ /**
2
+ * sk.route for Hyperliquid's HIP-4 outcome markets (E21-T3): an unsigned
3
+ * order, with the developer's own builder code, for the developer to sign.
4
+ *
5
+ * An order is an L1 action: its MessagePack bytes, the nonce, the vault flag
6
+ * and expiresAfter are hashed with Keccak-256, and the hash is signed as a
7
+ * "phantom agent" under the EIP-712 domain "Exchange" on chain 1337 (the
8
+ * signing page and the official Python SDK's signing.py, read 14 Nov 2026). A
9
+ * wallet that only signs for its own chain will not sign chain 1337: L1
10
+ * actions are signed by a key the developer holds, usually an API wallet the
11
+ * user approved. Nothing here signs, sends or takes a key.
12
+ *
13
+ * A builder code is the developer's: {"b": address, "f": fee in tenths of a
14
+ * basis point}. The user approves a maximum fee for that builder first, with
15
+ * their main wallet (hyperliquidApproveBuilderFee builds that request,
16
+ * unsigned). With no builder, the order carries none: no default code exists.
17
+ *
18
+ * const order = route({
19
+ * venue: "hyperliquid", outcome: 96, side: 0, isBuy: false,
20
+ * price: "0.55", size: "20", builder: "0xYourBuilder", builderFee: 10,
21
+ * });
22
+ * const signature = await apiWallet.signTypedData(order.typedData);
23
+ * const body = order.postBody(signature); // POST to HYPERLIQUID_EXCHANGE_URL
24
+ *
25
+ * Fees, read 14 Nov 2026. The HIP-4 page: "Fees are currently zero for outcome
26
+ * markets for initial testing. However, builder codes do work the same as
27
+ * normal spot trading, where builders earn builder fees on sell orders that
28
+ * specify their builder code." The fees page: "Outcome trading only charges
29
+ * fees when closing or settling, not when opening outcome positions." The two
30
+ * do not agree, and the testnet-only deployer page says builder fees also
31
+ * apply to buy orders, best effort; the order is the same either way.
32
+ */
33
+ import { type Packable } from "./msgpack.js";
34
+ type Hex = `0x${string}`;
35
+ /** Endpoints the developer posts to ("Exchange endpoint"); route never calls them. */
36
+ export declare const HYPERLIQUID_EXCHANGE_URL = "https://api.hyperliquid.xyz/exchange";
37
+ export declare const HYPERLIQUID_TESTNET_EXCHANGE_URL = "https://api.hyperliquid-testnet.xyz/exchange";
38
+ /** "Outcome asset ID: 100_000_000 + encoding", encoding = 10 * outcome + side (api/asset-ids). */
39
+ export declare const HYPERLIQUID_OUTCOME_ASSET_BASE = 100000000;
40
+ /** The L1 action's EIP-712 domain and type (signing.py, l1_payload). */
41
+ export declare const HYPERLIQUID_L1_DOMAIN: {
42
+ readonly name: "Exchange";
43
+ readonly version: "1";
44
+ readonly chainId: 1337;
45
+ readonly verifyingContract: "0x0000000000000000000000000000000000000000";
46
+ };
47
+ export declare const HYPERLIQUID_AGENT_TYPE: readonly [{
48
+ readonly name: "source";
49
+ readonly type: "string";
50
+ }, {
51
+ readonly name: "connectionId";
52
+ readonly type: "bytes32";
53
+ }];
54
+ /** Time in force: "Alo" adds liquidity only, "Ioc" takes what crosses now (a market order is an Ioc at the worst price accepted). */
55
+ export declare const HYPERLIQUID_TIFS: readonly ["Gtc", "Ioc", "Alo"];
56
+ export type HyperliquidTif = (typeof HYPERLIQUID_TIFS)[number];
57
+ /**
58
+ * "Prices can have up to 5 significant figures, but no more than MAX_DECIMALS
59
+ * - szDecimals decimal places where MAX_DECIMALS is 6 for perps and 8 for
60
+ * spot" (api/tick-and-lot-size). Outcomes trade like spot, so 8.
61
+ */
62
+ export declare const HYPERLIQUID_PRICE_SIG_FIGS = 5;
63
+ export declare const HYPERLIQUID_SPOT_MAX_DECIMALS = 8;
64
+ /** "at most 0.1% on perps and 1% on spot" in tenths of a basis point: spot's 1% is 1000; outcomes inherit spot's behaviour. */
65
+ export declare const HYPERLIQUID_BUILDER_FEE_MAX = 1000;
66
+ export declare const HYPERLIQUID_SIGN_DOMAIN_NAME = "HyperliquidSignTransaction";
67
+ export declare const HYPERLIQUID_APPROVE_BUILDER_FEE_TYPE: readonly [{
68
+ readonly name: "hyperliquidChain";
69
+ readonly type: "string";
70
+ }, {
71
+ readonly name: "maxFeeRate";
72
+ readonly type: "string";
73
+ }, {
74
+ readonly name: "builder";
75
+ readonly type: "address";
76
+ }, {
77
+ readonly name: "nonce";
78
+ readonly type: "uint64";
79
+ }];
80
+ /** The fields a Hyperliquid route takes; anything else, a key above all, is refused. */
81
+ export declare const HYPERLIQUID_FIELDS: readonly ["venue", "outcome", "side", "isBuy", "price", "size", "tif", "reduceOnly", "cloid", "builder", "builderFee", "szDecimals", "nonce", "vaultAddress", "expiresAfter", "mainnet"];
82
+ /** The fields hyperliquidApproveBuilderFee takes; anything else, a key above all, is refused. */
83
+ export declare const HYPERLIQUID_APPROVE_FIELDS: readonly ["builder", "maxFeeRate", "signatureChainId", "nonce", "mainnet"];
84
+ /**
85
+ * A HIP-4 outcome order to build: side 0 or 1 of `outcome` (coin "#960" is
86
+ * outcome 96, side 0). isBuy buys that side's token, else sells it. price and
87
+ * size: decimal strings (or integers); the price has at most 5 significant
88
+ * figures (an integer price always passes) and at most 8 - szDecimals
89
+ * decimals, the size at most szDecimals decimals. The docs do not give an
90
+ * outcome's szDecimals: pass it to check the order here, else only the 5
91
+ * figures and 8 decimals are checked and the venue rejects the rest. builder
92
+ * and builderFee (tenths of a basis point, at most 1000) are your own and go
93
+ * together; with neither, the order carries no builder. nonce: milliseconds,
94
+ * now by default. vaultAddress: a vault or subaccount you trade for.
95
+ * expiresAfter: milliseconds after which the venue drops the action.
96
+ */
97
+ export interface HyperliquidRoute {
98
+ venue: "hyperliquid";
99
+ outcome: number;
100
+ side: 0 | 1;
101
+ isBuy: boolean;
102
+ price: string | number;
103
+ size: string | number;
104
+ tif?: HyperliquidTif;
105
+ reduceOnly?: boolean;
106
+ cloid?: string;
107
+ builder?: string;
108
+ builderFee?: number;
109
+ szDecimals?: number;
110
+ nonce?: number;
111
+ vaultAddress?: string;
112
+ expiresAfter?: number;
113
+ mainnet?: boolean;
114
+ }
115
+ /** An L1 action's typed data, as viem's signTypedData takes it; ethers v6 takes its domain, types and message as three arguments. */
116
+ export interface HyperliquidL1TypedData {
117
+ domain: typeof HYPERLIQUID_L1_DOMAIN;
118
+ types: {
119
+ Agent: typeof HYPERLIQUID_AGENT_TYPE;
120
+ };
121
+ primaryType: "Agent";
122
+ message: {
123
+ source: "a" | "b";
124
+ connectionId: Hex;
125
+ };
126
+ }
127
+ export interface HyperliquidApproveTypedData {
128
+ domain: {
129
+ name: string;
130
+ version: string;
131
+ chainId: number;
132
+ verifyingContract: Hex;
133
+ };
134
+ types: {
135
+ "HyperliquidTransaction:ApproveBuilderFee": typeof HYPERLIQUID_APPROVE_BUILDER_FEE_TYPE;
136
+ };
137
+ primaryType: "HyperliquidTransaction:ApproveBuilderFee";
138
+ message: {
139
+ hyperliquidChain: "Mainnet" | "Testnet";
140
+ maxFeeRate: string;
141
+ builder: Hex;
142
+ nonce: bigint;
143
+ };
144
+ }
145
+ type Action = {
146
+ [key: string]: Packable;
147
+ };
148
+ /** The order's asset id for side (0 or 1) of outcome: 100_000_000 + 10 * outcome + side. */
149
+ export declare function hyperliquidOutcomeAsset(outcome: number, side: number): number;
150
+ /**
151
+ * Keccak-256 of the action's MessagePack bytes, the nonce (8 bytes, big
152
+ * endian), the vault flag (0x00, or 0x01 and the vault's 20 bytes) and, when
153
+ * set, 0x00 and expiresAfter (8 bytes): signing.py's action_hash.
154
+ */
155
+ export declare function hyperliquidActionHash(action: Action, nonce: number, vaultAddress?: string | null, expiresAfter?: number | null): Hex;
156
+ /** The typed data of an L1 action's phantom agent: source "a" on mainnet, "b" on testnet. */
157
+ export declare function hyperliquidL1TypedData(connectionId: Hex, mainnet?: boolean): HyperliquidL1TypedData;
158
+ type Field = {
159
+ readonly name: string;
160
+ readonly type: string;
161
+ };
162
+ /**
163
+ * The EIP-712 digest of flat typed data (strings, addresses, unsigned
164
+ * integers, bytes32), computed here: viem's signTypedData refuses the type
165
+ * name "HyperliquidTransaction:ApproveBuilderFee" (a colon), so a viem key
166
+ * signs this digest instead (account.sign({ hash: digest })).
167
+ */
168
+ export declare function eip712Digest(typed: {
169
+ domain: Record<string, unknown>;
170
+ types: Record<string, readonly Field[]>;
171
+ primaryType: string;
172
+ message: Record<string, unknown>;
173
+ }): Hex;
174
+ /**
175
+ * An unsigned Hyperliquid order. Sign `typedData` with the key that trades
176
+ * (an API wallet), then POST `postBody(signature)` to `exchangeUrl`. Nothing
177
+ * here was signed or sent.
178
+ */
179
+ export declare class HyperliquidOrder {
180
+ readonly action: Action;
181
+ readonly nonce: number;
182
+ readonly connectionId: Hex;
183
+ readonly typedData: HyperliquidL1TypedData;
184
+ readonly vaultAddress: Hex | null;
185
+ readonly expiresAfter: number | null;
186
+ readonly exchangeUrl: string;
187
+ readonly venue: "hyperliquid";
188
+ constructor(action: Action, nonce: number, connectionId: Hex, typedData: HyperliquidL1TypedData, vaultAddress: Hex | null, expiresAfter: number | null, exchangeUrl: string);
189
+ /** The typed data as eth_signTypedData_v4 takes it: JSON, the EIP712Domain type included. */
190
+ typedDataJson(): string;
191
+ /** The EIP-712 digest of typedData, for a signer that signs a hash. */
192
+ get digest(): Hex;
193
+ /** The POST /exchange body: action, nonce, the signature split as the official SDK sends it, vaultAddress and expiresAfter. */
194
+ postBody(signature: string): Record<string, unknown>;
195
+ }
196
+ export declare function hyperliquidOrder(input: HyperliquidRoute): HyperliquidOrder;
197
+ /**
198
+ * An unsigned approveBuilderFee: the user's main wallet signs `typedData`
199
+ * once per builder before orders carry its code. A browser wallet signs
200
+ * `typedDataJson()` with eth_signTypedData_v4. viem's signTypedData refuses
201
+ * the type name (it holds a colon): a viem key signs `digest` instead.
202
+ */
203
+ export declare class HyperliquidApproveBuilderFee {
204
+ readonly action: Record<string, string | number>;
205
+ readonly nonce: number;
206
+ readonly typedData: HyperliquidApproveTypedData;
207
+ readonly exchangeUrl: string;
208
+ constructor(action: Record<string, string | number>, nonce: number, typedData: HyperliquidApproveTypedData, exchangeUrl: string);
209
+ typedDataJson(): string;
210
+ /** The EIP-712 digest of typedData (see the class comment). */
211
+ get digest(): Hex;
212
+ /** The POST /exchange body; a user-signed action takes no vault and no expiresAfter. */
213
+ postBody(signature: string): Record<string, unknown>;
214
+ }
215
+ /**
216
+ * The unsigned approveBuilderFee the user's main wallet signs once before
217
+ * orders carry `builder`'s code. maxFeeRate: a percent string ("0.001%" is
218
+ * f=1, the official SDK's example; at most "1%"). signatureChainId: the chain
219
+ * the wallet signs on (42161, 0xa4b1, for Arbitrum One, the docs' example).
220
+ */
221
+ export declare function hyperliquidApproveBuilderFee(input: {
222
+ builder: string;
223
+ maxFeeRate: string;
224
+ signatureChainId: number;
225
+ nonce?: number;
226
+ mainnet?: boolean;
227
+ }): HyperliquidApproveBuilderFee;
228
+ export {};