@totalis/hip4-client 0.103.0 → 0.105.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 CHANGED
@@ -3,6 +3,44 @@
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.105.0
7
+
8
+ ### Added
9
+
10
+ - Singles on HyperCore (TT-2822). `placeSingle` builds, signs and sends a
11
+ Hyperliquid order for one outcome side, and `cancelSingles` cancels resting
12
+ ones by cloid or oid. The account or its Hyperliquid agent key signs, and the
13
+ order goes straight to Hyperliquid. Every order carries the Totalis builder
14
+ fee, 10 bps of notional (`totalisBuilder`). The account approves that fee
15
+ once with its own wallet (`approveTotalisBuilder`; `readTotalisBuilderFee`
16
+ reads the approval), and `approveHyperliquidAgent` approves an agent key.
17
+ An answer is `resting`, `filled`, `refused` or `unknown`; look up an
18
+ `unknown` order by its cloid with `readSingleOrder`. The parts
19
+ (`singleOrderAction`, `singleCancelAction`, `signL1Action`, `l1TypedData`,
20
+ `submitSingleOrder`, `outcomeAsset`, `outcomeCoin`) are exported too.
21
+
22
+ ## 0.104.0
23
+
24
+ ### Added
25
+
26
+ - Live `WALLET_BALANCE_CHANGED` payloads carry the transfer's `log_index`, `sender`,
27
+ `recipient` and `amount` (atomic USDC, 6 decimals), all optional:
28
+ wallet-history notices and older events lack them (TT-2796, contract
29
+ `240.0.0-wallet-transfer-parties`). The event now arrives
30
+ within seconds of the transfer, and the same transfer can arrive more than
31
+ once. Identify a transfer by `transaction_hash` and `log_index`; treat the
32
+ notice as a reason to reread balances, not something to count.
33
+
34
+ ### Changed
35
+
36
+ - Social positions (TT-2710). A HyperCore holding's `cost` counts each pair
37
+ at 1 on top of the net shares' cost, so a position held on both sides no
38
+ longer reads as costing 0; `value - cost` is what the shares held would
39
+ still make at the mark, and `pnl` is unchanged. A paired position that cost
40
+ 1 or more now shows on following positions instead of counting as dust.
41
+ A comment's `positions` is null for makers, API operators and the other
42
+ roles the public feed leaves out.
43
+
6
44
  ## 0.103.0
7
45
 
8
46
  ### Changed
package/README.md CHANGED
@@ -4,6 +4,7 @@ The official TypeScript SDK for [Totalis](https://totalis.trade) on Hyperliquid
4
4
 
5
5
  - **Typed clients** for every REST route, generated from the API contract
6
6
  - **Taker and maker flows** that run end to end: open a position, cash out, withdraw, quote, answer acceptances
7
+ - **Singles on HyperCore**: buy or sell one outcome side on Hyperliquid's own book, signed and sent by you
7
8
  - **A realtime stream** that resumes from its cursor and reconnects on its own
8
9
  - **Builders for every signed message** (EIP-712, USDC authorizations, the Hyperliquid bridge)
9
10
  - **Safe retries**: every command keeps one `Idempotency-Key` and is resent byte for byte, so a retry never trades twice
@@ -110,6 +111,43 @@ permit that has not landed yet. Approvals are per vault: these calls serve the a
110
111
  a vault is retired its WalletAccept can't pull, and the wallet clears an approval left to it with its own
111
112
  `approve(0)` or `permit(0)`.
112
113
 
114
+ ## Trade singles on HyperCore
115
+
116
+ A single buys or sells one side of one outcome on Hyperliquid's own book. You sign the order with the account
117
+ or its Hyperliquid agent key and the SDK sends it straight to Hyperliquid; Totalis never sees it. Every order
118
+ carries the Totalis builder fee, 10 bps of its notional (`totalisBuilder`), as orders in the Totalis app do, so
119
+ the account approves that fee once first:
120
+
121
+ ```ts
122
+ import { approveTotalisBuilder, hyperliquidNetwork, placeSingle, readSingleOrder, readTotalisBuilderFee, totalisBuilder } from "@totalis/hip4-client";
123
+ import { privateKeyToAccount } from "viem/accounts";
124
+
125
+ const network = hyperliquidNetwork(999); // GET /v1/deployment chain_id
126
+ const wallet = privateKeyToAccount(process.env.TOTALIS_WALLET_KEY as `0x${string}`);
127
+
128
+ // Once per account, signed by its own wallet (Hyperliquid refuses it from an agent).
129
+ if ((await readTotalisBuilderFee(network, wallet.address)) < totalisBuilder.feeDecibps) {
130
+ await approveTotalisBuilder(wallet, network);
131
+ }
132
+
133
+ const { signed, answer } = await placeSingle(wallet, network, {
134
+ outcomeId: "13160",
135
+ side: "YES",
136
+ buy: true,
137
+ price: "0.42", // USDC per share, at most 5 significant figures; a buy pays at most this
138
+ shares: 20, // whole shares, each pays 1 USDC if YES wins
139
+ tif: "Ioc", // fill what crosses now; "Gtc" (default) rests the rest
140
+ });
141
+ // answer: resting, filled, refused, or unknown. Unknown means no answer arrived:
142
+ // look it up by its cloid before placing it again.
143
+ if (answer.kind === "unknown") await readSingleOrder(network, wallet.address, signed.action.orders[0].c);
144
+ ```
145
+
146
+ `cancelSingles` cancels resting singles by cloid or oid. Browser wallets often refuse to sign orders (their
147
+ signing domain names chain 1337), so in a browser approve an agent key once with `approveHyperliquidAgent` and
148
+ sign orders with that. The agent can trade but never withdraw. `singleOrderAction`, `signL1Action` and
149
+ `submitSingleOrder` are the parts, if you send through your own Hyperliquid client.
150
+
113
151
  ## Make markets
114
152
 
115
153
  ```ts
package/dist/client.d.ts CHANGED
@@ -7,6 +7,7 @@ export type { AccessToken, ApiClientOptions, PublicEnvironment } from "./base.js
7
7
  export declare function createClient(environment: PublicEnvironment, options?: ApiClientOptions): import("openapi-fetch").Client<paths, `${string}/${string}`>;
8
8
  export { bestBid, bestQuote, createTotalis, defaultWalletApproval, EntryError, entryFailure, follow, WalletApprovalError, type Acceptance, type AcceptanceResult, type Amount, type ApprovalListener, type BridgeState, type ComboCash, type CashoutBid, type Chooser, type Deployment, type DepositAccepted, type EntryCash, type EntryFailure, type EntryFunding, type EntryQuote, type KnownWalletApproval, type LandedWalletApproval, type SignedWalletApproval, type WalletApproval, type WalletApprovalRequest, type CoreExit, type LegacySignedEntry, type Leg, type PreparedEntryFunding, type NotAdmitted, type RecordListener, type Operation, type Quote, type ResponseOf, type SellBackQuote, type SignedAcceptance, type SignedCashout, type SignedCoreExit, type SignedDeposit, type SignedEntry, type SignedReturnToCore, type Totalis, type TotalisOptions, type WalletCall, type Withdrawal, } from "./totalis.js";
9
9
  export { bridgeAction, bridgeGasBuffer, classifyHypercoreAnswer, coreSetupFee, hyperevmUsdcBridge, hyperliquidExchange, hyperliquidInfo, hyperliquidNetwork, hypercoreNonce, hypercoreSignature, readCoreCash, sendAssetTypedData, settleHypercore, signSendAsset, submitHypercore, usdcText, type BridgedCash, type CoreAccountMode, type CoreCash, type HypercoreAnswer, type HyperliquidInfo, type HypercoreSignature, type HypercoreTransport, type HyperliquidNetwork, type SendAssetAction, type SignedSendAsset, } from "./hypercore.js";
10
+ export { approveAgentAction, approveAgentTypedData, approveBuilderFeeTypedData, approveHyperliquidAgent, approveTotalisBuilder, approveTotalisBuilderAction, cancelSingles, l1ActionHash, l1TypedData, outcomeAsset, outcomeCoin, placeSingle, readSingleOrder, readTotalisBuilderFee, signL1Action, singleCancelAction, singleCancelAnswers, singleCloid, singleOrderAction, singleOrderAnswer, submitSingleCancel, submitSingleOrder, totalisBuilder, type ApproveAgentAction, type ApproveBuilderFeeAction, type CancelByCloidAction, type CancelByOidAction, type ExchangeOptions, type L1Options, type OutcomeSide, type SignedL1Action, type SignedUserAction, type SingleAction, type SingleCancel, type SingleCancelAction, type SingleCancelAnswer, type SingleOrder, type SingleOrderAction, type SingleOrderAnswer, type SingleOrderStatus, type SingleTif, } from "./singles.js";
10
11
  export { ApiError, envelope, NetworkError, randomBytes32, retryingFetch, sendOnce, unwrap, uuidv7, type Fetch, type Repaired, type RetryPolicy } from "./request.js";
11
12
  export { items, pages, type Page, type PageQuery } from "./pagination.js";
12
13
  export { toTotalisSigner, type SignerInput, type TotalisSigner } from "./signer.js";
package/dist/client.js CHANGED
@@ -6,6 +6,7 @@ export function createClient(environment, options) {
6
6
  }
7
7
  export { bestBid, bestQuote, createTotalis, defaultWalletApproval, EntryError, entryFailure, follow, WalletApprovalError, } from "./totalis.js";
8
8
  export { bridgeAction, bridgeGasBuffer, classifyHypercoreAnswer, coreSetupFee, hyperevmUsdcBridge, hyperliquidExchange, hyperliquidInfo, hyperliquidNetwork, hypercoreNonce, hypercoreSignature, readCoreCash, sendAssetTypedData, settleHypercore, signSendAsset, submitHypercore, usdcText, } from "./hypercore.js";
9
+ export { approveAgentAction, approveAgentTypedData, approveBuilderFeeTypedData, approveHyperliquidAgent, approveTotalisBuilder, approveTotalisBuilderAction, cancelSingles, l1ActionHash, l1TypedData, outcomeAsset, outcomeCoin, placeSingle, readSingleOrder, readTotalisBuilderFee, signL1Action, singleCancelAction, singleCancelAnswers, singleCloid, singleOrderAction, singleOrderAnswer, submitSingleCancel, submitSingleOrder, totalisBuilder, } from "./singles.js";
9
10
  export { ApiError, envelope, NetworkError, randomBytes32, retryingFetch, sendOnce, unwrap, uuidv7 } from "./request.js";
10
11
  export { items, pages } from "./pagination.js";
11
12
  export { toTotalisSigner } from "./signer.js";
@@ -5628,7 +5628,7 @@ export type components = {
5628
5628
  readonly pairs: components["schemas"]["Shares"];
5629
5629
  /** @description What each net share cost, fees included, rounded half away from zero to 8 decimals; for a settled position, as it settled. Null with no net shares, once sold, or when unknown. */
5630
5630
  readonly entry: components["schemas"]["Price"] | null;
5631
- /** @description What the net shares held now cost, fees included. Null once closed or when unknown. */
5631
+ /** @description What the shares held now cost, fees included: the net shares at average cost plus 1 for each pair, so value - cost is what the shares held would still make at the mark. Null once closed or when unknown. */
5632
5632
  readonly cost: components["schemas"]["$defs-Amount"] | null;
5633
5633
  /** @description The net side's Value per share used here, market data's published mark (docs.totalis.trade, Chance, Price and Value); null when unknown, with no net shares, and once closed. */
5634
5634
  readonly mark: components["schemas"]["Price"] | null;
@@ -5911,7 +5911,7 @@ export type components = {
5911
5911
  readonly holder: boolean | null;
5912
5912
  /** @description The HyperCore outcome sides of its market (the outcome, or any of the question's outcomes) its author's account wallet holds now, newest opened first; empty when it holds none. Null once it is deleted; when the author's public trader profile is off or their account is not ACTIVE, since exact positions would show which wallet is theirs, as GET /v1/traders/{username} refuses to; and while it is not known: off Mainnet, while the account index is behind or does not hold history since launch, when the author has no single account wallet, when an outcome token of the market moved to or from it by transfer, or before the market catalog names the question's outcomes. Servers before contract 214 omit it. */
5913
5913
  readonly singles: readonly components["schemas"]["CommentSingle"][] | null;
5914
- /** @description Its author's HyperCore positions on its market (the outcome, or any of the question's outcomes) held now by the holdings ledger's rules, newest opened first, as the position read they open counts them; empty when they hold none. Null once it is deleted, when the author's public profile is off or their account is not ACTIVE, when the author has no single account wallet, while the holdings ledger is behind (not yet caught up, or stopped for over five minutes), and before the market catalog names the question's outcomes. Replaces singles once callers moved. Servers before contract 236 omit it. */
5914
+ /** @description Its author's HyperCore positions on its market (the outcome, or any of the question's outcomes) held now by the holdings ledger's rules, newest opened first, as the position read they open counts them; empty when they hold none. Null once it is deleted, when the author's public profile is off or their account is not ACTIVE, when the author has no single account wallet, when the author is a maker, an API operator or another role the public social feed leaves out, while the holdings ledger is behind (not yet caught up, or stopped for over five minutes), and before the market catalog names the question's outcomes. Replaces singles once callers moved. Servers before contract 236 omit it. */
5915
5915
  readonly positions?: readonly components["schemas"]["SingleSummary"][] | null;
5916
5916
  readonly like_count: number;
5917
5917
  /** @description Live replies; always 0 on a reply. */
@@ -308,7 +308,7 @@ export type components = {
308
308
  * @constant
309
309
  */
310
310
  readonly event_type: "WALLET_BALANCE_CHANGED";
311
- /** @description An observed USDC transfer touched this linked wallet. Refresh GET /v1/me/balances for the wallet balance. */
311
+ /** @description An observed USDC transfer touched this linked wallet. Refresh GET /v1/me/balances for the wallet balance. The same transfer can be reported more than once. */
312
312
  readonly payload: {
313
313
  /** @description Linked wallet the transfer touched, as sender or recipient. */
314
314
  readonly address: components["schemas"]["LowercaseNonZeroAddress"];
@@ -316,6 +316,14 @@ export type components = {
316
316
  readonly transaction_hash: components["schemas"]["Bytes32"];
317
317
  /** @description HyperEVM block number (decimal) of the transfer. */
318
318
  readonly block_number: string;
319
+ /** @description Transfer log index within its block. Together with transaction_hash, identifies one transfer. Present on live notices; absent on wallet-history notices and older events. */
320
+ readonly log_index?: number;
321
+ /** @description Address the USDC came from (the Transfer's from; zero for a mint). Present on live notices; absent on wallet-history notices and older events. */
322
+ readonly sender?: string;
323
+ /** @description Address the USDC went to (the Transfer's to; zero for a burn). Present on live notices; absent on wallet-history notices and older events. */
324
+ readonly recipient?: string;
325
+ /** @description Transferred amount in atomic USDC (6 decimals, "1000000" = 1 USDC). Present on live notices; absent on wallet-history notices and older events. */
326
+ readonly amount?: components["schemas"]["Uint"];
319
327
  };
320
328
  }) | (components["schemas"]["EventBase"] & {
321
329
  /**
@@ -1268,6 +1276,8 @@ export type components = {
1268
1276
  /** @description When the withdrawal last changed, RFC3339 UTC. */
1269
1277
  readonly updated_at: components["schemas"]["Timestamp"];
1270
1278
  };
1279
+ /** Format: uint256-decimal */
1280
+ readonly Uint: string;
1271
1281
  /** Format: date-time */
1272
1282
  readonly "$defs-Timestamp": string;
1273
1283
  /** @description Freshness of the read. Pages of one list share the snapshot bound into their cursor. */
@@ -1361,8 +1371,6 @@ export type components = {
1361
1371
  /** @description Stream cursor the client asked to resume after; null when it started without one. */
1362
1372
  readonly cursor: components["schemas"]["Cursor"] | null;
1363
1373
  };
1364
- /** Format: uint256-decimal */
1365
- readonly Uint: string;
1366
1374
  readonly ScoreboardCompetitor: {
1367
1375
  /** @description The participant's name as our catalog spells it, cut to 96 characters ending in an ellipsis when longer. */
1368
1376
  readonly name: string;
@@ -1,9 +1,9 @@
1
- export declare const sdkVersion = "239.0.0-maker-opened-via";
2
- export declare const openapiSha256 = "8c7879f62945b6cc6510146cfd94472f8bd0de2ab4721bcf99f1f207d5d6e461";
3
- export declare const realtimeSha256 = "bfea15f8334b302a98e58ca5a71f1c9b259e15b5f2c9239620f127270e5b4c7f";
1
+ export declare const sdkVersion = "240.0.0-wallet-transfer-parties";
2
+ export declare const openapiSha256 = "f0b5dd6f997303eb57793b850c6c4df046ec9e562bfff500d6ccc88020602fa1";
3
+ export declare const realtimeSha256 = "bea4893352a7110f2659560f3338d9fb5eb441269652a989a7aa9d42a5394554";
4
4
  export declare const jsonSchemaSha256: {
5
5
  readonly "account.schema.json": "e6cd5a75429d074f23bd7f6ffd370fa59d0e3f7dbd6aef6433e5ba0d21b5baeb";
6
- readonly "comments.schema.json": "7d845b32d4b141da340510eb37facc258ea3a4992fd898537b05b9651d5b660d";
6
+ readonly "comments.schema.json": "6c59e0d7f45ec944fa4362a6999656cd6a3967bd7a60057665a0d68977addb67";
7
7
  readonly "common.schema.json": "04f51deb3cbea448e59195e26ede3212598d58a7940fe67eb2123fd9161c5edb";
8
8
  readonly "core-exit.schema.json": "c7f617e815225cdcac95c236f8b73fbe288ee5713ff444c3be90eb915fc3a401";
9
9
  readonly "error.schema.json": "0e362e916f59125775cf3201681827d394b53a004a53e21fb84746e794982c7f";
@@ -15,8 +15,8 @@ export declare const jsonSchemaSha256: {
15
15
  readonly "market-data.schema.json": "229fd522825621e53baa8f85cf6ca56715419ff85df36c0902b3401d50c48a9e";
16
16
  readonly "product-metadata.schema.json": "7c8ffbde878a0aedaed16814fcfd2e80038054b140886cc8736bb7b508042631";
17
17
  readonly "quote.schema.json": "52ee1f4708c8b1504e4cd2f2f9279e14c8ec8aeacac1f491441ae0e15ac3c71a";
18
- readonly "realtime.schema.json": "bfea15f8334b302a98e58ca5a71f1c9b259e15b5f2c9239620f127270e5b4c7f";
19
- readonly "social.schema.json": "c07d97d2410e3c6354328300833db32fa8261567c41398e274daca5417057681";
18
+ readonly "realtime.schema.json": "bea4893352a7110f2659560f3338d9fb5eb441269652a989a7aa9d42a5394554";
19
+ readonly "social.schema.json": "ffa1af6c12c974b1c786ca420670861a6e9389b3b9c052e3644bb9905033a919";
20
20
  };
21
21
  export declare const operations: {
22
22
  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", "getAccountValue", "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", "getMarketDisplay", "getMarketHistory", "getMarketRecurringRound", "getMarketReferenceCloses", "getMarketScoreTimeline", "getMarketStats", "getMyGenesis", "getMyReferralBonus", "getOperation", "getOutcomeMetadata", "getOwnMaker", "getPartnerAccountValue", "getPartnerReport", "getPerpMarks", "getProfitLeaderboard", "getQuestion", "getQuestionRecurringRound", "getQuestionScoreTimeline", "getRfq", "getSeries", "getSocialLeaderboard", "getSocialPerson", "getSocialPosition", "getSuggestedCombo", "getTaxonomy", "getTrader", "getTraderPnl", "getUsernameAvailability", "getVaultAgents", "getVolumeLeaderboard", "getWalletApproval", "getWithdrawal", "grantComboCopyAgent", "grantVaultAgent", "likeComment", "listAccountActivity", "listAccountPositions", "listComboCopies", "listComboFeed", "listCommentReplies", "listComments", "listControlledMakers", "listCopiedFills", "listCopyTrades", "listDiscovery", "listFollowingFeed", "listFollowingPositions", "listFollows", "listMakerActivity", "listMakerPositions", "listMakerQuoteHistory", "listMarkets", "listMyNotifications", "listOperations", "listPartnerFills", "listPartnerWebhookEvents", "listQuotes", "listSocialActivity", "listSocialFeed", "listSocialPositions", "listTraderPositions", "listTraderTrades", "markMyNotificationsRead", "placeGolden", "reactComment", "recordAcquisition", "recordGoldenTelegramClick", "refreshPicture", "requestComboCopyAgent", "requestCoreCopyAgent", "revokeComboCopyAgent", "searchCatalog", "setAvatar", "setCopyAllocation", "setCopySettings", "setPublicProfile", "setUsername", "setXHandleShown", "signGoldenGift", "stream", "streamMarkets", "switchOffComboCopyAgent", "switchOffCoreCopyAgent", "unfollowTrader", "unlikeComment", "unlockGolden", "unreactComment"];
@@ -1,10 +1,10 @@
1
1
  // Generated by scripts/generate.mjs; do not edit.
2
- export const sdkVersion = "239.0.0-maker-opened-via";
3
- export const openapiSha256 = "8c7879f62945b6cc6510146cfd94472f8bd0de2ab4721bcf99f1f207d5d6e461";
4
- export const realtimeSha256 = "bfea15f8334b302a98e58ca5a71f1c9b259e15b5f2c9239620f127270e5b4c7f";
2
+ export const sdkVersion = "240.0.0-wallet-transfer-parties";
3
+ export const openapiSha256 = "f0b5dd6f997303eb57793b850c6c4df046ec9e562bfff500d6ccc88020602fa1";
4
+ export const realtimeSha256 = "bea4893352a7110f2659560f3338d9fb5eb441269652a989a7aa9d42a5394554";
5
5
  export const jsonSchemaSha256 = {
6
6
  "account.schema.json": "e6cd5a75429d074f23bd7f6ffd370fa59d0e3f7dbd6aef6433e5ba0d21b5baeb",
7
- "comments.schema.json": "7d845b32d4b141da340510eb37facc258ea3a4992fd898537b05b9651d5b660d",
7
+ "comments.schema.json": "6c59e0d7f45ec944fa4362a6999656cd6a3967bd7a60057665a0d68977addb67",
8
8
  "common.schema.json": "04f51deb3cbea448e59195e26ede3212598d58a7940fe67eb2123fd9161c5edb",
9
9
  "core-exit.schema.json": "c7f617e815225cdcac95c236f8b73fbe288ee5713ff444c3be90eb915fc3a401",
10
10
  "error.schema.json": "0e362e916f59125775cf3201681827d394b53a004a53e21fb84746e794982c7f",
@@ -16,8 +16,8 @@ export const jsonSchemaSha256 = {
16
16
  "market-data.schema.json": "229fd522825621e53baa8f85cf6ca56715419ff85df36c0902b3401d50c48a9e",
17
17
  "product-metadata.schema.json": "7c8ffbde878a0aedaed16814fcfd2e80038054b140886cc8736bb7b508042631",
18
18
  "quote.schema.json": "52ee1f4708c8b1504e4cd2f2f9279e14c8ec8aeacac1f491441ae0e15ac3c71a",
19
- "realtime.schema.json": "bfea15f8334b302a98e58ca5a71f1c9b259e15b5f2c9239620f127270e5b4c7f",
20
- "social.schema.json": "c07d97d2410e3c6354328300833db32fa8261567c41398e274daca5417057681"
19
+ "realtime.schema.json": "bea4893352a7110f2659560f3338d9fb5eb441269652a989a7aa9d42a5394554",
20
+ "social.schema.json": "ffa1af6c12c974b1c786ca420670861a6e9389b3b9c052e3644bb9905033a919"
21
21
  };
22
22
  export const operations = {
23
23
  "client": [
@@ -0,0 +1,233 @@
1
+ import { type HypercoreAnswer, type HypercoreSignature, type HyperliquidInfo, type HyperliquidNetwork } from "./hypercore.js";
2
+ import { type SignerInput } from "./signer.js";
3
+ import type { Hex, TypedData } from "./typed-data.js";
4
+ /**
5
+ * Singles: one outcome side bought or sold on HyperCore's own book, signed by
6
+ * the account (or its Hyperliquid agent key) and sent straight to Hyperliquid.
7
+ * Totalis never sees the order. Every order this module builds carries the
8
+ * Totalis builder fee, as direct orders in the Totalis app do; the account
9
+ * approves it once (`approveTotalisBuilder`).
10
+ */
11
+ /** The Totalis builder and its fee, in tenths of a basis point: 100 is 10 bps of the order's notional. */
12
+ export declare const totalisBuilder: {
13
+ readonly address: "0x334fd4455dde94f36dd2a7c4041992ddc8407dc5";
14
+ readonly feeDecibps: 100;
15
+ };
16
+ export type OutcomeSide = "YES" | "NO";
17
+ export type SingleTif = "Gtc" | "Ioc" | "Alo";
18
+ /** HyperCore's asset number for one side of an outcome: what an order's `a` names. */
19
+ export declare function outcomeAsset(outcomeId: string | number, side: OutcomeSide): number;
20
+ /** HyperCore's coin name for one side of an outcome (`#` and outcome_id times 10 plus the side), as fills and books name it. */
21
+ export declare function outcomeCoin(outcomeId: string | number, side: OutcomeSide): string;
22
+ /** A fresh client order ID: 16 bytes, the first four the Totalis tag. */
23
+ export declare function singleCloid(): Hex;
24
+ export type SingleOrder = {
25
+ readonly outcomeId: string | number;
26
+ readonly side: OutcomeSide;
27
+ /** true buys the side's shares, false sells shares already held. */
28
+ readonly buy: boolean;
29
+ /** USDC per share: above 0, below 1, at most 5 significant figures and 8 decimals. A buy pays at most this; a sale takes at least it. */
30
+ readonly price: string;
31
+ /** Whole shares. Each pays 1 USDC if its side wins. */
32
+ readonly shares: string | number | bigint;
33
+ /** `Gtc` rests what does not fill (default), `Ioc` cancels it, `Alo` only ever rests. */
34
+ readonly tif?: SingleTif;
35
+ /** 16-byte hex client order ID; `singleCloid()` by default. Keep it to find the order when its answer is lost. */
36
+ readonly cloid?: Hex;
37
+ };
38
+ export type SingleOrderAction = {
39
+ readonly type: "order";
40
+ readonly orders: readonly [
41
+ {
42
+ readonly a: number;
43
+ readonly b: boolean;
44
+ readonly p: string;
45
+ readonly s: string;
46
+ readonly r: false;
47
+ readonly t: {
48
+ readonly limit: {
49
+ readonly tif: SingleTif;
50
+ };
51
+ };
52
+ readonly c: Hex;
53
+ }
54
+ ];
55
+ readonly grouping: "na";
56
+ readonly builder: {
57
+ readonly b: string;
58
+ readonly f: number;
59
+ };
60
+ };
61
+ /** One single as the `order` action Hyperliquid takes, with the Totalis builder fee attached. */
62
+ export declare function singleOrderAction(order: SingleOrder): SingleOrderAction;
63
+ /** A resting single to cancel, by the cloid it was placed with or the `oid` Hyperliquid gave it. */
64
+ export type SingleCancel = {
65
+ readonly outcomeId: string | number;
66
+ readonly side: OutcomeSide;
67
+ } & ({
68
+ readonly cloid: Hex;
69
+ } | {
70
+ readonly oid: number;
71
+ });
72
+ export type CancelByCloidAction = {
73
+ readonly type: "cancelByCloid";
74
+ readonly cancels: readonly {
75
+ readonly asset: number;
76
+ readonly cloid: Hex;
77
+ }[];
78
+ };
79
+ export type CancelByOidAction = {
80
+ readonly type: "cancel";
81
+ readonly cancels: readonly {
82
+ readonly a: number;
83
+ readonly o: number;
84
+ }[];
85
+ };
86
+ export type SingleCancelAction = CancelByCloidAction | CancelByOidAction;
87
+ /** Cancels as Hyperliquid takes them: one action for every target of one kind, so all by cloid or all by oid. */
88
+ export declare function singleCancelAction(targets: readonly SingleCancel[]): SingleCancelAction;
89
+ export type SingleAction = SingleOrderAction | SingleCancelAction;
90
+ /** The hash an L1 action's signature binds: the packed action, its nonce, no vault, then its deadline when it has one. */
91
+ export declare function l1ActionHash(action: SingleAction, nonce: number, expiresAfter?: number): Hex;
92
+ /** The EIP-712 payload any key signs for an L1 action, the account's own or its agent's. Mainnet and testnet differ only in `source`. */
93
+ export declare function l1TypedData(network: HyperliquidNetwork, action: SingleAction, nonce: number, expiresAfter?: number): TypedData;
94
+ /** An L1 action as Hyperliquid's `/exchange` takes it. Plain JSON. */
95
+ export type SignedL1Action<Action extends SingleAction = SingleAction> = {
96
+ readonly action: Action;
97
+ readonly nonce: number;
98
+ readonly signature: HypercoreSignature;
99
+ readonly expiresAfter?: number;
100
+ };
101
+ export type L1Options = {
102
+ /** Defaults to `hypercoreNonce()`. Each signer spends a nonce once. */
103
+ readonly nonce?: number;
104
+ /** Epoch ms after which Hyperliquid refuses the action, so a lost answer stops mattering. */
105
+ readonly expiresAfter?: number;
106
+ };
107
+ /**
108
+ * Sign an L1 action with the account's wallet or its Hyperliquid agent key.
109
+ * Browser wallets often refuse its signing domain (chain 1337); approve an
110
+ * agent key once (`approveHyperliquidAgent`) and sign orders with that.
111
+ */
112
+ export declare function signL1Action<Action extends SingleAction>(signer: SignerInput, network: HyperliquidNetwork, action: Action, options?: L1Options): Promise<SignedL1Action<Action>>;
113
+ export type ExchangeOptions = {
114
+ readonly fetch?: typeof fetch;
115
+ readonly signal?: AbortSignal;
116
+ };
117
+ /**
118
+ * What Hyperliquid did with one order. `refused` placed nothing. `unknown`
119
+ * means no readable answer: the order may have landed, so look it up by its
120
+ * cloid (`readSingleOrder`) before placing it again; resending the same
121
+ * signed bytes is safe, since Hyperliquid spends a nonce once.
122
+ */
123
+ export type SingleOrderAnswer = {
124
+ readonly kind: "resting";
125
+ readonly oid: number;
126
+ } | {
127
+ readonly kind: "filled";
128
+ readonly oid: number;
129
+ readonly shares: string;
130
+ readonly averagePrice: string;
131
+ } | {
132
+ readonly kind: "refused";
133
+ readonly error: string;
134
+ } | {
135
+ readonly kind: "unknown";
136
+ };
137
+ export declare function singleOrderAnswer(body: unknown): SingleOrderAnswer;
138
+ /** What Hyperliquid did with each cancel, in the order sent; every entry `unknown` when the answer was unreadable. */
139
+ export type SingleCancelAnswer = {
140
+ readonly kind: "cancelled";
141
+ } | {
142
+ readonly kind: "refused";
143
+ readonly error: string;
144
+ } | {
145
+ readonly kind: "unknown";
146
+ };
147
+ export declare function singleCancelAnswers(body: unknown, count: number): SingleCancelAnswer[];
148
+ export declare function submitSingleOrder(network: HyperliquidNetwork, signed: SignedL1Action<SingleOrderAction>, options?: ExchangeOptions): Promise<SingleOrderAnswer>;
149
+ export declare function submitSingleCancel(network: HyperliquidNetwork, signed: SignedL1Action<SingleCancelAction>, options?: ExchangeOptions): Promise<SingleCancelAnswer[]>;
150
+ /**
151
+ * Build, sign and send one single with the Totalis builder fee. `signer` is
152
+ * the account or its agent key. The account must have approved the fee
153
+ * (`approveTotalisBuilder`), or Hyperliquid refuses the order. Keep
154
+ * `signed.action.orders[0].c`, the cloid, to look the order up when the answer is `unknown`.
155
+ */
156
+ export declare function placeSingle(signer: SignerInput, network: HyperliquidNetwork, order: SingleOrder, options?: L1Options & ExchangeOptions): Promise<{
157
+ signed: SignedL1Action<SingleOrderAction>;
158
+ answer: SingleOrderAnswer;
159
+ }>;
160
+ /** Sign and send cancels of resting singles, all by cloid or all by oid. */
161
+ export declare function cancelSingles(signer: SignerInput, network: HyperliquidNetwork, targets: readonly SingleCancel[], options?: L1Options & ExchangeOptions): Promise<{
162
+ signed: SignedL1Action<SingleCancelAction>;
163
+ answers: SingleCancelAnswer[];
164
+ }>;
165
+ /** One order as Hyperliquid's `orderStatus` reports it; `null` when Hyperliquid holds none under that id. */
166
+ export type SingleOrderStatus = {
167
+ readonly oid: number;
168
+ readonly cloid: Hex | null;
169
+ readonly coin: string;
170
+ /** `open`, `filled`, `canceled`, or one of Hyperliquid's refusal states. */
171
+ readonly status: string;
172
+ readonly shares: string;
173
+ readonly remaining: string;
174
+ };
175
+ /**
176
+ * Read an order by its cloid or oid. `null` is Hyperliquid holding no order
177
+ * under that id: an order still in flight has none yet, so only after the
178
+ * action's `expiresAfter` does `null` prove it never landed.
179
+ */
180
+ export declare function readSingleOrder(network: HyperliquidNetwork, account: string, id: Hex | number, info?: HyperliquidInfo, signal?: AbortSignal): Promise<SingleOrderStatus | null>;
181
+ export type ApproveBuilderFeeAction = {
182
+ readonly type: "approveBuilderFee";
183
+ readonly hyperliquidChain: "Mainnet" | "Testnet";
184
+ readonly signatureChainId: Hex;
185
+ readonly maxFeeRate: string;
186
+ readonly builder: string;
187
+ readonly nonce: number;
188
+ };
189
+ export type ApproveAgentAction = {
190
+ readonly type: "approveAgent";
191
+ readonly hyperliquidChain: "Mainnet" | "Testnet";
192
+ readonly signatureChainId: Hex;
193
+ readonly agentAddress: string;
194
+ readonly agentName: string;
195
+ readonly nonce: number;
196
+ };
197
+ export type SignedUserAction<Action extends ApproveBuilderFeeAction | ApproveAgentAction> = {
198
+ readonly action: Action;
199
+ readonly nonce: number;
200
+ readonly signature: HypercoreSignature;
201
+ };
202
+ /** The approval of the Totalis builder at its fee (`0.1%`). */
203
+ export declare function approveTotalisBuilderAction(network: HyperliquidNetwork, nonce?: number): ApproveBuilderFeeAction;
204
+ export declare function approveBuilderFeeTypedData(action: ApproveBuilderFeeAction): TypedData;
205
+ /**
206
+ * An agent key for `account` under `agentName`: it can place and cancel
207
+ * orders, never withdraw or transfer. Approving a name the account already
208
+ * uses replaces that agent; an account holds a few named agents at most. The
209
+ * Totalis app uses `Totalis` and `TotalisCLI`; pick your own name.
210
+ */
211
+ export declare function approveAgentAction(network: HyperliquidNetwork, agentAddress: string, agentName: string, nonce?: number): ApproveAgentAction;
212
+ export declare function approveAgentTypedData(action: ApproveAgentAction): TypedData;
213
+ /** The builder fee `account` has approved for the Totalis builder, in tenths of a basis point; 0 when none. */
214
+ export declare function readTotalisBuilderFee(network: HyperliquidNetwork, account: string, info?: HyperliquidInfo, signal?: AbortSignal): Promise<number>;
215
+ /**
216
+ * Approve the Totalis builder fee for the account, once, before its first
217
+ * single. Signed by the account's own wallet: Hyperliquid refuses it from an
218
+ * agent key. Skip it when `readTotalisBuilderFee` already reaches
219
+ * `totalisBuilder.feeDecibps`.
220
+ */
221
+ export declare function approveTotalisBuilder(signer: SignerInput, network: HyperliquidNetwork, options?: ExchangeOptions & {
222
+ readonly nonce?: number;
223
+ }): Promise<{
224
+ signed: SignedUserAction<ApproveBuilderFeeAction>;
225
+ answer: HypercoreAnswer;
226
+ }>;
227
+ /** Approve `agentAddress` as the account's Hyperliquid agent under `agentName`. Signed by the account's own wallet. */
228
+ export declare function approveHyperliquidAgent(signer: SignerInput, network: HyperliquidNetwork, agentAddress: string, agentName: string, options?: ExchangeOptions & {
229
+ readonly nonce?: number;
230
+ }): Promise<{
231
+ signed: SignedUserAction<ApproveAgentAction>;
232
+ answer: HypercoreAnswer;
233
+ }>;
@@ -0,0 +1,372 @@
1
+ import { keccak_256 } from "@noble/hashes/sha3";
2
+ import { classifyHypercoreAnswer, hypercoreNonce, hypercoreSignature, hyperliquidInfo } from "./hypercore.js";
3
+ import { randomBytes } from "./runtime.js";
4
+ import { toTotalisSigner } from "./signer.js";
5
+ /**
6
+ * Singles: one outcome side bought or sold on HyperCore's own book, signed by
7
+ * the account (or its Hyperliquid agent key) and sent straight to Hyperliquid.
8
+ * Totalis never sees the order. Every order this module builds carries the
9
+ * Totalis builder fee, as direct orders in the Totalis app do; the account
10
+ * approves it once (`approveTotalisBuilder`).
11
+ */
12
+ /** The Totalis builder and its fee, in tenths of a basis point: 100 is 10 bps of the order's notional. */
13
+ export const totalisBuilder = { address: "0x334fd4455dde94f36dd2a7c4041992ddc8407dc5", feeDecibps: 100 };
14
+ // HIP-4 outcomes have no size decimals, so a price takes up to 5 significant figures and 8 decimals.
15
+ const PRICE_FIGURES = 5;
16
+ const PRICE_DECIMALS = 8;
17
+ const uint32Text = /^(0|[1-9][0-9]*)$/;
18
+ function outcomeNumber(outcomeId) {
19
+ const text = String(outcomeId);
20
+ const value = Number(text);
21
+ if (!uint32Text.test(text) || value > 0xffffffff)
22
+ throw new TypeError(`not a uint32 outcome_id: ${text}`);
23
+ return value;
24
+ }
25
+ const sideIndex = (side) => {
26
+ if (side !== "YES" && side !== "NO")
27
+ throw new TypeError(`not a side: ${String(side)}`);
28
+ return side === "YES" ? 0 : 1;
29
+ };
30
+ /** HyperCore's asset number for one side of an outcome: what an order's `a` names. */
31
+ export function outcomeAsset(outcomeId, side) {
32
+ const asset = 100_000_000 + outcomeNumber(outcomeId) * 10 + sideIndex(side);
33
+ if (asset > 0xffffffff)
34
+ throw new RangeError(`outcome ${String(outcomeId)} has no HyperCore asset: it would exceed uint32`);
35
+ return asset;
36
+ }
37
+ /** HyperCore's coin name for one side of an outcome (`#` and outcome_id times 10 plus the side), as fills and books name it. */
38
+ export function outcomeCoin(outcomeId, side) {
39
+ return `#${outcomeNumber(outcomeId) * 10 + sideIndex(side)}`;
40
+ }
41
+ /**
42
+ * A price strictly between 0 and 1 with at most 5 significant figures and 8
43
+ * decimals, as the minimal decimal text Hyperliquid hashes: "0.50" is "0.5".
44
+ * Any other spelling signs bytes the venue does not, so it recovers a
45
+ * different signer.
46
+ */
47
+ function priceWire(price) {
48
+ const match = /^0?\.(\d+)$/.exec(price);
49
+ const fraction = (match?.[1] ?? "").replace(/0+$/, "");
50
+ const figures = fraction.replace(/^0+/, "").length;
51
+ if (match === null || figures === 0 || figures > PRICE_FIGURES || fraction.length > PRICE_DECIMALS) {
52
+ throw new RangeError(`price must be above 0 and below 1 with at most ${PRICE_FIGURES} significant figures and ${PRICE_DECIMALS} decimals: ${price}`);
53
+ }
54
+ return `0.${fraction}`;
55
+ }
56
+ function sharesWire(shares) {
57
+ const text = String(shares);
58
+ if (!/^[1-9][0-9]*$/.test(text))
59
+ throw new RangeError(`shares must be a positive whole number: ${text}`);
60
+ return text;
61
+ }
62
+ // Every order the Totalis app places starts its client order ID with these
63
+ // bytes, so the leaderboard counts its fills; orders from this SDK carry them too.
64
+ const orderTag = new TextEncoder().encode("totl");
65
+ const hex = (bytes) => `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
66
+ /** A fresh client order ID: 16 bytes, the first four the Totalis tag. */
67
+ export function singleCloid() {
68
+ const id = randomBytes(16);
69
+ id.set(orderTag);
70
+ return hex(id);
71
+ }
72
+ /** One single as the `order` action Hyperliquid takes, with the Totalis builder fee attached. */
73
+ export function singleOrderAction(order) {
74
+ const cloid = order.cloid ?? singleCloid();
75
+ if (!/^0x[0-9a-fA-F]{32}$/.test(cloid))
76
+ throw new TypeError(`cloid must be 16 bytes of hex: ${cloid}`);
77
+ return {
78
+ type: "order",
79
+ orders: [{
80
+ a: outcomeAsset(order.outcomeId, order.side),
81
+ b: order.buy,
82
+ p: priceWire(order.price),
83
+ s: sharesWire(order.shares),
84
+ r: false,
85
+ t: { limit: { tif: order.tif ?? "Gtc" } },
86
+ c: cloid.toLowerCase(),
87
+ }],
88
+ grouping: "na",
89
+ builder: { b: totalisBuilder.address, f: totalisBuilder.feeDecibps },
90
+ };
91
+ }
92
+ /** Cancels as Hyperliquid takes them: one action for every target of one kind, so all by cloid or all by oid. */
93
+ export function singleCancelAction(targets) {
94
+ if (targets.length === 0)
95
+ throw new RangeError("nothing to cancel");
96
+ if (targets.every((target) => "cloid" in target)) {
97
+ return { type: "cancelByCloid", cancels: targets.map((target) => ({ asset: outcomeAsset(target.outcomeId, target.side), cloid: target.cloid.toLowerCase() })) };
98
+ }
99
+ if (targets.every((target) => "oid" in target)) {
100
+ return { type: "cancel", cancels: targets.map((target) => ({ a: outcomeAsset(target.outcomeId, target.side), o: target.oid })) };
101
+ }
102
+ throw new TypeError("cancel by cloid and by oid in separate actions");
103
+ }
104
+ // The MessagePack Hyperliquid hashes an L1 action as: maps in the key order
105
+ // written, the shortest encoding of each value, as the official SDK's msgpack.
106
+ function pack(value, out) {
107
+ if (typeof value === "string") {
108
+ const bytes = new TextEncoder().encode(value);
109
+ if (bytes.length < 32)
110
+ out.push(0xa0 | bytes.length);
111
+ else if (bytes.length < 0x100)
112
+ out.push(0xd9, bytes.length);
113
+ else
114
+ throw new RangeError("string too long for an action");
115
+ out.push(...bytes);
116
+ }
117
+ else if (typeof value === "boolean") {
118
+ out.push(value ? 0xc3 : 0xc2);
119
+ }
120
+ else if (typeof value === "number") {
121
+ if (!Number.isSafeInteger(value) || value < 0)
122
+ throw new RangeError(`not a uint: ${value}`);
123
+ if (value < 0x80)
124
+ out.push(value);
125
+ else if (value < 0x100)
126
+ out.push(0xcc, value);
127
+ else if (value < 0x10000)
128
+ out.push(0xcd, ...bigEndian(value, 2));
129
+ else if (value < 0x100000000)
130
+ out.push(0xce, ...bigEndian(value, 4));
131
+ else
132
+ out.push(0xcf, ...bigEndian(value, 8));
133
+ }
134
+ else if (Array.isArray(value)) {
135
+ header(value.length, 0x90, 0xdc, out);
136
+ for (const item of value)
137
+ pack(item, out);
138
+ }
139
+ else if (typeof value === "object" && value !== null) {
140
+ const entries = Object.entries(value);
141
+ header(entries.length, 0x80, 0xde, out);
142
+ for (const [key, item] of entries) {
143
+ pack(key, out);
144
+ pack(item, out);
145
+ }
146
+ }
147
+ else {
148
+ throw new TypeError(`cannot pack ${String(value)}`);
149
+ }
150
+ }
151
+ function header(size, fix, wide, out) {
152
+ if (size < 16)
153
+ out.push(fix | size);
154
+ else if (size < 0x10000)
155
+ out.push(wide, ...bigEndian(size, 2));
156
+ else
157
+ throw new RangeError("too many entries for an action");
158
+ }
159
+ function bigEndian(value, length) {
160
+ const bytes = [];
161
+ let rest = BigInt(value);
162
+ for (let index = 0; index < length; index++) {
163
+ bytes.unshift(Number(rest & 0xffn));
164
+ rest >>= 8n;
165
+ }
166
+ return bytes;
167
+ }
168
+ /** The hash an L1 action's signature binds: the packed action, its nonce, no vault, then its deadline when it has one. */
169
+ export function l1ActionHash(action, nonce, expiresAfter) {
170
+ const bytes = [];
171
+ pack(action, bytes);
172
+ bytes.push(...bigEndian(nonce, 8), 0);
173
+ if (expiresAfter !== undefined)
174
+ bytes.push(0, ...bigEndian(expiresAfter, 8));
175
+ return hex(keccak_256(Uint8Array.from(bytes)));
176
+ }
177
+ /** The EIP-712 payload any key signs for an L1 action, the account's own or its agent's. Mainnet and testnet differ only in `source`. */
178
+ export function l1TypedData(network, action, nonce, expiresAfter) {
179
+ return {
180
+ domain: { name: "Exchange", version: "1", chainId: 1337n, verifyingContract: "0x0000000000000000000000000000000000000000" },
181
+ types: { Agent: [{ name: "source", type: "string" }, { name: "connectionId", type: "bytes32" }] },
182
+ primaryType: "Agent",
183
+ message: { source: network.chain === "Mainnet" ? "a" : "b", connectionId: l1ActionHash(action, nonce, expiresAfter) },
184
+ };
185
+ }
186
+ /**
187
+ * Sign an L1 action with the account's wallet or its Hyperliquid agent key.
188
+ * Browser wallets often refuse its signing domain (chain 1337); approve an
189
+ * agent key once (`approveHyperliquidAgent`) and sign orders with that.
190
+ */
191
+ export async function signL1Action(signer, network, action, options = {}) {
192
+ const nonce = options.nonce ?? hypercoreNonce();
193
+ const raw = await toTotalisSigner(signer).signTypedData(l1TypedData(network, action, nonce, options.expiresAfter));
194
+ return { action, nonce, signature: hypercoreSignature(raw), ...(options.expiresAfter === undefined ? {} : { expiresAfter: options.expiresAfter }) };
195
+ }
196
+ /** POST one signed action to the network's `/exchange` and return its JSON answer; `undefined` when no answer arrived or it was not JSON. */
197
+ async function post(network, payload, options) {
198
+ const fetchImpl = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
199
+ try {
200
+ const response = await fetchImpl(network.exchangeUrl, {
201
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload),
202
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
203
+ });
204
+ const body = JSON.parse(await response.text());
205
+ return body;
206
+ }
207
+ catch {
208
+ return undefined;
209
+ }
210
+ }
211
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
212
+ export function singleOrderAnswer(body) {
213
+ if (isRecord(body) && body.status === "err" && typeof body.response === "string" && body.response.trim() !== "") {
214
+ return /^Invalid nonce/.test(body.response) ? { kind: "unknown" } : { kind: "refused", error: body.response };
215
+ }
216
+ if (!isRecord(body) || body.status !== "ok" || !isRecord(body.response) || body.response.type !== "order")
217
+ return { kind: "unknown" };
218
+ const data = body.response.data;
219
+ const statuses = isRecord(data) ? data.statuses : undefined;
220
+ if (!Array.isArray(statuses) || statuses.length !== 1)
221
+ return { kind: "unknown" };
222
+ const status = statuses[0];
223
+ if (!isRecord(status))
224
+ return { kind: "unknown" };
225
+ if (typeof status.error === "string")
226
+ return { kind: "refused", error: status.error };
227
+ const { resting, filled } = status;
228
+ if (isRecord(resting) && Number.isSafeInteger(resting.oid))
229
+ return { kind: "resting", oid: resting.oid };
230
+ if (isRecord(filled) && Number.isSafeInteger(filled.oid) && typeof filled.totalSz === "string" && typeof filled.avgPx === "string") {
231
+ return { kind: "filled", oid: filled.oid, shares: filled.totalSz, averagePrice: filled.avgPx };
232
+ }
233
+ return { kind: "unknown" };
234
+ }
235
+ export function singleCancelAnswers(body, count) {
236
+ const unknown = () => Array.from({ length: count }, () => ({ kind: "unknown" }));
237
+ if (isRecord(body) && body.status === "err" && typeof body.response === "string" && body.response.trim() !== "" && !/^Invalid nonce/.test(body.response)) {
238
+ const error = body.response;
239
+ return Array.from({ length: count }, () => ({ kind: "refused", error }));
240
+ }
241
+ if (!isRecord(body) || body.status !== "ok" || !isRecord(body.response) || body.response.type !== "cancel")
242
+ return unknown();
243
+ const data = body.response.data;
244
+ const statuses = isRecord(data) ? data.statuses : undefined;
245
+ if (!Array.isArray(statuses) || statuses.length !== count)
246
+ return unknown();
247
+ return statuses.map((status) => status === "success" ? { kind: "cancelled" } : isRecord(status) && typeof status.error === "string" ? { kind: "refused", error: status.error } : { kind: "unknown" });
248
+ }
249
+ export async function submitSingleOrder(network, signed, options = {}) {
250
+ return singleOrderAnswer(await post(network, signed, options));
251
+ }
252
+ export async function submitSingleCancel(network, signed, options = {}) {
253
+ return singleCancelAnswers(await post(network, signed, options), signed.action.cancels.length);
254
+ }
255
+ /**
256
+ * Build, sign and send one single with the Totalis builder fee. `signer` is
257
+ * the account or its agent key. The account must have approved the fee
258
+ * (`approveTotalisBuilder`), or Hyperliquid refuses the order. Keep
259
+ * `signed.action.orders[0].c`, the cloid, to look the order up when the answer is `unknown`.
260
+ */
261
+ export async function placeSingle(signer, network, order, options = {}) {
262
+ const signed = await signL1Action(signer, network, singleOrderAction(order), options);
263
+ return { signed, answer: await submitSingleOrder(network, signed, options) };
264
+ }
265
+ /** Sign and send cancels of resting singles, all by cloid or all by oid. */
266
+ export async function cancelSingles(signer, network, targets, options = {}) {
267
+ const signed = await signL1Action(signer, network, singleCancelAction(targets), options);
268
+ return { signed, answers: await submitSingleCancel(network, signed, options) };
269
+ }
270
+ /**
271
+ * Read an order by its cloid or oid. `null` is Hyperliquid holding no order
272
+ * under that id: an order still in flight has none yet, so only after the
273
+ * action's `expiresAfter` does `null` prove it never landed.
274
+ */
275
+ export async function readSingleOrder(network, account, id, info = hyperliquidInfo(), signal) {
276
+ const answer = await info(network, { type: "orderStatus", user: account.toLowerCase(), oid: typeof id === "string" ? id.toLowerCase() : id }, signal);
277
+ if (isRecord(answer) && answer.status === "unknownOid")
278
+ return null;
279
+ const wrapper = isRecord(answer) && answer.status === "order" ? answer.order : undefined;
280
+ const order = isRecord(wrapper) ? wrapper.order : undefined;
281
+ if (!isRecord(wrapper) || !isRecord(order) || typeof wrapper.status !== "string" || !Number.isSafeInteger(order.oid) || typeof order.coin !== "string" || typeof order.origSz !== "string" || typeof order.sz !== "string") {
282
+ throw new Error("Hyperliquid orderStatus answer was malformed");
283
+ }
284
+ return {
285
+ oid: order.oid,
286
+ cloid: typeof order.cloid === "string" && order.cloid !== "" ? order.cloid.toLowerCase() : null,
287
+ coin: order.coin,
288
+ status: wrapper.status,
289
+ shares: order.origSz,
290
+ remaining: order.sz,
291
+ };
292
+ }
293
+ // User-signed actions: the account's own wallet signs them, never an agent.
294
+ const userSignedDomain = (signatureChainId) => ({
295
+ name: "HyperliquidSignTransaction", version: "1", chainId: BigInt(signatureChainId), verifyingContract: "0x0000000000000000000000000000000000000000",
296
+ });
297
+ const approveBuilderFeeFields = [
298
+ { name: "hyperliquidChain", type: "string" },
299
+ { name: "maxFeeRate", type: "string" },
300
+ { name: "builder", type: "address" },
301
+ { name: "nonce", type: "uint64" },
302
+ ];
303
+ const approveAgentFields = [
304
+ { name: "hyperliquidChain", type: "string" },
305
+ { name: "agentAddress", type: "address" },
306
+ { name: "agentName", type: "string" },
307
+ { name: "nonce", type: "uint64" },
308
+ ];
309
+ /** The approval of the Totalis builder at its fee (`0.1%`). */
310
+ export function approveTotalisBuilderAction(network, nonce = hypercoreNonce()) {
311
+ return {
312
+ type: "approveBuilderFee", hyperliquidChain: network.chain, signatureChainId: network.signatureChainId,
313
+ maxFeeRate: `${totalisBuilder.feeDecibps / 1000}%`, builder: totalisBuilder.address, nonce,
314
+ };
315
+ }
316
+ export function approveBuilderFeeTypedData(action) {
317
+ return {
318
+ domain: userSignedDomain(action.signatureChainId),
319
+ types: { "HyperliquidTransaction:ApproveBuilderFee": approveBuilderFeeFields },
320
+ primaryType: "HyperliquidTransaction:ApproveBuilderFee",
321
+ message: { hyperliquidChain: action.hyperliquidChain, maxFeeRate: action.maxFeeRate, builder: action.builder, nonce: BigInt(action.nonce) },
322
+ };
323
+ }
324
+ /**
325
+ * An agent key for `account` under `agentName`: it can place and cancel
326
+ * orders, never withdraw or transfer. Approving a name the account already
327
+ * uses replaces that agent; an account holds a few named agents at most. The
328
+ * Totalis app uses `Totalis` and `TotalisCLI`; pick your own name.
329
+ */
330
+ export function approveAgentAction(network, agentAddress, agentName, nonce = hypercoreNonce()) {
331
+ if (!/^0x[0-9a-fA-F]{40}$/.test(agentAddress))
332
+ throw new TypeError(`not an address: ${agentAddress}`);
333
+ if (agentName === "")
334
+ throw new RangeError("name the agent");
335
+ return { type: "approveAgent", hyperliquidChain: network.chain, signatureChainId: network.signatureChainId, agentAddress: agentAddress.toLowerCase(), agentName, nonce };
336
+ }
337
+ export function approveAgentTypedData(action) {
338
+ return {
339
+ domain: userSignedDomain(action.signatureChainId),
340
+ types: { "HyperliquidTransaction:ApproveAgent": approveAgentFields },
341
+ primaryType: "HyperliquidTransaction:ApproveAgent",
342
+ message: { hyperliquidChain: action.hyperliquidChain, agentAddress: action.agentAddress, agentName: action.agentName, nonce: BigInt(action.nonce) },
343
+ };
344
+ }
345
+ async function sendUserSigned(signer, network, action, typedData, options) {
346
+ const signed = { action, nonce: action.nonce, signature: hypercoreSignature(await toTotalisSigner(signer).signTypedData(typedData)) };
347
+ const body = await post(network, signed, options);
348
+ const answer = body === undefined ? { kind: "unknown" } : classifyHypercoreAnswer(body);
349
+ return { signed, answer };
350
+ }
351
+ /** The builder fee `account` has approved for the Totalis builder, in tenths of a basis point; 0 when none. */
352
+ export async function readTotalisBuilderFee(network, account, info = hyperliquidInfo(), signal) {
353
+ const answer = await info(network, { type: "maxBuilderFee", user: account.toLowerCase(), builder: totalisBuilder.address }, signal);
354
+ if (typeof answer !== "number" || !Number.isSafeInteger(answer) || answer < 0)
355
+ throw new Error("Hyperliquid maxBuilderFee answer was malformed");
356
+ return answer;
357
+ }
358
+ /**
359
+ * Approve the Totalis builder fee for the account, once, before its first
360
+ * single. Signed by the account's own wallet: Hyperliquid refuses it from an
361
+ * agent key. Skip it when `readTotalisBuilderFee` already reaches
362
+ * `totalisBuilder.feeDecibps`.
363
+ */
364
+ export async function approveTotalisBuilder(signer, network, options = {}) {
365
+ const action = approveTotalisBuilderAction(network, options.nonce);
366
+ return sendUserSigned(signer, network, action, approveBuilderFeeTypedData(action), options);
367
+ }
368
+ /** Approve `agentAddress` as the account's Hyperliquid agent under `agentName`. Signed by the account's own wallet. */
369
+ export async function approveHyperliquidAgent(signer, network, agentAddress, agentName, options = {}) {
370
+ const action = approveAgentAction(network, agentAddress, agentName, options.nonce);
371
+ return sendUserSigned(signer, network, action, approveAgentTypedData(action), options);
372
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totalis/hip4-client",
3
- "version": "0.103.0",
3
+ "version": "0.105.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": [