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,376 @@
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 { RouteError } from "./errors.js";
34
+ import { keccak256, toHex } from "./keccak.js";
35
+ import { packb } from "./msgpack.js";
36
+ /** Endpoints the developer posts to ("Exchange endpoint"); route never calls them. */
37
+ export const HYPERLIQUID_EXCHANGE_URL = "https://api.hyperliquid.xyz/exchange";
38
+ export const HYPERLIQUID_TESTNET_EXCHANGE_URL = "https://api.hyperliquid-testnet.xyz/exchange";
39
+ /** "Outcome asset ID: 100_000_000 + encoding", encoding = 10 * outcome + side (api/asset-ids). */
40
+ export const HYPERLIQUID_OUTCOME_ASSET_BASE = 100_000_000;
41
+ /** The L1 action's EIP-712 domain and type (signing.py, l1_payload). */
42
+ export const HYPERLIQUID_L1_DOMAIN = {
43
+ name: "Exchange",
44
+ version: "1",
45
+ chainId: 1337,
46
+ verifyingContract: "0x0000000000000000000000000000000000000000",
47
+ };
48
+ export const HYPERLIQUID_AGENT_TYPE = [
49
+ { name: "source", type: "string" },
50
+ { name: "connectionId", type: "bytes32" },
51
+ ];
52
+ /** Time in force: "Alo" adds liquidity only, "Ioc" takes what crosses now (a market order is an Ioc at the worst price accepted). */
53
+ export const HYPERLIQUID_TIFS = ["Gtc", "Ioc", "Alo"];
54
+ /**
55
+ * "Prices can have up to 5 significant figures, but no more than MAX_DECIMALS
56
+ * - szDecimals decimal places where MAX_DECIMALS is 6 for perps and 8 for
57
+ * spot" (api/tick-and-lot-size). Outcomes trade like spot, so 8.
58
+ */
59
+ export const HYPERLIQUID_PRICE_SIG_FIGS = 5;
60
+ export const HYPERLIQUID_SPOT_MAX_DECIMALS = 8;
61
+ /** "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. */
62
+ export const HYPERLIQUID_BUILDER_FEE_MAX = 1000;
63
+ export const HYPERLIQUID_SIGN_DOMAIN_NAME = "HyperliquidSignTransaction";
64
+ export const HYPERLIQUID_APPROVE_BUILDER_FEE_TYPE = [
65
+ { name: "hyperliquidChain", type: "string" },
66
+ { name: "maxFeeRate", type: "string" },
67
+ { name: "builder", type: "address" },
68
+ { name: "nonce", type: "uint64" },
69
+ ];
70
+ const EIP712_DOMAIN = [
71
+ { name: "name", type: "string" },
72
+ { name: "version", type: "string" },
73
+ { name: "chainId", type: "uint256" },
74
+ { name: "verifyingContract", type: "address" },
75
+ ];
76
+ const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
77
+ const SIGNATURE = /^0x[0-9a-fA-F]{130}$/;
78
+ const CLOID = /^0x[0-9a-fA-F]{32}$/;
79
+ const DECIMAL = /^(\d+)(?:\.(\d+))?$/;
80
+ const U64 = 2n ** 64n;
81
+ /** The fields a Hyperliquid route takes; anything else, a key above all, is refused. */
82
+ export const HYPERLIQUID_FIELDS = [
83
+ "venue", "outcome", "side", "isBuy", "price", "size", "tif", "reduceOnly", "cloid", "builder", "builderFee",
84
+ "szDecimals", "nonce", "vaultAddress", "expiresAfter", "mainnet",
85
+ ];
86
+ /** The fields hyperliquidApproveBuilderFee takes; anything else, a key above all, is refused. */
87
+ export const HYPERLIQUID_APPROVE_FIELDS = ["builder", "maxFeeRate", "signatureChainId", "nonce", "mainnet"];
88
+ /** Refuses a field not in known: from JavaScript or a cast, a privateKey would otherwise be ignored silently. */
89
+ function onlyFields(what, input, known) {
90
+ const unknown = Object.keys(input).filter((k) => !known.includes(k));
91
+ if (unknown.length)
92
+ throw new RouteError(`${what}: unknown field ${unknown.join(", ")}; it takes no key and nothing else`);
93
+ }
94
+ /** The order's asset id for side (0 or 1) of outcome: 100_000_000 + 10 * outcome + side. */
95
+ export function hyperliquidOutcomeAsset(outcome, side) {
96
+ if (!Number.isSafeInteger(outcome) || outcome < 0)
97
+ throw new RouteError(`outcome: a non-negative integer, not ${JSON.stringify(outcome)}`);
98
+ if (side !== 0 && side !== 1)
99
+ throw new RouteError(`side: 0 or 1 (the outcome's two sides), not ${JSON.stringify(side)}`);
100
+ const asset = HYPERLIQUID_OUTCOME_ASSET_BASE + 10 * outcome + side;
101
+ if (!Number.isSafeInteger(asset))
102
+ throw new RouteError("outcome: too large");
103
+ return asset;
104
+ }
105
+ function num(name, value) {
106
+ let text;
107
+ if (typeof value === "number") {
108
+ if (!Number.isSafeInteger(value))
109
+ throw new RouteError(`${name}: pass a decimal string, not the float ${value}`);
110
+ text = String(value);
111
+ }
112
+ else if (typeof value === "string") {
113
+ text = value;
114
+ }
115
+ else {
116
+ throw new RouteError(`${name}: a decimal string`);
117
+ }
118
+ const m = DECIMAL.exec(text);
119
+ if (!m)
120
+ throw new RouteError(`${name}: ${JSON.stringify(value)} is not a decimal number`);
121
+ const int = (m[1] ?? "").replace(/^0+(?=\d)/, "");
122
+ const frac = (m[2] ?? "").replace(/0+$/, "");
123
+ if (/^0*$/.test(int + frac))
124
+ throw new RouteError(`${name}: must be above 0, not ${JSON.stringify(value)}`);
125
+ const digits = (int + frac).replace(/^0+/, "");
126
+ // As Decimal.normalize counts them: an integer's trailing zeros are not significant.
127
+ const significant = frac ? digits.length : digits.replace(/0+$/, "").length;
128
+ return { wire: frac ? `${int}.${frac}` : int, decimals: frac.length, significant, integer: !frac };
129
+ }
130
+ function address(name, value) {
131
+ if (typeof value !== "string" || !ADDRESS.test(value))
132
+ throw new RouteError(`${name}: ${JSON.stringify(value)} is not a 0x-prefixed 20-byte address`);
133
+ return value.toLowerCase();
134
+ }
135
+ function u64(name, value, what) {
136
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0)
137
+ throw new RouteError(`${name}: ${what}`);
138
+ return value;
139
+ }
140
+ function be8(n) {
141
+ const out = new Uint8Array(8);
142
+ let v = BigInt(n) % U64;
143
+ for (let i = 7; i >= 0; i--) {
144
+ out[i] = Number(v & 0xffn);
145
+ v >>= 8n;
146
+ }
147
+ return out;
148
+ }
149
+ const concat = (...parts) => {
150
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
151
+ let at = 0;
152
+ for (const p of parts) {
153
+ out.set(p, at);
154
+ at += p.length;
155
+ }
156
+ return out;
157
+ };
158
+ const hexBytes = (hex) => Uint8Array.from(hex.slice(2).match(/../g) ?? [], (b) => Number.parseInt(b, 16));
159
+ /**
160
+ * Keccak-256 of the action's MessagePack bytes, the nonce (8 bytes, big
161
+ * endian), the vault flag (0x00, or 0x01 and the vault's 20 bytes) and, when
162
+ * set, 0x00 and expiresAfter (8 bytes): signing.py's action_hash.
163
+ */
164
+ export function hyperliquidActionHash(action, nonce, vaultAddress, expiresAfter) {
165
+ const parts = [packb(action), be8(nonce), vaultAddress ? concat(Uint8Array.of(1), hexBytes(vaultAddress)) : Uint8Array.of(0)];
166
+ if (expiresAfter !== undefined && expiresAfter !== null)
167
+ parts.push(Uint8Array.of(0), be8(expiresAfter));
168
+ return toHex(keccak256(concat(...parts)));
169
+ }
170
+ /** The typed data of an L1 action's phantom agent: source "a" on mainnet, "b" on testnet. */
171
+ export function hyperliquidL1TypedData(connectionId, mainnet = true) {
172
+ return { domain: HYPERLIQUID_L1_DOMAIN, types: { Agent: HYPERLIQUID_AGENT_TYPE }, primaryType: "Agent", message: { source: mainnet ? "a" : "b", connectionId } };
173
+ }
174
+ function splitSignature(signature) {
175
+ if (typeof signature !== "string" || !SIGNATURE.test(signature)) {
176
+ throw new RouteError("signature: the 65-byte 0x-prefixed signature (r, s, v) of typedData");
177
+ }
178
+ let v = Number.parseInt(signature.slice(130, 132), 16);
179
+ if (v < 27)
180
+ v += 27;
181
+ if (v !== 27 && v !== 28)
182
+ throw new RouteError(`signature: v is ${signature.slice(130, 132)}, not 27 or 28 (or 0 or 1)`);
183
+ // As the official SDK sends it: r and s as 0x hex without leading zeros, v a number.
184
+ const hex = (h) => `0x${BigInt(`0x${h}`).toString(16)}`;
185
+ return { r: hex(signature.slice(2, 66)), s: hex(signature.slice(66, 130)), v };
186
+ }
187
+ function word(n) {
188
+ const out = new Uint8Array(32);
189
+ for (let i = 31; i >= 0 && n > 0n; i--) {
190
+ out[i] = Number(n & 0xffn);
191
+ n >>= 8n;
192
+ }
193
+ return out;
194
+ }
195
+ function encodeField(type, value) {
196
+ if (type === "string")
197
+ return keccak256(new TextEncoder().encode(String(value)));
198
+ if (type === "bytes32")
199
+ return hexBytes(String(value));
200
+ if (type === "address")
201
+ return word(BigInt(String(value)));
202
+ if (/^uint\d+$/.test(type))
203
+ return word(BigInt(value));
204
+ throw new RouteError(`EIP-712: type ${type} is not one this package hashes`);
205
+ }
206
+ function hashStruct(name, fields, value) {
207
+ const typeHash = keccak256(new TextEncoder().encode(`${name}(${fields.map((f) => `${f.type} ${f.name}`).join(",")})`));
208
+ return keccak256(concat(typeHash, ...fields.map((f) => encodeField(f.type, value[f.name]))));
209
+ }
210
+ /**
211
+ * The EIP-712 digest of flat typed data (strings, addresses, unsigned
212
+ * integers, bytes32), computed here: viem's signTypedData refuses the type
213
+ * name "HyperliquidTransaction:ApproveBuilderFee" (a colon), so a viem key
214
+ * signs this digest instead (account.sign({ hash: digest })).
215
+ */
216
+ export function eip712Digest(typed) {
217
+ const fields = typed.types[typed.primaryType];
218
+ if (!fields)
219
+ throw new RouteError(`EIP-712: no type ${typed.primaryType}`);
220
+ return toHex(keccak256(concat(Uint8Array.of(0x19, 0x01), hashStruct("EIP712Domain", EIP712_DOMAIN, typed.domain), hashStruct(typed.primaryType, fields, typed.message))));
221
+ }
222
+ function typedJson(typed) {
223
+ return JSON.stringify({ types: { EIP712Domain: EIP712_DOMAIN, ...typed.types }, primaryType: typed.primaryType, domain: typed.domain, message: typed.message }, (_k, v) => (typeof v === "bigint" ? v.toString() : v));
224
+ }
225
+ /**
226
+ * An unsigned Hyperliquid order. Sign `typedData` with the key that trades
227
+ * (an API wallet), then POST `postBody(signature)` to `exchangeUrl`. Nothing
228
+ * here was signed or sent.
229
+ */
230
+ export class HyperliquidOrder {
231
+ action;
232
+ nonce;
233
+ connectionId;
234
+ typedData;
235
+ vaultAddress;
236
+ expiresAfter;
237
+ exchangeUrl;
238
+ venue = "hyperliquid";
239
+ constructor(action, nonce, connectionId, typedData, vaultAddress, expiresAfter, exchangeUrl) {
240
+ this.action = action;
241
+ this.nonce = nonce;
242
+ this.connectionId = connectionId;
243
+ this.typedData = typedData;
244
+ this.vaultAddress = vaultAddress;
245
+ this.expiresAfter = expiresAfter;
246
+ this.exchangeUrl = exchangeUrl;
247
+ }
248
+ /** The typed data as eth_signTypedData_v4 takes it: JSON, the EIP712Domain type included. */
249
+ typedDataJson() {
250
+ return typedJson(this.typedData);
251
+ }
252
+ /** The EIP-712 digest of typedData, for a signer that signs a hash. */
253
+ get digest() {
254
+ return eip712Digest(this.typedData);
255
+ }
256
+ /** The POST /exchange body: action, nonce, the signature split as the official SDK sends it, vaultAddress and expiresAfter. */
257
+ postBody(signature) {
258
+ return { action: this.action, nonce: this.nonce, signature: splitSignature(signature), vaultAddress: this.vaultAddress, expiresAfter: this.expiresAfter };
259
+ }
260
+ }
261
+ export function hyperliquidOrder(input) {
262
+ onlyFields("hyperliquid", input, HYPERLIQUID_FIELDS);
263
+ const asset = hyperliquidOutcomeAsset(input.outcome, input.side);
264
+ if (typeof input.isBuy !== "boolean")
265
+ throw new RouteError("isBuy: true to buy the side's token, false to sell it");
266
+ const reduceOnly = input.reduceOnly ?? false;
267
+ if (typeof reduceOnly !== "boolean")
268
+ throw new RouteError("reduceOnly: true or false");
269
+ const tif = input.tif ?? "Gtc";
270
+ if (!HYPERLIQUID_TIFS.includes(tif))
271
+ throw new RouteError(`tif: one of ${HYPERLIQUID_TIFS.join(", ")}`);
272
+ const sz = input.szDecimals;
273
+ if (sz !== undefined && (!Number.isInteger(sz) || sz < 0 || sz > HYPERLIQUID_SPOT_MAX_DECIMALS)) {
274
+ throw new RouteError(`szDecimals: an integer from 0 to ${HYPERLIQUID_SPOT_MAX_DECIMALS}`);
275
+ }
276
+ const maxPriceDecimals = HYPERLIQUID_SPOT_MAX_DECIMALS - (sz ?? 0);
277
+ const maxSizeDecimals = sz ?? HYPERLIQUID_SPOT_MAX_DECIMALS;
278
+ const price = num("price", input.price);
279
+ if (!price.integer) {
280
+ if (price.significant > HYPERLIQUID_PRICE_SIG_FIGS)
281
+ throw new RouteError(`price: at most ${HYPERLIQUID_PRICE_SIG_FIGS} significant figures, not ${price.wire}`);
282
+ if (price.decimals > maxPriceDecimals)
283
+ throw new RouteError(`price: at most ${maxPriceDecimals} decimals, not ${price.wire}`);
284
+ }
285
+ const size = num("size", input.size);
286
+ if (size.decimals > maxSizeDecimals)
287
+ throw new RouteError(`size: at most ${maxSizeDecimals} decimals, not ${size.wire}`);
288
+ const wire = { a: asset, b: input.isBuy, p: price.wire, s: size.wire, r: reduceOnly, t: { limit: { tif } } };
289
+ if (input.cloid !== undefined) {
290
+ if (typeof input.cloid !== "string" || !CLOID.test(input.cloid))
291
+ throw new RouteError("cloid: a 0x-prefixed 128-bit hex string");
292
+ wire.c = input.cloid.toLowerCase();
293
+ }
294
+ const action = { type: "order", orders: [wire], grouping: "na" };
295
+ if ((input.builder === undefined) !== (input.builderFee === undefined)) {
296
+ throw new RouteError("builder and builderFee: both, or neither (no default builder exists)");
297
+ }
298
+ if (input.builder !== undefined) {
299
+ const b = address("builder", input.builder);
300
+ const f = input.builderFee;
301
+ if (typeof f !== "number" || !Number.isInteger(f) || f < 0 || f > HYPERLIQUID_BUILDER_FEE_MAX) {
302
+ throw new RouteError(`builderFee: tenths of a basis point, an integer from 0 to ${HYPERLIQUID_BUILDER_FEE_MAX} (1%, spot's cap)`);
303
+ }
304
+ action.builder = { b, f };
305
+ }
306
+ const nonce = input.nonce === undefined ? Date.now() : u64("nonce", input.nonce, "milliseconds since the epoch, a positive integer");
307
+ const vault = input.vaultAddress === undefined ? null : address("vaultAddress", input.vaultAddress);
308
+ const expires = input.expiresAfter === undefined ? null : u64("expiresAfter", input.expiresAfter, "milliseconds since the epoch, a positive integer");
309
+ const mainnet = input.mainnet ?? true;
310
+ if (typeof mainnet !== "boolean")
311
+ throw new RouteError("mainnet: true or false");
312
+ const connectionId = hyperliquidActionHash(action, nonce, vault, expires);
313
+ return new HyperliquidOrder(action, nonce, connectionId, hyperliquidL1TypedData(connectionId, mainnet), vault, expires, mainnet ? HYPERLIQUID_EXCHANGE_URL : HYPERLIQUID_TESTNET_EXCHANGE_URL);
314
+ }
315
+ /**
316
+ * An unsigned approveBuilderFee: the user's main wallet signs `typedData`
317
+ * once per builder before orders carry its code. A browser wallet signs
318
+ * `typedDataJson()` with eth_signTypedData_v4. viem's signTypedData refuses
319
+ * the type name (it holds a colon): a viem key signs `digest` instead.
320
+ */
321
+ export class HyperliquidApproveBuilderFee {
322
+ action;
323
+ nonce;
324
+ typedData;
325
+ exchangeUrl;
326
+ constructor(action, nonce, typedData, exchangeUrl) {
327
+ this.action = action;
328
+ this.nonce = nonce;
329
+ this.typedData = typedData;
330
+ this.exchangeUrl = exchangeUrl;
331
+ }
332
+ typedDataJson() {
333
+ return typedJson(this.typedData);
334
+ }
335
+ /** The EIP-712 digest of typedData (see the class comment). */
336
+ get digest() {
337
+ return eip712Digest(this.typedData);
338
+ }
339
+ /** The POST /exchange body; a user-signed action takes no vault and no expiresAfter. */
340
+ postBody(signature) {
341
+ return { action: this.action, nonce: this.nonce, signature: splitSignature(signature), vaultAddress: null, expiresAfter: null };
342
+ }
343
+ }
344
+ /**
345
+ * The unsigned approveBuilderFee the user's main wallet signs once before
346
+ * orders carry `builder`'s code. maxFeeRate: a percent string ("0.001%" is
347
+ * f=1, the official SDK's example; at most "1%"). signatureChainId: the chain
348
+ * the wallet signs on (42161, 0xa4b1, for Arbitrum One, the docs' example).
349
+ */
350
+ export function hyperliquidApproveBuilderFee(input) {
351
+ onlyFields("hyperliquid approveBuilderFee", input, HYPERLIQUID_APPROVE_FIELDS);
352
+ const builder = address("builder", input.builder);
353
+ const rate = input.maxFeeRate;
354
+ const m = typeof rate === "string" ? /^(\d+)(?:\.(\d+))?%$/.exec(rate) : null;
355
+ if (!m)
356
+ throw new RouteError('maxFeeRate: a percent string such as "0.01%"');
357
+ // Compared exactly, as Python's Decimal does: above 1 is a whole part above
358
+ // 1, or 1 with any nonzero decimal.
359
+ const whole = BigInt(m[1] ?? "0");
360
+ if (whole > 1n || (whole === 1n && /[1-9]/.test(m[2] ?? "")))
361
+ throw new RouteError("maxFeeRate: at most 1% (spot's cap; outcomes inherit it)");
362
+ const chainId = input.signatureChainId;
363
+ if (!Number.isSafeInteger(chainId) || chainId <= 0)
364
+ throw new RouteError("signatureChainId: the chain id the signing wallet is on, a positive integer");
365
+ const mainnet = input.mainnet ?? true;
366
+ if (typeof mainnet !== "boolean")
367
+ throw new RouteError("mainnet: true or false");
368
+ const nonce = input.nonce === undefined ? Date.now() : u64("nonce", input.nonce, "milliseconds since the epoch, a positive integer");
369
+ const chain = mainnet ? "Mainnet" : "Testnet";
370
+ return new HyperliquidApproveBuilderFee({ type: "approveBuilderFee", hyperliquidChain: chain, signatureChainId: `0x${chainId.toString(16)}`, maxFeeRate: rate, builder, nonce }, nonce, {
371
+ domain: { name: HYPERLIQUID_SIGN_DOMAIN_NAME, version: "1", chainId, verifyingContract: "0x0000000000000000000000000000000000000000" },
372
+ types: { "HyperliquidTransaction:ApproveBuilderFee": HYPERLIQUID_APPROVE_BUILDER_FEE_TYPE },
373
+ primaryType: "HyperliquidTransaction:ApproveBuilderFee",
374
+ message: { hyperliquidChain: chain, maxFeeRate: rate, builder, nonce: BigInt(nonce) },
375
+ }, mainnet ? HYPERLIQUID_EXCHANGE_URL : HYPERLIQUID_TESTNET_EXCHANGE_URL);
376
+ }
@@ -0,0 +1,297 @@
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 { HyperliquidOrder, type HyperliquidRoute } from "./route-hyperliquid.js";
23
+ export { RouteError };
24
+ /**
25
+ * The V2 order the exchange hashes (Polymarket/ctf-exchange-v2 @ 5c65f2d,
26
+ * src/exchange/libraries/Structs.sol,
27
+ * ORDER_TYPEHASH 0xbb86318a...818589), the same type
28
+ * docs.polymarket.com/trading/place-orders.md gives. `signature` is not
29
+ * hashed, and `expiration` is not part of the order: it rides in the POST body.
30
+ */
31
+ export declare const POLYMARKET_ORDER_TYPE: readonly [{
32
+ readonly name: "salt";
33
+ readonly type: "uint256";
34
+ }, {
35
+ readonly name: "maker";
36
+ readonly type: "address";
37
+ }, {
38
+ readonly name: "signer";
39
+ readonly type: "address";
40
+ }, {
41
+ readonly name: "tokenId";
42
+ readonly type: "uint256";
43
+ }, {
44
+ readonly name: "makerAmount";
45
+ readonly type: "uint256";
46
+ }, {
47
+ readonly name: "takerAmount";
48
+ readonly type: "uint256";
49
+ }, {
50
+ readonly name: "side";
51
+ readonly type: "uint8";
52
+ }, {
53
+ readonly name: "signatureType";
54
+ readonly type: "uint8";
55
+ }, {
56
+ readonly name: "timestamp";
57
+ readonly type: "uint256";
58
+ }, {
59
+ readonly name: "metadata";
60
+ readonly type: "bytes32";
61
+ }, {
62
+ readonly name: "builder";
63
+ readonly type: "bytes32";
64
+ }];
65
+ export declare const EIP712_DOMAIN_TYPE: readonly [{
66
+ readonly name: "name";
67
+ readonly type: "string";
68
+ }, {
69
+ readonly name: "version";
70
+ readonly type: "string";
71
+ }, {
72
+ readonly name: "chainId";
73
+ readonly type: "uint256";
74
+ }, {
75
+ readonly name: "verifyingContract";
76
+ readonly type: "address";
77
+ }];
78
+ export declare const POLYMARKET_DOMAIN_NAME = "Polymarket CTF Exchange";
79
+ export declare const POLYGON_CHAIN_ID = 137;
80
+ /**
81
+ * The exchange that verifies the order, and its domain version, by book
82
+ * (place-orders.md, "Create the Order Typed Data"; addresses also on
83
+ * docs.polymarket.com/resources/contracts.md, Polygon 137): the CTF exchange
84
+ * and the neg risk CTF exchange sign with version "2", a Protocol V2 book
85
+ * ("version": "v2" in the market's data, ExchangeV3) with "3". The developer
86
+ * names it: route() never guesses which book a token trades on.
87
+ */
88
+ export declare const POLYMARKET_EXCHANGES: {
89
+ readonly ctf: {
90
+ readonly version: "2";
91
+ readonly verifyingContract: "0xE111180000d2663C0091e4f400237545B87B996B";
92
+ };
93
+ readonly neg_risk: {
94
+ readonly version: "2";
95
+ readonly verifyingContract: "0xe2222d279d744050d28e00520010520000310F59";
96
+ };
97
+ readonly protocol_v2: {
98
+ readonly version: "3";
99
+ readonly verifyingContract: "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa";
100
+ };
101
+ };
102
+ export type PolymarketExchange = keyof typeof POLYMARKET_EXCHANGES;
103
+ /** Side and SignatureType (Structs.sol): BUY 0, SELL 1; EOA 0, POLY_PROXY 1, POLY_GNOSIS_SAFE 2, POLY_1271 3. */
104
+ export declare const POLYMARKET_SIDES: {
105
+ readonly BUY: 0;
106
+ readonly SELL: 1;
107
+ };
108
+ export declare const POLYMARKET_SIGNATURE_TYPES: {
109
+ readonly EOA: 0;
110
+ readonly POLY_PROXY: 1;
111
+ readonly POLY_GNOSIS_SAFE: 2;
112
+ readonly POLY_1271: 3;
113
+ };
114
+ export type PolymarketOrderType = "GTC" | "GTD" | "FOK" | "FAK";
115
+ /** Price, size and amount decimals by tick size (place-orders.md, "Rounding"). */
116
+ export declare const POLYMARKET_TICKS: Readonly<Record<string, readonly [number, number, number]>>;
117
+ /** Six-decimal base units: "1_000_000 is one pUSD or one share" (migrate/polymarket-v2/contract-integrations.md). */
118
+ export declare const POLYMARKET_DECIMALS = 6;
119
+ /** 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. */
120
+ export declare const POLYMARKET_MAX_SIZE: bigint;
121
+ /** A GTD order's expiration is Unix seconds at least three minutes ahead (place-orders.md). */
122
+ export declare const POLYMARKET_GTD_MIN_SECONDS = 180;
123
+ export declare const MAX_SAFE_SALT: number;
124
+ export declare const ZERO_BYTES32: `0x${string}`;
125
+ type Hex = `0x${string}`;
126
+ /**
127
+ * makerAmount and takerAmount in six-decimal units, by the docs' rounding: a
128
+ * BUY gives USD and takes shares, a SELL the reverse. A limit order (GTC, GTD)
129
+ * and a market SELL (FOK, FAK) are sized in shares; a market BUY in USD to
130
+ * spend, at most `price` a share.
131
+ */
132
+ export declare function polymarketAmounts(side: "BUY" | "SELL", price: string, tickSize: string, orderType: PolymarketOrderType, sizing: {
133
+ size?: string | undefined;
134
+ amount?: string | undefined;
135
+ }): {
136
+ makerAmount: bigint;
137
+ takerAmount: bigint;
138
+ };
139
+ /** The EIP-712 typed data of a Polymarket order, as viem's signTypedData takes it; ethers v6 takes its domain, types and message as three arguments. */
140
+ export interface PolymarketTypedData {
141
+ domain: {
142
+ name: string;
143
+ version: string;
144
+ chainId: number;
145
+ verifyingContract: Hex;
146
+ };
147
+ types: {
148
+ Order: typeof POLYMARKET_ORDER_TYPE;
149
+ };
150
+ primaryType: "Order";
151
+ message: {
152
+ salt: bigint;
153
+ maker: Hex;
154
+ signer: Hex;
155
+ tokenId: bigint;
156
+ makerAmount: bigint;
157
+ takerAmount: bigint;
158
+ side: number;
159
+ signatureType: number;
160
+ timestamp: bigint;
161
+ metadata: Hex;
162
+ builder: Hex;
163
+ };
164
+ }
165
+ /**
166
+ * An unsigned Polymarket V2 order. Sign `typedData` (EIP-712, the `Order`
167
+ * primary type) with the signer's wallet, then post `postBody(signature,
168
+ * owner)` to the CLOB's POST /order with your own CLOB credentials. Nothing
169
+ * here was signed or sent.
170
+ */
171
+ export declare class PolymarketOrder {
172
+ readonly typedData: PolymarketTypedData;
173
+ readonly orderType: PolymarketOrderType;
174
+ /** Unix seconds for a GTD order, 0 otherwise; not signed. */
175
+ readonly expiration: number;
176
+ readonly side: "BUY" | "SELL";
177
+ readonly venue: "polymarket";
178
+ constructor(typedData: PolymarketTypedData, orderType: PolymarketOrderType,
179
+ /** Unix seconds for a GTD order, 0 otherwise; not signed. */
180
+ expiration: number, side: "BUY" | "SELL");
181
+ /** The typed data as eth_signTypedData_v4 takes it: JSON, the EIP712Domain type included, integers as decimal strings. */
182
+ typedDataJson(): string;
183
+ /**
184
+ * The JSON body of POST /order (place-orders.md): the order with its
185
+ * signature, amounts and timestamp as strings, the salt a number, the side a
186
+ * word; `owner` is your CLOB API key's id. orderType and expiration are not
187
+ * part of what was signed.
188
+ */
189
+ postBody(signature: string, owner: string, options?: {
190
+ deferExec?: boolean;
191
+ postOnly?: boolean;
192
+ }): Record<string, unknown>;
193
+ }
194
+ /**
195
+ * A Polymarket order to build (ARCHITECTURE 13.3). exchange: the book's
196
+ * exchange, which sets the EIP-712 domain. tokenId: the outcome's asset id.
197
+ * price: the limit price, on the tick; for a market BUY the most you pay a
198
+ * share. size: shares (a limit order, a market SELL). amount: USD to spend (a
199
+ * market BUY only). tickSize: the book's tick size. maker: the address that
200
+ * funds the order. signer: the address that signs, the maker itself for an
201
+ * EOA (the default) or the owner of the proxy or Safe. builder: your
202
+ * Polymarket builder code (bytes32), carried in the signed order; omitted, the
203
+ * order carries the zero code, none. orderType: GTC, GTD (expiration in Unix
204
+ * seconds, at least three minutes ahead), FOK or FAK.
205
+ */
206
+ export interface PolymarketRoute {
207
+ venue: "polymarket";
208
+ exchange: PolymarketExchange;
209
+ tokenId: string | bigint;
210
+ side: "BUY" | "SELL";
211
+ price: string;
212
+ tickSize: string;
213
+ maker: string;
214
+ size?: string;
215
+ amount?: string;
216
+ orderType?: PolymarketOrderType;
217
+ signatureType?: keyof typeof POLYMARKET_SIGNATURE_TYPES | 0 | 1 | 2 | 3;
218
+ signer?: string;
219
+ builder?: string;
220
+ metadata?: string;
221
+ expiration?: number;
222
+ salt?: number | bigint;
223
+ timestampMs?: number;
224
+ }
225
+ /** The fields each venue's order takes: anything else, a private key above all, is refused. */
226
+ export declare const ROUTE_FIELDS: {
227
+ readonly polymarket: readonly ["venue", "exchange", "tokenId", "side", "price", "tickSize", "maker", "size", "amount", "orderType", "signatureType", "signer", "builder", "metadata", "expiration", "salt", "timestampMs"];
228
+ readonly kalshi_dflow: readonly ["venue", "inputMint", "outputMint", "amount", "userPublicKey", "slippageBps", "predictionMarketSlippageBps", "platformFeeScale", "platformFeeBps", "platformFeeMode", "feeAccount", "baseUrl"];
229
+ readonly hyperliquid: readonly ["venue", "outcome", "side", "isBuy", "price", "size", "tif", "reduceOnly", "cloid", "builder", "builderFee", "szDecimals", "nonce", "vaultAddress", "expiresAfter", "mainnet"];
230
+ };
231
+ export declare function polymarketOrder(input: PolymarketRoute): PolymarketOrder;
232
+ /**
233
+ * The Trading API that returns the unsigned transaction: GET /order on
234
+ * https://quote-api.dflow.net (pond.dflow.net/get-started/endpoints.md), with
235
+ * the developer's own key in the x-api-key header ("All calls to the
236
+ * production endpoints must use an API key", pond.dflow.net/get-started/api-key.md).
237
+ */
238
+ export declare const DFLOW_TRADING_API = "https://quote-api.dflow.net";
239
+ export declare const DFLOW_API_KEY_HEADER = "x-api-key";
240
+ /**
241
+ * platformFeeScale: "Optional platform fee scale for World prediction market
242
+ * swaps and async prediction market swaps, with 3 decimals ... Must be >= 0 and
243
+ * < 1000. For example, a value of 50 means 0.050." platformFeeBps: a fixed fee
244
+ * in basis points, for spot trades (pond.dflow.net/spot/trading/platform-fees.md).
245
+ */
246
+ export declare const DFLOW_FEE_SCALE_MAX = 999;
247
+ export declare const DFLOW_FEE_BPS_MAX = 10000;
248
+ /**
249
+ * The request that returns an unsigned DFlow transaction: GET `url` with
250
+ * `params` and your own DFlow key in the x-api-key header. The response's
251
+ * `transaction` (base64) is for your user to sign and submit. Nothing was
252
+ * sent: route() never calls DFlow.
253
+ */
254
+ export declare class DFlowOrderRequest {
255
+ readonly url: string;
256
+ readonly params: Readonly<Record<string, string>>;
257
+ readonly venue: "kalshi_dflow";
258
+ readonly apiKeyHeader = "x-api-key";
259
+ constructor(url: string, params: Readonly<Record<string, string>>);
260
+ get fullUrl(): string;
261
+ }
262
+ /**
263
+ * A DFlow order to build, for tokenized Kalshi outcome tokens or any DFlow
264
+ * trade, carrying the developer's own fee (ARCHITECTURE 13.3). amount: the
265
+ * input amount in the input mint's base units. userPublicKey: your user's
266
+ * wallet, so the response carries the transaction to sign. platformFeeScale:
267
+ * your fee for a prediction market swap, 0 to 999 in thousandths (DFlow's
268
+ * platformFeeScale; its docs give no formula). Or platformFeeBps: a fixed fee
269
+ * in basis points, DFlow's spot fee. Either needs feeAccount, your token
270
+ * account for the fee mint (the stablecoin for a prediction market swap),
271
+ * which must exist before the trade. With no fee, none is sent.
272
+ */
273
+ export interface DFlowRoute {
274
+ venue: "kalshi_dflow";
275
+ inputMint: string;
276
+ outputMint: string;
277
+ amount: number | bigint;
278
+ userPublicKey: string;
279
+ slippageBps?: number | "auto";
280
+ predictionMarketSlippageBps?: number;
281
+ platformFeeScale?: number;
282
+ platformFeeBps?: number;
283
+ platformFeeMode?: "outputMint" | "inputMint";
284
+ feeAccount?: string;
285
+ baseUrl?: string;
286
+ }
287
+ export declare function dflowOrder(input: DFlowRoute): DFlowOrderRequest;
288
+ export type RouteInput = PolymarketRoute | DFlowRoute | HyperliquidRoute;
289
+ /**
290
+ * An unsigned order for `venue` ("polymarket", "kalshi_dflow" or
291
+ * "hyperliquid", a HIP-4 outcome), with the developer's own builder code or
292
+ * fee. It never signs, never sends, and takes no private key.
293
+ */
294
+ export declare function route(order: PolymarketRoute): PolymarketOrder;
295
+ export declare function route(order: DFlowRoute): DFlowOrderRequest;
296
+ export declare function route(order: HyperliquidRoute): HyperliquidOrder;
297
+ export declare function route(order: RouteInput): PolymarketOrder | DFlowOrderRequest | HyperliquidOrder;