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.
- 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,457 @@
|
|
|
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
|
+
|
|
34
|
+
import { RouteError } from "./errors.js";
|
|
35
|
+
import { keccak256, toHex } from "./keccak.js";
|
|
36
|
+
import { type Packable, packb } from "./msgpack.js";
|
|
37
|
+
|
|
38
|
+
type Hex = `0x${string}`;
|
|
39
|
+
|
|
40
|
+
/** Endpoints the developer posts to ("Exchange endpoint"); route never calls them. */
|
|
41
|
+
export const HYPERLIQUID_EXCHANGE_URL = "https://api.hyperliquid.xyz/exchange";
|
|
42
|
+
export const HYPERLIQUID_TESTNET_EXCHANGE_URL = "https://api.hyperliquid-testnet.xyz/exchange";
|
|
43
|
+
|
|
44
|
+
/** "Outcome asset ID: 100_000_000 + encoding", encoding = 10 * outcome + side (api/asset-ids). */
|
|
45
|
+
export const HYPERLIQUID_OUTCOME_ASSET_BASE = 100_000_000;
|
|
46
|
+
|
|
47
|
+
/** The L1 action's EIP-712 domain and type (signing.py, l1_payload). */
|
|
48
|
+
export const HYPERLIQUID_L1_DOMAIN = {
|
|
49
|
+
name: "Exchange",
|
|
50
|
+
version: "1",
|
|
51
|
+
chainId: 1337,
|
|
52
|
+
verifyingContract: "0x0000000000000000000000000000000000000000",
|
|
53
|
+
} as const;
|
|
54
|
+
export const HYPERLIQUID_AGENT_TYPE = [
|
|
55
|
+
{ name: "source", type: "string" },
|
|
56
|
+
{ name: "connectionId", type: "bytes32" },
|
|
57
|
+
] as const;
|
|
58
|
+
|
|
59
|
+
/** Time in force: "Alo" adds liquidity only, "Ioc" takes what crosses now (a market order is an Ioc at the worst price accepted). */
|
|
60
|
+
export const HYPERLIQUID_TIFS = ["Gtc", "Ioc", "Alo"] as const;
|
|
61
|
+
export type HyperliquidTif = (typeof HYPERLIQUID_TIFS)[number];
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* "Prices can have up to 5 significant figures, but no more than MAX_DECIMALS
|
|
65
|
+
* - szDecimals decimal places where MAX_DECIMALS is 6 for perps and 8 for
|
|
66
|
+
* spot" (api/tick-and-lot-size). Outcomes trade like spot, so 8.
|
|
67
|
+
*/
|
|
68
|
+
export const HYPERLIQUID_PRICE_SIG_FIGS = 5;
|
|
69
|
+
export const HYPERLIQUID_SPOT_MAX_DECIMALS = 8;
|
|
70
|
+
|
|
71
|
+
/** "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. */
|
|
72
|
+
export const HYPERLIQUID_BUILDER_FEE_MAX = 1000;
|
|
73
|
+
|
|
74
|
+
export const HYPERLIQUID_SIGN_DOMAIN_NAME = "HyperliquidSignTransaction";
|
|
75
|
+
export const HYPERLIQUID_APPROVE_BUILDER_FEE_TYPE = [
|
|
76
|
+
{ name: "hyperliquidChain", type: "string" },
|
|
77
|
+
{ name: "maxFeeRate", type: "string" },
|
|
78
|
+
{ name: "builder", type: "address" },
|
|
79
|
+
{ name: "nonce", type: "uint64" },
|
|
80
|
+
] as const;
|
|
81
|
+
|
|
82
|
+
const EIP712_DOMAIN = [
|
|
83
|
+
{ name: "name", type: "string" },
|
|
84
|
+
{ name: "version", type: "string" },
|
|
85
|
+
{ name: "chainId", type: "uint256" },
|
|
86
|
+
{ name: "verifyingContract", type: "address" },
|
|
87
|
+
] as const;
|
|
88
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
89
|
+
const SIGNATURE = /^0x[0-9a-fA-F]{130}$/;
|
|
90
|
+
const CLOID = /^0x[0-9a-fA-F]{32}$/;
|
|
91
|
+
const DECIMAL = /^(\d+)(?:\.(\d+))?$/;
|
|
92
|
+
const U64 = 2n ** 64n;
|
|
93
|
+
|
|
94
|
+
/** The fields a Hyperliquid route takes; anything else, a key above all, is refused. */
|
|
95
|
+
export const HYPERLIQUID_FIELDS = [
|
|
96
|
+
"venue", "outcome", "side", "isBuy", "price", "size", "tif", "reduceOnly", "cloid", "builder", "builderFee",
|
|
97
|
+
"szDecimals", "nonce", "vaultAddress", "expiresAfter", "mainnet",
|
|
98
|
+
] as const;
|
|
99
|
+
|
|
100
|
+
/** The fields hyperliquidApproveBuilderFee takes; anything else, a key above all, is refused. */
|
|
101
|
+
export const HYPERLIQUID_APPROVE_FIELDS = ["builder", "maxFeeRate", "signatureChainId", "nonce", "mainnet"] as const;
|
|
102
|
+
|
|
103
|
+
/** Refuses a field not in known: from JavaScript or a cast, a privateKey would otherwise be ignored silently. */
|
|
104
|
+
function onlyFields(what: string, input: object, known: readonly string[]): void {
|
|
105
|
+
const unknown = Object.keys(input).filter((k) => !known.includes(k));
|
|
106
|
+
if (unknown.length) throw new RouteError(`${what}: unknown field ${unknown.join(", ")}; it takes no key and nothing else`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* A HIP-4 outcome order to build: side 0 or 1 of `outcome` (coin "#960" is
|
|
111
|
+
* outcome 96, side 0). isBuy buys that side's token, else sells it. price and
|
|
112
|
+
* size: decimal strings (or integers); the price has at most 5 significant
|
|
113
|
+
* figures (an integer price always passes) and at most 8 - szDecimals
|
|
114
|
+
* decimals, the size at most szDecimals decimals. The docs do not give an
|
|
115
|
+
* outcome's szDecimals: pass it to check the order here, else only the 5
|
|
116
|
+
* figures and 8 decimals are checked and the venue rejects the rest. builder
|
|
117
|
+
* and builderFee (tenths of a basis point, at most 1000) are your own and go
|
|
118
|
+
* together; with neither, the order carries no builder. nonce: milliseconds,
|
|
119
|
+
* now by default. vaultAddress: a vault or subaccount you trade for.
|
|
120
|
+
* expiresAfter: milliseconds after which the venue drops the action.
|
|
121
|
+
*/
|
|
122
|
+
export interface HyperliquidRoute {
|
|
123
|
+
venue: "hyperliquid";
|
|
124
|
+
outcome: number;
|
|
125
|
+
side: 0 | 1;
|
|
126
|
+
isBuy: boolean;
|
|
127
|
+
price: string | number;
|
|
128
|
+
size: string | number;
|
|
129
|
+
tif?: HyperliquidTif;
|
|
130
|
+
reduceOnly?: boolean;
|
|
131
|
+
cloid?: string;
|
|
132
|
+
builder?: string;
|
|
133
|
+
builderFee?: number;
|
|
134
|
+
szDecimals?: number;
|
|
135
|
+
nonce?: number;
|
|
136
|
+
vaultAddress?: string;
|
|
137
|
+
expiresAfter?: number;
|
|
138
|
+
mainnet?: boolean;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** An L1 action's typed data, as viem's signTypedData takes it; ethers v6 takes its domain, types and message as three arguments. */
|
|
142
|
+
export interface HyperliquidL1TypedData {
|
|
143
|
+
domain: typeof HYPERLIQUID_L1_DOMAIN;
|
|
144
|
+
types: { Agent: typeof HYPERLIQUID_AGENT_TYPE };
|
|
145
|
+
primaryType: "Agent";
|
|
146
|
+
message: { source: "a" | "b"; connectionId: Hex };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface HyperliquidApproveTypedData {
|
|
150
|
+
domain: { name: string; version: string; chainId: number; verifyingContract: Hex };
|
|
151
|
+
types: { "HyperliquidTransaction:ApproveBuilderFee": typeof HYPERLIQUID_APPROVE_BUILDER_FEE_TYPE };
|
|
152
|
+
primaryType: "HyperliquidTransaction:ApproveBuilderFee";
|
|
153
|
+
message: { hyperliquidChain: "Mainnet" | "Testnet"; maxFeeRate: string; builder: Hex; nonce: bigint };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
type Action = { [key: string]: Packable };
|
|
157
|
+
|
|
158
|
+
/** The order's asset id for side (0 or 1) of outcome: 100_000_000 + 10 * outcome + side. */
|
|
159
|
+
export function hyperliquidOutcomeAsset(outcome: number, side: number): number {
|
|
160
|
+
if (!Number.isSafeInteger(outcome) || outcome < 0) throw new RouteError(`outcome: a non-negative integer, not ${JSON.stringify(outcome)}`);
|
|
161
|
+
if (side !== 0 && side !== 1) throw new RouteError(`side: 0 or 1 (the outcome's two sides), not ${JSON.stringify(side)}`);
|
|
162
|
+
const asset = HYPERLIQUID_OUTCOME_ASSET_BASE + 10 * outcome + side;
|
|
163
|
+
if (!Number.isSafeInteger(asset)) throw new RouteError("outcome: too large");
|
|
164
|
+
return asset;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
interface Num {
|
|
168
|
+
wire: string; // no trailing zeros, no exponent
|
|
169
|
+
decimals: number;
|
|
170
|
+
significant: number;
|
|
171
|
+
integer: boolean;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function num(name: string, value: unknown): Num {
|
|
175
|
+
let text: string;
|
|
176
|
+
if (typeof value === "number") {
|
|
177
|
+
if (!Number.isSafeInteger(value)) throw new RouteError(`${name}: pass a decimal string, not the float ${value}`);
|
|
178
|
+
text = String(value);
|
|
179
|
+
} else if (typeof value === "string") {
|
|
180
|
+
text = value;
|
|
181
|
+
} else {
|
|
182
|
+
throw new RouteError(`${name}: a decimal string`);
|
|
183
|
+
}
|
|
184
|
+
const m = DECIMAL.exec(text);
|
|
185
|
+
if (!m) throw new RouteError(`${name}: ${JSON.stringify(value)} is not a decimal number`);
|
|
186
|
+
const int = (m[1] ?? "").replace(/^0+(?=\d)/, "");
|
|
187
|
+
const frac = (m[2] ?? "").replace(/0+$/, "");
|
|
188
|
+
if (/^0*$/.test(int + frac)) throw new RouteError(`${name}: must be above 0, not ${JSON.stringify(value)}`);
|
|
189
|
+
const digits = (int + frac).replace(/^0+/, "");
|
|
190
|
+
// As Decimal.normalize counts them: an integer's trailing zeros are not significant.
|
|
191
|
+
const significant = frac ? digits.length : digits.replace(/0+$/, "").length;
|
|
192
|
+
return { wire: frac ? `${int}.${frac}` : int, decimals: frac.length, significant, integer: !frac };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function address(name: string, value: unknown): Hex {
|
|
196
|
+
if (typeof value !== "string" || !ADDRESS.test(value)) throw new RouteError(`${name}: ${JSON.stringify(value)} is not a 0x-prefixed 20-byte address`);
|
|
197
|
+
return value.toLowerCase() as Hex;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function u64(name: string, value: unknown, what: string): number {
|
|
201
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) throw new RouteError(`${name}: ${what}`);
|
|
202
|
+
return value;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function be8(n: number): Uint8Array {
|
|
206
|
+
const out = new Uint8Array(8);
|
|
207
|
+
let v = BigInt(n) % U64;
|
|
208
|
+
for (let i = 7; i >= 0; i--) {
|
|
209
|
+
out[i] = Number(v & 0xffn);
|
|
210
|
+
v >>= 8n;
|
|
211
|
+
}
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const concat = (...parts: Uint8Array[]): Uint8Array => {
|
|
216
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
217
|
+
let at = 0;
|
|
218
|
+
for (const p of parts) {
|
|
219
|
+
out.set(p, at);
|
|
220
|
+
at += p.length;
|
|
221
|
+
}
|
|
222
|
+
return out;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const hexBytes = (hex: string): Uint8Array => Uint8Array.from(hex.slice(2).match(/../g) ?? [], (b) => Number.parseInt(b, 16));
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Keccak-256 of the action's MessagePack bytes, the nonce (8 bytes, big
|
|
229
|
+
* endian), the vault flag (0x00, or 0x01 and the vault's 20 bytes) and, when
|
|
230
|
+
* set, 0x00 and expiresAfter (8 bytes): signing.py's action_hash.
|
|
231
|
+
*/
|
|
232
|
+
export function hyperliquidActionHash(action: Action, nonce: number, vaultAddress?: string | null, expiresAfter?: number | null): Hex {
|
|
233
|
+
const parts = [packb(action), be8(nonce), vaultAddress ? concat(Uint8Array.of(1), hexBytes(vaultAddress)) : Uint8Array.of(0)];
|
|
234
|
+
if (expiresAfter !== undefined && expiresAfter !== null) parts.push(Uint8Array.of(0), be8(expiresAfter));
|
|
235
|
+
return toHex(keccak256(concat(...parts)));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** The typed data of an L1 action's phantom agent: source "a" on mainnet, "b" on testnet. */
|
|
239
|
+
export function hyperliquidL1TypedData(connectionId: Hex, mainnet = true): HyperliquidL1TypedData {
|
|
240
|
+
return { domain: HYPERLIQUID_L1_DOMAIN, types: { Agent: HYPERLIQUID_AGENT_TYPE }, primaryType: "Agent", message: { source: mainnet ? "a" : "b", connectionId } };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function splitSignature(signature: unknown): { r: string; s: string; v: number } {
|
|
244
|
+
if (typeof signature !== "string" || !SIGNATURE.test(signature)) {
|
|
245
|
+
throw new RouteError("signature: the 65-byte 0x-prefixed signature (r, s, v) of typedData");
|
|
246
|
+
}
|
|
247
|
+
let v = Number.parseInt(signature.slice(130, 132), 16);
|
|
248
|
+
if (v < 27) v += 27;
|
|
249
|
+
if (v !== 27 && v !== 28) throw new RouteError(`signature: v is ${signature.slice(130, 132)}, not 27 or 28 (or 0 or 1)`);
|
|
250
|
+
// As the official SDK sends it: r and s as 0x hex without leading zeros, v a number.
|
|
251
|
+
const hex = (h: string): string => `0x${BigInt(`0x${h}`).toString(16)}`;
|
|
252
|
+
return { r: hex(signature.slice(2, 66)), s: hex(signature.slice(66, 130)), v };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
type Field = { readonly name: string; readonly type: string };
|
|
256
|
+
|
|
257
|
+
function word(n: bigint): Uint8Array {
|
|
258
|
+
const out = new Uint8Array(32);
|
|
259
|
+
for (let i = 31; i >= 0 && n > 0n; i--) {
|
|
260
|
+
out[i] = Number(n & 0xffn);
|
|
261
|
+
n >>= 8n;
|
|
262
|
+
}
|
|
263
|
+
return out;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function encodeField(type: string, value: unknown): Uint8Array {
|
|
267
|
+
if (type === "string") return keccak256(new TextEncoder().encode(String(value)));
|
|
268
|
+
if (type === "bytes32") return hexBytes(String(value));
|
|
269
|
+
if (type === "address") return word(BigInt(String(value)));
|
|
270
|
+
if (/^uint\d+$/.test(type)) return word(BigInt(value as bigint | number | string));
|
|
271
|
+
throw new RouteError(`EIP-712: type ${type} is not one this package hashes`);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function hashStruct(name: string, fields: readonly Field[], value: Record<string, unknown>): Uint8Array {
|
|
275
|
+
const typeHash = keccak256(new TextEncoder().encode(`${name}(${fields.map((f) => `${f.type} ${f.name}`).join(",")})`));
|
|
276
|
+
return keccak256(concat(typeHash, ...fields.map((f) => encodeField(f.type, value[f.name]))));
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* The EIP-712 digest of flat typed data (strings, addresses, unsigned
|
|
281
|
+
* integers, bytes32), computed here: viem's signTypedData refuses the type
|
|
282
|
+
* name "HyperliquidTransaction:ApproveBuilderFee" (a colon), so a viem key
|
|
283
|
+
* signs this digest instead (account.sign({ hash: digest })).
|
|
284
|
+
*/
|
|
285
|
+
export function eip712Digest(typed: { domain: Record<string, unknown>; types: Record<string, readonly Field[]>; primaryType: string; message: Record<string, unknown> }): Hex {
|
|
286
|
+
const fields = typed.types[typed.primaryType];
|
|
287
|
+
if (!fields) throw new RouteError(`EIP-712: no type ${typed.primaryType}`);
|
|
288
|
+
return toHex(
|
|
289
|
+
keccak256(concat(Uint8Array.of(0x19, 0x01), hashStruct("EIP712Domain", EIP712_DOMAIN, typed.domain), hashStruct(typed.primaryType, fields, typed.message))),
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function typedJson(typed: { domain: object; types: object; primaryType: string; message: object }): string {
|
|
294
|
+
return JSON.stringify(
|
|
295
|
+
{ types: { EIP712Domain: EIP712_DOMAIN, ...typed.types }, primaryType: typed.primaryType, domain: typed.domain, message: typed.message },
|
|
296
|
+
(_k, v: unknown) => (typeof v === "bigint" ? v.toString() : v),
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* An unsigned Hyperliquid order. Sign `typedData` with the key that trades
|
|
302
|
+
* (an API wallet), then POST `postBody(signature)` to `exchangeUrl`. Nothing
|
|
303
|
+
* here was signed or sent.
|
|
304
|
+
*/
|
|
305
|
+
export class HyperliquidOrder {
|
|
306
|
+
readonly venue = "hyperliquid" as const;
|
|
307
|
+
|
|
308
|
+
constructor(
|
|
309
|
+
readonly action: Action,
|
|
310
|
+
readonly nonce: number,
|
|
311
|
+
readonly connectionId: Hex,
|
|
312
|
+
readonly typedData: HyperliquidL1TypedData,
|
|
313
|
+
readonly vaultAddress: Hex | null,
|
|
314
|
+
readonly expiresAfter: number | null,
|
|
315
|
+
readonly exchangeUrl: string,
|
|
316
|
+
) {}
|
|
317
|
+
|
|
318
|
+
/** The typed data as eth_signTypedData_v4 takes it: JSON, the EIP712Domain type included. */
|
|
319
|
+
typedDataJson(): string {
|
|
320
|
+
return typedJson(this.typedData);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** The EIP-712 digest of typedData, for a signer that signs a hash. */
|
|
324
|
+
get digest(): Hex {
|
|
325
|
+
return eip712Digest(this.typedData as unknown as Parameters<typeof eip712Digest>[0]);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** The POST /exchange body: action, nonce, the signature split as the official SDK sends it, vaultAddress and expiresAfter. */
|
|
329
|
+
postBody(signature: string): Record<string, unknown> {
|
|
330
|
+
return { action: this.action, nonce: this.nonce, signature: splitSignature(signature), vaultAddress: this.vaultAddress, expiresAfter: this.expiresAfter };
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export function hyperliquidOrder(input: HyperliquidRoute): HyperliquidOrder {
|
|
335
|
+
onlyFields("hyperliquid", input, HYPERLIQUID_FIELDS);
|
|
336
|
+
const asset = hyperliquidOutcomeAsset(input.outcome, input.side);
|
|
337
|
+
if (typeof input.isBuy !== "boolean") throw new RouteError("isBuy: true to buy the side's token, false to sell it");
|
|
338
|
+
const reduceOnly = input.reduceOnly ?? false;
|
|
339
|
+
if (typeof reduceOnly !== "boolean") throw new RouteError("reduceOnly: true or false");
|
|
340
|
+
const tif = input.tif ?? "Gtc";
|
|
341
|
+
if (!HYPERLIQUID_TIFS.includes(tif)) throw new RouteError(`tif: one of ${HYPERLIQUID_TIFS.join(", ")}`);
|
|
342
|
+
const sz = input.szDecimals;
|
|
343
|
+
if (sz !== undefined && (!Number.isInteger(sz) || sz < 0 || sz > HYPERLIQUID_SPOT_MAX_DECIMALS)) {
|
|
344
|
+
throw new RouteError(`szDecimals: an integer from 0 to ${HYPERLIQUID_SPOT_MAX_DECIMALS}`);
|
|
345
|
+
}
|
|
346
|
+
const maxPriceDecimals = HYPERLIQUID_SPOT_MAX_DECIMALS - (sz ?? 0);
|
|
347
|
+
const maxSizeDecimals = sz ?? HYPERLIQUID_SPOT_MAX_DECIMALS;
|
|
348
|
+
const price = num("price", input.price);
|
|
349
|
+
if (!price.integer) {
|
|
350
|
+
if (price.significant > HYPERLIQUID_PRICE_SIG_FIGS) throw new RouteError(`price: at most ${HYPERLIQUID_PRICE_SIG_FIGS} significant figures, not ${price.wire}`);
|
|
351
|
+
if (price.decimals > maxPriceDecimals) throw new RouteError(`price: at most ${maxPriceDecimals} decimals, not ${price.wire}`);
|
|
352
|
+
}
|
|
353
|
+
const size = num("size", input.size);
|
|
354
|
+
if (size.decimals > maxSizeDecimals) throw new RouteError(`size: at most ${maxSizeDecimals} decimals, not ${size.wire}`);
|
|
355
|
+
const wire: Action = { a: asset, b: input.isBuy, p: price.wire, s: size.wire, r: reduceOnly, t: { limit: { tif } } };
|
|
356
|
+
if (input.cloid !== undefined) {
|
|
357
|
+
if (typeof input.cloid !== "string" || !CLOID.test(input.cloid)) throw new RouteError("cloid: a 0x-prefixed 128-bit hex string");
|
|
358
|
+
wire.c = input.cloid.toLowerCase();
|
|
359
|
+
}
|
|
360
|
+
const action: Action = { type: "order", orders: [wire], grouping: "na" };
|
|
361
|
+
if ((input.builder === undefined) !== (input.builderFee === undefined)) {
|
|
362
|
+
throw new RouteError("builder and builderFee: both, or neither (no default builder exists)");
|
|
363
|
+
}
|
|
364
|
+
if (input.builder !== undefined) {
|
|
365
|
+
const b = address("builder", input.builder);
|
|
366
|
+
const f = input.builderFee;
|
|
367
|
+
if (typeof f !== "number" || !Number.isInteger(f) || f < 0 || f > HYPERLIQUID_BUILDER_FEE_MAX) {
|
|
368
|
+
throw new RouteError(`builderFee: tenths of a basis point, an integer from 0 to ${HYPERLIQUID_BUILDER_FEE_MAX} (1%, spot's cap)`);
|
|
369
|
+
}
|
|
370
|
+
action.builder = { b, f };
|
|
371
|
+
}
|
|
372
|
+
const nonce = input.nonce === undefined ? Date.now() : u64("nonce", input.nonce, "milliseconds since the epoch, a positive integer");
|
|
373
|
+
const vault = input.vaultAddress === undefined ? null : address("vaultAddress", input.vaultAddress);
|
|
374
|
+
const expires = input.expiresAfter === undefined ? null : u64("expiresAfter", input.expiresAfter, "milliseconds since the epoch, a positive integer");
|
|
375
|
+
const mainnet = input.mainnet ?? true;
|
|
376
|
+
if (typeof mainnet !== "boolean") throw new RouteError("mainnet: true or false");
|
|
377
|
+
const connectionId = hyperliquidActionHash(action, nonce, vault, expires);
|
|
378
|
+
return new HyperliquidOrder(
|
|
379
|
+
action,
|
|
380
|
+
nonce,
|
|
381
|
+
connectionId,
|
|
382
|
+
hyperliquidL1TypedData(connectionId, mainnet),
|
|
383
|
+
vault,
|
|
384
|
+
expires,
|
|
385
|
+
mainnet ? HYPERLIQUID_EXCHANGE_URL : HYPERLIQUID_TESTNET_EXCHANGE_URL,
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* An unsigned approveBuilderFee: the user's main wallet signs `typedData`
|
|
391
|
+
* once per builder before orders carry its code. A browser wallet signs
|
|
392
|
+
* `typedDataJson()` with eth_signTypedData_v4. viem's signTypedData refuses
|
|
393
|
+
* the type name (it holds a colon): a viem key signs `digest` instead.
|
|
394
|
+
*/
|
|
395
|
+
export class HyperliquidApproveBuilderFee {
|
|
396
|
+
constructor(
|
|
397
|
+
readonly action: Record<string, string | number>,
|
|
398
|
+
readonly nonce: number,
|
|
399
|
+
readonly typedData: HyperliquidApproveTypedData,
|
|
400
|
+
readonly exchangeUrl: string,
|
|
401
|
+
) {}
|
|
402
|
+
|
|
403
|
+
typedDataJson(): string {
|
|
404
|
+
return typedJson(this.typedData);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** The EIP-712 digest of typedData (see the class comment). */
|
|
408
|
+
get digest(): Hex {
|
|
409
|
+
return eip712Digest(this.typedData as unknown as Parameters<typeof eip712Digest>[0]);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** The POST /exchange body; a user-signed action takes no vault and no expiresAfter. */
|
|
413
|
+
postBody(signature: string): Record<string, unknown> {
|
|
414
|
+
return { action: this.action, nonce: this.nonce, signature: splitSignature(signature), vaultAddress: null, expiresAfter: null };
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* The unsigned approveBuilderFee the user's main wallet signs once before
|
|
420
|
+
* orders carry `builder`'s code. maxFeeRate: a percent string ("0.001%" is
|
|
421
|
+
* f=1, the official SDK's example; at most "1%"). signatureChainId: the chain
|
|
422
|
+
* the wallet signs on (42161, 0xa4b1, for Arbitrum One, the docs' example).
|
|
423
|
+
*/
|
|
424
|
+
export function hyperliquidApproveBuilderFee(input: {
|
|
425
|
+
builder: string;
|
|
426
|
+
maxFeeRate: string;
|
|
427
|
+
signatureChainId: number;
|
|
428
|
+
nonce?: number;
|
|
429
|
+
mainnet?: boolean;
|
|
430
|
+
}): HyperliquidApproveBuilderFee {
|
|
431
|
+
onlyFields("hyperliquid approveBuilderFee", input, HYPERLIQUID_APPROVE_FIELDS);
|
|
432
|
+
const builder = address("builder", input.builder);
|
|
433
|
+
const rate = input.maxFeeRate;
|
|
434
|
+
const m = typeof rate === "string" ? /^(\d+)(?:\.(\d+))?%$/.exec(rate) : null;
|
|
435
|
+
if (!m) throw new RouteError('maxFeeRate: a percent string such as "0.01%"');
|
|
436
|
+
// Compared exactly, as Python's Decimal does: above 1 is a whole part above
|
|
437
|
+
// 1, or 1 with any nonzero decimal.
|
|
438
|
+
const whole = BigInt(m[1] ?? "0");
|
|
439
|
+
if (whole > 1n || (whole === 1n && /[1-9]/.test(m[2] ?? ""))) throw new RouteError("maxFeeRate: at most 1% (spot's cap; outcomes inherit it)");
|
|
440
|
+
const chainId = input.signatureChainId;
|
|
441
|
+
if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new RouteError("signatureChainId: the chain id the signing wallet is on, a positive integer");
|
|
442
|
+
const mainnet = input.mainnet ?? true;
|
|
443
|
+
if (typeof mainnet !== "boolean") throw new RouteError("mainnet: true or false");
|
|
444
|
+
const nonce = input.nonce === undefined ? Date.now() : u64("nonce", input.nonce, "milliseconds since the epoch, a positive integer");
|
|
445
|
+
const chain = mainnet ? "Mainnet" : "Testnet";
|
|
446
|
+
return new HyperliquidApproveBuilderFee(
|
|
447
|
+
{ type: "approveBuilderFee", hyperliquidChain: chain, signatureChainId: `0x${chainId.toString(16)}`, maxFeeRate: rate, builder, nonce },
|
|
448
|
+
nonce,
|
|
449
|
+
{
|
|
450
|
+
domain: { name: HYPERLIQUID_SIGN_DOMAIN_NAME, version: "1", chainId, verifyingContract: "0x0000000000000000000000000000000000000000" },
|
|
451
|
+
types: { "HyperliquidTransaction:ApproveBuilderFee": HYPERLIQUID_APPROVE_BUILDER_FEE_TYPE },
|
|
452
|
+
primaryType: "HyperliquidTransaction:ApproveBuilderFee",
|
|
453
|
+
message: { hyperliquidChain: chain, maxFeeRate: rate, builder, nonce: BigInt(nonce) },
|
|
454
|
+
},
|
|
455
|
+
mainnet ? HYPERLIQUID_EXCHANGE_URL : HYPERLIQUID_TESTNET_EXCHANGE_URL,
|
|
456
|
+
);
|
|
457
|
+
}
|