@totalis/hip4-client 0.128.0 → 0.130.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.
package/dist/singles.d.ts CHANGED
@@ -19,6 +19,13 @@ export type SingleTif = "Gtc" | "Ioc" | "Alo";
19
19
  export declare function outcomeAsset(outcomeId: string | number, side: OutcomeSide): number;
20
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
21
  export declare function outcomeCoin(outcomeId: string | number, side: OutcomeSide): string;
22
+ /**
23
+ * A price strictly between 0 and 1 with at most 5 significant figures and 8
24
+ * decimals, as the minimal decimal text Hyperliquid hashes: "0.50" is "0.5".
25
+ * Any other spelling signs bytes the venue does not, so it recovers a
26
+ * different signer.
27
+ */
28
+ export declare function nativePrice(price: string): string | null;
22
29
  /** A fresh client order ID: 16 bytes, the first four the Totalis tag. */
23
30
  export declare function singleCloid(): Hex;
24
31
  export type SingleOrder = {
@@ -58,7 +65,23 @@ export type SingleOrderAction = {
58
65
  readonly f: number;
59
66
  };
60
67
  };
61
- /** One single as the `order` action Hyperliquid takes, with the Totalis builder fee attached. */
68
+ /** An `order` action without the builder fee: for an account that has not approved it yet, such as the buy whose cash creates it. */
69
+ export type SingleOrderActionWithoutBuilder = Omit<SingleOrderAction, "builder"> & {
70
+ readonly builder?: never;
71
+ };
72
+ /**
73
+ * One single as the `order` action Hyperliquid takes, with the Totalis
74
+ * builder fee attached unless `builder` is `false`.
75
+ */
76
+ export declare function singleOrderAction(order: SingleOrder, options: {
77
+ readonly builder: false;
78
+ }): SingleOrderActionWithoutBuilder;
79
+ export declare function singleOrderAction(order: SingleOrder, options: {
80
+ readonly builder?: true;
81
+ }): SingleOrderAction;
82
+ export declare function singleOrderAction(order: SingleOrder, options: {
83
+ readonly builder?: boolean;
84
+ }): SingleOrderAction | SingleOrderActionWithoutBuilder;
62
85
  export declare function singleOrderAction(order: SingleOrder): SingleOrderAction;
63
86
  /** A resting single to cancel, by the cloid it was placed with or the `oid` Hyperliquid gave it. */
64
87
  export type SingleCancel = {
@@ -87,12 +110,15 @@ export type SingleCancelAction = CancelByCloidAction | CancelByOidAction;
87
110
  /** Cancels as Hyperliquid takes them: one action for every target of one kind, so all by cloid or all by oid. */
88
111
  export declare function singleCancelAction(targets: readonly SingleCancel[]): SingleCancelAction;
89
112
  export type SingleAction = SingleOrderAction | SingleCancelAction;
113
+ type L1Action = SingleAction | SingleOrderActionWithoutBuilder;
90
114
  /** The hash an L1 action's signature binds: the packed action, its nonce, no vault, then its deadline when it has one. */
115
+ export declare function l1ActionHash(action: SingleOrderAction | SingleOrderActionWithoutBuilder, nonce: number, expiresAfter?: number): Hex;
91
116
  export declare function l1ActionHash(action: SingleAction, nonce: number, expiresAfter?: number): Hex;
92
117
  /** 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`. */
118
+ export declare function l1TypedData(network: HyperliquidNetwork, action: SingleOrderAction | SingleOrderActionWithoutBuilder, nonce: number, expiresAfter?: number): TypedData;
93
119
  export declare function l1TypedData(network: HyperliquidNetwork, action: SingleAction, nonce: number, expiresAfter?: number): TypedData;
94
120
  /** An L1 action as Hyperliquid's `/exchange` takes it. Plain JSON. */
95
- export type SignedL1Action<Action extends SingleAction = SingleAction> = {
121
+ export type SignedL1Action<Action extends L1Action = SingleAction> = {
96
122
  readonly action: Action;
97
123
  readonly nonce: number;
98
124
  readonly signature: HypercoreSignature;
@@ -109,6 +135,7 @@ export type L1Options = {
109
135
  * Browser wallets often refuse its signing domain (chain 1337); approve an
110
136
  * agent key once (`approveHyperliquidAgent`) and sign orders with that.
111
137
  */
138
+ export declare function signL1Action<Action extends SingleOrderAction | SingleOrderActionWithoutBuilder>(signer: SignerInput, network: HyperliquidNetwork, action: Action, options?: L1Options): Promise<SignedL1Action<Action>>;
112
139
  export declare function signL1Action<Action extends SingleAction>(signer: SignerInput, network: HyperliquidNetwork, action: Action, options?: L1Options): Promise<SignedL1Action<Action>>;
113
140
  export type ExchangeOptions = {
114
141
  readonly fetch?: typeof fetch;
@@ -145,6 +172,7 @@ export type SingleCancelAnswer = {
145
172
  readonly kind: "unknown";
146
173
  };
147
174
  export declare function singleCancelAnswers(body: unknown, count: number): SingleCancelAnswer[];
175
+ export declare function submitSingleOrder(network: HyperliquidNetwork, signed: SignedL1Action<SingleOrderAction | SingleOrderActionWithoutBuilder>, options?: ExchangeOptions): Promise<SingleOrderAnswer>;
148
176
  export declare function submitSingleOrder(network: HyperliquidNetwork, signed: SignedL1Action<SingleOrderAction>, options?: ExchangeOptions): Promise<SingleOrderAnswer>;
149
177
  export declare function submitSingleCancel(network: HyperliquidNetwork, signed: SignedL1Action<SingleCancelAction>, options?: ExchangeOptions): Promise<SingleCancelAnswer[]>;
150
178
  /**
@@ -174,8 +202,10 @@ export type SingleOrderStatus = {
174
202
  };
175
203
  /**
176
204
  * 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.
205
+ * under that id when it answered. That is a hint, never proof the order
206
+ * never landed, even after the action's `expiresAfter`: Hyperliquid gives no
207
+ * guarantee its reads are complete or current, so an order whose answer was
208
+ * lost stays unresolved until other evidence settles it.
179
209
  */
180
210
  export declare function readSingleOrder(network: HyperliquidNetwork, account: string, id: Hex | number, info?: HyperliquidInfo, signal?: AbortSignal): Promise<SingleOrderStatus | null>;
181
211
  export type ApproveBuilderFeeAction = {
@@ -231,3 +261,4 @@ export declare function approveHyperliquidAgent(signer: SignerInput, network: Hy
231
261
  signed: SignedUserAction<ApproveAgentAction>;
232
262
  answer: HypercoreAnswer;
233
263
  }>;
264
+ export {};
package/dist/singles.js CHANGED
@@ -44,14 +44,17 @@ export function outcomeCoin(outcomeId, side) {
44
44
  * Any other spelling signs bytes the venue does not, so it recovers a
45
45
  * different signer.
46
46
  */
47
- function priceWire(price) {
47
+ export function nativePrice(price) {
48
48
  const match = /^0?\.(\d+)$/.exec(price);
49
49
  const fraction = (match?.[1] ?? "").replace(/0+$/, "");
50
50
  const figures = fraction.replace(/^0+/, "").length;
51
- if (match === null || figures === 0 || figures > PRICE_FIGURES || fraction.length > PRICE_DECIMALS) {
51
+ return match === null || figures === 0 || figures > PRICE_FIGURES || fraction.length > PRICE_DECIMALS ? null : `0.${fraction}`;
52
+ }
53
+ function priceWire(price) {
54
+ const wire = nativePrice(price);
55
+ if (wire === null)
52
56
  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}`;
57
+ return wire;
55
58
  }
56
59
  function sharesWire(shares) {
57
60
  const text = String(shares);
@@ -69,12 +72,11 @@ export function singleCloid() {
69
72
  id.set(orderTag);
70
73
  return hex(id);
71
74
  }
72
- /** One single as the `order` action Hyperliquid takes, with the Totalis builder fee attached. */
73
- export function singleOrderAction(order) {
75
+ export function singleOrderAction(order, options = {}) {
74
76
  const cloid = order.cloid ?? singleCloid();
75
77
  if (!/^0x[0-9a-fA-F]{32}$/.test(cloid))
76
78
  throw new TypeError(`cloid must be 16 bytes of hex: ${cloid}`);
77
- return {
79
+ const action = {
78
80
  type: "order",
79
81
  orders: [{
80
82
  a: outcomeAsset(order.outcomeId, order.side),
@@ -86,8 +88,8 @@ export function singleOrderAction(order) {
86
88
  c: cloid.toLowerCase(),
87
89
  }],
88
90
  grouping: "na",
89
- builder: { b: totalisBuilder.address, f: totalisBuilder.feeDecibps },
90
91
  };
92
+ return options.builder === false ? action : { ...action, builder: { b: totalisBuilder.address, f: totalisBuilder.feeDecibps } };
91
93
  }
92
94
  /** Cancels as Hyperliquid takes them: one action for every target of one kind, so all by cloid or all by oid. */
93
95
  export function singleCancelAction(targets) {
@@ -165,8 +167,7 @@ function bigEndian(value, length) {
165
167
  }
166
168
  return bytes;
167
169
  }
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
+ function actionHash(action, nonce, expiresAfter) {
170
171
  const bytes = [];
171
172
  pack(action, bytes);
172
173
  bytes.push(...bigEndian(nonce, 8), 0);
@@ -174,23 +175,21 @@ export function l1ActionHash(action, nonce, expiresAfter) {
174
175
  bytes.push(0, ...bigEndian(expiresAfter, 8));
175
176
  return hex(keccak_256(Uint8Array.from(bytes)));
176
177
  }
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
+ const typedDataOf = (network, action, nonce, expiresAfter) => ({
179
+ domain: { name: "Exchange", version: "1", chainId: 1337n, verifyingContract: "0x0000000000000000000000000000000000000000" },
180
+ types: { Agent: [{ name: "source", type: "string" }, { name: "connectionId", type: "bytes32" }] },
181
+ primaryType: "Agent",
182
+ message: { source: network.chain === "Mainnet" ? "a" : "b", connectionId: actionHash(action, nonce, expiresAfter) },
183
+ });
184
+ export function l1ActionHash(action, nonce, expiresAfter) {
185
+ return actionHash(action, nonce, expiresAfter);
186
+ }
178
187
  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
- };
188
+ return typedDataOf(network, action, nonce, expiresAfter);
185
189
  }
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
190
  export async function signL1Action(signer, network, action, options = {}) {
192
191
  const nonce = options.nonce ?? hypercoreNonce();
193
- const raw = await toTotalisSigner(signer).signTypedData(l1TypedData(network, action, nonce, options.expiresAfter));
192
+ const raw = await toTotalisSigner(signer).signTypedData(typedDataOf(network, action, nonce, options.expiresAfter));
194
193
  return { action, nonce, signature: hypercoreSignature(raw), ...(options.expiresAfter === undefined ? {} : { expiresAfter: options.expiresAfter }) };
195
194
  }
196
195
  /** POST one signed action to the network's `/exchange` and return its JSON answer; `undefined` when no answer arrived or it was not JSON. */
@@ -269,8 +268,10 @@ export async function cancelSingles(signer, network, targets, options = {}) {
269
268
  }
270
269
  /**
271
270
  * 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.
271
+ * under that id when it answered. That is a hint, never proof the order
272
+ * never landed, even after the action's `expiresAfter`: Hyperliquid gives no
273
+ * guarantee its reads are complete or current, so an order whose answer was
274
+ * lost stays unresolved until other evidence settles it.
274
275
  */
275
276
  export async function readSingleOrder(network, account, id, info = hyperliquidInfo(), signal) {
276
277
  const answer = await info(network, { type: "orderStatus", user: account.toLowerCase(), oid: typeof id === "string" ? id.toLowerCase() : id }, signal);
package/dist/totalis.d.ts CHANGED
@@ -253,6 +253,18 @@ export declare const fundWindowMs = 4000;
253
253
  export type Chooser<Offer> = (offers: readonly Offer[]) => Offer | undefined;
254
254
  /** The highest payout (ties go to the earliest). */
255
255
  export declare function bestQuote(): Chooser<EntryQuote>;
256
+ /**
257
+ * The highest payout net of fees (`netPayout`), what the taker receives if
258
+ * every leg wins; ties go to the lowest `receipt_sequence` where both quotes
259
+ * carry one, then the lowest `quote_id`, whatever order they arrived in.
260
+ */
261
+ export declare function bestNetQuote<Offer extends {
262
+ readonly signing: {
263
+ readonly entry: Pick<EntryQuote["signing"]["entry"], "stake" | "payout" | "fee_bps" | "taker_fee_bps">;
264
+ };
265
+ readonly quote_id?: string;
266
+ readonly receipt_sequence?: string;
267
+ } = EntryQuote>(): Chooser<Offer>;
256
268
  /** The highest price and, given `minPrice` in USDC base units, no lower than it. */
257
269
  export declare function bestBid(minPrice?: bigint): Chooser<CashoutBid>;
258
270
  export type TotalisOptions = Omit<ApiClientOptions, "accessToken"> & {
package/dist/totalis.js CHANGED
@@ -3,7 +3,7 @@ import { createApiKeyClient, issueApiKey, rotateApiKey } from "./api-keys.js";
3
3
  import { audienceClient, headerRecord } from "./base.js";
4
4
  import { bridgeAction, bridgeGasBuffer, hyperliquidExchange, hyperliquidNetwork, readCoreCash, settleHypercore, signSendAsset, usdcUnits, } from "./hypercore.js";
5
5
  import { BalanceUnknownError, EntryError, ExitUnavailableError, normalizeError, WalletApprovalError } from "./flow-errors.js";
6
- import { comboAllowance, offeredCore, spendableCash } from "./money.js";
6
+ import { comboAllowance, netPayout, offeredCore, spendableCash } from "./money.js";
7
7
  import { ApiError, backoffDelay, NetworkError, randomBytes32, resendable, retryingFetch, rfqLegsInOrder, sendOnce, singleFetch, sleep, unwrap, uuidv7 } from "./request.js";
8
8
  import { abortReason, anySignal, timeoutSignal } from "./runtime.js";
9
9
  import { toTotalisSigner } from "./signer.js";
@@ -86,6 +86,26 @@ export function bestQuote() {
86
86
  return (quotes) => quotes
87
87
  .reduce((best, quote) => best === undefined || BigInt(quote.payout) > BigInt(best.payout) ? quote : best, undefined);
88
88
  }
89
+ /**
90
+ * The highest payout net of fees (`netPayout`), what the taker receives if
91
+ * every leg wins; ties go to the lowest `receipt_sequence` where both quotes
92
+ * carry one, then the lowest `quote_id`, whatever order they arrived in.
93
+ */
94
+ export function bestNetQuote() {
95
+ return (quotes) => quotes.reduce((best, quote) => {
96
+ if (best === undefined)
97
+ return quote;
98
+ const difference = netPayout(quote.signing.entry) - netPayout(best.signing.entry);
99
+ if (difference !== 0n)
100
+ return difference > 0n ? quote : best;
101
+ if (quote.receipt_sequence && best.receipt_sequence) {
102
+ const receipt = BigInt(quote.receipt_sequence) - BigInt(best.receipt_sequence);
103
+ if (receipt !== 0n)
104
+ return receipt < 0n ? quote : best;
105
+ }
106
+ return quote.quote_id && best.quote_id && quote.quote_id.toLowerCase() < best.quote_id.toLowerCase() ? quote : best;
107
+ }, undefined);
108
+ }
89
109
  /** The highest price and, given `minPrice` in USDC base units, no lower than it. */
90
110
  export function bestBid(minPrice) {
91
111
  return (bids) => bids
@@ -1349,8 +1369,11 @@ export function createTotalis(options) {
1349
1369
  * with its withdrawals. An account with no HyperCore account yet gets
1350
1370
  * CORE_ACCOUNT_ACTIVATION_REQUIRED until the user accepts Hyperliquid's
1351
1371
  * one-time 1 USDC activation fee, sent as `activationFeeAccepted` on an
1352
- * exit of at least 2 USDC. A deployment without exits to HyperCore (staging)
1353
- * throws `ExitUnavailableError` before anything is signed.
1372
+ * exit of at least 2 USDC. A deployment without exits to HyperCore throws
1373
+ * `ExitUnavailableError` before anything is signed. A client with an
1374
+ * `agent` signs this exit with it. On staging, whose vault names no router,
1375
+ * an agent's exit is refused (`INVALID_REQUEST`), so sign it there with a
1376
+ * client created without `agent`.
1354
1377
  */
1355
1378
  async function signCoreExit(request) {
1356
1379
  return signExit(request, await coreExitRoute());
@@ -1406,7 +1429,7 @@ export function createTotalis(options) {
1406
1429
  * POST a signed exit under its exit ID, resending the same bytes on a lost
1407
1430
  * answer. The 202 is admission: follow it with `waitForCoreExit`.
1408
1431
  * The venue's `CORE_EXIT_UNAVAILABLE`, answered only on a deployment that
1409
- * runs no exits (staging), throws `ExitUnavailableError`.
1432
+ * runs no exits, throws `ExitUnavailableError`.
1410
1433
  */
1411
1434
  async function sendCoreExit(signed) {
1412
1435
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totalis/hip4-client",
3
- "version": "0.128.0",
3
+ "version": "0.130.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": [