@totalis/hip4-client 0.104.0 → 0.106.0

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.
@@ -0,0 +1,233 @@
1
+ import { type HypercoreAnswer, type HypercoreSignature, type HyperliquidInfo, type HyperliquidNetwork } from "./hypercore.js";
2
+ import { type SignerInput } from "./signer.js";
3
+ import type { Hex, TypedData } from "./typed-data.js";
4
+ /**
5
+ * Singles: one outcome side bought or sold on HyperCore's own book, signed by
6
+ * the account (or its Hyperliquid agent key) and sent straight to Hyperliquid.
7
+ * Totalis never sees the order. Every order this module builds carries the
8
+ * Totalis builder fee, as direct orders in the Totalis app do; the account
9
+ * approves it once (`approveTotalisBuilder`).
10
+ */
11
+ /** The Totalis builder and its fee, in tenths of a basis point: 100 is 10 bps of the order's notional. */
12
+ export declare const totalisBuilder: {
13
+ readonly address: "0x334fd4455dde94f36dd2a7c4041992ddc8407dc5";
14
+ readonly feeDecibps: 100;
15
+ };
16
+ export type OutcomeSide = "YES" | "NO";
17
+ export type SingleTif = "Gtc" | "Ioc" | "Alo";
18
+ /** HyperCore's asset number for one side of an outcome: what an order's `a` names. */
19
+ export declare function outcomeAsset(outcomeId: string | number, side: OutcomeSide): number;
20
+ /** HyperCore's coin name for one side of an outcome (`#` and outcome_id times 10 plus the side), as fills and books name it. */
21
+ export declare function outcomeCoin(outcomeId: string | number, side: OutcomeSide): string;
22
+ /** A fresh client order ID: 16 bytes, the first four the Totalis tag. */
23
+ export declare function singleCloid(): Hex;
24
+ export type SingleOrder = {
25
+ readonly outcomeId: string | number;
26
+ readonly side: OutcomeSide;
27
+ /** true buys the side's shares, false sells shares already held. */
28
+ readonly buy: boolean;
29
+ /** USDC per share: above 0, below 1, at most 5 significant figures and 8 decimals. A buy pays at most this; a sale takes at least it. */
30
+ readonly price: string;
31
+ /** Whole shares. Each pays 1 USDC if its side wins. */
32
+ readonly shares: string | number | bigint;
33
+ /** `Gtc` rests what does not fill (default), `Ioc` cancels it, `Alo` only ever rests. */
34
+ readonly tif?: SingleTif;
35
+ /** 16-byte hex client order ID; `singleCloid()` by default. Keep it to find the order when its answer is lost. */
36
+ readonly cloid?: Hex;
37
+ };
38
+ export type SingleOrderAction = {
39
+ readonly type: "order";
40
+ readonly orders: readonly [
41
+ {
42
+ readonly a: number;
43
+ readonly b: boolean;
44
+ readonly p: string;
45
+ readonly s: string;
46
+ readonly r: false;
47
+ readonly t: {
48
+ readonly limit: {
49
+ readonly tif: SingleTif;
50
+ };
51
+ };
52
+ readonly c: Hex;
53
+ }
54
+ ];
55
+ readonly grouping: "na";
56
+ readonly builder: {
57
+ readonly b: string;
58
+ readonly f: number;
59
+ };
60
+ };
61
+ /** One single as the `order` action Hyperliquid takes, with the Totalis builder fee attached. */
62
+ export declare function singleOrderAction(order: SingleOrder): SingleOrderAction;
63
+ /** A resting single to cancel, by the cloid it was placed with or the `oid` Hyperliquid gave it. */
64
+ export type SingleCancel = {
65
+ readonly outcomeId: string | number;
66
+ readonly side: OutcomeSide;
67
+ } & ({
68
+ readonly cloid: Hex;
69
+ } | {
70
+ readonly oid: number;
71
+ });
72
+ export type CancelByCloidAction = {
73
+ readonly type: "cancelByCloid";
74
+ readonly cancels: readonly {
75
+ readonly asset: number;
76
+ readonly cloid: Hex;
77
+ }[];
78
+ };
79
+ export type CancelByOidAction = {
80
+ readonly type: "cancel";
81
+ readonly cancels: readonly {
82
+ readonly a: number;
83
+ readonly o: number;
84
+ }[];
85
+ };
86
+ export type SingleCancelAction = CancelByCloidAction | CancelByOidAction;
87
+ /** Cancels as Hyperliquid takes them: one action for every target of one kind, so all by cloid or all by oid. */
88
+ export declare function singleCancelAction(targets: readonly SingleCancel[]): SingleCancelAction;
89
+ export type SingleAction = SingleOrderAction | SingleCancelAction;
90
+ /** The hash an L1 action's signature binds: the packed action, its nonce, no vault, then its deadline when it has one. */
91
+ export declare function l1ActionHash(action: SingleAction, nonce: number, expiresAfter?: number): Hex;
92
+ /** The EIP-712 payload any key signs for an L1 action, the account's own or its agent's. Mainnet and testnet differ only in `source`. */
93
+ export declare function l1TypedData(network: HyperliquidNetwork, action: SingleAction, nonce: number, expiresAfter?: number): TypedData;
94
+ /** An L1 action as Hyperliquid's `/exchange` takes it. Plain JSON. */
95
+ export type SignedL1Action<Action extends SingleAction = SingleAction> = {
96
+ readonly action: Action;
97
+ readonly nonce: number;
98
+ readonly signature: HypercoreSignature;
99
+ readonly expiresAfter?: number;
100
+ };
101
+ export type L1Options = {
102
+ /** Defaults to `hypercoreNonce()`. Each signer spends a nonce once. */
103
+ readonly nonce?: number;
104
+ /** Epoch ms after which Hyperliquid refuses the action, so a lost answer stops mattering. */
105
+ readonly expiresAfter?: number;
106
+ };
107
+ /**
108
+ * Sign an L1 action with the account's wallet or its Hyperliquid agent key.
109
+ * Browser wallets often refuse its signing domain (chain 1337); approve an
110
+ * agent key once (`approveHyperliquidAgent`) and sign orders with that.
111
+ */
112
+ export declare function signL1Action<Action extends SingleAction>(signer: SignerInput, network: HyperliquidNetwork, action: Action, options?: L1Options): Promise<SignedL1Action<Action>>;
113
+ export type ExchangeOptions = {
114
+ readonly fetch?: typeof fetch;
115
+ readonly signal?: AbortSignal;
116
+ };
117
+ /**
118
+ * What Hyperliquid did with one order. `refused` placed nothing. `unknown`
119
+ * means no readable answer: the order may have landed, so look it up by its
120
+ * cloid (`readSingleOrder`) before placing it again; resending the same
121
+ * signed bytes is safe, since Hyperliquid spends a nonce once.
122
+ */
123
+ export type SingleOrderAnswer = {
124
+ readonly kind: "resting";
125
+ readonly oid: number;
126
+ } | {
127
+ readonly kind: "filled";
128
+ readonly oid: number;
129
+ readonly shares: string;
130
+ readonly averagePrice: string;
131
+ } | {
132
+ readonly kind: "refused";
133
+ readonly error: string;
134
+ } | {
135
+ readonly kind: "unknown";
136
+ };
137
+ export declare function singleOrderAnswer(body: unknown): SingleOrderAnswer;
138
+ /** What Hyperliquid did with each cancel, in the order sent; every entry `unknown` when the answer was unreadable. */
139
+ export type SingleCancelAnswer = {
140
+ readonly kind: "cancelled";
141
+ } | {
142
+ readonly kind: "refused";
143
+ readonly error: string;
144
+ } | {
145
+ readonly kind: "unknown";
146
+ };
147
+ export declare function singleCancelAnswers(body: unknown, count: number): SingleCancelAnswer[];
148
+ export declare function submitSingleOrder(network: HyperliquidNetwork, signed: SignedL1Action<SingleOrderAction>, options?: ExchangeOptions): Promise<SingleOrderAnswer>;
149
+ export declare function submitSingleCancel(network: HyperliquidNetwork, signed: SignedL1Action<SingleCancelAction>, options?: ExchangeOptions): Promise<SingleCancelAnswer[]>;
150
+ /**
151
+ * Build, sign and send one single with the Totalis builder fee. `signer` is
152
+ * the account or its agent key. The account must have approved the fee
153
+ * (`approveTotalisBuilder`), or Hyperliquid refuses the order. Keep
154
+ * `signed.action.orders[0].c`, the cloid, to look the order up when the answer is `unknown`.
155
+ */
156
+ export declare function placeSingle(signer: SignerInput, network: HyperliquidNetwork, order: SingleOrder, options?: L1Options & ExchangeOptions): Promise<{
157
+ signed: SignedL1Action<SingleOrderAction>;
158
+ answer: SingleOrderAnswer;
159
+ }>;
160
+ /** Sign and send cancels of resting singles, all by cloid or all by oid. */
161
+ export declare function cancelSingles(signer: SignerInput, network: HyperliquidNetwork, targets: readonly SingleCancel[], options?: L1Options & ExchangeOptions): Promise<{
162
+ signed: SignedL1Action<SingleCancelAction>;
163
+ answers: SingleCancelAnswer[];
164
+ }>;
165
+ /** One order as Hyperliquid's `orderStatus` reports it; `null` when Hyperliquid holds none under that id. */
166
+ export type SingleOrderStatus = {
167
+ readonly oid: number;
168
+ readonly cloid: Hex | null;
169
+ readonly coin: string;
170
+ /** `open`, `filled`, `canceled`, or one of Hyperliquid's refusal states. */
171
+ readonly status: string;
172
+ readonly shares: string;
173
+ readonly remaining: string;
174
+ };
175
+ /**
176
+ * Read an order by its cloid or oid. `null` is Hyperliquid holding no order
177
+ * under that id: an order still in flight has none yet, so only after the
178
+ * action's `expiresAfter` does `null` prove it never landed.
179
+ */
180
+ export declare function readSingleOrder(network: HyperliquidNetwork, account: string, id: Hex | number, info?: HyperliquidInfo, signal?: AbortSignal): Promise<SingleOrderStatus | null>;
181
+ export type ApproveBuilderFeeAction = {
182
+ readonly type: "approveBuilderFee";
183
+ readonly hyperliquidChain: "Mainnet" | "Testnet";
184
+ readonly signatureChainId: Hex;
185
+ readonly maxFeeRate: string;
186
+ readonly builder: string;
187
+ readonly nonce: number;
188
+ };
189
+ export type ApproveAgentAction = {
190
+ readonly type: "approveAgent";
191
+ readonly hyperliquidChain: "Mainnet" | "Testnet";
192
+ readonly signatureChainId: Hex;
193
+ readonly agentAddress: string;
194
+ readonly agentName: string;
195
+ readonly nonce: number;
196
+ };
197
+ export type SignedUserAction<Action extends ApproveBuilderFeeAction | ApproveAgentAction> = {
198
+ readonly action: Action;
199
+ readonly nonce: number;
200
+ readonly signature: HypercoreSignature;
201
+ };
202
+ /** The approval of the Totalis builder at its fee (`0.1%`). */
203
+ export declare function approveTotalisBuilderAction(network: HyperliquidNetwork, nonce?: number): ApproveBuilderFeeAction;
204
+ export declare function approveBuilderFeeTypedData(action: ApproveBuilderFeeAction): TypedData;
205
+ /**
206
+ * An agent key for `account` under `agentName`: it can place and cancel
207
+ * orders, never withdraw or transfer. Approving a name the account already
208
+ * uses replaces that agent; an account holds a few named agents at most. The
209
+ * Totalis app uses `Totalis` and `TotalisCLI`; pick your own name.
210
+ */
211
+ export declare function approveAgentAction(network: HyperliquidNetwork, agentAddress: string, agentName: string, nonce?: number): ApproveAgentAction;
212
+ export declare function approveAgentTypedData(action: ApproveAgentAction): TypedData;
213
+ /** The builder fee `account` has approved for the Totalis builder, in tenths of a basis point; 0 when none. */
214
+ export declare function readTotalisBuilderFee(network: HyperliquidNetwork, account: string, info?: HyperliquidInfo, signal?: AbortSignal): Promise<number>;
215
+ /**
216
+ * Approve the Totalis builder fee for the account, once, before its first
217
+ * single. Signed by the account's own wallet: Hyperliquid refuses it from an
218
+ * agent key. Skip it when `readTotalisBuilderFee` already reaches
219
+ * `totalisBuilder.feeDecibps`.
220
+ */
221
+ export declare function approveTotalisBuilder(signer: SignerInput, network: HyperliquidNetwork, options?: ExchangeOptions & {
222
+ readonly nonce?: number;
223
+ }): Promise<{
224
+ signed: SignedUserAction<ApproveBuilderFeeAction>;
225
+ answer: HypercoreAnswer;
226
+ }>;
227
+ /** Approve `agentAddress` as the account's Hyperliquid agent under `agentName`. Signed by the account's own wallet. */
228
+ export declare function approveHyperliquidAgent(signer: SignerInput, network: HyperliquidNetwork, agentAddress: string, agentName: string, options?: ExchangeOptions & {
229
+ readonly nonce?: number;
230
+ }): Promise<{
231
+ signed: SignedUserAction<ApproveAgentAction>;
232
+ answer: HypercoreAnswer;
233
+ }>;
@@ -0,0 +1,372 @@
1
+ import { keccak_256 } from "@noble/hashes/sha3";
2
+ import { classifyHypercoreAnswer, hypercoreNonce, hypercoreSignature, hyperliquidInfo } from "./hypercore.js";
3
+ import { randomBytes } from "./runtime.js";
4
+ import { toTotalisSigner } from "./signer.js";
5
+ /**
6
+ * Singles: one outcome side bought or sold on HyperCore's own book, signed by
7
+ * the account (or its Hyperliquid agent key) and sent straight to Hyperliquid.
8
+ * Totalis never sees the order. Every order this module builds carries the
9
+ * Totalis builder fee, as direct orders in the Totalis app do; the account
10
+ * approves it once (`approveTotalisBuilder`).
11
+ */
12
+ /** The Totalis builder and its fee, in tenths of a basis point: 100 is 10 bps of the order's notional. */
13
+ export const totalisBuilder = { address: "0x334fd4455dde94f36dd2a7c4041992ddc8407dc5", feeDecibps: 100 };
14
+ // HIP-4 outcomes have no size decimals, so a price takes up to 5 significant figures and 8 decimals.
15
+ const PRICE_FIGURES = 5;
16
+ const PRICE_DECIMALS = 8;
17
+ const uint32Text = /^(0|[1-9][0-9]*)$/;
18
+ function outcomeNumber(outcomeId) {
19
+ const text = String(outcomeId);
20
+ const value = Number(text);
21
+ if (!uint32Text.test(text) || value > 0xffffffff)
22
+ throw new TypeError(`not a uint32 outcome_id: ${text}`);
23
+ return value;
24
+ }
25
+ const sideIndex = (side) => {
26
+ if (side !== "YES" && side !== "NO")
27
+ throw new TypeError(`not a side: ${String(side)}`);
28
+ return side === "YES" ? 0 : 1;
29
+ };
30
+ /** HyperCore's asset number for one side of an outcome: what an order's `a` names. */
31
+ export function outcomeAsset(outcomeId, side) {
32
+ const asset = 100_000_000 + outcomeNumber(outcomeId) * 10 + sideIndex(side);
33
+ if (asset > 0xffffffff)
34
+ throw new RangeError(`outcome ${String(outcomeId)} has no HyperCore asset: it would exceed uint32`);
35
+ return asset;
36
+ }
37
+ /** HyperCore's coin name for one side of an outcome (`#` and outcome_id times 10 plus the side), as fills and books name it. */
38
+ export function outcomeCoin(outcomeId, side) {
39
+ return `#${outcomeNumber(outcomeId) * 10 + sideIndex(side)}`;
40
+ }
41
+ /**
42
+ * A price strictly between 0 and 1 with at most 5 significant figures and 8
43
+ * decimals, as the minimal decimal text Hyperliquid hashes: "0.50" is "0.5".
44
+ * Any other spelling signs bytes the venue does not, so it recovers a
45
+ * different signer.
46
+ */
47
+ function priceWire(price) {
48
+ const match = /^0?\.(\d+)$/.exec(price);
49
+ const fraction = (match?.[1] ?? "").replace(/0+$/, "");
50
+ const figures = fraction.replace(/^0+/, "").length;
51
+ if (match === null || figures === 0 || figures > PRICE_FIGURES || fraction.length > PRICE_DECIMALS) {
52
+ throw new RangeError(`price must be above 0 and below 1 with at most ${PRICE_FIGURES} significant figures and ${PRICE_DECIMALS} decimals: ${price}`);
53
+ }
54
+ return `0.${fraction}`;
55
+ }
56
+ function sharesWire(shares) {
57
+ const text = String(shares);
58
+ if (!/^[1-9][0-9]*$/.test(text))
59
+ throw new RangeError(`shares must be a positive whole number: ${text}`);
60
+ return text;
61
+ }
62
+ // Every order the Totalis app places starts its client order ID with these
63
+ // bytes, so the leaderboard counts its fills; orders from this SDK carry them too.
64
+ const orderTag = new TextEncoder().encode("totl");
65
+ const hex = (bytes) => `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
66
+ /** A fresh client order ID: 16 bytes, the first four the Totalis tag. */
67
+ export function singleCloid() {
68
+ const id = randomBytes(16);
69
+ id.set(orderTag);
70
+ return hex(id);
71
+ }
72
+ /** One single as the `order` action Hyperliquid takes, with the Totalis builder fee attached. */
73
+ export function singleOrderAction(order) {
74
+ const cloid = order.cloid ?? singleCloid();
75
+ if (!/^0x[0-9a-fA-F]{32}$/.test(cloid))
76
+ throw new TypeError(`cloid must be 16 bytes of hex: ${cloid}`);
77
+ return {
78
+ type: "order",
79
+ orders: [{
80
+ a: outcomeAsset(order.outcomeId, order.side),
81
+ b: order.buy,
82
+ p: priceWire(order.price),
83
+ s: sharesWire(order.shares),
84
+ r: false,
85
+ t: { limit: { tif: order.tif ?? "Gtc" } },
86
+ c: cloid.toLowerCase(),
87
+ }],
88
+ grouping: "na",
89
+ builder: { b: totalisBuilder.address, f: totalisBuilder.feeDecibps },
90
+ };
91
+ }
92
+ /** Cancels as Hyperliquid takes them: one action for every target of one kind, so all by cloid or all by oid. */
93
+ export function singleCancelAction(targets) {
94
+ if (targets.length === 0)
95
+ throw new RangeError("nothing to cancel");
96
+ if (targets.every((target) => "cloid" in target)) {
97
+ return { type: "cancelByCloid", cancels: targets.map((target) => ({ asset: outcomeAsset(target.outcomeId, target.side), cloid: target.cloid.toLowerCase() })) };
98
+ }
99
+ if (targets.every((target) => "oid" in target)) {
100
+ return { type: "cancel", cancels: targets.map((target) => ({ a: outcomeAsset(target.outcomeId, target.side), o: target.oid })) };
101
+ }
102
+ throw new TypeError("cancel by cloid and by oid in separate actions");
103
+ }
104
+ // The MessagePack Hyperliquid hashes an L1 action as: maps in the key order
105
+ // written, the shortest encoding of each value, as the official SDK's msgpack.
106
+ function pack(value, out) {
107
+ if (typeof value === "string") {
108
+ const bytes = new TextEncoder().encode(value);
109
+ if (bytes.length < 32)
110
+ out.push(0xa0 | bytes.length);
111
+ else if (bytes.length < 0x100)
112
+ out.push(0xd9, bytes.length);
113
+ else
114
+ throw new RangeError("string too long for an action");
115
+ out.push(...bytes);
116
+ }
117
+ else if (typeof value === "boolean") {
118
+ out.push(value ? 0xc3 : 0xc2);
119
+ }
120
+ else if (typeof value === "number") {
121
+ if (!Number.isSafeInteger(value) || value < 0)
122
+ throw new RangeError(`not a uint: ${value}`);
123
+ if (value < 0x80)
124
+ out.push(value);
125
+ else if (value < 0x100)
126
+ out.push(0xcc, value);
127
+ else if (value < 0x10000)
128
+ out.push(0xcd, ...bigEndian(value, 2));
129
+ else if (value < 0x100000000)
130
+ out.push(0xce, ...bigEndian(value, 4));
131
+ else
132
+ out.push(0xcf, ...bigEndian(value, 8));
133
+ }
134
+ else if (Array.isArray(value)) {
135
+ header(value.length, 0x90, 0xdc, out);
136
+ for (const item of value)
137
+ pack(item, out);
138
+ }
139
+ else if (typeof value === "object" && value !== null) {
140
+ const entries = Object.entries(value);
141
+ header(entries.length, 0x80, 0xde, out);
142
+ for (const [key, item] of entries) {
143
+ pack(key, out);
144
+ pack(item, out);
145
+ }
146
+ }
147
+ else {
148
+ throw new TypeError(`cannot pack ${String(value)}`);
149
+ }
150
+ }
151
+ function header(size, fix, wide, out) {
152
+ if (size < 16)
153
+ out.push(fix | size);
154
+ else if (size < 0x10000)
155
+ out.push(wide, ...bigEndian(size, 2));
156
+ else
157
+ throw new RangeError("too many entries for an action");
158
+ }
159
+ function bigEndian(value, length) {
160
+ const bytes = [];
161
+ let rest = BigInt(value);
162
+ for (let index = 0; index < length; index++) {
163
+ bytes.unshift(Number(rest & 0xffn));
164
+ rest >>= 8n;
165
+ }
166
+ return bytes;
167
+ }
168
+ /** The hash an L1 action's signature binds: the packed action, its nonce, no vault, then its deadline when it has one. */
169
+ export function l1ActionHash(action, nonce, expiresAfter) {
170
+ const bytes = [];
171
+ pack(action, bytes);
172
+ bytes.push(...bigEndian(nonce, 8), 0);
173
+ if (expiresAfter !== undefined)
174
+ bytes.push(0, ...bigEndian(expiresAfter, 8));
175
+ return hex(keccak_256(Uint8Array.from(bytes)));
176
+ }
177
+ /** The EIP-712 payload any key signs for an L1 action, the account's own or its agent's. Mainnet and testnet differ only in `source`. */
178
+ export function l1TypedData(network, action, nonce, expiresAfter) {
179
+ return {
180
+ domain: { name: "Exchange", version: "1", chainId: 1337n, verifyingContract: "0x0000000000000000000000000000000000000000" },
181
+ types: { Agent: [{ name: "source", type: "string" }, { name: "connectionId", type: "bytes32" }] },
182
+ primaryType: "Agent",
183
+ message: { source: network.chain === "Mainnet" ? "a" : "b", connectionId: l1ActionHash(action, nonce, expiresAfter) },
184
+ };
185
+ }
186
+ /**
187
+ * Sign an L1 action with the account's wallet or its Hyperliquid agent key.
188
+ * Browser wallets often refuse its signing domain (chain 1337); approve an
189
+ * agent key once (`approveHyperliquidAgent`) and sign orders with that.
190
+ */
191
+ export async function signL1Action(signer, network, action, options = {}) {
192
+ const nonce = options.nonce ?? hypercoreNonce();
193
+ const raw = await toTotalisSigner(signer).signTypedData(l1TypedData(network, action, nonce, options.expiresAfter));
194
+ return { action, nonce, signature: hypercoreSignature(raw), ...(options.expiresAfter === undefined ? {} : { expiresAfter: options.expiresAfter }) };
195
+ }
196
+ /** POST one signed action to the network's `/exchange` and return its JSON answer; `undefined` when no answer arrived or it was not JSON. */
197
+ async function post(network, payload, options) {
198
+ const fetchImpl = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
199
+ try {
200
+ const response = await fetchImpl(network.exchangeUrl, {
201
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload),
202
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
203
+ });
204
+ const body = JSON.parse(await response.text());
205
+ return body;
206
+ }
207
+ catch {
208
+ return undefined;
209
+ }
210
+ }
211
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
212
+ export function singleOrderAnswer(body) {
213
+ if (isRecord(body) && body.status === "err" && typeof body.response === "string" && body.response.trim() !== "") {
214
+ return /^Invalid nonce/.test(body.response) ? { kind: "unknown" } : { kind: "refused", error: body.response };
215
+ }
216
+ if (!isRecord(body) || body.status !== "ok" || !isRecord(body.response) || body.response.type !== "order")
217
+ return { kind: "unknown" };
218
+ const data = body.response.data;
219
+ const statuses = isRecord(data) ? data.statuses : undefined;
220
+ if (!Array.isArray(statuses) || statuses.length !== 1)
221
+ return { kind: "unknown" };
222
+ const status = statuses[0];
223
+ if (!isRecord(status))
224
+ return { kind: "unknown" };
225
+ if (typeof status.error === "string")
226
+ return { kind: "refused", error: status.error };
227
+ const { resting, filled } = status;
228
+ if (isRecord(resting) && Number.isSafeInteger(resting.oid))
229
+ return { kind: "resting", oid: resting.oid };
230
+ if (isRecord(filled) && Number.isSafeInteger(filled.oid) && typeof filled.totalSz === "string" && typeof filled.avgPx === "string") {
231
+ return { kind: "filled", oid: filled.oid, shares: filled.totalSz, averagePrice: filled.avgPx };
232
+ }
233
+ return { kind: "unknown" };
234
+ }
235
+ export function singleCancelAnswers(body, count) {
236
+ const unknown = () => Array.from({ length: count }, () => ({ kind: "unknown" }));
237
+ if (isRecord(body) && body.status === "err" && typeof body.response === "string" && body.response.trim() !== "" && !/^Invalid nonce/.test(body.response)) {
238
+ const error = body.response;
239
+ return Array.from({ length: count }, () => ({ kind: "refused", error }));
240
+ }
241
+ if (!isRecord(body) || body.status !== "ok" || !isRecord(body.response) || body.response.type !== "cancel")
242
+ return unknown();
243
+ const data = body.response.data;
244
+ const statuses = isRecord(data) ? data.statuses : undefined;
245
+ if (!Array.isArray(statuses) || statuses.length !== count)
246
+ return unknown();
247
+ return statuses.map((status) => status === "success" ? { kind: "cancelled" } : isRecord(status) && typeof status.error === "string" ? { kind: "refused", error: status.error } : { kind: "unknown" });
248
+ }
249
+ export async function submitSingleOrder(network, signed, options = {}) {
250
+ return singleOrderAnswer(await post(network, signed, options));
251
+ }
252
+ export async function submitSingleCancel(network, signed, options = {}) {
253
+ return singleCancelAnswers(await post(network, signed, options), signed.action.cancels.length);
254
+ }
255
+ /**
256
+ * Build, sign and send one single with the Totalis builder fee. `signer` is
257
+ * the account or its agent key. The account must have approved the fee
258
+ * (`approveTotalisBuilder`), or Hyperliquid refuses the order. Keep
259
+ * `signed.action.orders[0].c`, the cloid, to look the order up when the answer is `unknown`.
260
+ */
261
+ export async function placeSingle(signer, network, order, options = {}) {
262
+ const signed = await signL1Action(signer, network, singleOrderAction(order), options);
263
+ return { signed, answer: await submitSingleOrder(network, signed, options) };
264
+ }
265
+ /** Sign and send cancels of resting singles, all by cloid or all by oid. */
266
+ export async function cancelSingles(signer, network, targets, options = {}) {
267
+ const signed = await signL1Action(signer, network, singleCancelAction(targets), options);
268
+ return { signed, answers: await submitSingleCancel(network, signed, options) };
269
+ }
270
+ /**
271
+ * Read an order by its cloid or oid. `null` is Hyperliquid holding no order
272
+ * under that id: an order still in flight has none yet, so only after the
273
+ * action's `expiresAfter` does `null` prove it never landed.
274
+ */
275
+ export async function readSingleOrder(network, account, id, info = hyperliquidInfo(), signal) {
276
+ const answer = await info(network, { type: "orderStatus", user: account.toLowerCase(), oid: typeof id === "string" ? id.toLowerCase() : id }, signal);
277
+ if (isRecord(answer) && answer.status === "unknownOid")
278
+ return null;
279
+ const wrapper = isRecord(answer) && answer.status === "order" ? answer.order : undefined;
280
+ const order = isRecord(wrapper) ? wrapper.order : undefined;
281
+ if (!isRecord(wrapper) || !isRecord(order) || typeof wrapper.status !== "string" || !Number.isSafeInteger(order.oid) || typeof order.coin !== "string" || typeof order.origSz !== "string" || typeof order.sz !== "string") {
282
+ throw new Error("Hyperliquid orderStatus answer was malformed");
283
+ }
284
+ return {
285
+ oid: order.oid,
286
+ cloid: typeof order.cloid === "string" && order.cloid !== "" ? order.cloid.toLowerCase() : null,
287
+ coin: order.coin,
288
+ status: wrapper.status,
289
+ shares: order.origSz,
290
+ remaining: order.sz,
291
+ };
292
+ }
293
+ // User-signed actions: the account's own wallet signs them, never an agent.
294
+ const userSignedDomain = (signatureChainId) => ({
295
+ name: "HyperliquidSignTransaction", version: "1", chainId: BigInt(signatureChainId), verifyingContract: "0x0000000000000000000000000000000000000000",
296
+ });
297
+ const approveBuilderFeeFields = [
298
+ { name: "hyperliquidChain", type: "string" },
299
+ { name: "maxFeeRate", type: "string" },
300
+ { name: "builder", type: "address" },
301
+ { name: "nonce", type: "uint64" },
302
+ ];
303
+ const approveAgentFields = [
304
+ { name: "hyperliquidChain", type: "string" },
305
+ { name: "agentAddress", type: "address" },
306
+ { name: "agentName", type: "string" },
307
+ { name: "nonce", type: "uint64" },
308
+ ];
309
+ /** The approval of the Totalis builder at its fee (`0.1%`). */
310
+ export function approveTotalisBuilderAction(network, nonce = hypercoreNonce()) {
311
+ return {
312
+ type: "approveBuilderFee", hyperliquidChain: network.chain, signatureChainId: network.signatureChainId,
313
+ maxFeeRate: `${totalisBuilder.feeDecibps / 1000}%`, builder: totalisBuilder.address, nonce,
314
+ };
315
+ }
316
+ export function approveBuilderFeeTypedData(action) {
317
+ return {
318
+ domain: userSignedDomain(action.signatureChainId),
319
+ types: { "HyperliquidTransaction:ApproveBuilderFee": approveBuilderFeeFields },
320
+ primaryType: "HyperliquidTransaction:ApproveBuilderFee",
321
+ message: { hyperliquidChain: action.hyperliquidChain, maxFeeRate: action.maxFeeRate, builder: action.builder, nonce: BigInt(action.nonce) },
322
+ };
323
+ }
324
+ /**
325
+ * An agent key for `account` under `agentName`: it can place and cancel
326
+ * orders, never withdraw or transfer. Approving a name the account already
327
+ * uses replaces that agent; an account holds a few named agents at most. The
328
+ * Totalis app uses `Totalis` and `TotalisCLI`; pick your own name.
329
+ */
330
+ export function approveAgentAction(network, agentAddress, agentName, nonce = hypercoreNonce()) {
331
+ if (!/^0x[0-9a-fA-F]{40}$/.test(agentAddress))
332
+ throw new TypeError(`not an address: ${agentAddress}`);
333
+ if (agentName === "")
334
+ throw new RangeError("name the agent");
335
+ return { type: "approveAgent", hyperliquidChain: network.chain, signatureChainId: network.signatureChainId, agentAddress: agentAddress.toLowerCase(), agentName, nonce };
336
+ }
337
+ export function approveAgentTypedData(action) {
338
+ return {
339
+ domain: userSignedDomain(action.signatureChainId),
340
+ types: { "HyperliquidTransaction:ApproveAgent": approveAgentFields },
341
+ primaryType: "HyperliquidTransaction:ApproveAgent",
342
+ message: { hyperliquidChain: action.hyperliquidChain, agentAddress: action.agentAddress, agentName: action.agentName, nonce: BigInt(action.nonce) },
343
+ };
344
+ }
345
+ async function sendUserSigned(signer, network, action, typedData, options) {
346
+ const signed = { action, nonce: action.nonce, signature: hypercoreSignature(await toTotalisSigner(signer).signTypedData(typedData)) };
347
+ const body = await post(network, signed, options);
348
+ const answer = body === undefined ? { kind: "unknown" } : classifyHypercoreAnswer(body);
349
+ return { signed, answer };
350
+ }
351
+ /** The builder fee `account` has approved for the Totalis builder, in tenths of a basis point; 0 when none. */
352
+ export async function readTotalisBuilderFee(network, account, info = hyperliquidInfo(), signal) {
353
+ const answer = await info(network, { type: "maxBuilderFee", user: account.toLowerCase(), builder: totalisBuilder.address }, signal);
354
+ if (typeof answer !== "number" || !Number.isSafeInteger(answer) || answer < 0)
355
+ throw new Error("Hyperliquid maxBuilderFee answer was malformed");
356
+ return answer;
357
+ }
358
+ /**
359
+ * Approve the Totalis builder fee for the account, once, before its first
360
+ * single. Signed by the account's own wallet: Hyperliquid refuses it from an
361
+ * agent key. Skip it when `readTotalisBuilderFee` already reaches
362
+ * `totalisBuilder.feeDecibps`.
363
+ */
364
+ export async function approveTotalisBuilder(signer, network, options = {}) {
365
+ const action = approveTotalisBuilderAction(network, options.nonce);
366
+ return sendUserSigned(signer, network, action, approveBuilderFeeTypedData(action), options);
367
+ }
368
+ /** Approve `agentAddress` as the account's Hyperliquid agent under `agentName`. Signed by the account's own wallet. */
369
+ export async function approveHyperliquidAgent(signer, network, agentAddress, agentName, options = {}) {
370
+ const action = approveAgentAction(network, agentAddress, agentName, options.nonce);
371
+ return sendUserSigned(signer, network, action, approveAgentTypedData(action), options);
372
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totalis/hip4-client",
3
- "version": "0.104.0",
3
+ "version": "0.106.0",
4
4
  "description": "Totalis HIP-4 SDK: typed HTTP clients, signer-agnostic typed data, a retrying request layer, pagination, a realtime stream and taker/maker flows",
5
5
  "type": "module",
6
6
  "files": [