@totalis/hip4-client 0.130.0 → 0.131.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/CHANGELOG.md +114 -0
- package/README.md +13 -1
- package/dist/client.d.ts +2 -1
- package/dist/client.js +2 -1
- package/dist/generated/client.d.ts +3 -1
- package/dist/generated/errors.d.ts +3 -1
- package/dist/generated/errors.js +17 -2
- package/dist/generated/maker.d.ts +2 -1
- package/dist/generated/openapi.d.ts +258 -59
- package/dist/generated/realtime.d.ts +12 -1
- package/dist/generated/version.d.ts +7 -7
- package/dist/generated/version.js +8 -5
- package/dist/hypercore.d.ts +6 -0
- package/dist/hypercore.js +7 -1
- package/dist/single-orders.d.ts +223 -0
- package/dist/single-orders.js +277 -0
- package/dist/singles.d.ts +4 -1
- package/dist/singles.js +4 -1
- package/dist/totalis.d.ts +6 -0
- package/dist/totalis.js +34 -0
- package/package.json +2 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Generated by scripts/generate.mjs; do not edit.
|
|
2
|
-
export const sdkVersion = "
|
|
3
|
-
export const openapiSha256 = "
|
|
2
|
+
export const sdkVersion = "288.0.0-social-feed-moments";
|
|
3
|
+
export const openapiSha256 = "a5ad4ec8c298fcb2d43e9537cac14551baaf25ef521cb294b60f4e98e0a65e29";
|
|
4
4
|
export const realtimeSha256 = "02c6dff24166c102d9dc8d0441bc6ed0268850d126d5ac184efa0101d22099f8";
|
|
5
5
|
export const jsonSchemaSha256 = {
|
|
6
6
|
"account.schema.json": "3120357249f55f8481d5afb7a99112f803c22c6a1cbe3adadca478bb313f8160",
|
|
@@ -13,11 +13,11 @@ export const jsonSchemaSha256 = {
|
|
|
13
13
|
"maker-access.schema.json": "49698ee0235e42064aae0397db1e0f646bdc10d9dfa10121714ba06dd69fee3b",
|
|
14
14
|
"maker-action.schema.json": "07a5cb07976d06315733282d1bb4f1416c23d3e7a8a4e8941228ac559a2f7467",
|
|
15
15
|
"maker-telemetry.schema.json": "85b111ce0f4935299d1116071b43de12e775bef4e0c283c12f19046d34374a9c",
|
|
16
|
-
"market-data.schema.json": "
|
|
17
|
-
"product-metadata.schema.json": "
|
|
16
|
+
"market-data.schema.json": "2eb622b7412a2771a74a57a7e1fdc3e8efcda49b944e41e3bff88e0f355f2cc9",
|
|
17
|
+
"product-metadata.schema.json": "18d1dad117c8ef3c8b3d1d147631cc565ef7816aadec99f2534f8a7fbd2e16a4",
|
|
18
18
|
"quote.schema.json": "5c16a54c428656a4e8c1042b2057ce8290e6eebcc02b237f5dce7e4c13b7ded0",
|
|
19
19
|
"realtime.schema.json": "02c6dff24166c102d9dc8d0441bc6ed0268850d126d5ac184efa0101d22099f8",
|
|
20
|
-
"social.schema.json": "
|
|
20
|
+
"social.schema.json": "28304fc474f2d4fe1fab33c68dd32a24e6eb8a43da62c89f79c51c8875be6cd4"
|
|
21
21
|
};
|
|
22
22
|
export const operations = {
|
|
23
23
|
"client": [
|
|
@@ -150,12 +150,14 @@ export const operations = {
|
|
|
150
150
|
"listOperations",
|
|
151
151
|
"listPartnerFills",
|
|
152
152
|
"listPartnerWebhookEvents",
|
|
153
|
+
"listPolymarketMarkets",
|
|
153
154
|
"listQuotes",
|
|
154
155
|
"listSocialActivity",
|
|
155
156
|
"listSocialFeed",
|
|
156
157
|
"listSocialFollowers",
|
|
157
158
|
"listSocialFollowing",
|
|
158
159
|
"listSocialPositions",
|
|
160
|
+
"listSocialSuggestions",
|
|
159
161
|
"listTraderPositions",
|
|
160
162
|
"listTraderTrades",
|
|
161
163
|
"markMyNotificationsRead",
|
|
@@ -232,6 +234,7 @@ export const operations = {
|
|
|
232
234
|
"listMakerQuoteHistory",
|
|
233
235
|
"listMarkets",
|
|
234
236
|
"listOperations",
|
|
237
|
+
"listPolymarketMarkets",
|
|
235
238
|
"listRfqs",
|
|
236
239
|
"publishMakerTelemetry",
|
|
237
240
|
"searchCatalog",
|
package/dist/hypercore.d.ts
CHANGED
|
@@ -37,6 +37,12 @@ export type SignedSendAsset = {
|
|
|
37
37
|
readonly signature: HypercoreSignature;
|
|
38
38
|
};
|
|
39
39
|
export declare function sendAssetTypedData(action: SendAssetAction): TypedData;
|
|
40
|
+
/**
|
|
41
|
+
* The nonce after `last` at millisecond time `now`: `now`, or `last + 1` when
|
|
42
|
+
* that is not past it. Hyperliquid spends each nonce once, so keep `last`
|
|
43
|
+
* where it outlives a restart and draw every action's nonce from it.
|
|
44
|
+
*/
|
|
45
|
+
export declare const nextNonce: (last: number, now: number) => number;
|
|
40
46
|
/** Millisecond time, strictly increasing within this process: Hyperliquid spends each nonce once. */
|
|
41
47
|
export declare function hypercoreNonce(now?: number): number;
|
|
42
48
|
/** 6-decimal USDC base units as Hyperliquid's decimal text: 1500000n is "1.5". */
|
package/dist/hypercore.js
CHANGED
|
@@ -34,10 +34,16 @@ export function sendAssetTypedData(action) {
|
|
|
34
34
|
message: { ...fields, nonce: BigInt(nonce) },
|
|
35
35
|
};
|
|
36
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* The nonce after `last` at millisecond time `now`: `now`, or `last + 1` when
|
|
39
|
+
* that is not past it. Hyperliquid spends each nonce once, so keep `last`
|
|
40
|
+
* where it outlives a restart and draw every action's nonce from it.
|
|
41
|
+
*/
|
|
42
|
+
export const nextNonce = (last, now) => Math.max(now, last + 1);
|
|
37
43
|
let lastNonce = 0;
|
|
38
44
|
/** Millisecond time, strictly increasing within this process: Hyperliquid spends each nonce once. */
|
|
39
45
|
export function hypercoreNonce(now = Date.now()) {
|
|
40
|
-
lastNonce =
|
|
46
|
+
lastNonce = nextNonce(lastNonce, now);
|
|
41
47
|
return lastNonce;
|
|
42
48
|
}
|
|
43
49
|
/** 6-decimal USDC base units as Hyperliquid's decimal text: 1500000n is "1.5". */
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { type OrderFill } from "./book-walk.js";
|
|
2
|
+
import type { paths } from "./generated/client.js";
|
|
3
|
+
import { type HyperliquidNetwork } from "./hypercore.js";
|
|
4
|
+
import type { Repaired } from "./request.js";
|
|
5
|
+
import type { SignerInput } from "./signer.js";
|
|
6
|
+
import { type ExchangeOptions, type OutcomeSide, type SignedL1Action, type SingleOrder, type SingleOrderAction, type SingleOrderActionWithoutBuilder, type SingleOrderAnswer, type SingleOrderStatus } from "./singles.js";
|
|
7
|
+
import { type Hex } from "./typed-data.js";
|
|
8
|
+
type OrderTerms = {
|
|
9
|
+
readonly kind: "ORDER";
|
|
10
|
+
/** The intent's ID: one press, whatever retries it. */
|
|
11
|
+
readonly idempotencyKey: string;
|
|
12
|
+
/** The main account the order trades for, lowercase: never the agent key that signed it. */
|
|
13
|
+
readonly account: Hex;
|
|
14
|
+
/** The Hyperliquid network's chain: 999 mainnet, 998 testnet. */
|
|
15
|
+
readonly chainId: 998 | 999;
|
|
16
|
+
readonly outcomeId: string;
|
|
17
|
+
readonly side: OutcomeSide;
|
|
18
|
+
readonly direction: "BUY" | "SELL";
|
|
19
|
+
readonly size: string;
|
|
20
|
+
readonly price: string;
|
|
21
|
+
readonly tif: "Ioc";
|
|
22
|
+
readonly cloid: Hex;
|
|
23
|
+
readonly expiresAfter: number;
|
|
24
|
+
readonly recordedAt: number;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* A Core-funded IOC as it was claimed before it was signed: plain JSON
|
|
28
|
+
* without the signature, so nothing recovered from it can be sent or signed
|
|
29
|
+
* again. Its terms are exactly the ones signed. The fields are the Totalis
|
|
30
|
+
* app's own order record's, plus `version`, `nonce` and `afterHeight`, which
|
|
31
|
+
* bound where the order could land. A record an older Totalis app wrote, or
|
|
32
|
+
* rewrote, has none of the three: it is found by its cloid, but its absence is
|
|
33
|
+
* never proven.
|
|
34
|
+
*/
|
|
35
|
+
export type SingleOrderRecord = OrderTerms & ({
|
|
36
|
+
readonly version: 1;
|
|
37
|
+
readonly nonce: number;
|
|
38
|
+
readonly afterHeight: number | null;
|
|
39
|
+
} | {
|
|
40
|
+
readonly version?: never;
|
|
41
|
+
readonly nonce?: never;
|
|
42
|
+
readonly afterHeight?: never;
|
|
43
|
+
});
|
|
44
|
+
/**
|
|
45
|
+
* Where the node order history that proves IOCs stood for one account on one
|
|
46
|
+
* network (`readOrderHistory`): `height` is `null` until it follows the
|
|
47
|
+
* account. It counts only for that account and network.
|
|
48
|
+
*/
|
|
49
|
+
export type OrderHistoryCursor = {
|
|
50
|
+
readonly account: Hex;
|
|
51
|
+
readonly chainId: 998 | 999;
|
|
52
|
+
readonly height: number | null;
|
|
53
|
+
};
|
|
54
|
+
/** The venue's proof of one IOC by its cloid (`GET /v1/hypercore/orders/{cloid}`). */
|
|
55
|
+
export type SingleOrderProof = Repaired<paths["/v1/hypercore/orders/{cloid}"]["get"]["responses"][200]["content"]["application/json"]>;
|
|
56
|
+
/**
|
|
57
|
+
* What a saved IOC did, as far as the evidence proves it.
|
|
58
|
+
*
|
|
59
|
+
* - `filled`: it traded `fill.shares`, all of it (`fill.kind` `filled`) or
|
|
60
|
+
* part, the rest cancelled (`partial`). `averagePrice` and `fee` are `null`
|
|
61
|
+
* until the reply or its fills give them (`settledFill`).
|
|
62
|
+
* - `none`: it traded nothing and never will: Hyperliquid refused it
|
|
63
|
+
* (`REFUSED`, with its `error`), it reached the book and filled nothing
|
|
64
|
+
* (`UNFILLED`), the venue's node history proves it never reached matching
|
|
65
|
+
* (`ABSENT`), or it was claimed but never sent and never will be
|
|
66
|
+
* (`NOT_SENT`: the signature failed or was refused, or a key other than the
|
|
67
|
+
* account's or its agent's signed it, as when a wallet switches mid-press).
|
|
68
|
+
* - `unknown`: not proven yet; read again. While it lasts, hold new buys of
|
|
69
|
+
* its outcome (`buyHeldBy`) and never send it, or another, in its place.
|
|
70
|
+
* - `unprovable`: its deadline has passed in the node history, Hyperliquid
|
|
71
|
+
* answered that it holds no order under its cloid, and the history can
|
|
72
|
+
* never prove whether it landed: it missed blocks in the order's window
|
|
73
|
+
* (`GAP`), or does not reach back to where it starts (`UNCOVERED`: an order
|
|
74
|
+
* placed before the history followed the account, or a record without the
|
|
75
|
+
* window). Only then may the user choose to buy again; keep the record,
|
|
76
|
+
* since a later read can still find the order. Only `settleSingleOrder`,
|
|
77
|
+
* from a Hyperliquid lookup it makes itself, says this.
|
|
78
|
+
*/
|
|
79
|
+
export type SingleOrderOutcome = {
|
|
80
|
+
readonly kind: "filled";
|
|
81
|
+
readonly fill: OrderFill & {
|
|
82
|
+
readonly oid: number;
|
|
83
|
+
};
|
|
84
|
+
} | {
|
|
85
|
+
readonly kind: "none";
|
|
86
|
+
readonly reason: "REFUSED" | "UNFILLED" | "ABSENT" | "NOT_SENT";
|
|
87
|
+
readonly error?: string;
|
|
88
|
+
} | {
|
|
89
|
+
readonly kind: "unknown";
|
|
90
|
+
} | {
|
|
91
|
+
readonly kind: "unprovable";
|
|
92
|
+
readonly reason: "GAP" | "UNCOVERED";
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Evidence about a saved IOC: its reply, Hyperliquid's `orderStatus` by its
|
|
96
|
+
* cloid (`readSingleOrder`, `null` for `unknownOid`) and the venue's proof.
|
|
97
|
+
* Leave out what was not read or failed to read.
|
|
98
|
+
*/
|
|
99
|
+
export type SingleOrderEvidence = {
|
|
100
|
+
readonly answer?: SingleOrderAnswer;
|
|
101
|
+
readonly status?: SingleOrderStatus | null;
|
|
102
|
+
readonly proof?: SingleOrderProof;
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* Carries a signed order to Hyperliquid and returns Hyperliquid's own answer
|
|
106
|
+
* body. Throw when no answer arrived or the one that did is not Hyperliquid's
|
|
107
|
+
* (an HTTP status other than 2xx, such as a gateway's): the order may have
|
|
108
|
+
* landed.
|
|
109
|
+
*/
|
|
110
|
+
export type L1Transport = (signed: SignedL1Action<SingleOrderAction | SingleOrderActionWithoutBuilder>, signal?: AbortSignal) => Promise<unknown>;
|
|
111
|
+
/** A single sent as an IOC: whatever does not fill at once is cancelled. */
|
|
112
|
+
export type SingleIoc = Omit<SingleOrder, "tif" | "cloid">;
|
|
113
|
+
export type SingleIocRequest = {
|
|
114
|
+
/**
|
|
115
|
+
* The intent's UUIDv7, made once per press and kept by every retry of it:
|
|
116
|
+
* an intent is placed at most once. A new press is a new intent.
|
|
117
|
+
*/
|
|
118
|
+
readonly intentId: string;
|
|
119
|
+
/** The main account the order trades for. */
|
|
120
|
+
readonly account: string;
|
|
121
|
+
/**
|
|
122
|
+
* The address of the account's approved Hyperliquid agent when `signer` is
|
|
123
|
+
* that agent key. The order is sent only when its signature recovers to the
|
|
124
|
+
* account or this agent. Approve a freshly generated key every time and
|
|
125
|
+
* never approve an old one again: once Hyperliquid prunes an agent (replaced,
|
|
126
|
+
* expired, or its account emptied) it may drop the agent's used nonces, and
|
|
127
|
+
* anything that key signed before can then be replayed.
|
|
128
|
+
*/
|
|
129
|
+
readonly agent?: string;
|
|
130
|
+
readonly order: SingleIoc;
|
|
131
|
+
/**
|
|
132
|
+
* The latest `readOrderHistory()` read before this call, or `null`. Read it
|
|
133
|
+
* in the background, never on the way to signing. One for another account
|
|
134
|
+
* or network counts as `null`.
|
|
135
|
+
*/
|
|
136
|
+
readonly history: OrderHistoryCursor | null;
|
|
137
|
+
/**
|
|
138
|
+
* The claim, before anything is signed. Atomically, under the account's
|
|
139
|
+
* lock: when a claim is stored under `singleIntentKey(record)`, resolve
|
|
140
|
+
* with its record unchanged; otherwise refuse (throw) when `buyHeldBy`
|
|
141
|
+
* finds a buy to wait on, store the claim under that key, put the record
|
|
142
|
+
* wherever the app's order journal keeps it, and resolve with the claim's
|
|
143
|
+
* record as read back. The claim key is the intent's alone: nothing that
|
|
144
|
+
* retires journal records, an older app's included, ever removes it. Mark a
|
|
145
|
+
* claim settled once its order is `filled` or `none`: a settled claim holds
|
|
146
|
+
* no buy and counts toward no limit on pending orders, and only its key need
|
|
147
|
+
* stay, for as long as the intent can still be retried.
|
|
148
|
+
*/
|
|
149
|
+
readonly save: (record: SingleOrderRecord) => Promise<unknown>;
|
|
150
|
+
/** `false` leaves the Totalis builder fee off; it is attached by default. */
|
|
151
|
+
readonly builder?: boolean;
|
|
152
|
+
/** Defaults to `hypercoreNonce()`; pass the next from your own nonce line. */
|
|
153
|
+
readonly nonce?: number;
|
|
154
|
+
/** Epoch ms after which Hyperliquid refuses the order; 30 s from now by default. */
|
|
155
|
+
readonly expiresAfter?: number;
|
|
156
|
+
/** Sends the signed order; one POST to the network's `/exchange` by default. */
|
|
157
|
+
readonly transport?: L1Transport;
|
|
158
|
+
};
|
|
159
|
+
/** Where an intent's claim is stored: its own key per account, network and intent, apart from any order journal. */
|
|
160
|
+
export declare const singleIntentKey: (record: Pick<SingleOrderRecord, "account" | "chainId" | "idempotencyKey">) => string;
|
|
161
|
+
/** The cursor `GET /v1/hypercore/order-history` answered, on the deployment's chain. */
|
|
162
|
+
export declare function orderHistoryCursor(answer: {
|
|
163
|
+
readonly account: string;
|
|
164
|
+
readonly height: number | null;
|
|
165
|
+
}, chainId: string): OrderHistoryCursor;
|
|
166
|
+
/**
|
|
167
|
+
* A saved record from its JSON text or parsed value: one `placeSingleIoc`
|
|
168
|
+
* wrote, or an IOC record of an older Totalis app (no `version`); `null` for
|
|
169
|
+
* anything else.
|
|
170
|
+
*/
|
|
171
|
+
export declare function parseSingleOrderRecord(value: unknown): SingleOrderRecord | null;
|
|
172
|
+
/**
|
|
173
|
+
* Place one intent as an IOC, at most once: claim its record with `save`,
|
|
174
|
+
* sign exactly what was claimed, check that the account or its agent signed
|
|
175
|
+
* it, then send it once. It never resends or re-signs. An intent this account
|
|
176
|
+
* claimed before on this network comes back as its claimed record with
|
|
177
|
+
* `unknown`, unsigned and unsent: settle it. A throw means nothing was
|
|
178
|
+
* claimed or sent. A claimed order that could not be signed, or was signed by
|
|
179
|
+
* another key, comes back `none` `NOT_SENT`: settle its claim, which keeps the
|
|
180
|
+
* intent from being placed again and holds no buy. Otherwise `outcome` is
|
|
181
|
+
* what the answer proves; on `unknown`, settle the record by evidence
|
|
182
|
+
* (`settleSingleOrder`).
|
|
183
|
+
*/
|
|
184
|
+
export declare function placeSingleIoc(signer: SignerInput, network: HyperliquidNetwork, request: SingleIocRequest, options?: ExchangeOptions): Promise<{
|
|
185
|
+
readonly record: SingleOrderRecord;
|
|
186
|
+
readonly outcome: SingleOrderOutcome;
|
|
187
|
+
}>;
|
|
188
|
+
/**
|
|
189
|
+
* The saved order a new buy of `outcomeId` waits on: an unsettled buy of
|
|
190
|
+
* either side of it, by the same account on the same network. Pass the
|
|
191
|
+
* records not yet settled. Sells never wait: Hyperliquid refuses a sale of
|
|
192
|
+
* shares the account no longer holds.
|
|
193
|
+
*/
|
|
194
|
+
export declare function buyHeldBy(records: readonly SingleOrderRecord[], press: {
|
|
195
|
+
readonly account: string;
|
|
196
|
+
readonly chainId: number;
|
|
197
|
+
readonly outcomeId: string | number;
|
|
198
|
+
}): SingleOrderRecord | undefined;
|
|
199
|
+
/**
|
|
200
|
+
* The window a record is proven over: from `afterHeight` when it has one,
|
|
201
|
+
* else from a day before its nonce. A record without a nonce is searched from
|
|
202
|
+
* a day before its deadline, which only finds it: its absence is never proven.
|
|
203
|
+
*/
|
|
204
|
+
export declare const proofWindow: (record: SingleOrderRecord) => {
|
|
205
|
+
nonce: number;
|
|
206
|
+
afterHeight: number | null;
|
|
207
|
+
};
|
|
208
|
+
/**
|
|
209
|
+
* What the evidence proves about a saved IOC (`SingleOrderOutcome`). An order
|
|
210
|
+
* found anywhere settles it, and evidence that contradicts the record counts
|
|
211
|
+
* for nothing. Absence comes only from the venue's proof over the record's
|
|
212
|
+
* own window: Hyperliquid not knowing the cloid is never proof, and the
|
|
213
|
+
* deadline alone settles nothing. Never `unprovable`: only
|
|
214
|
+
* `settleSingleOrder` says that, from a lookup it made itself.
|
|
215
|
+
*/
|
|
216
|
+
export declare function singleOrderOutcome(record: SingleOrderRecord, evidence: SingleOrderEvidence): SingleOrderOutcome;
|
|
217
|
+
/**
|
|
218
|
+
* `singleOrderOutcome`, where `lookedUpAfter` says `evidence.status` is a
|
|
219
|
+
* Hyperliquid lookup made after `evidence.proof` was read: only then can the
|
|
220
|
+
* outcome be `unprovable`.
|
|
221
|
+
*/
|
|
222
|
+
export declare function outcomeOf(record: SingleOrderRecord, evidence: SingleOrderEvidence, lookedUpAfter: boolean): SingleOrderOutcome;
|
|
223
|
+
export {};
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { secp256k1 } from "@noble/curves/secp256k1";
|
|
2
|
+
import { keccak_256 } from "@noble/hashes/sha3";
|
|
3
|
+
import { settledFill } from "./book-walk.js";
|
|
4
|
+
import { hypercoreNonce } from "./hypercore.js";
|
|
5
|
+
import { l1TypedData, nativePrice, outcomeAsset, outcomeCoin, signL1Action, singleCloid, singleOrderAction, singleOrderAnswer, } from "./singles.js";
|
|
6
|
+
import { hashTypedData } from "./typed-data.js";
|
|
7
|
+
const orderLifeMs = 30_000;
|
|
8
|
+
const day = 24 * 60 * 60 * 1000;
|
|
9
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10
|
+
const matches = (pattern, value) => typeof value === "string" && pattern.test(value);
|
|
11
|
+
const isHex = (pattern, value) => matches(pattern, value);
|
|
12
|
+
const isAccount = (value) => isHex(/^0x[0-9a-f]{40}$/, value);
|
|
13
|
+
const positive = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
14
|
+
const uuid7 = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
15
|
+
/** Where an intent's claim is stored: its own key per account, network and intent, apart from any order journal. */
|
|
16
|
+
export const singleIntentKey = (record) => `totalis:single-intent:v1:${record.chainId}:${record.account}:${record.idempotencyKey}`;
|
|
17
|
+
function knownOutcome(outcomeId, side) {
|
|
18
|
+
try {
|
|
19
|
+
outcomeAsset(outcomeId, side);
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** The cursor `GET /v1/hypercore/order-history` answered, on the deployment's chain. */
|
|
27
|
+
export function orderHistoryCursor(answer, chainId) {
|
|
28
|
+
const account = answer.account.toLowerCase();
|
|
29
|
+
const chain = Number(chainId);
|
|
30
|
+
if (!isAccount(account) || (chain !== 998 && chain !== 999) || (answer.height !== null && !positive(answer.height)))
|
|
31
|
+
throw new Error("the order history cursor was malformed");
|
|
32
|
+
return { account, chainId: chain, height: answer.height };
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* A saved record from its JSON text or parsed value: one `placeSingleIoc`
|
|
36
|
+
* wrote, or an IOC record of an older Totalis app (no `version`); `null` for
|
|
37
|
+
* anything else.
|
|
38
|
+
*/
|
|
39
|
+
export function parseSingleOrderRecord(value) {
|
|
40
|
+
let entry = value;
|
|
41
|
+
if (typeof value === "string") {
|
|
42
|
+
try {
|
|
43
|
+
entry = JSON.parse(value);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (!isObject(entry))
|
|
50
|
+
return null;
|
|
51
|
+
const { kind, idempotencyKey, account, chainId, outcomeId, side, direction, size, price, tif, cloid, expiresAfter, recordedAt } = entry;
|
|
52
|
+
if (kind !== "ORDER" || tif !== "Ioc" || (chainId !== 998 && chainId !== 999))
|
|
53
|
+
return null;
|
|
54
|
+
if (!matches(uuid7, idempotencyKey) || !isAccount(account) || !isHex(/^0x[0-9a-f]{32}$/, cloid))
|
|
55
|
+
return null;
|
|
56
|
+
if (side !== "YES" && side !== "NO")
|
|
57
|
+
return null;
|
|
58
|
+
if (!matches(/^(0|[1-9][0-9]*)$/, outcomeId) || !knownOutcome(outcomeId, side))
|
|
59
|
+
return null;
|
|
60
|
+
if (direction !== "BUY" && direction !== "SELL")
|
|
61
|
+
return null;
|
|
62
|
+
if (!matches(/^[1-9][0-9]*$/, size) || typeof price !== "string" || nativePrice(price) !== price)
|
|
63
|
+
return null;
|
|
64
|
+
if (!positive(expiresAfter) || !positive(recordedAt))
|
|
65
|
+
return null;
|
|
66
|
+
const terms = { kind, idempotencyKey, account, chainId, outcomeId, side, direction, size, price, tif, cloid, expiresAfter, recordedAt };
|
|
67
|
+
const { version, nonce, afterHeight } = entry;
|
|
68
|
+
if (version === undefined && nonce === undefined && afterHeight === undefined)
|
|
69
|
+
return terms;
|
|
70
|
+
if (version !== 1 || !positive(nonce) || expiresAfter < nonce || (afterHeight !== null && !positive(afterHeight)))
|
|
71
|
+
return null;
|
|
72
|
+
return { version, ...terms, nonce, afterHeight };
|
|
73
|
+
}
|
|
74
|
+
const sameRecord = (left, right) => JSON.stringify(left) === JSON.stringify(right);
|
|
75
|
+
// One POST to the exchange itself, never a redirect, keeping its HTTP status:
|
|
76
|
+
// only a 2xx from that URL carries Hyperliquid's own answer. React Native's
|
|
77
|
+
// networking follows redirects whatever it is asked, so a response from
|
|
78
|
+
// another URL is no answer either.
|
|
79
|
+
const exchange = (network, fetchImpl = (input, init) => globalThis.fetch(input, init)) => async (signed, signal) => {
|
|
80
|
+
const response = await fetchImpl(network.exchangeUrl, {
|
|
81
|
+
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(signed), redirect: "error", ...(signal === undefined ? {} : { signal }),
|
|
82
|
+
});
|
|
83
|
+
if (!response.ok || response.redirected || (response.url !== "" && response.url !== network.exchangeUrl))
|
|
84
|
+
throw new Error(`Hyperliquid's exchange answered HTTP ${response.status} from ${response.url}`);
|
|
85
|
+
const body = JSON.parse(await response.text());
|
|
86
|
+
return body;
|
|
87
|
+
};
|
|
88
|
+
/** The address whose key made an L1 action's signature; `null` when it does not recover. */
|
|
89
|
+
function signerOf(network, signed) {
|
|
90
|
+
try {
|
|
91
|
+
const digest = hashTypedData(l1TypedData(network, signed.action, signed.nonce, signed.expiresAfter));
|
|
92
|
+
const { r, s, v } = signed.signature;
|
|
93
|
+
const key = secp256k1.Signature.fromCompact(`${r.slice(2)}${s.slice(2)}`).addRecoveryBit(v - 27).recoverPublicKey(digest.slice(2)).toRawBytes(false);
|
|
94
|
+
return `0x${Array.from(keccak_256(key.slice(1)).slice(-20), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const notSent = (record, error) => ({ record, outcome: { kind: "none", reason: "NOT_SENT", error } });
|
|
101
|
+
/**
|
|
102
|
+
* Place one intent as an IOC, at most once: claim its record with `save`,
|
|
103
|
+
* sign exactly what was claimed, check that the account or its agent signed
|
|
104
|
+
* it, then send it once. It never resends or re-signs. An intent this account
|
|
105
|
+
* claimed before on this network comes back as its claimed record with
|
|
106
|
+
* `unknown`, unsigned and unsent: settle it. A throw means nothing was
|
|
107
|
+
* claimed or sent. A claimed order that could not be signed, or was signed by
|
|
108
|
+
* another key, comes back `none` `NOT_SENT`: settle its claim, which keeps the
|
|
109
|
+
* intent from being placed again and holds no buy. Otherwise `outcome` is
|
|
110
|
+
* what the answer proves; on `unknown`, settle the record by evidence
|
|
111
|
+
* (`settleSingleOrder`).
|
|
112
|
+
*/
|
|
113
|
+
export async function placeSingleIoc(signer, network, request, options = {}) {
|
|
114
|
+
// Every term signed, saved and sent to is read here, before the first await; only these copies are used after it.
|
|
115
|
+
const net = { ...network };
|
|
116
|
+
const { signal } = options;
|
|
117
|
+
const { intentId, history, save, transport = exchange(net, options.fetch), builder = true } = request;
|
|
118
|
+
const { outcomeId, side, buy, price, shares } = request.order;
|
|
119
|
+
const account = request.account.toLowerCase();
|
|
120
|
+
const agent = request.agent?.toLowerCase();
|
|
121
|
+
if (!matches(uuid7, intentId))
|
|
122
|
+
throw new TypeError(`intentId must be a lowercase UUIDv7: ${intentId}`);
|
|
123
|
+
if (!isAccount(account))
|
|
124
|
+
throw new TypeError(`not an account: ${request.account}`);
|
|
125
|
+
if (agent !== undefined && !isAccount(agent))
|
|
126
|
+
throw new TypeError(`not an agent address: ${request.agent}`);
|
|
127
|
+
const chainId = net.chain === "Mainnet" && net.signatureChainId === "0x3e7" ? 999 : net.chain === "Testnet" && net.signatureChainId === "0x3e6" ? 998 : undefined;
|
|
128
|
+
if (chainId === undefined)
|
|
129
|
+
throw new RangeError(`Hyperliquid ${net.chain} does not sign for chain ${net.signatureChainId}`);
|
|
130
|
+
const action = singleOrderAction({ outcomeId, side, buy, price, shares, tif: "Ioc", cloid: singleCloid() }, { builder });
|
|
131
|
+
const [wire] = action.orders;
|
|
132
|
+
const nonce = request.nonce ?? hypercoreNonce();
|
|
133
|
+
const expiresAfter = request.expiresAfter ?? Date.now() + orderLifeMs;
|
|
134
|
+
if (!positive(nonce) || !positive(expiresAfter) || expiresAfter < nonce)
|
|
135
|
+
throw new RangeError(`the order's deadline ${expiresAfter} must be at or after its nonce ${nonce}`);
|
|
136
|
+
const afterHeight = history !== null && history.account === account && history.chainId === chainId ? history.height : null;
|
|
137
|
+
const record = {
|
|
138
|
+
version: 1, kind: "ORDER", idempotencyKey: intentId, account, chainId, outcomeId: String(outcomeId), side, direction: wire.b ? "BUY" : "SELL",
|
|
139
|
+
size: wire.s, price: wire.p, tif: "Ioc", cloid: wire.c, expiresAfter, recordedAt: Date.now(), nonce, afterHeight,
|
|
140
|
+
};
|
|
141
|
+
const stored = parseSingleOrderRecord(await save(record));
|
|
142
|
+
if (stored === null || stored.idempotencyKey !== intentId)
|
|
143
|
+
throw new Error("the order record did not read back, so nothing was sent");
|
|
144
|
+
if (stored.account !== account || stored.chainId !== chainId)
|
|
145
|
+
throw new Error("this intent's claim is another account's or network's, so nothing was sent");
|
|
146
|
+
if (!sameRecord(stored, record))
|
|
147
|
+
return { record: stored, outcome: { kind: "unknown" } };
|
|
148
|
+
let signed;
|
|
149
|
+
try {
|
|
150
|
+
signed = await signL1Action(signer, net, action, { nonce, expiresAfter });
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
return notSent(record, `not signed: ${error instanceof Error ? error.message : String(error)}`);
|
|
154
|
+
}
|
|
155
|
+
const by = signerOf(net, signed);
|
|
156
|
+
if (by === null || (by !== account && by !== agent))
|
|
157
|
+
return notSent(record, `signed by ${by ?? "a key that does not recover"}, not the account or its agent`);
|
|
158
|
+
const answer = singleOrderAnswer(await Promise.resolve().then(() => transport(signed, signal)).catch(() => undefined));
|
|
159
|
+
return { record, outcome: singleOrderOutcome(record, { answer }) };
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The saved order a new buy of `outcomeId` waits on: an unsettled buy of
|
|
163
|
+
* either side of it, by the same account on the same network. Pass the
|
|
164
|
+
* records not yet settled. Sells never wait: Hyperliquid refuses a sale of
|
|
165
|
+
* shares the account no longer holds.
|
|
166
|
+
*/
|
|
167
|
+
export function buyHeldBy(records, press) {
|
|
168
|
+
const account = press.account.toLowerCase();
|
|
169
|
+
const outcomeId = String(press.outcomeId);
|
|
170
|
+
return records.find((record) => record.direction === "BUY" && record.account === account && record.chainId === press.chainId && record.outcomeId === outcomeId);
|
|
171
|
+
}
|
|
172
|
+
/** Whole shares from Hyperliquid's size text ("25" or "25.0"); `null` for anything else. */
|
|
173
|
+
function wholeShares(text) {
|
|
174
|
+
const match = /^(\d+)(\.0*)?$/.exec(text);
|
|
175
|
+
return match === null ? null : BigInt(match[1] ?? "");
|
|
176
|
+
}
|
|
177
|
+
function traded(record, oid, shares, averagePrice = null) {
|
|
178
|
+
const size = BigInt(record.size);
|
|
179
|
+
if (shares === null || shares < 0n || shares > size)
|
|
180
|
+
return undefined;
|
|
181
|
+
if (shares === 0n)
|
|
182
|
+
return { kind: "none", reason: "UNFILLED" };
|
|
183
|
+
return { kind: "filled", fill: { kind: shares === size ? "filled" : "partial", shares, averagePrice, fee: null, oid } };
|
|
184
|
+
}
|
|
185
|
+
function byAnswer(record, answer) {
|
|
186
|
+
if (answer.kind === "refused")
|
|
187
|
+
return { kind: "none", reason: "REFUSED", error: answer.error };
|
|
188
|
+
return answer.kind === "filled" ? traded(record, answer.oid, wholeShares(answer.shares), answer.averagePrice) : undefined;
|
|
189
|
+
}
|
|
190
|
+
// Hyperliquid's statuses for an order that ended, as the Totalis app reads
|
|
191
|
+
// them: nearly every cancellation ends in Canceled and every refusal at the
|
|
192
|
+
// book in Rejected. Anything else is not yet decided.
|
|
193
|
+
function byStatus(record, status) {
|
|
194
|
+
const size = BigInt(record.size);
|
|
195
|
+
if (status.coin !== outcomeCoin(record.outcomeId, record.side) || (status.cloid !== null && status.cloid !== record.cloid) || wholeShares(status.shares) !== size)
|
|
196
|
+
return undefined;
|
|
197
|
+
const state = status.status;
|
|
198
|
+
if (state === "filled")
|
|
199
|
+
return traded(record, status.oid, size);
|
|
200
|
+
if (state === "canceled" || state === "scheduledCancel" || state.endsWith("Canceled")) {
|
|
201
|
+
const left = wholeShares(status.remaining);
|
|
202
|
+
return left === null ? undefined : traded(record, status.oid, size - left);
|
|
203
|
+
}
|
|
204
|
+
return state === "rejected" || state.endsWith("Rejected") ? { kind: "none", reason: "UNFILLED" } : undefined;
|
|
205
|
+
}
|
|
206
|
+
function byProof(record, order) {
|
|
207
|
+
const size = BigInt(record.size);
|
|
208
|
+
if (order.direction !== record.direction || wholeShares(order.original_size) !== size)
|
|
209
|
+
return undefined;
|
|
210
|
+
if (order.status === "FILLED")
|
|
211
|
+
return traded(record, order.oid, size);
|
|
212
|
+
if (order.status === "REJECTED")
|
|
213
|
+
return { kind: "none", reason: "UNFILLED" };
|
|
214
|
+
if (order.status !== "CANCELLED")
|
|
215
|
+
return undefined;
|
|
216
|
+
if (order.remaining_size !== undefined) {
|
|
217
|
+
const left = wholeShares(order.remaining_size);
|
|
218
|
+
return traded(record, order.oid, left === null ? null : size - left);
|
|
219
|
+
}
|
|
220
|
+
if (order.fills_status !== "KNOWN" || order.fills === undefined)
|
|
221
|
+
return undefined;
|
|
222
|
+
const counts = order.fills.map((fill) => wholeShares(fill.size));
|
|
223
|
+
return traded(record, order.oid, counts.some((count) => count === null) ? null : counts.reduce((sum, count) => sum + (count ?? 0n), 0n));
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* The window a record is proven over: from `afterHeight` when it has one,
|
|
227
|
+
* else from a day before its nonce. A record without a nonce is searched from
|
|
228
|
+
* a day before its deadline, which only finds it: its absence is never proven.
|
|
229
|
+
*/
|
|
230
|
+
export const proofWindow = (record) => ({ nonce: record.nonce ?? record.expiresAfter, afterHeight: record.afterHeight ?? null });
|
|
231
|
+
const provesRecord = (record, proof) => {
|
|
232
|
+
const { nonce, afterHeight } = proofWindow(record);
|
|
233
|
+
const window = afterHeight === null
|
|
234
|
+
? proof.after_height === undefined && proof.from !== undefined && Date.parse(proof.from) === nonce - day
|
|
235
|
+
: proof.after_height === afterHeight && proof.from === undefined;
|
|
236
|
+
return window && proof.account.toLowerCase() === record.account && proof.cloid === record.cloid
|
|
237
|
+
&& proof.coin === outcomeCoin(record.outcomeId, record.side) && Date.parse(proof.through) === record.expiresAfter;
|
|
238
|
+
};
|
|
239
|
+
/**
|
|
240
|
+
* What the evidence proves about a saved IOC (`SingleOrderOutcome`). An order
|
|
241
|
+
* found anywhere settles it, and evidence that contradicts the record counts
|
|
242
|
+
* for nothing. Absence comes only from the venue's proof over the record's
|
|
243
|
+
* own window: Hyperliquid not knowing the cloid is never proof, and the
|
|
244
|
+
* deadline alone settles nothing. Never `unprovable`: only
|
|
245
|
+
* `settleSingleOrder` says that, from a lookup it made itself.
|
|
246
|
+
*/
|
|
247
|
+
export function singleOrderOutcome(record, evidence) {
|
|
248
|
+
return outcomeOf(record, evidence, false);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* `singleOrderOutcome`, where `lookedUpAfter` says `evidence.status` is a
|
|
252
|
+
* Hyperliquid lookup made after `evidence.proof` was read: only then can the
|
|
253
|
+
* outcome be `unprovable`.
|
|
254
|
+
*/
|
|
255
|
+
export function outcomeOf(record, evidence, lookedUpAfter) {
|
|
256
|
+
const proof = evidence.proof !== undefined && provesRecord(record, evidence.proof) ? evidence.proof : undefined;
|
|
257
|
+
const order = proof?.result === "FOUND" ? proof.order : undefined;
|
|
258
|
+
const found = (evidence.answer === undefined ? undefined : byAnswer(record, evidence.answer))
|
|
259
|
+
?? (evidence.status ? byStatus(record, evidence.status) : undefined)
|
|
260
|
+
?? (order === undefined ? undefined : byProof(record, order));
|
|
261
|
+
if (found !== undefined) {
|
|
262
|
+
return found.kind === "filled" && order?.fills_status === "KNOWN" && order.oid === found.fill.oid ? { ...found, fill: settledFill(found.fill, order.fills ?? []) } : found;
|
|
263
|
+
}
|
|
264
|
+
const reached = evidence.status != null || evidence.answer?.kind === "resting" || evidence.answer?.kind === "filled" || order !== undefined;
|
|
265
|
+
if (reached || proof === undefined || proof.result === "FOUND")
|
|
266
|
+
return { kind: "unknown" };
|
|
267
|
+
if (record.version === 1 && proof.result === "ABSENT")
|
|
268
|
+
return { kind: "none", reason: "ABSENT" };
|
|
269
|
+
// Past here the history cannot settle it. The choice to buy again needs the deadline passed in the history and a
|
|
270
|
+
// lookup made after that read which answered: a Hyperliquid read that failed is no lookup.
|
|
271
|
+
const passed = proof.history !== undefined && Date.parse(proof.history.time) > record.expiresAfter;
|
|
272
|
+
if (!passed || !lookedUpAfter || evidence.status !== null)
|
|
273
|
+
return { kind: "unknown" };
|
|
274
|
+
if (record.version !== 1)
|
|
275
|
+
return proof.result === "UNPROVEN" && proof.reason === "BEHIND" ? { kind: "unknown" } : { kind: "unprovable", reason: "UNCOVERED" };
|
|
276
|
+
return proof.result === "UNPROVEN" && (proof.reason === "GAP" || proof.reason === "UNCOVERED") ? { kind: "unprovable", reason: proof.reason } : { kind: "unknown" };
|
|
277
|
+
}
|
package/dist/singles.d.ts
CHANGED
|
@@ -236,7 +236,10 @@ export declare function approveBuilderFeeTypedData(action: ApproveBuilderFeeActi
|
|
|
236
236
|
* An agent key for `account` under `agentName`: it can place and cancel
|
|
237
237
|
* orders, never withdraw or transfer. Approving a name the account already
|
|
238
238
|
* uses replaces that agent; an account holds a few named agents at most. The
|
|
239
|
-
* Totalis app uses `Totalis` and `TotalisCLI`; pick your own name.
|
|
239
|
+
* Totalis app uses `Totalis` and `TotalisCLI`; pick your own name. Approve a
|
|
240
|
+
* freshly generated key each time, never one approved before: once
|
|
241
|
+
* Hyperliquid prunes an agent its used nonces may go too, and anything the key
|
|
242
|
+
* signed before can then be replayed.
|
|
240
243
|
*/
|
|
241
244
|
export declare function approveAgentAction(network: HyperliquidNetwork, agentAddress: string, agentName: string, nonce?: number): ApproveAgentAction;
|
|
242
245
|
export declare function approveAgentTypedData(action: ApproveAgentAction): TypedData;
|
package/dist/singles.js
CHANGED
|
@@ -326,7 +326,10 @@ export function approveBuilderFeeTypedData(action) {
|
|
|
326
326
|
* An agent key for `account` under `agentName`: it can place and cancel
|
|
327
327
|
* orders, never withdraw or transfer. Approving a name the account already
|
|
328
328
|
* uses replaces that agent; an account holds a few named agents at most. The
|
|
329
|
-
* Totalis app uses `Totalis` and `TotalisCLI`; pick your own name.
|
|
329
|
+
* Totalis app uses `Totalis` and `TotalisCLI`; pick your own name. Approve a
|
|
330
|
+
* freshly generated key each time, never one approved before: once
|
|
331
|
+
* Hyperliquid prunes an agent its used nonces may go too, and anything the key
|
|
332
|
+
* signed before can then be replayed.
|
|
330
333
|
*/
|
|
331
334
|
export function approveAgentAction(network, agentAddress, agentName, nonce = hypercoreNonce()) {
|
|
332
335
|
if (!/^0x[0-9a-fA-F]{40}$/.test(agentAddress))
|
package/dist/totalis.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { BalanceUnknownError, EntryError, ExitUnavailableError, WalletApprovalEr
|
|
|
6
6
|
import { ApiError, NetworkError, type RetryPolicy } from "./request.js";
|
|
7
7
|
import { type SignerInput } from "./signer.js";
|
|
8
8
|
import { TotalisStream, type StreamEvent, type StreamOptions, type StreamSubscription } from "./stream.js";
|
|
9
|
+
import { type OrderHistoryCursor, type SingleOrderOutcome, type SingleOrderRecord } from "./single-orders.js";
|
|
9
10
|
import { type Hex } from "./typed-data.js";
|
|
10
11
|
type Json<T> = T extends {
|
|
11
12
|
readonly content: {
|
|
@@ -356,6 +357,11 @@ export declare function createTotalis(options: TotalisOptions): {
|
|
|
356
357
|
readonly info?: HyperliquidInfo;
|
|
357
358
|
readonly signal?: AbortSignal;
|
|
358
359
|
}) => Promise<ComboCash>;
|
|
360
|
+
readOrderHistory: (signal?: AbortSignal) => Promise<OrderHistoryCursor>;
|
|
361
|
+
settleSingleOrder: (record: SingleOrderRecord, options?: {
|
|
362
|
+
readonly info?: HyperliquidInfo;
|
|
363
|
+
readonly signal?: AbortSignal;
|
|
364
|
+
}) => Promise<SingleOrderOutcome>;
|
|
359
365
|
openPosition: (request: {
|
|
360
366
|
readonly legs: readonly Leg[];
|
|
361
367
|
readonly stake: Amount;
|