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,507 @@
1
+ /**
2
+ * sk.route: an unsigned order for the developer to sign and submit (F2,
3
+ * ADR-0016, ARCHITECTURE 13.3).
4
+ *
5
+ * route() builds and checks an order, and stops there: it never signs, never
6
+ * sends, never takes a private key, and needs no Skewtape key. Every code and
7
+ * fee it carries is the developer's own: the Polymarket builder code, the
8
+ * DFlow fee account and fee. Omitting them sends none, and no Skewtape value
9
+ * exists in this package (a test scans it). The developer is responsible for
10
+ * their users: who may trade where, and under which terms (sk.geoblock helps
11
+ * with Polymarket's).
12
+ *
13
+ * const order = route({
14
+ * venue: "polymarket", exchange: "ctf", tokenId: "7132...", side: "BUY",
15
+ * price: "0.52", size: "10", tickSize: "0.01", maker: "0xYourAddress",
16
+ * builder: "0xYourBuilderCode", // optional, yours
17
+ * });
18
+ * const signature = await walletClient.signTypedData(order.typedData);
19
+ * const body = order.postBody(signature, yourClobApiKeyId);
20
+ */
21
+ import { RouteError } from "./errors.js";
22
+ import { HYPERLIQUID_FIELDS, hyperliquidOrder } from "./route-hyperliquid.js";
23
+ export { RouteError };
24
+ /** A table's own entry for key, never one inherited from Object.prototype ("toString", "constructor"). */
25
+ function own(table, key) {
26
+ return typeof key === "string" && Object.hasOwn(table, key) ? table[key] : undefined;
27
+ }
28
+ const pow10 = (k) => 10n ** BigInt(k);
29
+ function parseDec(name, value) {
30
+ if (typeof value !== "string") {
31
+ throw new RouteError(`${name}: pass a decimal string such as "0.52" (a number is a float, not exact)`);
32
+ }
33
+ const m = /^(\d+)(?:\.(\d+))?$/.exec(value.trim());
34
+ if (!m)
35
+ throw new RouteError(`${name}: ${JSON.stringify(value)} is not a non-negative decimal`);
36
+ const frac = m[2] ?? "";
37
+ return { n: BigInt((m[1] ?? "") + frac), s: frac.length };
38
+ }
39
+ function normalize(d) {
40
+ let { n, s } = d;
41
+ while (s > 0 && n % 10n === 0n) {
42
+ n /= 10n;
43
+ s -= 1;
44
+ }
45
+ return { n, s };
46
+ }
47
+ const places = (d) => normalize(d).s;
48
+ const cmp = (a, b) => {
49
+ const x = a.n * pow10(b.s);
50
+ const y = b.n * pow10(a.s);
51
+ return x < y ? -1 : x > y ? 1 : 0;
52
+ };
53
+ const mul = (a, b) => ({ n: a.n * b.n, s: a.s + b.s });
54
+ const sub = (a, b) => {
55
+ const s = Math.max(a.s, b.s);
56
+ return { n: a.n * pow10(s - a.s) - b.n * pow10(s - b.s), s };
57
+ };
58
+ function roundDown(d, p) {
59
+ return d.s <= p ? { n: d.n * pow10(p - d.s), s: p } : { n: d.n / pow10(d.s - p), s: p };
60
+ }
61
+ function roundUp(d, p) {
62
+ if (d.s <= p)
63
+ return { n: d.n * pow10(p - d.s), s: p };
64
+ const q = pow10(d.s - p);
65
+ return { n: (d.n + q - 1n) / q, s: p };
66
+ }
67
+ /** a / b rounded up to p places, exactly. */
68
+ function divUp(a, b, p) {
69
+ const num = a.n * pow10(b.s + p);
70
+ const den = b.n * pow10(a.s);
71
+ return { n: (num + den - 1n) / den, s: p };
72
+ }
73
+ const toString = (d) => {
74
+ const x = normalize(d);
75
+ const str = x.n.toString().padStart(x.s + 1, "0");
76
+ return x.s ? `${str.slice(0, -x.s)}.${str.slice(-x.s)}` : str;
77
+ };
78
+ // --- Polymarket ---------------------------------------------------------------
79
+ /**
80
+ * The V2 order the exchange hashes (Polymarket/ctf-exchange-v2 @ 5c65f2d,
81
+ * src/exchange/libraries/Structs.sol,
82
+ * ORDER_TYPEHASH 0xbb86318a...818589), the same type
83
+ * docs.polymarket.com/trading/place-orders.md gives. `signature` is not
84
+ * hashed, and `expiration` is not part of the order: it rides in the POST body.
85
+ */
86
+ export const POLYMARKET_ORDER_TYPE = [
87
+ { name: "salt", type: "uint256" },
88
+ { name: "maker", type: "address" },
89
+ { name: "signer", type: "address" },
90
+ { name: "tokenId", type: "uint256" },
91
+ { name: "makerAmount", type: "uint256" },
92
+ { name: "takerAmount", type: "uint256" },
93
+ { name: "side", type: "uint8" },
94
+ { name: "signatureType", type: "uint8" },
95
+ { name: "timestamp", type: "uint256" },
96
+ { name: "metadata", type: "bytes32" },
97
+ { name: "builder", type: "bytes32" },
98
+ ];
99
+ export const EIP712_DOMAIN_TYPE = [
100
+ { name: "name", type: "string" },
101
+ { name: "version", type: "string" },
102
+ { name: "chainId", type: "uint256" },
103
+ { name: "verifyingContract", type: "address" },
104
+ ];
105
+ export const POLYMARKET_DOMAIN_NAME = "Polymarket CTF Exchange";
106
+ export const POLYGON_CHAIN_ID = 137;
107
+ /**
108
+ * The exchange that verifies the order, and its domain version, by book
109
+ * (place-orders.md, "Create the Order Typed Data"; addresses also on
110
+ * docs.polymarket.com/resources/contracts.md, Polygon 137): the CTF exchange
111
+ * and the neg risk CTF exchange sign with version "2", a Protocol V2 book
112
+ * ("version": "v2" in the market's data, ExchangeV3) with "3". The developer
113
+ * names it: route() never guesses which book a token trades on.
114
+ */
115
+ export const POLYMARKET_EXCHANGES = {
116
+ ctf: { version: "2", verifyingContract: "0xE111180000d2663C0091e4f400237545B87B996B" },
117
+ neg_risk: { version: "2", verifyingContract: "0xe2222d279d744050d28e00520010520000310F59" },
118
+ protocol_v2: { version: "3", verifyingContract: "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa" },
119
+ };
120
+ /** Side and SignatureType (Structs.sol): BUY 0, SELL 1; EOA 0, POLY_PROXY 1, POLY_GNOSIS_SAFE 2, POLY_1271 3. */
121
+ export const POLYMARKET_SIDES = { BUY: 0, SELL: 1 };
122
+ export const POLYMARKET_SIGNATURE_TYPES = { EOA: 0, POLY_PROXY: 1, POLY_GNOSIS_SAFE: 2, POLY_1271: 3 };
123
+ const ORDER_TYPES = ["GTC", "GTD", "FOK", "FAK"];
124
+ /** Price, size and amount decimals by tick size (place-orders.md, "Rounding"). */
125
+ export const POLYMARKET_TICKS = {
126
+ "0.1": [1, 2, 3],
127
+ "0.01": [2, 2, 4],
128
+ "0.005": [3, 2, 5],
129
+ "0.0025": [4, 2, 6],
130
+ "0.001": [3, 2, 5],
131
+ "0.0001": [4, 2, 6],
132
+ };
133
+ /** Six-decimal base units: "1_000_000 is one pUSD or one share" (migrate/polymarket-v2/contract-integrations.md). */
134
+ export const POLYMARKET_DECIMALS = 6;
135
+ /** A size or amount (shares or USD) at or above 10^15 is refused, as in the Python SDK, which needs the bound for its decimal context. */
136
+ export const POLYMARKET_MAX_SIZE = 10n ** 15n;
137
+ function sized(name, value) {
138
+ const d = parseDec(name, value);
139
+ if (cmp(d, { n: POLYMARKET_MAX_SIZE, s: 0 }) >= 0)
140
+ throw new RouteError(`${name}: below 10^15, not ${value}`);
141
+ return d;
142
+ }
143
+ /** A GTD order's expiration is Unix seconds at least three minutes ahead (place-orders.md). */
144
+ export const POLYMARKET_GTD_MIN_SECONDS = 180;
145
+ export const MAX_SAFE_SALT = 2 ** 53 - 1;
146
+ export const ZERO_BYTES32 = `0x${"00".repeat(32)}`;
147
+ const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
148
+ const BYTES32 = /^0x[0-9a-fA-F]{64}$/;
149
+ const SIGNATURE = /^0x[0-9a-fA-F]{130}$/;
150
+ function address(name, value) {
151
+ if (typeof value !== "string" || !ADDRESS.test(value)) {
152
+ throw new RouteError(`${name}: ${JSON.stringify(value)} is not a 0x-prefixed 20-byte address`);
153
+ }
154
+ return value;
155
+ }
156
+ function bytes32(name, value) {
157
+ if (typeof value !== "string" || !BYTES32.test(value)) {
158
+ throw new RouteError(`${name}: ${JSON.stringify(value)} is not a 0x-prefixed 32-byte hex value`);
159
+ }
160
+ return value;
161
+ }
162
+ function wholeNumber(name, value, max) {
163
+ if (typeof value === "bigint") {
164
+ if (value < 0n || value > max)
165
+ throw new RouteError(`${name}: out of range`);
166
+ return value;
167
+ }
168
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && BigInt(value) <= max)
169
+ return BigInt(value);
170
+ throw new RouteError(`${name}: an integer from 0 to ${max}`);
171
+ }
172
+ /** The docs' third rounding step: a USD amount with more than the amount decimals is rounded up to amount + 4, then down to amount. */
173
+ function usd(d, amountDecimals) {
174
+ if (places(d) > amountDecimals) {
175
+ d = roundUp(d, amountDecimals + 4);
176
+ if (places(d) > amountDecimals)
177
+ d = roundDown(d, amountDecimals);
178
+ }
179
+ return d;
180
+ }
181
+ const units = (d) => roundDown(d, POLYMARKET_DECIMALS).n;
182
+ /**
183
+ * makerAmount and takerAmount in six-decimal units, by the docs' rounding: a
184
+ * BUY gives USD and takes shares, a SELL the reverse. A limit order (GTC, GTD)
185
+ * and a market SELL (FOK, FAK) are sized in shares; a market BUY in USD to
186
+ * spend, at most `price` a share.
187
+ */
188
+ export function polymarketAmounts(side, price, tickSize, orderType, sizing) {
189
+ const tick = own(POLYMARKET_TICKS, tickSize);
190
+ if (!tick)
191
+ throw new RouteError(`tickSize: one of ${Object.keys(POLYMARKET_TICKS).join(", ")}, the book's tick size`);
192
+ const [, sizeDec, amountDec] = tick;
193
+ const p = parseDec("price", price);
194
+ if (orderType === "FOK" || orderType === "FAK" ? side === "BUY" : false) {
195
+ if (sizing.amount === undefined || sizing.size !== undefined) {
196
+ throw new RouteError("a market BUY (FOK, FAK) is sized by amount, the USD to spend, not size");
197
+ }
198
+ const maker = roundDown(sized("amount", sizing.amount), sizeDec);
199
+ if (maker.n === 0n)
200
+ throw new RouteError(`amount ${sizing.amount} rounds to nothing at ${sizeDec} decimals`);
201
+ // maker / price, rounded up past the +4 decimals the docs round at, then by usd().
202
+ const taker = usd(divUp(maker, p, amountDec + 8), amountDec);
203
+ return { makerAmount: units(maker), takerAmount: units(taker) };
204
+ }
205
+ if (sizing.size === undefined || sizing.amount !== undefined) {
206
+ throw new RouteError("this order is sized by size, the shares; amount is for a market BUY only");
207
+ }
208
+ const shares = roundDown(sized("size", sizing.size), sizeDec);
209
+ if (shares.n === 0n)
210
+ throw new RouteError(`size ${sizing.size} rounds to nothing at ${sizeDec} decimals`);
211
+ const value = usd(mul(shares, p), amountDec);
212
+ return side === "BUY"
213
+ ? { makerAmount: units(value), takerAmount: units(shares) }
214
+ : { makerAmount: units(shares), takerAmount: units(value) };
215
+ }
216
+ /**
217
+ * An unsigned Polymarket V2 order. Sign `typedData` (EIP-712, the `Order`
218
+ * primary type) with the signer's wallet, then post `postBody(signature,
219
+ * owner)` to the CLOB's POST /order with your own CLOB credentials. Nothing
220
+ * here was signed or sent.
221
+ */
222
+ export class PolymarketOrder {
223
+ typedData;
224
+ orderType;
225
+ expiration;
226
+ side;
227
+ venue = "polymarket";
228
+ constructor(typedData, orderType,
229
+ /** Unix seconds for a GTD order, 0 otherwise; not signed. */
230
+ expiration, side) {
231
+ this.typedData = typedData;
232
+ this.orderType = orderType;
233
+ this.expiration = expiration;
234
+ this.side = side;
235
+ }
236
+ /** The typed data as eth_signTypedData_v4 takes it: JSON, the EIP712Domain type included, integers as decimal strings. */
237
+ typedDataJson() {
238
+ const { domain, message } = this.typedData;
239
+ return JSON.stringify({
240
+ types: { EIP712Domain: EIP712_DOMAIN_TYPE, Order: POLYMARKET_ORDER_TYPE },
241
+ primaryType: "Order",
242
+ domain,
243
+ message: Object.fromEntries(Object.entries(message).map(([k, v]) => [k, typeof v === "bigint" ? v.toString() : v])),
244
+ });
245
+ }
246
+ /**
247
+ * The JSON body of POST /order (place-orders.md): the order with its
248
+ * signature, amounts and timestamp as strings, the salt a number, the side a
249
+ * word; `owner` is your CLOB API key's id. orderType and expiration are not
250
+ * part of what was signed.
251
+ */
252
+ postBody(signature, owner, options = {}) {
253
+ if (typeof signature !== "string" || !SIGNATURE.test(signature)) {
254
+ throw new RouteError("signature: a 0x-prefixed 65-byte signature over typedData");
255
+ }
256
+ if (typeof owner !== "string" || !owner)
257
+ throw new RouteError("owner: your CLOB API key's id");
258
+ const m = this.typedData.message;
259
+ const body = {
260
+ deferExec: options.deferExec ?? false,
261
+ order: {
262
+ builder: m.builder,
263
+ expiration: String(this.expiration),
264
+ maker: m.maker,
265
+ makerAmount: m.makerAmount.toString(),
266
+ metadata: m.metadata,
267
+ salt: Number(m.salt),
268
+ side: this.side,
269
+ signature,
270
+ signatureType: m.signatureType,
271
+ signer: m.signer,
272
+ takerAmount: m.takerAmount.toString(),
273
+ timestamp: m.timestamp.toString(),
274
+ tokenId: m.tokenId.toString(),
275
+ },
276
+ orderType: this.orderType,
277
+ owner,
278
+ };
279
+ if (options.postOnly !== undefined)
280
+ body.postOnly = options.postOnly;
281
+ return body;
282
+ }
283
+ }
284
+ /** The fields each venue's order takes: anything else, a private key above all, is refused. */
285
+ export const ROUTE_FIELDS = {
286
+ polymarket: [
287
+ "venue", "exchange", "tokenId", "side", "price", "tickSize", "maker", "size", "amount", "orderType",
288
+ "signatureType", "signer", "builder", "metadata", "expiration", "salt", "timestampMs",
289
+ ],
290
+ kalshi_dflow: [
291
+ "venue", "inputMint", "outputMint", "amount", "userPublicKey", "slippageBps", "predictionMarketSlippageBps",
292
+ "platformFeeScale", "platformFeeBps", "platformFeeMode", "feeAccount", "baseUrl",
293
+ ],
294
+ hyperliquid: HYPERLIQUID_FIELDS,
295
+ };
296
+ function onlyFields(venue, input) {
297
+ const known = ROUTE_FIELDS[venue];
298
+ const unknown = Object.keys(input).filter((k) => !known.includes(k));
299
+ if (unknown.length)
300
+ throw new RouteError(`${venue}: unknown field ${unknown.join(", ")}; route() takes no key and nothing else`);
301
+ }
302
+ function randomSalt() {
303
+ const words = new Uint32Array(2);
304
+ globalThis.crypto.getRandomValues(words);
305
+ return ((BigInt(words[0] ?? 0) & 0x1fffffn) << 32n) | BigInt(words[1] ?? 0);
306
+ }
307
+ export function polymarketOrder(input) {
308
+ onlyFields("polymarket", input);
309
+ const ex = own(POLYMARKET_EXCHANGES, input.exchange);
310
+ if (!ex)
311
+ throw new RouteError(`exchange: one of ${Object.keys(POLYMARKET_EXCHANGES).join(", ")}, the book's exchange (no default)`);
312
+ const side = typeof input.side === "string" ? input.side.toUpperCase() : input.side;
313
+ if (side !== "BUY" && side !== "SELL")
314
+ throw new RouteError("side: BUY or SELL");
315
+ const orderType = input.orderType ?? "GTC";
316
+ if (!ORDER_TYPES.includes(orderType))
317
+ throw new RouteError(`orderType: one of ${ORDER_TYPES.join(", ")}`);
318
+ const tick = own(POLYMARKET_TICKS, input.tickSize);
319
+ if (!tick)
320
+ throw new RouteError(`tickSize: one of ${Object.keys(POLYMARKET_TICKS).join(", ")}, the book's tick size`);
321
+ const tickDec = parseDec("tickSize", input.tickSize);
322
+ const price = parseDec("price", input.price);
323
+ const one = { n: 1n, s: 0 };
324
+ // On the tick: price / tick is a whole number.
325
+ const onTick = (price.n * pow10(tickDec.s)) % (tickDec.n * pow10(price.s)) === 0n;
326
+ if (!onTick || cmp(price, tickDec) < 0 || cmp(price, sub(one, tickDec)) > 0) {
327
+ throw new RouteError(`price ${input.price} is not on the ${input.tickSize} tick between ${input.tickSize} and ${toString(sub(one, tickDec))}`);
328
+ }
329
+ const { makerAmount, takerAmount } = polymarketAmounts(side, input.price, input.tickSize, orderType, { size: input.size, amount: input.amount });
330
+ const sigInput = input.signatureType ?? "EOA";
331
+ const sigType = typeof sigInput === "string" ? POLYMARKET_SIGNATURE_TYPES[sigInput] : sigInput;
332
+ if (sigType !== 0 && sigType !== 1 && sigType !== 2 && sigType !== 3) {
333
+ throw new RouteError(`signatureType: one of ${Object.keys(POLYMARKET_SIGNATURE_TYPES).join(", ")} or 0 to 3`);
334
+ }
335
+ if (sigType === 3) {
336
+ throw new RouteError("signatureType POLY_1271 (a Deposit Wallet): its order is signed as an ERC-7739 TypedDataSign wrapper, which route() does not build; sign it with Polymarket's own client");
337
+ }
338
+ const maker = address("maker", input.maker);
339
+ let signer;
340
+ if (input.signer === undefined) {
341
+ if (sigType !== 0)
342
+ throw new RouteError("signer: the address that owns the proxy or Safe and signs (required unless EOA)");
343
+ signer = maker;
344
+ }
345
+ else {
346
+ signer = address("signer", input.signer);
347
+ }
348
+ if (sigType === 0 && signer.toLowerCase() !== maker.toLowerCase()) {
349
+ throw new RouteError("an EOA order is signed by its maker: signer must equal maker");
350
+ }
351
+ const token = typeof input.tokenId === "bigint" ? input.tokenId.toString() : input.tokenId;
352
+ if (typeof token !== "string" || !/^\d+$/.test(token) || BigInt(token) >= 2n ** 256n) {
353
+ throw new RouteError("tokenId: the outcome's asset id, a decimal uint256");
354
+ }
355
+ const builder = input.builder === undefined ? ZERO_BYTES32 : bytes32("builder", input.builder);
356
+ const metadata = input.metadata === undefined ? ZERO_BYTES32 : bytes32("metadata", input.metadata);
357
+ const ts = input.timestampMs ?? Date.now();
358
+ if (!Number.isSafeInteger(ts) || ts <= 0)
359
+ throw new RouteError("timestampMs: Unix milliseconds");
360
+ let expiration = 0;
361
+ if (orderType === "GTD") {
362
+ if (!Number.isSafeInteger(input.expiration) || (input.expiration ?? 0) < Math.floor(ts / 1000) + POLYMARKET_GTD_MIN_SECONDS) {
363
+ throw new RouteError("expiration: a GTD order's Unix seconds, at least three minutes after the order's timestamp");
364
+ }
365
+ expiration = input.expiration;
366
+ }
367
+ else if (input.expiration !== undefined && input.expiration !== 0) {
368
+ throw new RouteError(`expiration: only a GTD order has one; a ${orderType} order sends 0`);
369
+ }
370
+ const salt = input.salt === undefined ? randomSalt() : wholeNumber("salt", input.salt, BigInt(MAX_SAFE_SALT));
371
+ return new PolymarketOrder({
372
+ domain: { name: POLYMARKET_DOMAIN_NAME, version: ex.version, chainId: POLYGON_CHAIN_ID, verifyingContract: ex.verifyingContract },
373
+ types: { Order: POLYMARKET_ORDER_TYPE },
374
+ primaryType: "Order",
375
+ message: {
376
+ salt,
377
+ maker,
378
+ signer,
379
+ tokenId: BigInt(token),
380
+ makerAmount,
381
+ takerAmount,
382
+ side: POLYMARKET_SIDES[side],
383
+ signatureType: sigType,
384
+ timestamp: BigInt(ts),
385
+ metadata,
386
+ builder,
387
+ },
388
+ }, orderType, expiration, side);
389
+ }
390
+ // --- DFlow --------------------------------------------------------------------
391
+ /**
392
+ * The Trading API that returns the unsigned transaction: GET /order on
393
+ * https://quote-api.dflow.net (pond.dflow.net/get-started/endpoints.md), with
394
+ * the developer's own key in the x-api-key header ("All calls to the
395
+ * production endpoints must use an API key", pond.dflow.net/get-started/api-key.md).
396
+ */
397
+ export const DFLOW_TRADING_API = "https://quote-api.dflow.net";
398
+ export const DFLOW_API_KEY_HEADER = "x-api-key";
399
+ /**
400
+ * platformFeeScale: "Optional platform fee scale for World prediction market
401
+ * swaps and async prediction market swaps, with 3 decimals ... Must be >= 0 and
402
+ * < 1000. For example, a value of 50 means 0.050." platformFeeBps: a fixed fee
403
+ * in basis points, for spot trades (pond.dflow.net/spot/trading/platform-fees.md).
404
+ */
405
+ export const DFLOW_FEE_SCALE_MAX = 999;
406
+ export const DFLOW_FEE_BPS_MAX = 10_000;
407
+ const DFLOW_FEE_MODES = ["outputMint", "inputMint"];
408
+ const BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
409
+ function solanaAddress(name, value) {
410
+ if (typeof value !== "string" || value.length < 32 || value.length > 44 || [...value].some((c) => !BASE58.includes(c))) {
411
+ throw new RouteError(`${name}: ${JSON.stringify(value)} is not a base58 Solana address`);
412
+ }
413
+ let n = 0n;
414
+ for (const c of value)
415
+ n = n * 58n + BigInt(BASE58.indexOf(c));
416
+ let bytes = n === 0n ? 0 : Math.ceil(n.toString(16).length / 2);
417
+ bytes += value.length - value.replace(/^1+/, "").length;
418
+ if (bytes !== 32)
419
+ throw new RouteError(`${name}: ${JSON.stringify(value)} does not decode to 32 bytes`);
420
+ return value;
421
+ }
422
+ /**
423
+ * The request that returns an unsigned DFlow transaction: GET `url` with
424
+ * `params` and your own DFlow key in the x-api-key header. The response's
425
+ * `transaction` (base64) is for your user to sign and submit. Nothing was
426
+ * sent: route() never calls DFlow.
427
+ */
428
+ export class DFlowOrderRequest {
429
+ url;
430
+ params;
431
+ venue = "kalshi_dflow";
432
+ apiKeyHeader = DFLOW_API_KEY_HEADER;
433
+ constructor(url, params) {
434
+ this.url = url;
435
+ this.params = params;
436
+ }
437
+ get fullUrl() {
438
+ return `${this.url}?${new URLSearchParams(this.params).toString()}`;
439
+ }
440
+ }
441
+ function intIn(name, value, max) {
442
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > max) {
443
+ throw new RouteError(`${name}: an integer from 0 to ${max}`);
444
+ }
445
+ return value;
446
+ }
447
+ export function dflowOrder(input) {
448
+ onlyFields("kalshi_dflow", input);
449
+ const params = {
450
+ inputMint: solanaAddress("inputMint", input.inputMint),
451
+ outputMint: solanaAddress("outputMint", input.outputMint),
452
+ };
453
+ const amount = input.amount;
454
+ if (!(typeof amount === "bigint" ? amount > 0n : Number.isSafeInteger(amount) && amount > 0)) {
455
+ throw new RouteError("amount: a positive integer, in the input mint's base units");
456
+ }
457
+ params.amount = amount.toString();
458
+ params.userPublicKey = solanaAddress("userPublicKey", input.userPublicKey);
459
+ if (input.slippageBps !== undefined) {
460
+ if (input.slippageBps !== "auto")
461
+ intIn('slippageBps (or "auto")', input.slippageBps, 65535);
462
+ params.slippageBps = String(input.slippageBps);
463
+ }
464
+ if (input.predictionMarketSlippageBps !== undefined) {
465
+ params.predictionMarketSlippageBps = String(intIn("predictionMarketSlippageBps", input.predictionMarketSlippageBps, 65535));
466
+ }
467
+ if (input.platformFeeScale !== undefined && input.platformFeeBps !== undefined) {
468
+ throw new RouteError("platformFeeScale (a prediction market swap) or platformFeeBps (spot), not both");
469
+ }
470
+ let fee = 0;
471
+ if (input.platformFeeScale !== undefined) {
472
+ fee = intIn("platformFeeScale (in thousandths, 50 is 0.050)", input.platformFeeScale, DFLOW_FEE_SCALE_MAX);
473
+ if (fee)
474
+ params.platformFeeScale = String(fee);
475
+ }
476
+ if (input.platformFeeBps !== undefined) {
477
+ fee = intIn("platformFeeBps", input.platformFeeBps, DFLOW_FEE_BPS_MAX);
478
+ if (fee)
479
+ params.platformFeeBps = String(fee);
480
+ }
481
+ if (fee && input.feeAccount === undefined) {
482
+ throw new RouteError("feeAccount: your token account for the fee mint; DFlow requires it with a fee");
483
+ }
484
+ if (!fee && input.feeAccount !== undefined) {
485
+ throw new RouteError("feeAccount without a fee: DFlow collects nothing, so send neither");
486
+ }
487
+ if (input.feeAccount !== undefined)
488
+ params.feeAccount = solanaAddress("feeAccount", input.feeAccount);
489
+ if (input.platformFeeMode !== undefined) {
490
+ if (!DFLOW_FEE_MODES.includes(input.platformFeeMode))
491
+ throw new RouteError(`platformFeeMode: one of ${DFLOW_FEE_MODES.join(", ")}`);
492
+ params.platformFeeMode = input.platformFeeMode;
493
+ }
494
+ const base = input.baseUrl ?? DFLOW_TRADING_API;
495
+ if (typeof base !== "string" || !base.startsWith("https://"))
496
+ throw new RouteError("baseUrl: an https URL of DFlow's Trading API");
497
+ return new DFlowOrderRequest(`${base.replace(/\/+$/, "")}/order`, params);
498
+ }
499
+ export function route(order) {
500
+ if (order.venue === "polymarket")
501
+ return polymarketOrder(order);
502
+ if (order.venue === "kalshi_dflow")
503
+ return dflowOrder(order);
504
+ if (order.venue === "hyperliquid")
505
+ return hyperliquidOrder(order);
506
+ throw new RouteError(`venue: one of ${Object.keys(ROUTE_FIELDS).join(", ")}`);
507
+ }
@@ -0,0 +1,99 @@
1
+ export declare const FEED_PATH = "/v1/feed";
2
+ /** A server message, as docs/public/feed.md gives it. */
3
+ export type FeedMessage = {
4
+ op: string;
5
+ [field: string]: unknown;
6
+ };
7
+ /**
8
+ * What the stream needs of a WebSocket: the WHATWG interface. The handlers'
9
+ * events are typed loosely so the platform's WebSocket and the ws package's
10
+ * both fit as they are; the stream reads data, code and reason alone.
11
+ */
12
+ export interface FeedSocket {
13
+ send(data: string): void;
14
+ close(code?: number, reason?: string): void;
15
+ onopen: ((ev: any) => void) | null;
16
+ onmessage: ((ev: any) => void) | null;
17
+ onclose: ((ev: any) => void) | null;
18
+ onerror: ((ev: any) => void) | null;
19
+ }
20
+ export type FeedSocketConstructor = new (url: string) => FeedSocket;
21
+ export interface StreamOptions {
22
+ topics: string[];
23
+ venues?: string[];
24
+ markets?: {
25
+ venue: string;
26
+ market_id: string;
27
+ }[];
28
+ events?: string[];
29
+ /** A seq kept earlier: the feed replays the events after it. */
30
+ resumeFrom?: number;
31
+ /** Failed connections in a row before the stream gives up; none by default. */
32
+ maxReconnects?: number;
33
+ /** A WebSocket constructor, where the platform has none (Node 20). */
34
+ WebSocket?: FeedSocketConstructor;
35
+ }
36
+ /** Messages received and not yet taken by the loop, at most. */
37
+ export declare const MAX_BUFFERED = 10000;
38
+ /** How many trade identities are remembered. */
39
+ export declare const DEDUPE_TRADES = 100000;
40
+ /** The feed's WebSocket URL for an API base URL: https to wss, http to ws. */
41
+ export declare function feedUrl(baseUrl: string): string;
42
+ /** One subscription to the live feed, across as many connections as it takes. */
43
+ export declare class Stream implements AsyncIterable<FeedMessage> {
44
+ #private;
45
+ readonly url: string;
46
+ /** A sleep for tests; none is a timer close() clears. */
47
+ private readonly sleep?;
48
+ private readonly jitter;
49
+ private readonly now;
50
+ /** The seq of the last event yielded, or the resumeFrom given. */
51
+ lastSeq: number | undefined;
52
+ hello: FeedMessage | undefined;
53
+ subscribed: FeedMessage | undefined;
54
+ private readonly subscription;
55
+ private readonly seen;
56
+ private socket;
57
+ private closed;
58
+ private wake;
59
+ /** Where to resume when no event was yielded since: the first hello's seq, raised by a close reason's or a resync's. */
60
+ private floor;
61
+ private failures;
62
+ /** A connection of this stream was subscribed once: a connection limit after it may be its own moved connection. */
63
+ private worked;
64
+ private limitedSince;
65
+ private readonly closedSignal;
66
+ /** Ends the timer of a wait in progress (pause), at once. */
67
+ private endPause;
68
+ private signalClosed;
69
+ constructor(url: string, apiKey: string, options: StreamOptions,
70
+ /** A sleep for tests; none is a timer close() clears. */
71
+ sleep?: ((seconds: number) => Promise<void>) | undefined, jitter?: () => number, now?: () => number);
72
+ private readonly WS;
73
+ private readonly maxReconnects;
74
+ /** Ends the stream: the connection closes, a wait ends, and iteration stops. */
75
+ close(): void;
76
+ [Symbol.asyncIterator](): AsyncIterator<FeedMessage>;
77
+ /**
78
+ * Waits seconds, or less when close() runs. With no sleep given, the wait
79
+ * is a timer close() clears, so a closed stream keeps no timer pending
80
+ * and the process can exit.
81
+ */
82
+ private pause;
83
+ private push;
84
+ private next;
85
+ private wait;
86
+ /**
87
+ * Where the stream would resume: the last seq yielded, or its position
88
+ * before its first event or past a resync, the later of the two. Keep
89
+ * this one, not lastSeq, to go on later with sk.stream({ ..., resumeFrom }).
90
+ */
91
+ get resumeFrom(): number | undefined;
92
+ private raiseFloor;
93
+ /** Whether a connection limit is tried again: on a reconnect, for LIMIT_RETRY after the first refusal. */
94
+ private limitRetry;
95
+ private sendSubscribe;
96
+ private session;
97
+ private event;
98
+ private remember;
99
+ }