skewtape 0.0.1 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +182 -0
- package/dist/cjs/backtest.d.ts +146 -0
- package/dist/cjs/backtest.js +410 -0
- package/dist/cjs/client.d.ts +255 -0
- package/dist/cjs/client.js +447 -0
- package/dist/cjs/download.d.ts +33 -0
- package/dist/cjs/download.js +160 -0
- package/dist/cjs/errors.d.ts +76 -0
- package/dist/cjs/errors.js +159 -0
- package/dist/cjs/exact.d.ts +36 -0
- package/dist/cjs/exact.js +168 -0
- package/dist/cjs/fees.d.ts +68 -0
- package/dist/cjs/fees.js +196 -0
- package/dist/cjs/geoblock.d.ts +48 -0
- package/dist/cjs/geoblock.js +78 -0
- package/dist/cjs/index.d.ts +31 -0
- package/dist/cjs/index.js +98 -0
- package/dist/cjs/kalshi.d.ts +261 -0
- package/dist/cjs/kalshi.js +416 -0
- package/dist/cjs/keccak.d.ts +10 -0
- package/dist/cjs/keccak.js +84 -0
- package/dist/cjs/msgpack.d.ts +15 -0
- package/dist/cjs/msgpack.js +112 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/paginated.d.ts +26 -0
- package/dist/cjs/paginated.js +51 -0
- package/dist/cjs/quote-math.d.ts +146 -0
- package/dist/cjs/quote-math.js +446 -0
- package/dist/cjs/quote.d.ts +108 -0
- package/dist/cjs/quote.js +307 -0
- package/dist/cjs/route-hyperliquid.d.ts +228 -0
- package/dist/cjs/route-hyperliquid.js +387 -0
- package/dist/cjs/route.d.ts +297 -0
- package/dist/cjs/route.js +516 -0
- package/dist/cjs/stream.d.ts +99 -0
- package/dist/cjs/stream.js +529 -0
- package/dist/cjs/version.d.ts +6 -0
- package/dist/cjs/version.js +9 -0
- package/dist/esm/backtest.d.ts +146 -0
- package/dist/esm/backtest.js +403 -0
- package/dist/esm/client.d.ts +255 -0
- package/dist/esm/client.js +441 -0
- package/dist/esm/download.d.ts +33 -0
- package/dist/esm/download.js +155 -0
- package/dist/esm/errors.d.ts +76 -0
- package/dist/esm/errors.js +142 -0
- package/dist/esm/exact.d.ts +36 -0
- package/dist/esm/exact.js +158 -0
- package/dist/esm/fees.d.ts +68 -0
- package/dist/esm/fees.js +185 -0
- package/dist/esm/geoblock.d.ts +48 -0
- package/dist/esm/geoblock.js +74 -0
- package/dist/esm/index.d.ts +31 -0
- package/dist/esm/index.js +30 -0
- package/dist/esm/kalshi.d.ts +261 -0
- package/dist/esm/kalshi.js +404 -0
- package/dist/esm/keccak.d.ts +10 -0
- package/dist/esm/keccak.js +80 -0
- package/dist/esm/msgpack.d.ts +15 -0
- package/dist/esm/msgpack.js +109 -0
- package/dist/esm/paginated.d.ts +26 -0
- package/dist/esm/paginated.js +47 -0
- package/dist/esm/quote-math.d.ts +146 -0
- package/dist/esm/quote-math.js +437 -0
- package/dist/esm/quote.d.ts +108 -0
- package/dist/esm/quote.js +297 -0
- package/dist/esm/route-hyperliquid.d.ts +228 -0
- package/dist/esm/route-hyperliquid.js +376 -0
- package/dist/esm/route.d.ts +297 -0
- package/dist/esm/route.js +507 -0
- package/dist/esm/stream.d.ts +99 -0
- package/dist/esm/stream.js +524 -0
- package/dist/esm/version.d.ts +6 -0
- package/dist/esm/version.js +6 -0
- package/package.json +48 -1
- package/src/backtest.ts +490 -0
- package/src/client.ts +595 -0
- package/src/download.ts +161 -0
- package/src/errors.ts +143 -0
- package/src/exact.ts +159 -0
- package/src/fees.ts +189 -0
- package/src/generated/schema.d.ts +2500 -0
- package/src/geoblock.ts +90 -0
- package/src/index.ts +146 -0
- package/src/kalshi.ts +563 -0
- package/src/keccak.ts +82 -0
- package/src/msgpack.ts +83 -0
- package/src/paginated.ts +51 -0
- package/src/quote-math.ts +555 -0
- package/src/quote.ts +324 -0
- package/src/route-hyperliquid.ts +457 -0
- package/src/route.ts +631 -0
- package/src/stream.ts +539 -0
- package/src/version.ts +6 -0
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* sk.quote(eventId, {outcome, side, size}): the best venue, or split across
|
|
4
|
+
* venues, to take a size of one outcome of a matched event once each venue's
|
|
5
|
+
* taker fee is counted. It places nothing.
|
|
6
|
+
*
|
|
7
|
+
* One call to Skewtape (GET /v1/quote-context/{event_id}, a metered data
|
|
8
|
+
* call) gives the members, their tokens, outcome maps and fee rows; the books
|
|
9
|
+
* are read from each venue, from this machine, with a plain fetch that never
|
|
10
|
+
* carries the Skewtape key. A venue that cannot be reached is left out and
|
|
11
|
+
* named (venue_unreachable); nothing routes around a block. The arithmetic is
|
|
12
|
+
* quote-math.ts, which passes tape's conformance vectors.
|
|
13
|
+
*/
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.MICRO = exports.DEFAULT_BOOK_READERS = exports.readKalshiBookThroughDflow = exports.readKalshiBook = exports.readPolymarketBook = exports.BOOK_TIMEOUT_SECONDS = exports.BookUnavailable = exports.KALSHI_FRACTION_MICRO = exports.POLYMARKET_CLOB_URL = void 0;
|
|
16
|
+
exports.micros = micros;
|
|
17
|
+
exports.outcomesOf = outcomesOf;
|
|
18
|
+
exports.quoteFromContext = quoteFromContext;
|
|
19
|
+
const kalshi_js_1 = require("./kalshi.js");
|
|
20
|
+
const quote_math_js_1 = require("./quote-math.js");
|
|
21
|
+
Object.defineProperty(exports, "MICRO", { enumerable: true, get: function () { return quote_math_js_1.MICRO; } });
|
|
22
|
+
const version_js_1 = require("./version.js");
|
|
23
|
+
exports.POLYMARKET_CLOB_URL = "https://clob.polymarket.com";
|
|
24
|
+
/** Kalshi's smallest count where a market allows fractions: 0.01 contracts. */
|
|
25
|
+
exports.KALSHI_FRACTION_MICRO = 10_000;
|
|
26
|
+
/** A book reader could not read the book; message is the reason the quote names (venue_unreachable). */
|
|
27
|
+
class BookUnavailable extends Error {
|
|
28
|
+
constructor(message) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.name = "BookUnavailable";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
exports.BookUnavailable = BookUnavailable;
|
|
34
|
+
/**
|
|
35
|
+
* A decimal amount in millionths, exact when it has at most six decimals,
|
|
36
|
+
* otherwise rounded up or down. Strings are parsed exactly; a number goes
|
|
37
|
+
* through its shortest decimal form.
|
|
38
|
+
*/
|
|
39
|
+
function micros(value, up = false) {
|
|
40
|
+
const text = typeof value === "number" ? numberText(value) : value.trim();
|
|
41
|
+
const m = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(text);
|
|
42
|
+
if (!m || (m[2] === "" && (m[3] ?? "") === ""))
|
|
43
|
+
throw new Error(`not a number: ${JSON.stringify(value)}`);
|
|
44
|
+
const negative = m[1] === "-";
|
|
45
|
+
let digits = (m[2] ?? "") + (m[3] ?? "");
|
|
46
|
+
// The decimal point sits after point digits; exp moves it.
|
|
47
|
+
let point = (m[2] ?? "").length + Number(m[4] ?? 0) + 6;
|
|
48
|
+
if (point < 0) {
|
|
49
|
+
digits = "0".repeat(-point) + digits;
|
|
50
|
+
point = 0;
|
|
51
|
+
}
|
|
52
|
+
digits = digits.padEnd(point, "0");
|
|
53
|
+
const whole = BigInt(digits.slice(0, point) || "0");
|
|
54
|
+
const rest = digits.slice(point).replace(/0+$/, "");
|
|
55
|
+
let v = whole;
|
|
56
|
+
// Toward +infinity for up, -infinity otherwise.
|
|
57
|
+
if (rest !== "" && up !== negative)
|
|
58
|
+
v += 1n;
|
|
59
|
+
const out = Number(negative ? -v : v);
|
|
60
|
+
if (!Number.isSafeInteger(out))
|
|
61
|
+
throw new Error(`${JSON.stringify(value)} is past the safe integer range`);
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
function numberText(n) {
|
|
65
|
+
if (!Number.isFinite(n))
|
|
66
|
+
throw new Error(`not a finite number: ${n}`);
|
|
67
|
+
return String(n);
|
|
68
|
+
}
|
|
69
|
+
/** How long a book read may take, the request and its body, in seconds. */
|
|
70
|
+
exports.BOOK_TIMEOUT_SECONDS = 10;
|
|
71
|
+
/** A failed book request or body read, as the reason the quote names: a timeout by its seconds, anything else by its error. */
|
|
72
|
+
function fetchFailure(err) {
|
|
73
|
+
if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
|
|
74
|
+
return `clob.polymarket.com did not answer within ${exports.BOOK_TIMEOUT_SECONDS} s`;
|
|
75
|
+
}
|
|
76
|
+
return err instanceof Error ? `${err.name}: ${err.message}` : String(err);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The token's book from Polymarket's CLOB (GET /book?token_id=), the asks
|
|
80
|
+
* for a buy and the bids for a sell: levels as {"price", "size"} decimal
|
|
81
|
+
* strings, in dollars and contracts, as the CLOB's market channel sends them,
|
|
82
|
+
* and min_order_size in contracts. An ask's price rounds up and a bid's down
|
|
83
|
+
* past six decimals, and sizes down, so a quote never counts on more than the
|
|
84
|
+
* book holds.
|
|
85
|
+
*
|
|
86
|
+
* TODO(decision): the shape is the CLOB's book as the market channel's book
|
|
87
|
+
* event carries it (tape internal/venue/polymarket/live.go); the REST page
|
|
88
|
+
* could not be read on 14 Nov 2026 (docs.polymarket.com served an expired
|
|
89
|
+
* certificate). A staging recording of one /book reply confirms it, and shows
|
|
90
|
+
* whether the CLOB answers 404 for a token with no book (a closed market),
|
|
91
|
+
* which would then read as an empty book, not unreachable.
|
|
92
|
+
*/
|
|
93
|
+
const readPolymarketBook = async (request, fetchImpl) => {
|
|
94
|
+
const url = `${exports.POLYMARKET_CLOB_URL}/book?token_id=${encodeURIComponent(request.tokenId)}`;
|
|
95
|
+
let response;
|
|
96
|
+
try {
|
|
97
|
+
// A redirect is not followed: a block page reached through one is a
|
|
98
|
+
// status the check below names, as Python's client reports it.
|
|
99
|
+
response = await fetchImpl(url, {
|
|
100
|
+
method: "GET",
|
|
101
|
+
redirect: "manual",
|
|
102
|
+
headers: { "User-Agent": `skewtape-ts/${version_js_1.VERSION}` },
|
|
103
|
+
signal: AbortSignal.timeout(exports.BOOK_TIMEOUT_SECONDS * 1000),
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
throw new BookUnavailable(fetchFailure(err));
|
|
108
|
+
}
|
|
109
|
+
if (response.type === "opaqueredirect")
|
|
110
|
+
throw new BookUnavailable("clob.polymarket.com answered with a redirect");
|
|
111
|
+
if (response.status !== 200)
|
|
112
|
+
throw new BookUnavailable(`clob.polymarket.com answered HTTP ${response.status}`);
|
|
113
|
+
// The timeout covers the body read too, and is named as the request's is.
|
|
114
|
+
let text;
|
|
115
|
+
try {
|
|
116
|
+
text = await response.text();
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
throw new BookUnavailable(fetchFailure(err));
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const body = JSON.parse(text);
|
|
123
|
+
const raw = (request.side === "buy" ? body.asks : body.bids) ?? [];
|
|
124
|
+
const levels = [];
|
|
125
|
+
for (const l of raw) {
|
|
126
|
+
const size = micros(l.size);
|
|
127
|
+
if (size > 0)
|
|
128
|
+
levels.push({ price_micros: micros(l.price, request.side === "buy"), size_micro: size });
|
|
129
|
+
}
|
|
130
|
+
const min = body.min_order_size;
|
|
131
|
+
return { levels, min_size_micro: min === undefined || min === null || min === "" ? 0 : micros(min, true) };
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
throw new BookUnavailable(`clob.polymarket.com sent a book this version cannot read (${err instanceof Error ? err.message : String(err)})`);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
exports.readPolymarketBook = readPolymarketBook;
|
|
138
|
+
/**
|
|
139
|
+
* A kalshi member's book from Kalshi's public orderbook (GET
|
|
140
|
+
* /markets/{ticker}/orderbook, through kalshi.ts with no key, one try).
|
|
141
|
+
* Kalshi lists bids only, yes and no: a no bid at p is a yes ask at 1 - p.
|
|
142
|
+
* So a buy of yes takes the no bids at 1 - p (rounded up past six decimals)
|
|
143
|
+
* and a buy of no the yes bids at 1 - p; a sell of yes takes the yes bids
|
|
144
|
+
* and a sell of no the no bids (rounded down). Counts are rounded down to
|
|
145
|
+
* millionths.
|
|
146
|
+
*
|
|
147
|
+
* The size step: Kalshi counts in hundredths of a contract where a market
|
|
148
|
+
* allows fractions and in whole contracts elsewhere (docs.kalshi.com,
|
|
149
|
+
* fixed-point migration, 5 Nov 2026), and names no field that says which. A
|
|
150
|
+
* book with a fractional count on either side is taken as fractional (0.01);
|
|
151
|
+
* any other as whole contracts, so a quote never counts on a size the market
|
|
152
|
+
* may refuse. Kalshi documents no minimum order beyond that.
|
|
153
|
+
*/
|
|
154
|
+
const readKalshiBook = async (request, fetchImpl) => {
|
|
155
|
+
if (request.tokenId !== "yes" && request.tokenId !== "no") {
|
|
156
|
+
throw new BookUnavailable(`Kalshi's book has a yes and a no side, and the token is ${JSON.stringify(request.tokenId)}`);
|
|
157
|
+
}
|
|
158
|
+
let book;
|
|
159
|
+
try {
|
|
160
|
+
book = await new kalshi_js_1.Kalshi({ fetch: fetchImpl, maxRetries: 0, timeout: exports.BOOK_TIMEOUT_SECONDS }).orderbook(request.marketId);
|
|
161
|
+
}
|
|
162
|
+
catch (err) {
|
|
163
|
+
if (err instanceof kalshi_js_1.KalshiError)
|
|
164
|
+
throw new BookUnavailable(`Kalshi's orderbook for ${request.marketId}: ${err.message}`);
|
|
165
|
+
throw new BookUnavailable(err instanceof Error ? `${err.name}: ${err.message}` : String(err));
|
|
166
|
+
}
|
|
167
|
+
// kalshi.ts leaves out a row that is not [price, count]: here that is a
|
|
168
|
+
// book this version cannot read, not a thinner side, which would quietly
|
|
169
|
+
// move a quote to another venue.
|
|
170
|
+
const sides = book.raw.orderbook_fp;
|
|
171
|
+
for (const [side, parsed] of [
|
|
172
|
+
["yes_dollars", book.yes],
|
|
173
|
+
["no_dollars", book.no],
|
|
174
|
+
]) {
|
|
175
|
+
const rows = sides?.[side];
|
|
176
|
+
if (rows !== undefined && rows !== null && (!Array.isArray(rows) || rows.length !== parsed.length)) {
|
|
177
|
+
throw new BookUnavailable(`Kalshi sent a book this version cannot read (a row of ${side} is not [price, count])`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const [same, other] = request.tokenId === "yes" ? [book.yes, book.no] : [book.no, book.yes];
|
|
181
|
+
const buy = request.side === "buy";
|
|
182
|
+
try {
|
|
183
|
+
const levels = [];
|
|
184
|
+
for (const l of buy ? other : same) {
|
|
185
|
+
const size = micros(l.count_fp);
|
|
186
|
+
// floor and ceil of the price in millionths: 1 - p rounded up is
|
|
187
|
+
// MICRO - floor(p).
|
|
188
|
+
const lo = micros(l.price_dollars);
|
|
189
|
+
if (!(micros(l.price_dollars, true) > 0 && lo < quote_math_js_1.MICRO))
|
|
190
|
+
throw new Error(`price ${l.price_dollars} is outside (0, 1)`);
|
|
191
|
+
if (size > 0)
|
|
192
|
+
levels.push({ price_micros: buy ? quote_math_js_1.MICRO - lo : lo, size_micro: size });
|
|
193
|
+
}
|
|
194
|
+
const fractional = [...book.yes, ...book.no].some((l) => micros(l.count_fp) % quote_math_js_1.MICRO !== 0);
|
|
195
|
+
return { levels, size_step_micro: fractional ? exports.KALSHI_FRACTION_MICRO : quote_math_js_1.MICRO };
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
throw new BookUnavailable(`Kalshi sent a book this version cannot read (${err instanceof Error ? err.message : String(err)})`);
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
exports.readKalshiBook = readKalshiBook;
|
|
202
|
+
/**
|
|
203
|
+
* A kalshi_dflow member trades through DFlow (ADR-0016), whose orderbook
|
|
204
|
+
* needs DFlow access, not set up yet, so the member is left out with that
|
|
205
|
+
* reason, plainly; nothing reads the book another way. (A kalshi member is
|
|
206
|
+
* read from Kalshi's own book: readKalshiBook.)
|
|
207
|
+
*
|
|
208
|
+
* TODO(decision): DFlow's orderbook endpoint, its shape and the key it needs
|
|
209
|
+
* (production access is by request). Until then a caller can pass its own
|
|
210
|
+
* reader in bookReaders.
|
|
211
|
+
*/
|
|
212
|
+
const readKalshiBookThroughDflow = async () => {
|
|
213
|
+
throw new BookUnavailable("kalshi_dflow's book is read through DFlow's orderbook, and DFlow access is not set up yet");
|
|
214
|
+
};
|
|
215
|
+
exports.readKalshiBookThroughDflow = readKalshiBookThroughDflow;
|
|
216
|
+
exports.DEFAULT_BOOK_READERS = {
|
|
217
|
+
polymarket: exports.readPolymarketBook,
|
|
218
|
+
kalshi: exports.readKalshiBook,
|
|
219
|
+
kalshi_dflow: exports.readKalshiBookThroughDflow,
|
|
220
|
+
};
|
|
221
|
+
/** Each outcome's name (its label, or its token id when the market gives two outcomes the same label) to its token id. */
|
|
222
|
+
function names(member) {
|
|
223
|
+
const labels = member.tokens.map((o) => o.label);
|
|
224
|
+
const repeats = new Set(labels).size !== labels.length;
|
|
225
|
+
return new Map(member.tokens.map((o) => [repeats ? o.token_id : o.label, o.token_id]));
|
|
226
|
+
}
|
|
227
|
+
function tokenFor(member, outcome) {
|
|
228
|
+
const byName = names(member);
|
|
229
|
+
for (const [name, eventOutcome] of Object.entries(member.outcome_map)) {
|
|
230
|
+
if (eventOutcome === outcome && byName.has(name))
|
|
231
|
+
return byName.get(name);
|
|
232
|
+
}
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
function feeOf(member) {
|
|
236
|
+
const fee = member.fee;
|
|
237
|
+
if (!fee)
|
|
238
|
+
return null;
|
|
239
|
+
return { formula: fee.formula, rounding: fee.rounding, taker_params: { ...fee.taker_params }, min_fee_micros: fee.min_fee_micros ?? null };
|
|
240
|
+
}
|
|
241
|
+
/** The event's outcome names a quote can take, as the members' outcome maps name them. */
|
|
242
|
+
function outcomesOf(context) {
|
|
243
|
+
const seen = [];
|
|
244
|
+
for (const m of context.members)
|
|
245
|
+
for (const v of Object.values(m.outcome_map))
|
|
246
|
+
if (!seen.includes(v))
|
|
247
|
+
seen.push(v);
|
|
248
|
+
return seen;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* A quote on a context already read: each member's book read with its
|
|
252
|
+
* venue's reader (bookReaders first, then the defaults), then computeQuote.
|
|
253
|
+
* A member whose fee_status is blocked is left out without reading anything,
|
|
254
|
+
* and a rule mismatch is refused before any book is read.
|
|
255
|
+
*/
|
|
256
|
+
async function quoteFromContext(context, options) {
|
|
257
|
+
const { outcome, side } = options;
|
|
258
|
+
if (side !== "buy" && side !== "sell")
|
|
259
|
+
throw new quote_math_js_1.InvalidQuoteInputError(`side ${JSON.stringify(side)} is neither buy nor sell`);
|
|
260
|
+
let size;
|
|
261
|
+
try {
|
|
262
|
+
size = micros(options.size);
|
|
263
|
+
if (micros(options.size, true) !== size)
|
|
264
|
+
throw new Error(`size ${options.size} has more than six decimals`);
|
|
265
|
+
}
|
|
266
|
+
catch (err) {
|
|
267
|
+
throw new quote_math_js_1.InvalidQuoteInputError(err instanceof Error ? err.message : String(err));
|
|
268
|
+
}
|
|
269
|
+
const known = outcomesOf(context);
|
|
270
|
+
if (!known.includes(outcome))
|
|
271
|
+
throw new quote_math_js_1.InvalidQuoteInputError(`outcome ${JSON.stringify(outcome)} is not one of the event's: ${known.join(", ") || "none"}`);
|
|
272
|
+
// Before any book is read (ARCHITECTURE 13.1, step 2).
|
|
273
|
+
if (!context.resolution_equal && !options.allowRuleMismatch)
|
|
274
|
+
throw new quote_math_js_1.RuleMismatchError(context.rule_note);
|
|
275
|
+
const readers = { ...exports.DEFAULT_BOOK_READERS, ...(options.bookReaders ?? {}) };
|
|
276
|
+
const fetchImpl = options.venueFetch ?? fetch;
|
|
277
|
+
const members = await Promise.all(context.members.map(async (m) => {
|
|
278
|
+
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 };
|
|
279
|
+
if (m.fee_status === "blocked")
|
|
280
|
+
return { ...member, blocked: true };
|
|
281
|
+
const token = tokenFor(m, outcome);
|
|
282
|
+
if (token === undefined)
|
|
283
|
+
return { ...member, unreachable: `no token of the market maps to ${JSON.stringify(outcome)}` };
|
|
284
|
+
member.token_id = token;
|
|
285
|
+
const reader = readers[m.venue];
|
|
286
|
+
if (!reader)
|
|
287
|
+
return { ...member, unreachable: `sk.quote has no book reader for ${m.venue}; pass one in bookReaders` };
|
|
288
|
+
try {
|
|
289
|
+
member.book = await reader({ venue: m.venue, marketId: m.market_id, tokenId: token, side }, fetchImpl);
|
|
290
|
+
}
|
|
291
|
+
catch (err) {
|
|
292
|
+
if (!(err instanceof BookUnavailable))
|
|
293
|
+
throw err;
|
|
294
|
+
member.unreachable = err.message || "the book could not be read";
|
|
295
|
+
}
|
|
296
|
+
return member;
|
|
297
|
+
}));
|
|
298
|
+
return (0, quote_math_js_1.computeQuote)({
|
|
299
|
+
event_id: context.event_id,
|
|
300
|
+
side,
|
|
301
|
+
size_micro: size,
|
|
302
|
+
resolution_equal: context.resolution_equal,
|
|
303
|
+
rule_note: context.rule_note,
|
|
304
|
+
allow_rule_mismatch: options.allowRuleMismatch ?? false,
|
|
305
|
+
members,
|
|
306
|
+
});
|
|
307
|
+
}
|
|
@@ -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 {};
|