@totalis/hip4-client 0.93.0 → 0.94.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 +28 -0
- package/README.md +17 -2
- package/dist/generated/openapi.d.ts +9 -3
- package/dist/generated/version.d.ts +2 -2
- package/dist/generated/version.js +2 -2
- package/dist/hypercore.js +3 -2
- package/dist/partner.d.ts +3 -3
- package/dist/partner.js +5 -4
- package/dist/request.js +7 -12
- package/dist/runtime.d.ts +29 -0
- package/dist/runtime.js +61 -0
- package/dist/stream.d.ts +4 -3
- package/dist/stream.js +16 -7
- package/dist/totalis.js +13 -7
- package/dist/wallet-session.js +4 -4
- package/package.json +5 -2
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,34 @@
|
|
|
3
3
|
`@totalis/hip4-client` follows [semantic versioning](https://semver.org).
|
|
4
4
|
The contract version the generated types come from is `sdkVersion` in `./version`.
|
|
5
5
|
|
|
6
|
+
## 0.94.0
|
|
7
|
+
|
|
8
|
+
### Added
|
|
9
|
+
|
|
10
|
+
- Announcements (contract `223.0.0-announcements`). `listMyNotifications`
|
|
11
|
+
can answer a notification of kind `ANNOUNCEMENT`, a message Totalis sent,
|
|
12
|
+
with optional `title`, `body` and `link` (an app path starting with `/` or
|
|
13
|
+
an https URL). Clients that switch on `kind` exhaustively must handle it.
|
|
14
|
+
|
|
15
|
+
## 0.93.1
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
- React Native (TT-2757). Every request failed on React Native: its `Request`
|
|
20
|
+
(whatwg-fetch) has no `body`, so the resending layer rebuilt each GET with
|
|
21
|
+
an empty body, which whatwg-fetch refuses, and after five tries surfaced
|
|
22
|
+
`NetworkError: GET … failed without a response`. Each send is now a clone of
|
|
23
|
+
the original request. Also fixed on React Native: the stream sends its
|
|
24
|
+
bearer header (React Native's WebSocket takes headers as a third argument,
|
|
25
|
+
and dropped the SDK's), and flows with a timeout or an abort work on React
|
|
26
|
+
Native before 0.87, which has no `AbortSignal.timeout`, `AbortSignal.any`,
|
|
27
|
+
`throwIfAborted` or abort reason. Supported runtimes are now listed in the
|
|
28
|
+
README: Node 22+, browsers, React Native 0.81+ (Expo SDK 54+). On React
|
|
29
|
+
Native, import `react-native-get-random-values` before the SDK; without
|
|
30
|
+
`crypto.getRandomValues` the SDK now says so. A partner server key
|
|
31
|
+
(`createPartnerServer`, `signInWithWallet`'s `serverKey`) is now refused on
|
|
32
|
+
React Native as in a browser, since an app cannot keep it secret.
|
|
33
|
+
|
|
6
34
|
## 0.93.0
|
|
7
35
|
|
|
8
36
|
### Added
|
package/README.md
CHANGED
|
@@ -9,8 +9,8 @@ The official TypeScript SDK for [Totalis](https://totalis.trade) on Hyperliquid
|
|
|
9
9
|
- **Safe retries**: every command keeps one `Idempotency-Key` and is resent byte for byte, so a retry never trades twice
|
|
10
10
|
|
|
11
11
|
It never holds a key. Every signature goes to the signer you pass in: a viem account or wallet client, an
|
|
12
|
-
EIP-1193 provider such as `window.ethereum`, or an ethers signer. It is ESM, runs in browsers and
|
|
13
|
-
|
|
12
|
+
EIP-1193 provider such as `window.ethereum`, or an ethers signer. It is ESM, runs in Node, browsers and
|
|
13
|
+
React Native ([Runtimes](#runtimes)), and has no wallet dependency.
|
|
14
14
|
|
|
15
15
|
**Documentation: [docs.totalis.trade/hyperliquid/sdk](https://docs.totalis.trade/hyperliquid/sdk)**
|
|
16
16
|
|
|
@@ -22,6 +22,21 @@ npm install @totalis/hip4-client viem
|
|
|
22
22
|
|
|
23
23
|
`viem` is optional. The examples below use it to turn a private key into a signer.
|
|
24
24
|
|
|
25
|
+
## Runtimes
|
|
26
|
+
|
|
27
|
+
| Runtime | Versions |
|
|
28
|
+
| --- | --- |
|
|
29
|
+
| Node | 22 or later |
|
|
30
|
+
| Browsers | Current Chrome, Firefox, Safari and Edge |
|
|
31
|
+
| React Native | 0.81 or later (Expo SDK 54 or later) |
|
|
32
|
+
|
|
33
|
+
On React Native, import `react-native-get-random-values` once, before the SDK. React Native has no secure
|
|
34
|
+
random source of its own, and the SDK needs one for request IDs, idempotency keys and signed nonces. Most
|
|
35
|
+
wallet libraries need it too, so an app that signs usually has it already.
|
|
36
|
+
|
|
37
|
+
A partner server key (`createPartnerServer`, or `serverKey` in `signInWithWallet`) is a secret, so it is
|
|
38
|
+
accepted only on a server, never in a browser or an app.
|
|
39
|
+
|
|
25
40
|
## Make a first call
|
|
26
41
|
|
|
27
42
|
Create a `ttk_` API key for your account
|
|
@@ -9254,11 +9254,11 @@ export interface operations {
|
|
|
9254
9254
|
*/
|
|
9255
9255
|
readonly id: string;
|
|
9256
9256
|
/**
|
|
9257
|
-
* @description What happened. FEATURE_UNLOCKED: the account unlocked the feature named by subject.
|
|
9257
|
+
* @description What happened. FEATURE_UNLOCKED: the account unlocked the feature named by subject. ANNOUNCEMENT: Totalis sent a message, in title, body and link. A client shows only kinds it knows.
|
|
9258
9258
|
* @enum {string}
|
|
9259
9259
|
*/
|
|
9260
|
-
readonly kind: "FEATURE_UNLOCKED";
|
|
9261
|
-
/** @description What the notification is about. For FEATURE_UNLOCKED, the feature: REFERRALS, the account's own invite link, which admits people once the account has traded $5. A client shows only subjects it knows. */
|
|
9260
|
+
readonly kind: "FEATURE_UNLOCKED" | "ANNOUNCEMENT";
|
|
9261
|
+
/** @description What the notification is about. For FEATURE_UNLOCKED, the feature: REFERRALS, the account's own invite link, which admits people once the account has traded $5. For ANNOUNCEMENT, an opaque id of the message. A client shows only subjects it knows. */
|
|
9262
9262
|
readonly subject: string;
|
|
9263
9263
|
/** Format: date-time */
|
|
9264
9264
|
readonly created_at: string;
|
|
@@ -9267,6 +9267,12 @@ export interface operations {
|
|
|
9267
9267
|
* @description When the account first read it; absent while unread.
|
|
9268
9268
|
*/
|
|
9269
9269
|
readonly read_at?: string;
|
|
9270
|
+
/** @description An ANNOUNCEMENT's title, one line of plain text. */
|
|
9271
|
+
readonly title?: string;
|
|
9272
|
+
/** @description An ANNOUNCEMENT's message, plain text that may hold line breaks. */
|
|
9273
|
+
readonly body?: string;
|
|
9274
|
+
/** @description Where an ANNOUNCEMENT points, when it does: an app path starting with / or an https URL. */
|
|
9275
|
+
readonly link?: string;
|
|
9270
9276
|
}[];
|
|
9271
9277
|
readonly unread: number;
|
|
9272
9278
|
};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export declare const sdkVersion = "
|
|
2
|
-
export declare const openapiSha256 = "
|
|
1
|
+
export declare const sdkVersion = "223.0.0-announcements";
|
|
2
|
+
export declare const openapiSha256 = "c66b5d72a81151c7e70f54c9d8ca6641d72adadc12e1c17c7fdb66578729e7c9";
|
|
3
3
|
export declare const realtimeSha256 = "32e56c8bb642401f5b03e9c38274087c09bebb73ffe60c0d34432c2e78ce1e15";
|
|
4
4
|
export declare const jsonSchemaSha256: {
|
|
5
5
|
readonly "account.schema.json": "c11a94438d5f7b54e08d3b559098ce2671f4c9aad3a79feb684b7a81f77d809a";
|
|
@@ -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 = "223.0.0-announcements";
|
|
3
|
+
export const openapiSha256 = "c66b5d72a81151c7e70f54c9d8ca6641d72adadc12e1c17c7fdb66578729e7c9";
|
|
4
4
|
export const realtimeSha256 = "32e56c8bb642401f5b03e9c38274087c09bebb73ffe60c0d34432c2e78ce1e15";
|
|
5
5
|
export const jsonSchemaSha256 = {
|
|
6
6
|
"account.schema.json": "c11a94438d5f7b54e08d3b559098ce2671f4c9aad3a79feb684b7a81f77d809a",
|
package/dist/hypercore.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { sleep } from "./request.js";
|
|
2
|
+
import { anySignal, timeoutSignal } from "./runtime.js";
|
|
2
3
|
import { canonicalSignature } from "./typed-data.js";
|
|
3
4
|
const networks = {
|
|
4
5
|
"999": { chain: "Mainnet", signatureChainId: "0x3e7", exchangeUrl: "https://api.hyperliquid.xyz/exchange", infoUrl: "https://api.hyperliquid.xyz/info", usdcToken: "USDC:0x6d1e7cde53ba9467b783cb7c530ce054" },
|
|
@@ -118,8 +119,8 @@ export async function submitHypercore(signed, transport = exchange, signal) {
|
|
|
118
119
|
*/
|
|
119
120
|
export async function settleHypercore(signed, options = {}) {
|
|
120
121
|
const { transport = exchange, deadline, now = Date.now, retryDelayMs = 500 } = options;
|
|
121
|
-
const stops = [options.signal, deadline === undefined ? undefined :
|
|
122
|
-
const stop = stops.length
|
|
122
|
+
const stops = [options.signal, deadline === undefined ? undefined : timeoutSignal(Math.max(0, Math.ceil(deadline - now())))].filter((signal) => signal !== undefined);
|
|
123
|
+
const stop = stops.length < 2 ? stops[0] : anySignal(stops);
|
|
123
124
|
for (;;) {
|
|
124
125
|
if (stop?.aborted || deadline !== undefined && now() >= deadline)
|
|
125
126
|
return { kind: "unknown" };
|
package/dist/partner.d.ts
CHANGED
|
@@ -42,7 +42,7 @@ export declare function signAdmissionConsent(request: {
|
|
|
42
42
|
}>;
|
|
43
43
|
export type PartnerServerOptions = Omit<ApiClientOptions, "accessToken" | "partnerKey"> & {
|
|
44
44
|
readonly environment: PublicEnvironment;
|
|
45
|
-
/** The partner's secret server key (`tpk_v1_…`). Keep it on your server; never ship it to a browser. */
|
|
45
|
+
/** The partner's secret server key (`tpk_v1_…`). Keep it on your server; never ship it to a browser or an app. */
|
|
46
46
|
readonly serverKey: string;
|
|
47
47
|
};
|
|
48
48
|
/**
|
|
@@ -51,8 +51,8 @@ export type PartnerServerOptions = Omit<ApiClientOptions, "accessToken" | "partn
|
|
|
51
51
|
* wallet's consent (`signAdmissionConsent` in your frontend), and its next
|
|
52
52
|
* wallet sign-in creates the account, attributed to you. `report` reads your
|
|
53
53
|
* fees, terms and payouts (TT-2420), and `fills` each fee event on your
|
|
54
|
-
* users' positions (TT-2749). Refuses to run in a browser
|
|
55
|
-
* server key would be exposed.
|
|
54
|
+
* users' positions (TT-2749). Refuses to run in a browser or a React Native
|
|
55
|
+
* app, where the server key would be exposed.
|
|
56
56
|
*/
|
|
57
57
|
export declare function createPartnerServer(options: PartnerServerOptions): {
|
|
58
58
|
/**
|
package/dist/partner.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { audienceClient } from "./base.js";
|
|
2
2
|
import { unwrap, uuidv7 } from "./request.js";
|
|
3
|
+
import { runtime } from "./runtime.js";
|
|
3
4
|
import { toTotalisSigner } from "./signer.js";
|
|
4
5
|
/** The key environment a consent names, from the SDK's environment. */
|
|
5
6
|
const keyEnvironment = { production: "production", staging: "staging", local: "development" };
|
|
@@ -33,12 +34,12 @@ export async function signAdmissionConsent(request) {
|
|
|
33
34
|
* wallet's consent (`signAdmissionConsent` in your frontend), and its next
|
|
34
35
|
* wallet sign-in creates the account, attributed to you. `report` reads your
|
|
35
36
|
* fees, terms and payouts (TT-2420), and `fills` each fee event on your
|
|
36
|
-
* users' positions (TT-2749). Refuses to run in a browser
|
|
37
|
-
* server key would be exposed.
|
|
37
|
+
* users' positions (TT-2749). Refuses to run in a browser or a React Native
|
|
38
|
+
* app, where the server key would be exposed.
|
|
38
39
|
*/
|
|
39
40
|
export function createPartnerServer(options) {
|
|
40
|
-
if (
|
|
41
|
-
throw new Error("createPartnerServer runs on your server; a browser would expose the tpk_ server key");
|
|
41
|
+
if (runtime() !== "server") {
|
|
42
|
+
throw new Error("createPartnerServer runs on your server; a browser or an app would expose the tpk_ server key");
|
|
42
43
|
}
|
|
43
44
|
const { environment, serverKey, ...clientOptions } = options;
|
|
44
45
|
if (!serverKey.startsWith("tpk_v1_"))
|
package/dist/request.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { errorRegistry } from "./generated/errors.js";
|
|
2
|
+
import { abortReason, randomBytes } from "./runtime.js";
|
|
2
3
|
/** A lowercase RFC 9562 UUIDv7: the venue requires it for request IDs and idempotency keys. */
|
|
3
4
|
export function uuidv7(now = Date.now()) {
|
|
4
|
-
const bytes =
|
|
5
|
+
const bytes = randomBytes(16);
|
|
5
6
|
for (let index = 0; index < 6; index++)
|
|
6
7
|
bytes[index] = Math.floor(now / 2 ** (8 * (5 - index))) & 0xff;
|
|
7
8
|
bytes[6] = (bytes[6] & 0x0f) | 0x70;
|
|
@@ -11,7 +12,7 @@ export function uuidv7(now = Date.now()) {
|
|
|
11
12
|
}
|
|
12
13
|
/** 32 random bytes as 0x-hex, for salts and nonces. */
|
|
13
14
|
export function randomBytes32() {
|
|
14
|
-
return `0x${Array.from(
|
|
15
|
+
return `0x${Array.from(randomBytes(32), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
15
16
|
}
|
|
16
17
|
/**
|
|
17
18
|
* The envelope core exits and maker onboarding still carry. Every other
|
|
@@ -83,14 +84,14 @@ export function backoffDelay(retry, baseDelayMs, maxDelayMs) {
|
|
|
83
84
|
export function sleep(ms, signal) {
|
|
84
85
|
return new Promise((resolve, reject) => {
|
|
85
86
|
if (signal?.aborted)
|
|
86
|
-
return reject(signal
|
|
87
|
+
return reject(abortReason(signal));
|
|
87
88
|
const timer = setTimeout(() => {
|
|
88
89
|
signal?.removeEventListener("abort", abort);
|
|
89
90
|
resolve();
|
|
90
91
|
}, ms);
|
|
91
92
|
const abort = () => {
|
|
92
93
|
clearTimeout(timer);
|
|
93
|
-
reject(signal
|
|
94
|
+
reject(abortReason(signal));
|
|
94
95
|
};
|
|
95
96
|
signal?.addEventListener("abort", abort, { once: true });
|
|
96
97
|
});
|
|
@@ -105,19 +106,13 @@ async function wantsBackoff(response) {
|
|
|
105
106
|
export function retryingFetch(fetchImpl = (request) => globalThis.fetch(request), policy = {}) {
|
|
106
107
|
const { attempts = 5, baseDelayMs = 250, maxDelayMs = 10_000, maxRetryAfterMs = 30_000, sleep: wait = sleep } = policy;
|
|
107
108
|
return async (original) => {
|
|
108
|
-
const body = original.body === null ? null : new Uint8Array(await original.arrayBuffer());
|
|
109
109
|
const replayable = ["GET", "HEAD", "DELETE"].includes(original.method) || original.headers.has("Idempotency-Key");
|
|
110
|
-
const build = () => new Request(original.url, {
|
|
111
|
-
method: original.method, headers: original.headers, body, signal: original.signal,
|
|
112
|
-
credentials: original.credentials, cache: original.cache, redirect: original.redirect,
|
|
113
|
-
mode: original.mode, integrity: original.integrity, referrer: original.referrer,
|
|
114
|
-
referrerPolicy: original.referrerPolicy, keepalive: original.keepalive,
|
|
115
|
-
});
|
|
116
110
|
for (let attempt = 1;; attempt++) {
|
|
117
111
|
const backoff = backoffDelay(attempt - 1, baseDelayMs, maxDelayMs);
|
|
118
112
|
let response;
|
|
119
113
|
try {
|
|
120
|
-
|
|
114
|
+
// Each send is a clone, so the original is never read and every resend carries its exact bytes.
|
|
115
|
+
response = await fetchImpl(original.clone());
|
|
121
116
|
}
|
|
122
117
|
catch (cause) {
|
|
123
118
|
if (original.signal.aborted)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the SDK needs from its runtime that differs between the runtimes it
|
|
3
|
+
* supports: Node 22+, browsers, and React Native 0.81+ (Expo SDK 54+). See
|
|
4
|
+
* "Runtimes" in the README. Everything else in the SDK uses only APIs all of
|
|
5
|
+
* them share, and CI runs the whole test suite under each
|
|
6
|
+
* (test/runtimes/react-native.mjs).
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* `browser`: the page sets Origin itself and its WebSocket takes no headers.
|
|
10
|
+
* `react-native`: no page, and WebSocket takes headers as a third argument.
|
|
11
|
+
* `server`: Node and the like, where WebSocket takes `{ protocols, headers }`.
|
|
12
|
+
*/
|
|
13
|
+
export type Runtime = "browser" | "react-native" | "server";
|
|
14
|
+
export declare function runtime(): Runtime;
|
|
15
|
+
/** Cryptographically secure random bytes. React Native has no source of its own: the app installs one. */
|
|
16
|
+
export declare function randomBytes(length: number): Uint8Array;
|
|
17
|
+
/**
|
|
18
|
+
* Why `signal` aborted. React Native before 0.87 keeps no reason, so a signal
|
|
19
|
+
* aborted without one reads as an AbortError, as it would in a browser.
|
|
20
|
+
*/
|
|
21
|
+
export declare function abortReason(signal: AbortSignal): unknown;
|
|
22
|
+
/** `AbortSignal.timeout`, which React Native before 0.87 lacks. Like it, the timer never keeps Node running. */
|
|
23
|
+
export declare function timeoutSignal(ms: number): AbortSignal;
|
|
24
|
+
/**
|
|
25
|
+
* `AbortSignal.any`, which React Native before 0.87 lacks. It stops listening
|
|
26
|
+
* to every input once one aborts, so give it inputs that end (a timeout, or a
|
|
27
|
+
* controller the caller aborts when done).
|
|
28
|
+
*/
|
|
29
|
+
export declare function anySignal(signals: readonly AbortSignal[]): AbortSignal;
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the SDK needs from its runtime that differs between the runtimes it
|
|
3
|
+
* supports: Node 22+, browsers, and React Native 0.81+ (Expo SDK 54+). See
|
|
4
|
+
* "Runtimes" in the README. Everything else in the SDK uses only APIs all of
|
|
5
|
+
* them share, and CI runs the whole test suite under each
|
|
6
|
+
* (test/runtimes/react-native.mjs).
|
|
7
|
+
*/
|
|
8
|
+
export function runtime() {
|
|
9
|
+
if (typeof globalThis.document !== "undefined")
|
|
10
|
+
return "browser";
|
|
11
|
+
return globalThis.navigator?.product === "ReactNative" ? "react-native" : "server";
|
|
12
|
+
}
|
|
13
|
+
/** Cryptographically secure random bytes. React Native has no source of its own: the app installs one. */
|
|
14
|
+
export function randomBytes(length) {
|
|
15
|
+
if (typeof globalThis.crypto?.getRandomValues !== "function") {
|
|
16
|
+
throw new Error("@totalis/hip4-client needs crypto.getRandomValues: on React Native, import \"react-native-get-random-values\" before the SDK");
|
|
17
|
+
}
|
|
18
|
+
return globalThis.crypto.getRandomValues(new Uint8Array(length));
|
|
19
|
+
}
|
|
20
|
+
const namedError = (name, message) => Object.assign(new Error(message), { name });
|
|
21
|
+
/**
|
|
22
|
+
* Why `signal` aborted. React Native before 0.87 keeps no reason, so a signal
|
|
23
|
+
* aborted without one reads as an AbortError, as it would in a browser.
|
|
24
|
+
*/
|
|
25
|
+
export function abortReason(signal) {
|
|
26
|
+
return signal.reason ?? namedError("AbortError", "This operation was aborted");
|
|
27
|
+
}
|
|
28
|
+
/** Abort with `reason`, recording it where the runtime would drop it (React Native before 0.87). */
|
|
29
|
+
function abortWith(controller, reason) {
|
|
30
|
+
if (!("reason" in controller.signal))
|
|
31
|
+
Object.defineProperty(controller.signal, "reason", { value: reason });
|
|
32
|
+
controller.abort(reason);
|
|
33
|
+
}
|
|
34
|
+
/** `AbortSignal.timeout`, which React Native before 0.87 lacks. Like it, the timer never keeps Node running. */
|
|
35
|
+
export function timeoutSignal(ms) {
|
|
36
|
+
const controller = new AbortController();
|
|
37
|
+
const timer = setTimeout(() => abortWith(controller, namedError("TimeoutError", "The operation timed out")), ms);
|
|
38
|
+
timer.unref?.();
|
|
39
|
+
return controller.signal;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* `AbortSignal.any`, which React Native before 0.87 lacks. It stops listening
|
|
43
|
+
* to every input once one aborts, so give it inputs that end (a timeout, or a
|
|
44
|
+
* controller the caller aborts when done).
|
|
45
|
+
*/
|
|
46
|
+
export function anySignal(signals) {
|
|
47
|
+
const controller = new AbortController();
|
|
48
|
+
const stop = (signal) => {
|
|
49
|
+
for (const input of signals)
|
|
50
|
+
input.removeEventListener("abort", listeners.get(input));
|
|
51
|
+
abortWith(controller, abortReason(signal));
|
|
52
|
+
};
|
|
53
|
+
const listeners = new Map(signals.map((signal) => [signal, () => stop(signal)]));
|
|
54
|
+
const aborted = signals.find((signal) => signal.aborted);
|
|
55
|
+
if (aborted !== undefined)
|
|
56
|
+
stop(aborted);
|
|
57
|
+
else
|
|
58
|
+
for (const [signal, listener] of listeners)
|
|
59
|
+
signal.addEventListener("abort", listener, { once: true });
|
|
60
|
+
return controller.signal;
|
|
61
|
+
}
|
package/dist/stream.d.ts
CHANGED
|
@@ -27,8 +27,9 @@ export type StreamFrame = {
|
|
|
27
27
|
export type StreamStatus = "idle" | "connecting" | "live" | "disconnected" | "closed";
|
|
28
28
|
/**
|
|
29
29
|
* Opens the socket. In a browser the credential travels as the
|
|
30
|
-
* `auth.<token>` subprotocol with the page's Origin; elsewhere (Node 22+,
|
|
31
|
-
* as a bearer header, so `headers` carries Authorization
|
|
30
|
+
* `auth.<token>` subprotocol with the page's Origin; elsewhere (Node 22+,
|
|
31
|
+
* React Native, bots) as a bearer header, so `headers` carries Authorization
|
|
32
|
+
* and any extra headers.
|
|
32
33
|
*/
|
|
33
34
|
export type WebSocketFactory = (url: string, protocols: string[], headers: Record<string, string>) => WebSocket;
|
|
34
35
|
export type StreamOptions = {
|
|
@@ -108,7 +109,7 @@ export declare function realtimeCredentialProtocol(accessToken: string): string;
|
|
|
108
109
|
* reconnect. Delivery is at least once; this client orders and deduplicates by
|
|
109
110
|
* cursor and `event_id`, reconnects with jittered backoff from the last applied
|
|
110
111
|
* cursor, and follows each close reason's retry: BACKOFF resumes, REFRESH takes
|
|
111
|
-
* a fresh snapshot, NEVER stops. It works with the
|
|
112
|
+
* a fresh snapshot, NEVER stops. It works with the WebSocket of every supported runtime.
|
|
112
113
|
*/
|
|
113
114
|
export declare class TotalisStream {
|
|
114
115
|
private readonly options;
|
package/dist/stream.js
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
import { streamServerUrl } from "./base.js";
|
|
2
2
|
import { errorRegistry } from "./generated/errors.js";
|
|
3
3
|
import { backoffDelay } from "./request.js";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
import { abortReason, runtime } from "./runtime.js";
|
|
5
|
+
const openWebSocket = (url, protocols, headers) => {
|
|
6
|
+
switch (runtime()) {
|
|
7
|
+
case "browser":
|
|
8
|
+
return new WebSocket(url, protocols);
|
|
9
|
+
case "react-native":
|
|
10
|
+
return new WebSocket(url, protocols, { headers });
|
|
11
|
+
case "server":
|
|
12
|
+
// Node's WebSocket (undici) accepts `{ protocols, headers }` in place of protocols.
|
|
13
|
+
return new WebSocket(url, { protocols, headers });
|
|
14
|
+
}
|
|
15
|
+
};
|
|
7
16
|
/**
|
|
8
17
|
* The stream closed for good: the server's NEVER reason (for example
|
|
9
18
|
* SUBSCRIPTION_DENIED or STREAM_REPLACED), or `closed` after `close()`. It
|
|
@@ -49,7 +58,7 @@ const sameStream = (a, b) => a.stream_id === b.stream_id && a.generation_id ===
|
|
|
49
58
|
* reconnect. Delivery is at least once; this client orders and deduplicates by
|
|
50
59
|
* cursor and `event_id`, reconnects with jittered backoff from the last applied
|
|
51
60
|
* cursor, and follows each close reason's retry: BACKOFF resumes, REFRESH takes
|
|
52
|
-
* a fresh snapshot, NEVER stops. It works with the
|
|
61
|
+
* a fresh snapshot, NEVER stops. It works with the WebSocket of every supported runtime.
|
|
53
62
|
*/
|
|
54
63
|
export class TotalisStream {
|
|
55
64
|
options;
|
|
@@ -133,9 +142,9 @@ export class TotalisStream {
|
|
|
133
142
|
else if (this.status === "closed")
|
|
134
143
|
done(() => reject(this.closeError()));
|
|
135
144
|
};
|
|
136
|
-
const abort = () => done(() => reject(signal
|
|
145
|
+
const abort = () => done(() => reject(abortReason(signal)));
|
|
137
146
|
if (signal?.aborted)
|
|
138
|
-
return reject(signal
|
|
147
|
+
return reject(abortReason(signal));
|
|
139
148
|
signal?.addEventListener("abort", abort, { once: true });
|
|
140
149
|
offs.push(this.on("status", test), this.on("event", test));
|
|
141
150
|
test();
|
|
@@ -193,7 +202,7 @@ export class TotalisStream {
|
|
|
193
202
|
return;
|
|
194
203
|
const open = this.options.webSocket ?? openWebSocket;
|
|
195
204
|
const url = realtimeUrl(environment, baseUrl, streamBaseUrl);
|
|
196
|
-
socket =
|
|
205
|
+
socket = runtime() === "browser"
|
|
197
206
|
? open(url, [realtimeProtocol, realtimeCredentialProtocol(token)], {})
|
|
198
207
|
: open(url, [realtimeProtocol], { ...this.options.headers, Authorization: `Bearer ${token}` });
|
|
199
208
|
}
|
package/dist/totalis.js
CHANGED
|
@@ -5,6 +5,7 @@ import { bridgeAction, bridgeGasBuffer, hyperliquidExchange, hyperliquidNetwork,
|
|
|
5
5
|
import { BalanceUnknownError, EntryError, ExitUnavailableError, normalizeError, WalletApprovalError } from "./flow-errors.js";
|
|
6
6
|
import { comboAllowance, offeredCore, spendableCash } from "./money.js";
|
|
7
7
|
import { ApiError, backoffDelay, envelope, NetworkError, randomBytes32, resendable, retryingFetch, sendOnce, singleFetch, sleep, unwrap, uuidv7 } from "./request.js";
|
|
8
|
+
import { abortReason, anySignal, timeoutSignal } from "./runtime.js";
|
|
8
9
|
import { toTotalisSigner } from "./signer.js";
|
|
9
10
|
import { TotalisStream } from "./stream.js";
|
|
10
11
|
import { items } from "./pagination.js";
|
|
@@ -129,7 +130,7 @@ export const terminalOperationStatuses = new Set(["COMMITTED", "REVERTED", "EXPI
|
|
|
129
130
|
const permitLifeSeconds = 30 * 60;
|
|
130
131
|
const approvalFunding = { kind: "WALLET_APPROVAL" };
|
|
131
132
|
function withTimeout(signal, ms) {
|
|
132
|
-
return signal === undefined ?
|
|
133
|
+
return signal === undefined ? timeoutSignal(ms) : anySignal([signal, timeoutSignal(ms)]);
|
|
133
134
|
}
|
|
134
135
|
const unavailable = new Set([500, 502, 503, 504]);
|
|
135
136
|
/** A failed recovery read worth retrying: a lost response, a BACKOFF error, or a 500/502/503/504 without the venue's error envelope. */
|
|
@@ -152,10 +153,14 @@ function recoveryReads(stream, read, onValue, fail, stop, retry = {}) {
|
|
|
152
153
|
if (wakeable)
|
|
153
154
|
interrupt = () => cut.abort();
|
|
154
155
|
const ended = new Promise((resolve) => {
|
|
155
|
-
|
|
156
|
-
|
|
156
|
+
const end = () => {
|
|
157
|
+
stop.removeEventListener("abort", end);
|
|
158
|
+
resolve();
|
|
159
|
+
};
|
|
160
|
+
cut.signal.addEventListener("abort", end, { once: true });
|
|
161
|
+
stop.addEventListener("abort", end, { once: true });
|
|
157
162
|
});
|
|
158
|
-
await Promise.race([wait(ms,
|
|
163
|
+
await Promise.race([wait(ms, anySignal([stop, cut.signal])).catch(() => undefined), ended]);
|
|
159
164
|
interrupt = undefined;
|
|
160
165
|
cut.abort();
|
|
161
166
|
return !stop.aborted;
|
|
@@ -240,7 +245,7 @@ function followUntil(stream, read, done, wake, recheckMs, signal, retry, command
|
|
|
240
245
|
if (delay !== undefined)
|
|
241
246
|
recheck = setTimeout(() => void check(), Math.max(delay, 0));
|
|
242
247
|
}, (error) => finish(() => reject(error)), stop.signal, retry);
|
|
243
|
-
const abort = () => finish(() => reject(signal
|
|
248
|
+
const abort = () => finish(() => reject(abortReason(signal)));
|
|
244
249
|
if (signal?.aborted)
|
|
245
250
|
return abort();
|
|
246
251
|
// A stream already closed for good never reports it again.
|
|
@@ -944,7 +949,8 @@ export function createTotalis(options) {
|
|
|
944
949
|
if (signed.kind === "ENTRY" && signed.version !== 2)
|
|
945
950
|
throw new Error("this entry was signed by an older SDK, which sent its bridge before the accept; recoverAcceptance it instead");
|
|
946
951
|
await checkScope(signed);
|
|
947
|
-
options.signal?.
|
|
952
|
+
if (options.signal?.aborted)
|
|
953
|
+
throw abortReason(options.signal);
|
|
948
954
|
const clock = venueClock();
|
|
949
955
|
if (signed.kind === "ENTRY" && signed.bridge !== undefined) {
|
|
950
956
|
// The held accept's own stamp runs late by the maker's wait; a read sent alongside bounds the venue clock tightly.
|
|
@@ -1273,7 +1279,7 @@ export function createTotalis(options) {
|
|
|
1273
1279
|
finish(() => reject(new Error(`withdrawal ${withdrawalId} failed`)));
|
|
1274
1280
|
};
|
|
1275
1281
|
const recover = recoveryReads(stream, async (stop) => unwrap(await client.GET("/v1/me/withdrawals/{withdrawal_id}", { params: { path: { withdrawal_id: withdrawalId } }, signal: stop, fetch: recoveryFetch })), settle, (error) => finish(() => reject(error)), stop.signal, retry);
|
|
1276
|
-
const abort = () => finish(() => reject(signal
|
|
1282
|
+
const abort = () => finish(() => reject(abortReason(signal)));
|
|
1277
1283
|
if (signal?.aborted)
|
|
1278
1284
|
return abort();
|
|
1279
1285
|
signal?.addEventListener("abort", abort, { once: true });
|
package/dist/wallet-session.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { audienceClient } from "./base.js";
|
|
2
2
|
import { ApiError, unwrap, uuidv7 } from "./request.js";
|
|
3
|
+
import { runtime } from "./runtime.js";
|
|
3
4
|
import { toTotalisSigner } from "./signer.js";
|
|
4
5
|
const sessionStatement = "Create a Totalis venue transport session. This does not authorize a financial action.";
|
|
5
|
-
const inBrowser = () => typeof globalThis.document !== "undefined";
|
|
6
6
|
/**
|
|
7
7
|
* Check a sign-in challenge before the wallet signs it: the exact Totalis
|
|
8
8
|
* session message, for this origin, wallet and request, and not expired.
|
|
@@ -35,13 +35,13 @@ export async function signInWithWallet(options) {
|
|
|
35
35
|
const { environment, signer: input, origin = globalThis.location?.origin, serverKey, ...clientOptions } = options;
|
|
36
36
|
if (origin === undefined || origin === "")
|
|
37
37
|
throw new Error("signInWithWallet needs an origin outside a browser");
|
|
38
|
-
if (serverKey !== undefined && (
|
|
38
|
+
if (serverKey !== undefined && (runtime() !== "server" || !serverKey.startsWith("tpk_v1_")))
|
|
39
39
|
throw new Error("serverKey takes a tpk_v1 partner server key, and only on a server");
|
|
40
40
|
const signer = toTotalisSigner(input);
|
|
41
41
|
const address = await signer.address();
|
|
42
42
|
const client = audienceClient(environment, serverKey === undefined ? clientOptions : { ...clientOptions, accessToken: serverKey });
|
|
43
43
|
// A browser sets Origin itself and refuses a script's value.
|
|
44
|
-
const originHeader =
|
|
44
|
+
const originHeader = runtime() === "browser" ? {} : { Origin: origin };
|
|
45
45
|
const requestId = uuidv7();
|
|
46
46
|
const challenge = unwrap(await client.POST("/v1/auth/wallet-challenges", {
|
|
47
47
|
params: { header: { "Idempotency-Key": requestId } }, body: { address, origin }, headers: originHeader,
|
|
@@ -56,7 +56,7 @@ export async function signInWithWallet(options) {
|
|
|
56
56
|
export async function signOutWallet(options) {
|
|
57
57
|
const { environment, origin = globalThis.location?.origin, ...clientOptions } = options;
|
|
58
58
|
const client = audienceClient(environment, clientOptions);
|
|
59
|
-
const headers =
|
|
59
|
+
const headers = runtime() === "browser" || origin === undefined ? {} : { Origin: origin };
|
|
60
60
|
const { error, response } = await client.DELETE("/v1/auth/wallet-sessions/current", { headers });
|
|
61
61
|
if (error !== undefined || !response.ok)
|
|
62
62
|
throw ApiError.from(response, error);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@totalis/hip4-client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.94.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": [
|
|
@@ -64,7 +64,8 @@
|
|
|
64
64
|
"generate": "node scripts/generate.mjs",
|
|
65
65
|
"check": "node scripts/generate.mjs --check && node scripts/compatibility.mjs && tsc --noEmit -p tsconfig.test.json",
|
|
66
66
|
"build": "npm run generate && tsc",
|
|
67
|
-
"test": "npm run build && node --test test/*.test.mjs",
|
|
67
|
+
"test": "npm run build && node --test test/*.test.mjs && node --import ./test/runtimes/react-native.mjs --test test/*.test.mjs",
|
|
68
|
+
"test:react-native": "npm run build && node --import ./test/runtimes/react-native.mjs --test test/*.test.mjs",
|
|
68
69
|
"test:staging-read": "npm run build && node test/staging-read-smoke.mjs",
|
|
69
70
|
"test:production-read": "npm run build && node test/staging-read-smoke.mjs production",
|
|
70
71
|
"test:staging-smoke": "npm run build && node test/staging-smoke.mjs",
|
|
@@ -86,10 +87,12 @@
|
|
|
86
87
|
"openapi-fetch": "0.17.0"
|
|
87
88
|
},
|
|
88
89
|
"devDependencies": {
|
|
90
|
+
"abort-controller": "3.0.0",
|
|
89
91
|
"ethers": "6.17.0",
|
|
90
92
|
"openapi-typescript": "7.13.0",
|
|
91
93
|
"typescript": "5.9.3",
|
|
92
94
|
"viem": "2.56.9",
|
|
95
|
+
"whatwg-fetch": "3.6.20",
|
|
93
96
|
"ws": "8.21.0"
|
|
94
97
|
},
|
|
95
98
|
"engines": {
|