@totalis/hip4-client 0.92.0 → 0.93.1

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 CHANGED
@@ -3,6 +3,56 @@
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.93.1
7
+
8
+ ### Fixed
9
+
10
+ - React Native (TT-2757). Every request failed on React Native: its `Request`
11
+ (whatwg-fetch) has no `body`, so the resending layer rebuilt each GET with
12
+ an empty body, which whatwg-fetch refuses, and after five tries surfaced
13
+ `NetworkError: GET … failed without a response`. Each send is now a clone of
14
+ the original request. Also fixed on React Native: the stream sends its
15
+ bearer header (React Native's WebSocket takes headers as a third argument,
16
+ and dropped the SDK's), and flows with a timeout or an abort work on React
17
+ Native before 0.87, which has no `AbortSignal.timeout`, `AbortSignal.any`,
18
+ `throwIfAborted` or abort reason. Supported runtimes are now listed in the
19
+ README: Node 22+, browsers, React Native 0.81+ (Expo SDK 54+). On React
20
+ Native, import `react-native-get-random-values` before the SDK; without
21
+ `crypto.getRandomValues` the SDK now says so. A partner server key
22
+ (`createPartnerServer`, `signInWithWallet`'s `serverKey`) is now refused on
23
+ React Native as in a browser, since an app cannot keep it secret.
24
+
25
+ ## 0.93.0
26
+
27
+ ### Added
28
+
29
+ - Referral bonus (contract `222.0.0-referral-bonus`). `getMyReferralBonus`,
30
+ `GET /v1/me/referral-bonus`: the signed-in account's referral bonus. A
31
+ referral is someone the account's own invite code admitted; once their own
32
+ Combo stake since signing up reaches `qualifying_stake` ($50) the account
33
+ earns `bonus` ($5), up to `monthly_cap` ($500) a UTC month. The answer has
34
+ `started_at` (null until the bonus starts), `months` (`earned`, `capped`,
35
+ `bonus`), the most recent `qualified` referrals with their `outcome`
36
+ (`EARNED`, `CAPPED`, `BEFORE_START`, `SELF`) and the most recent `pending`
37
+ referrals with what they have `staked`. Answers `CONTRACT_UNAVAILABLE` where
38
+ the bonus is off. Additive.
39
+ - Awaiting result (contract `221.0.0-awaiting-result`). Optional
40
+ `Market.awaiting_result` (`boolean | null`): `true` while a market's event
41
+ is over and Hyperliquid has not recorded its result (a live scoreboard shows
42
+ its game final, or a price market's observation time has passed), `false`
43
+ when it is known not to be, `null` or absent when unknown. Optional
44
+ per-side `last_chance` (integer string at scale 10^18, or `null`) on
45
+ `MarketSide` and on stream `reference_upserts` items: the side's last real
46
+ chance, set only while `awaiting_result` is `true` and `reference.chance` is
47
+ null. Both are display only: they never change trading, `chance`, `mark` or
48
+ Combo admission. The market stream sends `awaiting_result` in catalog
49
+ upserts. Nothing sends them yet; a schema that rejects unknown properties
50
+ must accept them before the backend starts to. Additive.
51
+ - Market-data now sends `awaiting_result` and `last_chance` (omitted when
52
+ null). Games read `true` once their live scoreboard shows final; price
53
+ markets once their observation time passes. The last chance is the last real
54
+ price (a trade, or a tight-book midpoint), not clamped to a one-sided book.
55
+
6
56
  ## 0.92.0
7
57
 
8
58
  ### 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 Node 22 or
13
- later, and has no wallet dependency.
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
@@ -535,6 +535,8 @@ export type components = {
535
535
  readonly maker_id: components["schemas"]["NonZeroUInt64String"];
536
536
  /** @description Current position owner wallet (lowercase). */
537
537
  readonly owner: components["schemas"]["LowercaseNonZeroAddress"];
538
+ /** @description On a maker's read, the owner's username when the owner wallet is the account wallet of a participant whose public trader profile is on, the pair GET /v1/traders/{username} shows; otherwise null, as for a participant's other linked wallets, and always null on a personal read. */
539
+ readonly owner_username: components["schemas"]["Username"] | null;
538
540
  /**
539
541
  * @description OPEN: not yet known eligible for settlement; AWAITING_SETTLEMENT: every leg resolved, or the payout with every unresolved leg counted as a win already rounds down to zero, but no settlement observed; SETTLED_UNCLAIMED: settled with profit still unclaimed; CLOSED: closed by zero-profit settlement, final claim or sell-back.
540
542
  * @enum {string}
@@ -906,6 +908,8 @@ export type components = {
906
908
  /** @description Hyperliquid trade ID, as a decimal string. */
907
909
  readonly tid: components["schemas"]["NonZeroUInt64String"];
908
910
  };
911
+ /** @description 3 to 20 lowercase letters, digits or underscores. Unique across accounts. */
912
+ readonly Username: string;
909
913
  /**
910
914
  * @description Where the quote stands now. OPEN: live and acceptable. AWAITING_CONFIRMATION: the taker accepted it and the maker has not answered within its two-second deadline yet. ACCEPTED: the maker confirmed and the trade is queued or on its way to chain. FILLED: the trade committed on chain. FAILED: the trade reverted or expired unexecuted. DECLINED: the maker declined the acceptance. TIMED_OUT: the maker did not answer the acceptance in time. CANCELLED: the maker withdrew the quote. REPLACED: the maker's newer quote on the same RFQ replaced it. EXPIRED: it or its RFQ lapsed unaccepted. NOT_SELECTED: the RFQ's taker accepted another quote first. RFQ_CANCELLED: the taker cancelled or replaced the RFQ.
911
915
  * @enum {string}
@@ -464,6 +464,8 @@ export type components = {
464
464
  readonly coin: string;
465
465
  /** @description Current reference price of this side, or why none is available. */
466
466
  readonly reference: components["schemas"]["Reference"];
467
+ /** @description For display only: the side's last real chance at the probability scale (10^18), set only while the market's awaiting_result is true and reference.chance is null. It is the newest evidence the chance rule holds, unclamped: the last book execution, or the last midpoint of a book at most 10% of scale wide. It needs a fresh, uncrossed book on this side; an empty book keeps it. YES and NO sum to scale. Null or absent otherwise. It is not a price, a value or a chance: never trade, value a position or pick a Combo leg with it. */
468
+ readonly last_chance?: components["schemas"]["IntegerValue"] | null;
467
469
  };
468
470
  readonly DateEvent: {
469
471
  /**
@@ -519,6 +521,8 @@ export type components = {
519
521
  ];
520
522
  /** @description Display dates and the market class; null when the market has neither reviewed timing nor a market class. Never controls availability or settlement. */
521
523
  readonly dates: components["schemas"]["MarketDates"] | null;
524
+ /** @description For display only: whether the market's event is over while Hyperliquid has not recorded its result. true when a live scoreboard shows its game final (every winner, spread and total market of that game) or a price market's observation time has passed with its result unresolved; false when its event is known not to be over yet or its result is recorded; null or absent when unknown: other kinds of market, a game no scoreboard covers or reads now, or a native result that could not be read. It never closes trading, settles, or changes chance, mark, eligibility or Combo admission. */
525
+ readonly awaiting_result?: boolean | null;
522
526
  };
523
527
  readonly DiscoveryQuestionItem: components["schemas"]["DiscoveryDisplay"] & {
524
528
  /** @description Item ID, question: followed by the native question ID. */
@@ -57,6 +57,7 @@ export type paths = {
57
57
  readonly "/v1/me/notifications": Pick<SharedPaths["/v1/me/notifications"], "parameters" | "get">;
58
58
  readonly "/v1/me/notifications/read": Pick<SharedPaths["/v1/me/notifications/read"], "parameters" | "post">;
59
59
  readonly "/v1/me/genesis": Pick<SharedPaths["/v1/me/genesis"], "parameters" | "get">;
60
+ readonly "/v1/me/referral-bonus": Pick<SharedPaths["/v1/me/referral-bonus"], "parameters" | "get">;
60
61
  readonly "/v1/me/copy-summary": Pick<SharedPaths["/v1/me/copy-summary"], "parameters" | "get">;
61
62
  readonly "/v1/me/copy-fills": Pick<SharedPaths["/v1/me/copy-fills"], "parameters" | "get">;
62
63
  readonly "/v1/me/copy-agents": Pick<SharedPaths["/v1/me/copy-agents"], "parameters" | "get">;
@@ -117,4 +118,4 @@ export type paths = {
117
118
  readonly "/v1/makers/{maker_id}/exposure": Pick<SharedPaths["/v1/makers/{maker_id}/exposure"], "parameters" | "get">;
118
119
  readonly "/v1/makers/{maker_id}/performance": Pick<SharedPaths["/v1/makers/{maker_id}/performance"], "parameters" | "get">;
119
120
  };
120
- export type operations = Pick<SharedOperations, "abandonCoreExit" | "acceptQuote" | "activeCoreExits" | "admitOwnMaker" | "admitPartnerWallet" | "approveWallet" | "bindEmbeddedWallet" | "cancelRfq" | "confirmComboCopyAgent" | "confirmCoreCopyAgent" | "createCashout" | "createComment" | "createCoreExit" | "createDeposit" | "createGoldenRfq" | "createRfq" | "createRunOffClaim" | "createWalletChallenge" | "createWalletSession" | "createWithdrawal" | "deleteComment" | "editComment" | "endWalletSession" | "followTrader" | "getAcceptance" | "getAccountActivity" | "getAccountPnl" | "getAccountPosition" | "getBalances" | "getCopyAgents" | "getCopyBudget" | "getCopySettings" | "getCopySummary" | "getCoreExit" | "getDeployment" | "getGolden" | "getGoldenMarkets" | "getGoldenOffer" | "getGoldenSuggestions" | "getHypercoreBalance" | "getHypercorePortfolio" | "getHypercoreSettlementCredits" | "getIdentity" | "getMakerActivity" | "getMakerCapital" | "getMakerExposure" | "getMakerPerformance" | "getMakerPosition" | "getMakerQuotes" | "getMakerTelemetry" | "getMakerVaultFundingTransaction" | "getMakerWithdrawal" | "getMarket" | "getMarketDataConfig" | "getMarketDefinitions" | "getMarketHistory" | "getMarketRecurringRound" | "getMarketReferenceCloses" | "getMarketScoreTimeline" | "getMarketStats" | "getMyGenesis" | "getOperation" | "getOwnMaker" | "getPartnerReport" | "getPerpMarks" | "getProfitLeaderboard" | "getQuestion" | "getQuestionRecurringRound" | "getQuestionScoreTimeline" | "getRfq" | "getSeries" | "getSuggestedCombo" | "getTaxonomy" | "getTrader" | "getTraderPnl" | "getUsernameAvailability" | "getVaultAgents" | "getVolumeLeaderboard" | "getWalletApproval" | "getWithdrawal" | "grantComboCopyAgent" | "grantVaultAgent" | "likeComment" | "listAccountActivity" | "listAccountPositions" | "listComboCopies" | "listComboFeed" | "listCommentReplies" | "listComments" | "listControlledMakers" | "listCopiedFills" | "listCopyTrades" | "listDiscovery" | "listFollows" | "listMakerActivity" | "listMakerPositions" | "listMakerQuoteHistory" | "listMarkets" | "listMyNotifications" | "listOperations" | "listPartnerFills" | "listQuotes" | "listTraderPositions" | "listTraderTrades" | "markMyNotificationsRead" | "placeGolden" | "reactComment" | "recordAcquisition" | "refreshPicture" | "requestComboCopyAgent" | "requestCoreCopyAgent" | "revokeComboCopyAgent" | "searchCatalog" | "setAvatar" | "setCopyAllocation" | "setCopySettings" | "setPublicProfile" | "setUsername" | "setXHandleShown" | "signGoldenGift" | "stream" | "streamMarkets" | "switchOffComboCopyAgent" | "switchOffCoreCopyAgent" | "unfollowTrader" | "unlikeComment" | "unreactComment">;
121
+ export type operations = Pick<SharedOperations, "abandonCoreExit" | "acceptQuote" | "activeCoreExits" | "admitOwnMaker" | "admitPartnerWallet" | "approveWallet" | "bindEmbeddedWallet" | "cancelRfq" | "confirmComboCopyAgent" | "confirmCoreCopyAgent" | "createCashout" | "createComment" | "createCoreExit" | "createDeposit" | "createGoldenRfq" | "createRfq" | "createRunOffClaim" | "createWalletChallenge" | "createWalletSession" | "createWithdrawal" | "deleteComment" | "editComment" | "endWalletSession" | "followTrader" | "getAcceptance" | "getAccountActivity" | "getAccountPnl" | "getAccountPosition" | "getBalances" | "getCopyAgents" | "getCopyBudget" | "getCopySettings" | "getCopySummary" | "getCoreExit" | "getDeployment" | "getGolden" | "getGoldenMarkets" | "getGoldenOffer" | "getGoldenSuggestions" | "getHypercoreBalance" | "getHypercorePortfolio" | "getHypercoreSettlementCredits" | "getIdentity" | "getMakerActivity" | "getMakerCapital" | "getMakerExposure" | "getMakerPerformance" | "getMakerPosition" | "getMakerQuotes" | "getMakerTelemetry" | "getMakerVaultFundingTransaction" | "getMakerWithdrawal" | "getMarket" | "getMarketDataConfig" | "getMarketDefinitions" | "getMarketHistory" | "getMarketRecurringRound" | "getMarketReferenceCloses" | "getMarketScoreTimeline" | "getMarketStats" | "getMyGenesis" | "getMyReferralBonus" | "getOperation" | "getOwnMaker" | "getPartnerReport" | "getPerpMarks" | "getProfitLeaderboard" | "getQuestion" | "getQuestionRecurringRound" | "getQuestionScoreTimeline" | "getRfq" | "getSeries" | "getSuggestedCombo" | "getTaxonomy" | "getTrader" | "getTraderPnl" | "getUsernameAvailability" | "getVaultAgents" | "getVolumeLeaderboard" | "getWalletApproval" | "getWithdrawal" | "grantComboCopyAgent" | "grantVaultAgent" | "likeComment" | "listAccountActivity" | "listAccountPositions" | "listComboCopies" | "listComboFeed" | "listCommentReplies" | "listComments" | "listControlledMakers" | "listCopiedFills" | "listCopyTrades" | "listDiscovery" | "listFollows" | "listMakerActivity" | "listMakerPositions" | "listMakerQuoteHistory" | "listMarkets" | "listMyNotifications" | "listOperations" | "listPartnerFills" | "listQuotes" | "listTraderPositions" | "listTraderTrades" | "markMyNotificationsRead" | "placeGolden" | "reactComment" | "recordAcquisition" | "refreshPicture" | "requestComboCopyAgent" | "requestCoreCopyAgent" | "revokeComboCopyAgent" | "searchCatalog" | "setAvatar" | "setCopyAllocation" | "setCopySettings" | "setPublicProfile" | "setUsername" | "setXHandleShown" | "signGoldenGift" | "stream" | "streamMarkets" | "switchOffComboCopyAgent" | "switchOffCoreCopyAgent" | "unfollowTrader" | "unlikeComment" | "unreactComment">;
@@ -449,6 +449,7 @@ export declare const operationErrors: {
449
449
  readonly getMarketScoreTimeline: readonly ["INVALID_REQUEST", "NOT_FOUND", "MARKET_DATA_UNAVAILABLE", "INVALID_QUERY"];
450
450
  readonly getMarketStats: readonly ["MARKET_DATA_UNAVAILABLE", "INVALID_QUERY"];
451
451
  readonly getMyGenesis: readonly ["UNAUTHENTICATED", "FORBIDDEN", "AUTHORIZATION_UNAVAILABLE", "RATE_LIMITED", "ORIGIN_REQUIRED", "IDENTITY_NOT_FOUND", "INVALID_QUERY", "CONTRACT_UNAVAILABLE"];
452
+ readonly getMyReferralBonus: readonly ["UNAUTHENTICATED", "FORBIDDEN", "AUTHORIZATION_UNAVAILABLE", "RATE_LIMITED", "ORIGIN_REQUIRED", "IDENTITY_NOT_FOUND", "INVALID_QUERY", "CONTRACT_UNAVAILABLE"];
452
453
  readonly getOperation: readonly ["UNAUTHENTICATED", "FORBIDDEN", "AUTHORIZATION_UNAVAILABLE", "DEPENDENCY_STALE", "RATE_LIMITED", "INVALID_REQUEST", "NOT_FOUND", "IDENTITY_NOT_FOUND"];
453
454
  readonly getOwnMaker: readonly ["UNAUTHENTICATED", "FORBIDDEN", "AUTHORIZATION_UNAVAILABLE", "DEPENDENCY_STALE", "RATE_LIMITED", "ORIGIN_REQUIRED", "NOT_FOUND", "IDENTITY_NOT_FOUND"];
454
455
  readonly getPartnerReport: readonly ["INVALID_QUERY", "UNAUTHENTICATED", "FORBIDDEN", "RATE_LIMITED", "AUTHORIZATION_UNAVAILABLE", "SOURCE_UNAVAILABLE"];
@@ -1246,6 +1246,16 @@ export const operationErrors = {
1246
1246
  "INVALID_QUERY",
1247
1247
  "CONTRACT_UNAVAILABLE"
1248
1248
  ],
1249
+ "getMyReferralBonus": [
1250
+ "UNAUTHENTICATED",
1251
+ "FORBIDDEN",
1252
+ "AUTHORIZATION_UNAVAILABLE",
1253
+ "RATE_LIMITED",
1254
+ "ORIGIN_REQUIRED",
1255
+ "IDENTITY_NOT_FOUND",
1256
+ "INVALID_QUERY",
1257
+ "CONTRACT_UNAVAILABLE"
1258
+ ],
1249
1259
  "getOperation": [
1250
1260
  "UNAUTHENTICATED",
1251
1261
  "FORBIDDEN",
@@ -1183,6 +1183,26 @@ export type paths = {
1183
1183
  readonly patch?: never;
1184
1184
  readonly trace?: never;
1185
1185
  };
1186
+ readonly "/v1/me/referral-bonus": {
1187
+ readonly parameters: {
1188
+ readonly query?: never;
1189
+ readonly header?: never;
1190
+ readonly path?: never;
1191
+ readonly cookie?: never;
1192
+ };
1193
+ /**
1194
+ * Get my referral bonus
1195
+ * @description The authenticated account's referral bonus. A referral is someone the account's own invite code admitted; they qualify once their own Combo stake since signing up reaches qualifying_stake, and the account earns bonus for each, up to monthly_cap a UTC month by when each qualified. Referrals past the cap earn nothing that month and nothing carries over. A one-leg entry is a single-market buy, not a Combo, and a golden Combo is not the referral's own stake. The bonus is separate from the fee share in GET /v1/referrals/me. Answers CONTRACT_UNAVAILABLE where the referral bonus is off.
1196
+ */
1197
+ readonly get: operations["getMyReferralBonus"];
1198
+ readonly put?: never;
1199
+ readonly post?: never;
1200
+ readonly delete?: never;
1201
+ readonly options?: never;
1202
+ readonly head?: never;
1203
+ readonly patch?: never;
1204
+ readonly trace?: never;
1205
+ };
1186
1206
  readonly "/v1/me/copy-summary": {
1187
1207
  readonly parameters: {
1188
1208
  readonly query?: never;
@@ -3602,6 +3622,8 @@ export type components = {
3602
3622
  /** @description Opaque list cursor. Send a previous response's next_cursor back unchanged; never build or parse one. */
3603
3623
  readonly PageCursor: string;
3604
3624
  readonly LowercaseNonZeroAddress: string;
3625
+ /** @description 3 to 20 lowercase letters, digits or underscores. Unique across accounts. */
3626
+ readonly Username: string;
3605
3627
  readonly UInt32String: string;
3606
3628
  readonly Leg: {
3607
3629
  /** @description HIP-4 outcome ID of the leg, as a decimal string. */
@@ -3655,6 +3677,8 @@ export type components = {
3655
3677
  readonly maker_id: components["schemas"]["NonZeroUInt64String"];
3656
3678
  /** @description Current position owner wallet (lowercase). */
3657
3679
  readonly owner: components["schemas"]["LowercaseNonZeroAddress"];
3680
+ /** @description On a maker's read, the owner's username when the owner wallet is the account wallet of a participant whose public trader profile is on, the pair GET /v1/traders/{username} shows; otherwise null, as for a participant's other linked wallets, and always null on a personal read. */
3681
+ readonly owner_username: components["schemas"]["Username"] | null;
3658
3682
  /**
3659
3683
  * @description OPEN: not yet known eligible for settlement; AWAITING_SETTLEMENT: every leg resolved, or the payout with every unresolved leg counted as a win already rounds down to zero, but no settlement observed; SETTLED_UNCLAIMED: settled with profit still unclaimed; CLOSED: closed by zero-profit settlement, final claim or sell-back.
3660
3684
  * @enum {string}
@@ -4146,8 +4170,6 @@ export type components = {
4146
4170
  };
4147
4171
  /** Format: uuid */
4148
4172
  readonly Uuid: string;
4149
- /** @description 3 to 20 lowercase letters, digits or underscores. Unique across accounts. */
4150
- readonly Username: string;
4151
4173
  /** @description A random (version 4) UUID, lowercase. */
4152
4174
  readonly AvatarSeed: string;
4153
4175
  /** @description An X profile picture on pbs.twimg.com or abs.twimg.com, at the size X gave Privy, usually the 48-pixel file ending in _normal; X also serves _bigger (73 px) and _400x400 under the same name. */
@@ -4707,6 +4729,8 @@ export type components = {
4707
4729
  readonly coin: string;
4708
4730
  /** @description Current reference price of this side, or why none is available. */
4709
4731
  readonly reference: components["schemas"]["Reference"];
4732
+ /** @description For display only: the side's last real chance at the probability scale (10^18), set only while the market's awaiting_result is true and reference.chance is null. It is the newest evidence the chance rule holds, unclamped: the last book execution, or the last midpoint of a book at most 10% of scale wide. It needs a fresh, uncrossed book on this side; an empty book keeps it. YES and NO sum to scale. Null or absent otherwise. It is not a price, a value or a chance: never trade, value a position or pick a Combo leg with it. */
4733
+ readonly last_chance?: components["schemas"]["IntegerValue"] | null;
4710
4734
  };
4711
4735
  readonly DateEvent: {
4712
4736
  /**
@@ -4759,6 +4783,8 @@ export type components = {
4759
4783
  readonly sides: readonly components["schemas"]["MarketSide"][];
4760
4784
  /** @description Display dates and the market class; null when the market has neither reviewed timing nor a market class. Never controls availability or settlement. */
4761
4785
  readonly dates: components["schemas"]["MarketDates"] | null;
4786
+ /** @description For display only: whether the market's event is over while Hyperliquid has not recorded its result. true when a live scoreboard shows its game final (every winner, spread and total market of that game) or a price market's observation time has passed with its result unresolved; false when its event is known not to be over yet or its result is recorded; null or absent when unknown: other kinds of market, a game no scoreboard covers or reads now, or a native result that could not be read. It never closes trading, settles, or changes chance, mark, eligibility or Combo admission. */
4787
+ readonly awaiting_result?: boolean | null;
4762
4788
  };
4763
4789
  readonly DiscoveryQuestionItem: components["schemas"]["DiscoveryDisplay"] & {
4764
4790
  /** @description Item ID, question: followed by the native question ID. */
@@ -9334,6 +9360,76 @@ export interface operations {
9334
9360
  readonly 503: components["responses"]["Unavailable"];
9335
9361
  };
9336
9362
  };
9363
+ readonly getMyReferralBonus: {
9364
+ readonly parameters: {
9365
+ readonly query?: never;
9366
+ readonly header?: never;
9367
+ readonly path?: never;
9368
+ readonly cookie?: never;
9369
+ };
9370
+ readonly requestBody?: never;
9371
+ readonly responses: {
9372
+ /** @description The referral bonus */
9373
+ readonly 200: {
9374
+ headers: {
9375
+ readonly "Cache-Control"?: "no-store";
9376
+ readonly [name: string]: unknown;
9377
+ };
9378
+ content: {
9379
+ readonly "application/json": {
9380
+ /** @description A referral qualifies once their own Combo stake since signing up with the account's code reaches this, in HyperEVM USDC base units (10^-6). */
9381
+ readonly qualifying_stake: components["schemas"]["$defs-Amount"];
9382
+ /** @description What each qualified referral earns, in HyperEVM USDC base units (10^-6). */
9383
+ readonly bonus: components["schemas"]["$defs-Amount"];
9384
+ /** @description The most the account earns in one UTC month, in HyperEVM USDC base units (10^-6). */
9385
+ readonly monthly_cap: components["schemas"]["$defs-Amount"];
9386
+ /** @description When the bonus started in this deployment; null until it has. A referral that qualified before it earns nothing. */
9387
+ readonly started_at: components["schemas"]["$defs-Timestamp"] | null;
9388
+ /** @description Each UTC month a referral qualified in, newest first. */
9389
+ readonly months: readonly {
9390
+ /** @description The UTC month, YYYY-MM. */
9391
+ readonly month: string;
9392
+ /** @description Referrals that qualified this month and earned the bonus. */
9393
+ readonly earned: number;
9394
+ /** @description Referrals that qualified this month after the cap was reached; they earn nothing, and nothing carries over. */
9395
+ readonly capped: number;
9396
+ /** @description What the month's referrals earned, in HyperEVM USDC base units (10^-6). */
9397
+ readonly bonus: components["schemas"]["$defs-Amount"];
9398
+ }[];
9399
+ /** @description The 100 most recently qualified referrals, newest first. */
9400
+ readonly qualified: readonly {
9401
+ /** @description The referral's username, or null until they pick one. */
9402
+ readonly username: components["schemas"]["Username"] | null;
9403
+ /** @description When their stake reached qualifying_stake: the commit of the Combo that took it there. */
9404
+ readonly qualified_at: components["schemas"]["$defs-Timestamp"];
9405
+ /**
9406
+ * @description EARNED earned the bonus; CAPPED came after the month's cap; BEFORE_START qualified before started_at; SELF shares a wallet with the account.
9407
+ * @enum {unknown}
9408
+ */
9409
+ readonly outcome: "EARNED" | "CAPPED" | "BEFORE_START" | "SELF";
9410
+ /** @description What this referral earned, in HyperEVM USDC base units (10^-6). */
9411
+ readonly bonus: components["schemas"]["$defs-Amount"];
9412
+ }[];
9413
+ /** @description The 100 most recently admitted referrals who have not qualified yet, newest first. */
9414
+ readonly pending: readonly {
9415
+ /** @description The referral's username, or null until they pick one. */
9416
+ readonly username: components["schemas"]["Username"] | null;
9417
+ /** @description When they signed up with the account's code. */
9418
+ readonly admitted_at: components["schemas"]["$defs-Timestamp"];
9419
+ /** @description Their own Combo stake since then, in HyperEVM USDC base units (10^-6). */
9420
+ readonly staked: components["schemas"]["$defs-Amount"];
9421
+ }[];
9422
+ };
9423
+ };
9424
+ };
9425
+ readonly 400: components["responses"]["Error"];
9426
+ readonly 401: components["responses"]["Error"];
9427
+ readonly 403: components["responses"]["Error"];
9428
+ readonly 404: components["responses"]["Error"];
9429
+ readonly 429: components["responses"]["RateLimited"];
9430
+ readonly 503: components["responses"]["Unavailable"];
9431
+ };
9432
+ };
9337
9433
  readonly getCopySummary: {
9338
9434
  readonly parameters: {
9339
9435
  readonly query?: never;
@@ -1380,6 +1380,8 @@ export type components = {
1380
1380
  readonly deadline: components["schemas"]["Deadline"] | components["schemas"]["$defs-Deadline"];
1381
1381
  /** @description The YES and NO sides, in that order. */
1382
1382
  readonly sides: readonly components["schemas"]["PublicationCatalogSide"][];
1383
+ /** @description For display only: whether the market's event is over while its result is not recorded, as the market's awaiting_result. Absent means null. A change arrives as a catalog upsert, without a metadata revision. */
1384
+ readonly awaiting_result?: boolean | null;
1383
1385
  /** @description Publication version at which this item last changed; at most the packet's terminal version. */
1384
1386
  readonly version: components["schemas"]["PositiveInt64"];
1385
1387
  };
@@ -1522,6 +1524,8 @@ export type components = {
1522
1524
  readonly side: components["schemas"]["Side"];
1523
1525
  /** @description Current reference price of this side, or why none is available. */
1524
1526
  readonly reference: components["schemas"]["FeedReference"];
1527
+ /** @description For display only: the side's last real chance while its market awaits its result and reference.chance is null, as the market side's last_chance. Absent means null. It travels in this reference upsert, so a newer upsert replaces both. */
1528
+ readonly last_chance?: components["schemas"]["IntegerValue"] | null;
1525
1529
  /** @description Publication version at which this reference last changed. */
1526
1530
  readonly version: components["schemas"]["PositiveInt64"];
1527
1531
  };
@@ -1,5 +1,5 @@
1
- export declare const sdkVersion = "220.0.0-partner-fills";
2
- export declare const openapiSha256 = "b89f395adf9844ddd0e6543b439cbedaed15b1986dea3ca38800bdcfdd78ca43";
1
+ export declare const sdkVersion = "222.0.0-referral-bonus";
2
+ export declare const openapiSha256 = "7af9309ed00fe5096f9f0c9237b49a0be02baa1c173f2607d3c473175a54cad2";
3
3
  export declare const realtimeSha256 = "32e56c8bb642401f5b03e9c38274087c09bebb73ffe60c0d34432c2e78ce1e15";
4
4
  export declare const jsonSchemaSha256: {
5
5
  readonly "account.schema.json": "c11a94438d5f7b54e08d3b559098ce2671f4c9aad3a79feb684b7a81f77d809a";
@@ -12,13 +12,13 @@ export declare const jsonSchemaSha256: {
12
12
  readonly "maker-access.schema.json": "49698ee0235e42064aae0397db1e0f646bdc10d9dfa10121714ba06dd69fee3b";
13
13
  readonly "maker-action.schema.json": "dc41e52c868848e85cdeb918992cb710d34616d2803a63f6d9a658e016744a50";
14
14
  readonly "maker-telemetry.schema.json": "85b111ce0f4935299d1116071b43de12e775bef4e0c283c12f19046d34374a9c";
15
- readonly "market-data.schema.json": "85db33fac6a29b0fa87a500bfda947d0ab3913b13f1c26663d4a7c0484c35786";
15
+ readonly "market-data.schema.json": "d9b277cdd7094a3c32a0c0957ad1de94458b0ea36b9a9fdf6f1f6211bd3c5e61";
16
16
  readonly "product-metadata.schema.json": "7c8ffbde878a0aedaed16814fcfd2e80038054b140886cc8736bb7b508042631";
17
17
  readonly "quote.schema.json": "52ee1f4708c8b1504e4cd2f2f9279e14c8ec8aeacac1f491441ae0e15ac3c71a";
18
18
  readonly "realtime.schema.json": "32e56c8bb642401f5b03e9c38274087c09bebb73ffe60c0d34432c2e78ce1e15";
19
19
  };
20
20
  export declare const operations: {
21
- readonly client: readonly ["abandonCoreExit", "acceptQuote", "activeCoreExits", "admitOwnMaker", "admitPartnerWallet", "approveWallet", "bindEmbeddedWallet", "cancelRfq", "confirmComboCopyAgent", "confirmCoreCopyAgent", "createCashout", "createComment", "createCoreExit", "createDeposit", "createGoldenRfq", "createRfq", "createRunOffClaim", "createWalletChallenge", "createWalletSession", "createWithdrawal", "deleteComment", "editComment", "endWalletSession", "followTrader", "getAcceptance", "getAccountActivity", "getAccountPnl", "getAccountPosition", "getBalances", "getCopyAgents", "getCopyBudget", "getCopySettings", "getCopySummary", "getCoreExit", "getDeployment", "getGolden", "getGoldenMarkets", "getGoldenOffer", "getGoldenSuggestions", "getHypercoreBalance", "getHypercorePortfolio", "getHypercoreSettlementCredits", "getIdentity", "getMakerActivity", "getMakerCapital", "getMakerExposure", "getMakerPerformance", "getMakerPosition", "getMakerQuotes", "getMakerTelemetry", "getMakerVaultFundingTransaction", "getMakerWithdrawal", "getMarket", "getMarketDataConfig", "getMarketDefinitions", "getMarketHistory", "getMarketRecurringRound", "getMarketReferenceCloses", "getMarketScoreTimeline", "getMarketStats", "getMyGenesis", "getOperation", "getOwnMaker", "getPartnerReport", "getPerpMarks", "getProfitLeaderboard", "getQuestion", "getQuestionRecurringRound", "getQuestionScoreTimeline", "getRfq", "getSeries", "getSuggestedCombo", "getTaxonomy", "getTrader", "getTraderPnl", "getUsernameAvailability", "getVaultAgents", "getVolumeLeaderboard", "getWalletApproval", "getWithdrawal", "grantComboCopyAgent", "grantVaultAgent", "likeComment", "listAccountActivity", "listAccountPositions", "listComboCopies", "listComboFeed", "listCommentReplies", "listComments", "listControlledMakers", "listCopiedFills", "listCopyTrades", "listDiscovery", "listFollows", "listMakerActivity", "listMakerPositions", "listMakerQuoteHistory", "listMarkets", "listMyNotifications", "listOperations", "listPartnerFills", "listQuotes", "listTraderPositions", "listTraderTrades", "markMyNotificationsRead", "placeGolden", "reactComment", "recordAcquisition", "refreshPicture", "requestComboCopyAgent", "requestCoreCopyAgent", "revokeComboCopyAgent", "searchCatalog", "setAvatar", "setCopyAllocation", "setCopySettings", "setPublicProfile", "setUsername", "setXHandleShown", "signGoldenGift", "stream", "streamMarkets", "switchOffComboCopyAgent", "switchOffCoreCopyAgent", "unfollowTrader", "unlikeComment", "unreactComment"];
21
+ readonly client: readonly ["abandonCoreExit", "acceptQuote", "activeCoreExits", "admitOwnMaker", "admitPartnerWallet", "approveWallet", "bindEmbeddedWallet", "cancelRfq", "confirmComboCopyAgent", "confirmCoreCopyAgent", "createCashout", "createComment", "createCoreExit", "createDeposit", "createGoldenRfq", "createRfq", "createRunOffClaim", "createWalletChallenge", "createWalletSession", "createWithdrawal", "deleteComment", "editComment", "endWalletSession", "followTrader", "getAcceptance", "getAccountActivity", "getAccountPnl", "getAccountPosition", "getBalances", "getCopyAgents", "getCopyBudget", "getCopySettings", "getCopySummary", "getCoreExit", "getDeployment", "getGolden", "getGoldenMarkets", "getGoldenOffer", "getGoldenSuggestions", "getHypercoreBalance", "getHypercorePortfolio", "getHypercoreSettlementCredits", "getIdentity", "getMakerActivity", "getMakerCapital", "getMakerExposure", "getMakerPerformance", "getMakerPosition", "getMakerQuotes", "getMakerTelemetry", "getMakerVaultFundingTransaction", "getMakerWithdrawal", "getMarket", "getMarketDataConfig", "getMarketDefinitions", "getMarketHistory", "getMarketRecurringRound", "getMarketReferenceCloses", "getMarketScoreTimeline", "getMarketStats", "getMyGenesis", "getMyReferralBonus", "getOperation", "getOwnMaker", "getPartnerReport", "getPerpMarks", "getProfitLeaderboard", "getQuestion", "getQuestionRecurringRound", "getQuestionScoreTimeline", "getRfq", "getSeries", "getSuggestedCombo", "getTaxonomy", "getTrader", "getTraderPnl", "getUsernameAvailability", "getVaultAgents", "getVolumeLeaderboard", "getWalletApproval", "getWithdrawal", "grantComboCopyAgent", "grantVaultAgent", "likeComment", "listAccountActivity", "listAccountPositions", "listComboCopies", "listComboFeed", "listCommentReplies", "listComments", "listControlledMakers", "listCopiedFills", "listCopyTrades", "listDiscovery", "listFollows", "listMakerActivity", "listMakerPositions", "listMakerQuoteHistory", "listMarkets", "listMyNotifications", "listOperations", "listPartnerFills", "listQuotes", "listTraderPositions", "listTraderTrades", "markMyNotificationsRead", "placeGolden", "reactComment", "recordAcquisition", "refreshPicture", "requestComboCopyAgent", "requestCoreCopyAgent", "revokeComboCopyAgent", "searchCatalog", "setAvatar", "setCopyAllocation", "setCopySettings", "setPublicProfile", "setUsername", "setXHandleShown", "signGoldenGift", "stream", "streamMarkets", "switchOffComboCopyAgent", "switchOffCoreCopyAgent", "unfollowTrader", "unlikeComment", "unreactComment"];
22
22
  readonly maker: readonly ["cancelQuote", "confirmQuote", "createCollateralReduction", "createQuote", "getAccountActivity", "getAccountPosition", "getCollateralReduction", "getDeployment", "getMakerActivity", "getMakerCapital", "getMakerExposure", "getMakerPerformance", "getMakerPosition", "getMakerQuotes", "getMakerTelemetry", "getMakerTelemetryPublication", "getMakerVaultFundingTransaction", "getMakerWithdrawal", "getMarket", "getMarketHistory", "getMarketRecurringRound", "getMarketReferenceCloses", "getOperation", "getQuestion", "getQuestionRecurringRound", "getRfq", "getSeries", "getTaxonomy", "listAccountActivity", "listAccountPositions", "listDiscovery", "listMakerAcceptances", "listMakerActivity", "listMakerPositions", "listMakerQuoteHistory", "listMarkets", "listOperations", "listRfqs", "publishMakerTelemetry", "releaseQuoteLease", "renewQuoteLease", "searchCatalog", "stream", "submitMakerSelfFundedTransaction"];
23
23
  readonly operator: readonly ["live", "ready"];
24
24
  };
@@ -1,6 +1,6 @@
1
1
  // Generated by scripts/generate.mjs; do not edit.
2
- export const sdkVersion = "220.0.0-partner-fills";
3
- export const openapiSha256 = "b89f395adf9844ddd0e6543b439cbedaed15b1986dea3ca38800bdcfdd78ca43";
2
+ export const sdkVersion = "222.0.0-referral-bonus";
3
+ export const openapiSha256 = "7af9309ed00fe5096f9f0c9237b49a0be02baa1c173f2607d3c473175a54cad2";
4
4
  export const realtimeSha256 = "32e56c8bb642401f5b03e9c38274087c09bebb73ffe60c0d34432c2e78ce1e15";
5
5
  export const jsonSchemaSha256 = {
6
6
  "account.schema.json": "c11a94438d5f7b54e08d3b559098ce2671f4c9aad3a79feb684b7a81f77d809a",
@@ -13,7 +13,7 @@ export const jsonSchemaSha256 = {
13
13
  "maker-access.schema.json": "49698ee0235e42064aae0397db1e0f646bdc10d9dfa10121714ba06dd69fee3b",
14
14
  "maker-action.schema.json": "dc41e52c868848e85cdeb918992cb710d34616d2803a63f6d9a658e016744a50",
15
15
  "maker-telemetry.schema.json": "85b111ce0f4935299d1116071b43de12e775bef4e0c283c12f19046d34374a9c",
16
- "market-data.schema.json": "85db33fac6a29b0fa87a500bfda947d0ab3913b13f1c26663d4a7c0484c35786",
16
+ "market-data.schema.json": "d9b277cdd7094a3c32a0c0957ad1de94458b0ea36b9a9fdf6f1f6211bd3c5e61",
17
17
  "product-metadata.schema.json": "7c8ffbde878a0aedaed16814fcfd2e80038054b140886cc8736bb7b508042631",
18
18
  "quote.schema.json": "52ee1f4708c8b1504e4cd2f2f9279e14c8ec8aeacac1f491441ae0e15ac3c71a",
19
19
  "realtime.schema.json": "32e56c8bb642401f5b03e9c38274087c09bebb73ffe60c0d34432c2e78ce1e15"
@@ -81,6 +81,7 @@ export const operations = {
81
81
  "getMarketScoreTimeline",
82
82
  "getMarketStats",
83
83
  "getMyGenesis",
84
+ "getMyReferralBonus",
84
85
  "getOperation",
85
86
  "getOwnMaker",
86
87
  "getPartnerReport",
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 : AbortSignal.timeout(Math.max(0, Math.ceil(deadline - now())))].filter((signal) => signal !== undefined);
122
- const stop = stops.length === 0 ? undefined : AbortSignal.any(stops);
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, where the
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, where the
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 (typeof globalThis.document !== "undefined") {
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 = crypto.getRandomValues(new Uint8Array(16));
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(crypto.getRandomValues(new Uint8Array(32)), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
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.reason);
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?.reason);
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
- response = await fetchImpl(build());
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;
@@ -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+, bots)
31
- * as a bearer header, so `headers` carries Authorization and any extra headers.
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 browser WebSocket and Node's.
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
- const inBrowser = () => typeof globalThis.document !== "undefined";
5
- // Node's WebSocket (undici) and Bun accept `{ protocols, headers }` in place of protocols.
6
- const openWebSocket = (url, protocols, headers) => inBrowser() ? new WebSocket(url, protocols) : new WebSocket(url, { protocols, headers });
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 browser WebSocket and Node's.
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?.reason));
145
+ const abort = () => done(() => reject(abortReason(signal)));
137
146
  if (signal?.aborted)
138
- return reject(signal.reason);
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 = inBrowser()
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 ? AbortSignal.timeout(ms) : AbortSignal.any([signal, AbortSignal.timeout(ms)]);
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
- cut.signal.addEventListener("abort", () => resolve(), { once: true });
156
- stop.addEventListener("abort", () => resolve(), { once: true, signal: cut.signal });
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, AbortSignal.any([stop, cut.signal])).catch(() => undefined), ended]);
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?.reason));
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?.throwIfAborted();
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?.reason));
1282
+ const abort = () => finish(() => reject(abortReason(signal)));
1277
1283
  if (signal?.aborted)
1278
1284
  return abort();
1279
1285
  signal?.addEventListener("abort", abort, { once: true });
@@ -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 && (inBrowser() || !serverKey.startsWith("tpk_v1_")))
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 = inBrowser() ? {} : { Origin: origin };
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 = inBrowser() || origin === undefined ? {} : { Origin: origin };
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.92.0",
3
+ "version": "0.93.1",
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": {