@totalis/hip4-client 0.127.0 → 0.129.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.
@@ -1,6 +1,6 @@
1
- export declare const sdkVersion = "282.0.0-no-intent-errors";
2
- export declare const openapiSha256 = "47db60764499d2fc83e8bdfe7dbc299db969190a7d3a8661a4ebff278f08b77f";
3
- export declare const realtimeSha256 = "f85e0ee178b1aa88dae8ec44f97acd829a1f6308ea601ded2e0809dcf9e35168";
1
+ export declare const sdkVersion = "284.0.0-light-renditions";
2
+ export declare const openapiSha256 = "f08bae94317903c430043ca6d1ef27542d35742b3e0494c25d0f8a6bcfdca70b";
3
+ export declare const realtimeSha256 = "7e4b6e595b53e601e0ef2e05a6e52dd2d53ada0edeef5f16653914714b56728f";
4
4
  export declare const jsonSchemaSha256: {
5
5
  readonly "account.schema.json": "3120357249f55f8481d5afb7a99112f803c22c6a1cbe3adadca478bb313f8160";
6
6
  readonly "comments.schema.json": "5773471b4442ba9d8af0dc012d71561baaf50d0e1c2571039241780848edb4a4";
@@ -12,14 +12,14 @@ export declare const jsonSchemaSha256: {
12
12
  readonly "maker-access.schema.json": "49698ee0235e42064aae0397db1e0f646bdc10d9dfa10121714ba06dd69fee3b";
13
13
  readonly "maker-action.schema.json": "07a5cb07976d06315733282d1bb4f1416c23d3e7a8a4e8941228ac559a2f7467";
14
14
  readonly "maker-telemetry.schema.json": "85b111ce0f4935299d1116071b43de12e775bef4e0c283c12f19046d34374a9c";
15
- readonly "market-data.schema.json": "fd00eaf6524d25019db1dce6c20a3c6f0b9786608583aa6bd1cc14cd2388702f";
15
+ readonly "market-data.schema.json": "ffb916d3e448a44567687c6ca75ce64742569de5919f3903f07c529070a80aea";
16
16
  readonly "product-metadata.schema.json": "7c8ffbde878a0aedaed16814fcfd2e80038054b140886cc8736bb7b508042631";
17
17
  readonly "quote.schema.json": "5c16a54c428656a4e8c1042b2057ce8290e6eebcc02b237f5dce7e4c13b7ded0";
18
- readonly "realtime.schema.json": "f85e0ee178b1aa88dae8ec44f97acd829a1f6308ea601ded2e0809dcf9e35168";
18
+ readonly "realtime.schema.json": "7e4b6e595b53e601e0ef2e05a6e52dd2d53ada0edeef5f16653914714b56728f";
19
19
  readonly "social.schema.json": "98e5c2a3159e5833e9af5e776231875bc42133144476e771e73575cec3f36380";
20
20
  };
21
21
  export declare const operations: {
22
- readonly client: readonly ["abandonCoreExit", "acceptQuote", "activeCoreExits", "admitOwnMaker", "admitPartnerWallet", "approveWallet", "bindEmbeddedWallet", "cancelRfq", "claimGoldenLink", "confirmComboCopyAgent", "confirmCoreCopyAgent", "createCashout", "createComment", "createCoreExit", "createDeposit", "createGoldenRfq", "createRfq", "createRunOffClaim", "createWalletChallenge", "createWalletSession", "createWithdrawal", "declineGolden", "deleteComment", "editComment", "endWalletSession", "followTrader", "getAcceptance", "getAccountActivity", "getAccountPnl", "getAccountPosition", "getAccountValue", "getBalances", "getChart", "getCopyAgents", "getCopyBudget", "getCopySettings", "getCopySummary", "getCoreExit", "getDeployment", "getGenesis", "getGolden", "getGoldenLinkSuggestions", "getGoldenMarkets", "getGoldenOffer", "getGoldenSuggestions", "getHypercoreBalance", "getHypercoreOrders", "getHypercorePortfolio", "getHypercoreSettlementCredits", "getIdentity", "getLiveMarks", "getMakerActivity", "getMakerCapital", "getMakerExposure", "getMakerPerformance", "getMakerPosition", "getMakerQuotes", "getMakerTelemetry", "getMakerVaultFundingTransaction", "getMakerWithdrawal", "getMarket", "getMarketDataConfig", "getMarketDefinitions", "getMarketDisplay", "getMarketRecurringRound", "getMarketReferenceCloses", "getMarketResults", "getMarketRoundHistory", "getMarketScoreTimeline", "getMarketStats", "getMyGenesis", "getMyReferralBonus", "getMyTradingRewards", "getOperation", "getOutcomeMetadata", "getOwnMaker", "getPartnerAccountValue", "getPartnerReport", "getPerpMarks", "getPicture", "getProfitLeaderboard", "getPublicGoldenMarkets", "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", "listFollowers", "listFollowingFeed", "listFollowingPositions", "listFollows", "listHypercorePositions", "listMakerActivity", "listMakerPositions", "listMakerQuoteHistory", "listMarketTrades", "listMarkets", "listMyNotifications", "listOperations", "listPartnerFills", "listPartnerWebhookEvents", "listQuotes", "listSocialActivity", "listSocialFeed", "listSocialFollowers", "listSocialFollowing", "listSocialPositions", "listTraderPositions", "listTraderTrades", "markMyNotificationsRead", "placeGolden", "reactComment", "recordAcquisition", "recordCopiedTrade", "recordGoldenTelegramClick", "refreshPicture", "removeUploadedPicture", "requestComboCopyAgent", "requestCoreCopyAgent", "revokeComboCopyAgent", "searchCatalog", "searchTraders", "setAvatar", "setCopyAllocation", "setCopySettings", "setPublicProfile", "setUsername", "setXHandleShown", "setXPictureShown", "signGoldenGift", "stream", "streamMarkets", "switchOffComboCopyAgent", "switchOffCoreCopyAgent", "unfollowTrader", "unlikeComment", "unlockGolden", "unreactComment", "uploadPicture"];
23
- readonly maker: readonly ["cancelAllQuotes", "cancelQuote", "confirmQuote", "createCollateralReduction", "createQuote", "getAccountActivity", "getAccountPosition", "getChart", "getCollateralReduction", "getDeployment", "getMakerActivity", "getMakerCapital", "getMakerExposure", "getMakerPerformance", "getMakerPosition", "getMakerQuotes", "getMakerTelemetry", "getMakerTelemetryPublication", "getMakerVaultFundingTransaction", "getMakerWithdrawal", "getMarket", "getMarketDisplay", "getMarketRecurringRound", "getMarketReferenceCloses", "getMarketResults", "getMarketRoundHistory", "getOperation", "getQuestion", "getQuestionRecurringRound", "getRfq", "getSeries", "getTaxonomy", "listAccountActivity", "listAccountPositions", "listDiscovery", "listMakerAcceptances", "listMakerActivity", "listMakerPositions", "listMakerQuoteHistory", "listMarkets", "listOperations", "listRfqs", "publishMakerTelemetry", "searchCatalog", "stream", "submitMakerSelfFundedTransaction"];
22
+ readonly client: readonly ["abandonCoreExit", "acceptQuote", "activeCoreExits", "admitOwnMaker", "admitPartnerWallet", "approveWallet", "bindEmbeddedWallet", "cancelRfq", "claimGoldenLink", "confirmComboCopyAgent", "confirmCoreCopyAgent", "createCashout", "createComment", "createCoreExit", "createDeposit", "createGoldenRfq", "createRfq", "createRunOffClaim", "createWalletChallenge", "createWalletSession", "createWithdrawal", "declineGolden", "deleteComment", "editComment", "endWalletSession", "followTrader", "getAcceptance", "getAccountActivity", "getAccountPnl", "getAccountPosition", "getAccountValue", "getBalances", "getChart", "getCopyAgents", "getCopyBudget", "getCopySettings", "getCopySummary", "getCoreExit", "getDeployment", "getGenesis", "getGolden", "getGoldenLinkSuggestions", "getGoldenMarkets", "getGoldenOffer", "getGoldenSuggestions", "getHypercoreBalance", "getHypercoreOrderHistory", "getHypercoreOrderProof", "getHypercoreOrders", "getHypercorePortfolio", "getHypercoreSettlementCredits", "getIdentity", "getLiveMarks", "getMakerActivity", "getMakerCapital", "getMakerExposure", "getMakerPerformance", "getMakerPosition", "getMakerQuotes", "getMakerTelemetry", "getMakerVaultFundingTransaction", "getMakerWithdrawal", "getMarket", "getMarketDataConfig", "getMarketDefinitions", "getMarketDisplay", "getMarketRecurringRound", "getMarketReferenceCloses", "getMarketResults", "getMarketRoundHistory", "getMarketScoreTimeline", "getMarketStats", "getMyGenesis", "getMyReferralBonus", "getMyTradingRewards", "getOperation", "getOutcomeMetadata", "getOwnMaker", "getPartnerAccountValue", "getPartnerReport", "getPerpMarks", "getPicture", "getPolymarketMarket", "getProfitLeaderboard", "getPublicGoldenMarkets", "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", "listFollowers", "listFollowingFeed", "listFollowingPositions", "listFollows", "listHypercorePositions", "listMakerActivity", "listMakerPositions", "listMakerQuoteHistory", "listMarketTrades", "listMarkets", "listMyNotifications", "listOperations", "listPartnerFills", "listPartnerWebhookEvents", "listQuotes", "listSocialActivity", "listSocialFeed", "listSocialFollowers", "listSocialFollowing", "listSocialPositions", "listTraderPositions", "listTraderTrades", "markMyNotificationsRead", "placeGolden", "reactComment", "recordAcquisition", "recordCopiedTrade", "recordGoldenTelegramClick", "refreshPicture", "removeUploadedPicture", "requestComboCopyAgent", "requestCoreCopyAgent", "revokeComboCopyAgent", "searchCatalog", "searchTraders", "setAvatar", "setCopyAllocation", "setCopySettings", "setPublicProfile", "setUsername", "setXHandleShown", "setXPictureShown", "signGoldenGift", "stream", "streamMarkets", "switchOffComboCopyAgent", "switchOffCoreCopyAgent", "unfollowTrader", "unlikeComment", "unlockGolden", "unreactComment", "uploadPicture"];
23
+ readonly maker: readonly ["cancelAllQuotes", "cancelQuote", "confirmQuote", "createCollateralReduction", "createQuote", "getAccountActivity", "getAccountPosition", "getChart", "getCollateralReduction", "getDeployment", "getMakerActivity", "getMakerCapital", "getMakerExposure", "getMakerPerformance", "getMakerPosition", "getMakerQuotes", "getMakerTelemetry", "getMakerTelemetryPublication", "getMakerVaultFundingTransaction", "getMakerWithdrawal", "getMarket", "getMarketDisplay", "getMarketRecurringRound", "getMarketReferenceCloses", "getMarketResults", "getMarketRoundHistory", "getOperation", "getPolymarketMarket", "getQuestion", "getQuestionRecurringRound", "getRfq", "getSeries", "getTaxonomy", "listAccountActivity", "listAccountPositions", "listDiscovery", "listMakerAcceptances", "listMakerActivity", "listMakerPositions", "listMakerQuoteHistory", "listMarkets", "listOperations", "listRfqs", "publishMakerTelemetry", "searchCatalog", "stream", "submitMakerSelfFundedTransaction"];
24
24
  readonly operator: readonly ["live", "ready"];
25
25
  };
@@ -1,7 +1,7 @@
1
1
  // Generated by scripts/generate.mjs; do not edit.
2
- export const sdkVersion = "282.0.0-no-intent-errors";
3
- export const openapiSha256 = "47db60764499d2fc83e8bdfe7dbc299db969190a7d3a8661a4ebff278f08b77f";
4
- export const realtimeSha256 = "f85e0ee178b1aa88dae8ec44f97acd829a1f6308ea601ded2e0809dcf9e35168";
2
+ export const sdkVersion = "284.0.0-light-renditions";
3
+ export const openapiSha256 = "f08bae94317903c430043ca6d1ef27542d35742b3e0494c25d0f8a6bcfdca70b";
4
+ export const realtimeSha256 = "7e4b6e595b53e601e0ef2e05a6e52dd2d53ada0edeef5f16653914714b56728f";
5
5
  export const jsonSchemaSha256 = {
6
6
  "account.schema.json": "3120357249f55f8481d5afb7a99112f803c22c6a1cbe3adadca478bb313f8160",
7
7
  "comments.schema.json": "5773471b4442ba9d8af0dc012d71561baaf50d0e1c2571039241780848edb4a4",
@@ -13,10 +13,10 @@ export const jsonSchemaSha256 = {
13
13
  "maker-access.schema.json": "49698ee0235e42064aae0397db1e0f646bdc10d9dfa10121714ba06dd69fee3b",
14
14
  "maker-action.schema.json": "07a5cb07976d06315733282d1bb4f1416c23d3e7a8a4e8941228ac559a2f7467",
15
15
  "maker-telemetry.schema.json": "85b111ce0f4935299d1116071b43de12e775bef4e0c283c12f19046d34374a9c",
16
- "market-data.schema.json": "fd00eaf6524d25019db1dce6c20a3c6f0b9786608583aa6bd1cc14cd2388702f",
16
+ "market-data.schema.json": "ffb916d3e448a44567687c6ca75ce64742569de5919f3903f07c529070a80aea",
17
17
  "product-metadata.schema.json": "7c8ffbde878a0aedaed16814fcfd2e80038054b140886cc8736bb7b508042631",
18
18
  "quote.schema.json": "5c16a54c428656a4e8c1042b2057ce8290e6eebcc02b237f5dce7e4c13b7ded0",
19
- "realtime.schema.json": "f85e0ee178b1aa88dae8ec44f97acd829a1f6308ea601ded2e0809dcf9e35168",
19
+ "realtime.schema.json": "7e4b6e595b53e601e0ef2e05a6e52dd2d53ada0edeef5f16653914714b56728f",
20
20
  "social.schema.json": "98e5c2a3159e5833e9af5e776231875bc42133144476e771e73575cec3f36380"
21
21
  };
22
22
  export const operations = {
@@ -67,6 +67,8 @@ export const operations = {
67
67
  "getGoldenOffer",
68
68
  "getGoldenSuggestions",
69
69
  "getHypercoreBalance",
70
+ "getHypercoreOrderHistory",
71
+ "getHypercoreOrderProof",
70
72
  "getHypercoreOrders",
71
73
  "getHypercorePortfolio",
72
74
  "getHypercoreSettlementCredits",
@@ -101,6 +103,7 @@ export const operations = {
101
103
  "getPartnerReport",
102
104
  "getPerpMarks",
103
105
  "getPicture",
106
+ "getPolymarketMarket",
104
107
  "getProfitLeaderboard",
105
108
  "getPublicGoldenMarkets",
106
109
  "getQuestion",
@@ -214,6 +217,7 @@ export const operations = {
214
217
  "getMarketResults",
215
218
  "getMarketRoundHistory",
216
219
  "getOperation",
220
+ "getPolymarketMarket",
217
221
  "getQuestion",
218
222
  "getQuestionRecurringRound",
219
223
  "getRfq",
package/dist/money.d.ts CHANGED
@@ -6,6 +6,35 @@ type CashoutTerms = {
6
6
  readonly kind: "SELL_BACK";
7
7
  readonly price: string;
8
8
  };
9
+ /** One cent of USDC, in base units (6 decimals). */
10
+ export declare const usdcCent = 10000n;
11
+ export declare const ceilDiv: (numerator: bigint, denominator: bigint) => bigint;
12
+ export declare const nearestDiv: (numerator: bigint, denominator: bigint) => bigint;
13
+ /** Decimal text as an integer at `decimals` places; the caller has checked it is decimal text with no more places. */
14
+ export declare const decimalParts: (value: string, decimals: number) => bigint;
15
+ /**
16
+ * Decimal text (`"25.5"`, `"-0.002"`) as integer units at `decimals` places,
17
+ * exactly: `null` for anything else, or for more places than the asset has,
18
+ * which would need rounding. USDC on HyperEVM has 6 decimals, HyperCore USDC 8.
19
+ */
20
+ export declare function decimalUnits(text: string, decimals: number): bigint | null;
21
+ /** USDC base units as HyperCore USDC units, exactly. */
22
+ export declare const coreUnits: (atoms: bigint) => bigint;
23
+ /** HyperCore USDC units as USDC base units, rounded down: money received never reads more than landed. */
24
+ export declare const coreAtomsFloor: (units: bigint) => bigint;
25
+ /**
26
+ * What a dollar amount is picks its cent. Money the user gets rounds down,
27
+ * so a screen never says more than lands; a fee rounds up, so it never says
28
+ * less than is taken; a cost, or money held, rounds to the nearest (half away
29
+ * from zero). The most the user can spend or move rounds down, so entering
30
+ * the limit named always goes through.
31
+ */
32
+ export type UsdKind = "received" | "fee" | "cost" | "held" | "spendable";
33
+ /** Whole cents of `amount`, a USDC amount at `decimals` places (6 by default, 8 for HyperCore), rounded as its `kind` says. */
34
+ export declare const usdCents: (kind: UsdKind, amount: bigint, decimals?: number) => bigint;
35
+ /** `amount` at `decimals` places rounded to the cent as its `kind` says, in USDC base units (6 decimals). */
36
+ export declare const centAmount: (kind: UsdKind, amount: bigint, decimals?: number) => bigint;
37
+ export declare const centFloor: (atoms: bigint) => bigint;
9
38
  /**
10
39
  * Spendable Totalis cash from `GET /v1/me/balances`, in USDC base units, as
11
40
  * the SDK plans entries and withdrawals with it. `null` means unknown (the
@@ -73,4 +102,77 @@ export declare function netCashout(bid: CashoutTerms, position: {
73
102
  readonly net_stake: string | null;
74
103
  readonly fee_bps: number;
75
104
  }): bigint | null;
105
+ /**
106
+ * A Combo's cash sources as read, in USDC base units: free vault cash and
107
+ * available wallet USDC (`spendableCash`), HyperCore spendable USDC before
108
+ * the bridge's gas (`readCoreCash`), and whether a bridge from it pays the
109
+ * setup fee. Each is `null` while unread; a source known to be ineligible is
110
+ * 0, never `null`.
111
+ */
112
+ export type ComboSources = {
113
+ readonly vault: bigint | null;
114
+ readonly wallet: bigint | null;
115
+ readonly core: bigint | null;
116
+ readonly setupFee: boolean | null;
117
+ };
118
+ /** The largest stake one Combo can take from these sources: free vault cash, available wallet USDC and the Core a bridge can route. `null` while any of them is unknown. */
119
+ export declare function maxStake(sources: ComboSources): bigint | null;
120
+ /**
121
+ * Whether these sources hold enough for a Combo of `stake`: `true` once the
122
+ * sources read cover it, whatever is still unread; `false` only when every
123
+ * source is read and they fall short; `null` while short on what is read
124
+ * with a source unread. It is capacity, not readiness: an entry also needs
125
+ * the reads its funding route uses (`openPosition` needs the free vault
126
+ * read, and the Core read when the wallet falls short), so never let a
127
+ * press go ahead on it alone.
128
+ */
129
+ export declare function fundable(stake: bigint, sources: ComboSources): boolean | null;
130
+ /** The vault cash (6 decimals) that covers what HyperCore spot (`spot`, 8 decimals) lacks of `need` (8 decimals), rounded up so the move always covers it. */
131
+ export declare const coreShortfall: (need: bigint, spot: bigint) => bigint;
132
+ /** What a move that creates the HyperCore account sends so that `shortfall` still lands after the setup fee: `max(shortfall + fee, 2 × fee)`. */
133
+ export declare const activationTopUp: (shortfall: bigint) => bigint;
134
+ /** Vault cash that still lands on HyperCore once its move pays the setup fee that creates the account; 0 below the minimum move. */
135
+ export declare const afterActivation: (vault: bigint) => bigint;
136
+ /** What a send out can take when it also pays the account's own setup fee on top. */
137
+ export declare const sendableAfterSetup: (available: bigint) => bigint;
138
+ /** A buy's stake once the setup fee of the move that creates the account comes out of it, floored to the cent. */
139
+ export declare const stakeAfterSetup: (stake: bigint) => bigint;
140
+ /** Vault cash a buy can move to HyperCore before it trades, less the setup fee when that move creates the account; 0 while unread. */
141
+ export declare const directBuyVault: (vault: bigint | null, activation?: boolean) => bigint;
142
+ /**
143
+ * All the cash a single buy can spend, in HyperCore USDC units (8 decimals):
144
+ * spot USDC, plus the vault cash (6 decimals) it can move first, unless that
145
+ * move creates the account and is under the minimum. `null` while spot is
146
+ * unread. The buy pays its shares, its builder fee and any setup fee out of it.
147
+ */
148
+ export declare function directBuyBudget(spot: bigint | null, vault: bigint | null, activation?: boolean): bigint | null;
149
+ /**
150
+ * What a HyperCore send can take from `available` (6 decimals) once its fees
151
+ * are off: `setupFee` is Hyperliquid's one-time fee on this send, and while
152
+ * it is unread (`null`) so is the room; `senderSetup` is the sender's own
153
+ * account missing, so the vault cash it moves first pays that account's
154
+ * setup fee.
155
+ */
156
+ export declare function withdrawRoom(available: bigint, setupFee: boolean | null, senderSetup?: boolean): bigint | null;
157
+ /** The least wallet USDC the venue takes as a sponsored deposit into the vault: 0.10 USDC. */
158
+ export declare const walletSweepMinimum = 100000n;
159
+ /** The wallet's USDC a deposit can move into the vault before an exit: all of it from the minimum up, none for an account that controls or may control a maker (`maker` anything but `NOT_CREATED`, or unread). */
160
+ export declare const walletDepositable: (maker: string | null, wallet: bigint | null) => bigint;
161
+ /**
162
+ * How much wallet USDC to sweep into the vault now, or `null` to wait. An
163
+ * embedded wallet whose account controls no maker sweeps all of it from
164
+ * `walletSweepMinimum` up, only while nothing else moves the account's cash:
165
+ * no deposit pending, no operation in an unknown state, no exit crossing or
166
+ * saved. Anything unread (`null`) waits. `wallet` is already less what
167
+ * withdrawals and fundings reserve.
168
+ */
169
+ export declare function sweepAmount(state: {
170
+ readonly embedded: boolean;
171
+ readonly maker: string | null;
172
+ readonly wallet: bigint | null;
173
+ readonly vaultDeposits: bigint | null;
174
+ readonly unknownOperations: boolean;
175
+ readonly exiting: boolean;
176
+ readonly exitSaved: boolean;
177
+ }): bigint | null;
76
178
  export {};
package/dist/money.js CHANGED
@@ -1,5 +1,45 @@
1
1
  import { bridgeGasBuffer, coreSetupFee } from "./hypercore.js";
2
2
  const bps = 10000n;
3
+ /** One cent of USDC, in base units (6 decimals). */
4
+ export const usdcCent = 10000n;
5
+ export const ceilDiv = (numerator, denominator) => (numerator < 0n ? numerator : numerator + denominator - 1n) / denominator;
6
+ const floorDiv = (numerator, denominator) => (numerator < 0n ? numerator - denominator + 1n : numerator) / denominator;
7
+ export const nearestDiv = (numerator, denominator) => {
8
+ const value = ((numerator < 0n ? -numerator : numerator) + denominator / 2n) / denominator;
9
+ return numerator < 0n ? -value : value;
10
+ };
11
+ /** Decimal text as an integer at `decimals` places; the caller has checked it is decimal text with no more places. */
12
+ export const decimalParts = (value, decimals) => {
13
+ const [whole = "", fraction = ""] = value.split(".");
14
+ return BigInt(whole + fraction.padEnd(decimals, "0"));
15
+ };
16
+ /**
17
+ * Decimal text (`"25.5"`, `"-0.002"`) as integer units at `decimals` places,
18
+ * exactly: `null` for anything else, or for more places than the asset has,
19
+ * which would need rounding. USDC on HyperEVM has 6 decimals, HyperCore USDC 8.
20
+ */
21
+ export function decimalUnits(text, decimals) {
22
+ if (!/^-?\d+(\.\d+)?$/.test(text))
23
+ return null;
24
+ const negative = text.startsWith("-");
25
+ const digits = negative ? text.slice(1) : text;
26
+ if ((digits.split(".")[1]?.length ?? 0) > decimals)
27
+ return null;
28
+ const units = decimalParts(digits, decimals);
29
+ return negative ? -units : units;
30
+ }
31
+ /** HyperCore USDC units (8 decimals) per USDC base unit (6 decimals). */
32
+ const coreUnitsPerAtom = 100n;
33
+ /** USDC base units as HyperCore USDC units, exactly. */
34
+ export const coreUnits = (atoms) => atoms * coreUnitsPerAtom;
35
+ /** HyperCore USDC units as USDC base units, rounded down: money received never reads more than landed. */
36
+ export const coreAtomsFloor = (units) => floorDiv(units, coreUnitsPerAtom);
37
+ const toCent = { received: floorDiv, fee: ceilDiv, cost: nearestDiv, held: nearestDiv, spendable: floorDiv };
38
+ /** Whole cents of `amount`, a USDC amount at `decimals` places (6 by default, 8 for HyperCore), rounded as its `kind` says. */
39
+ export const usdCents = (kind, amount, decimals = 6) => toCent[kind](amount, 10n ** BigInt(decimals - 2));
40
+ /** `amount` at `decimals` places rounded to the cent as its `kind` says, in USDC base units (6 decimals). */
41
+ export const centAmount = (kind, amount, decimals = 6) => usdCents(kind, amount, decimals) * usdcCent;
42
+ export const centFloor = (atoms) => centAmount("received", atoms);
3
43
  /**
4
44
  * Spendable Totalis cash from `GET /v1/me/balances`, in USDC base units, as
5
45
  * the SDK plans entries and withdrawals with it. `null` means unknown (the
@@ -88,3 +128,88 @@ export function netPayout(quote) {
88
128
  export function netCashout(bid, position) {
89
129
  return position.net_stake === null ? null : netOfProfitFee(bid.price, position.net_stake, position.fee_bps);
90
130
  }
131
+ function routableCore({ core, setupFee }) {
132
+ if (core === null)
133
+ return null;
134
+ if (core <= bridgeGasBuffer)
135
+ return 0n;
136
+ const offered = offeredCore(core, setupFee);
137
+ return offered === null ? null : offered > bridgeGasBuffer ? offered - bridgeGasBuffer : 0n;
138
+ }
139
+ /** The largest stake one Combo can take from these sources: free vault cash, available wallet USDC and the Core a bridge can route. `null` while any of them is unknown. */
140
+ export function maxStake(sources) {
141
+ const core = routableCore(sources);
142
+ return sources.vault === null || sources.wallet === null || core === null ? null : sources.vault + sources.wallet + core;
143
+ }
144
+ /**
145
+ * Whether these sources hold enough for a Combo of `stake`: `true` once the
146
+ * sources read cover it, whatever is still unread; `false` only when every
147
+ * source is read and they fall short; `null` while short on what is read
148
+ * with a source unread. It is capacity, not readiness: an entry also needs
149
+ * the reads its funding route uses (`openPosition` needs the free vault
150
+ * read, and the Core read when the wallet falls short), so never let a
151
+ * press go ahead on it alone.
152
+ */
153
+ export function fundable(stake, sources) {
154
+ const core = routableCore(sources);
155
+ if ((sources.vault ?? 0n) + (sources.wallet ?? 0n) + (core ?? 0n) >= stake)
156
+ return true;
157
+ return sources.vault === null || sources.wallet === null || core === null ? null : false;
158
+ }
159
+ /** The vault cash (6 decimals) that covers what HyperCore spot (`spot`, 8 decimals) lacks of `need` (8 decimals), rounded up so the move always covers it. */
160
+ export const coreShortfall = (need, spot) => (need > spot ? ceilDiv(need - spot, coreUnitsPerAtom) : 0n);
161
+ /** The smallest move that creates a HyperCore account: Hyperliquid admits it only from twice the setup fee. */
162
+ const activationMinimum = 2n * coreSetupFee;
163
+ /** What a move that creates the HyperCore account sends so that `shortfall` still lands after the setup fee: `max(shortfall + fee, 2 × fee)`. */
164
+ export const activationTopUp = (shortfall) => shortfall + coreSetupFee > activationMinimum ? shortfall + coreSetupFee : activationMinimum;
165
+ /** Vault cash that still lands on HyperCore once its move pays the setup fee that creates the account; 0 below the minimum move. */
166
+ export const afterActivation = (vault) => (vault >= activationMinimum ? vault - coreSetupFee : 0n);
167
+ /** What a send out can take when it also pays the account's own setup fee on top. */
168
+ export const sendableAfterSetup = (available) => (available > coreSetupFee ? available - coreSetupFee : 0n);
169
+ /** A buy's stake once the setup fee of the move that creates the account comes out of it, floored to the cent. */
170
+ export const stakeAfterSetup = (stake) => centFloor(stake > coreSetupFee ? stake - coreSetupFee : 0n);
171
+ /** Vault cash a buy can move to HyperCore before it trades, less the setup fee when that move creates the account; 0 while unread. */
172
+ export const directBuyVault = (vault, activation = false) => (vault === null ? 0n : activation ? afterActivation(vault) : vault);
173
+ /**
174
+ * All the cash a single buy can spend, in HyperCore USDC units (8 decimals):
175
+ * spot USDC, plus the vault cash (6 decimals) it can move first, unless that
176
+ * move creates the account and is under the minimum. `null` while spot is
177
+ * unread. The buy pays its shares, its builder fee and any setup fee out of it.
178
+ */
179
+ export function directBuyBudget(spot, vault, activation = false) {
180
+ if (spot === null)
181
+ return null;
182
+ return spot + coreUnits(vault === null || (activation && vault < activationMinimum) ? 0n : vault);
183
+ }
184
+ /**
185
+ * What a HyperCore send can take from `available` (6 decimals) once its fees
186
+ * are off: `setupFee` is Hyperliquid's one-time fee on this send, and while
187
+ * it is unread (`null`) so is the room; `senderSetup` is the sender's own
188
+ * account missing, so the vault cash it moves first pays that account's
189
+ * setup fee.
190
+ */
191
+ export function withdrawRoom(available, setupFee, senderSetup = false) {
192
+ if (setupFee === null)
193
+ return null;
194
+ const sendable = senderSetup ? afterActivation(available) : available;
195
+ const room = setupFee ? sendable - coreSetupFee : sendable;
196
+ return room > 0n ? room : 0n;
197
+ }
198
+ /** The least wallet USDC the venue takes as a sponsored deposit into the vault: 0.10 USDC. */
199
+ export const walletSweepMinimum = 100000n;
200
+ /** The wallet's USDC a deposit can move into the vault before an exit: all of it from the minimum up, none for an account that controls or may control a maker (`maker` anything but `NOT_CREATED`, or unread). */
201
+ export const walletDepositable = (maker, wallet) => maker === "NOT_CREATED" && wallet !== null && wallet >= walletSweepMinimum ? wallet : 0n;
202
+ /**
203
+ * How much wallet USDC to sweep into the vault now, or `null` to wait. An
204
+ * embedded wallet whose account controls no maker sweeps all of it from
205
+ * `walletSweepMinimum` up, only while nothing else moves the account's cash:
206
+ * no deposit pending, no operation in an unknown state, no exit crossing or
207
+ * saved. Anything unread (`null`) waits. `wallet` is already less what
208
+ * withdrawals and fundings reserve.
209
+ */
210
+ export function sweepAmount(state) {
211
+ const { wallet } = state;
212
+ if (!state.embedded || state.maker !== "NOT_CREATED" || wallet === null || wallet < walletSweepMinimum)
213
+ return null;
214
+ return state.vaultDeposits !== 0n || state.unknownOperations || state.exiting || state.exitSaved ? null : wallet;
215
+ }
@@ -0,0 +1,56 @@
1
+ /** A fee as an exact fraction of the amount it is charged on. */
2
+ export type FeeRate = {
3
+ readonly value: bigint;
4
+ readonly scale: bigint;
5
+ };
6
+ /**
7
+ * One account's spot rates as Hyperliquid's `userFees` states them, in
8
+ * decimal text. Its volume tier and staking discount are already in the
9
+ * rates; the referral discount comes off on top. A negative maker rate is a
10
+ * rebate, which outcome markets never pay.
11
+ */
12
+ export type AccountFees = {
13
+ readonly taker: string;
14
+ readonly maker: string;
15
+ readonly referral: string;
16
+ };
17
+ /**
18
+ * Hyperliquid's base spot schedule: 7 bps taker, 4 maker, no discount. A
19
+ * visitor with no account to read pays it, and no volume tier, staking or
20
+ * referral discount charges more, so it bounds what any account pays.
21
+ */
22
+ export declare const guestFees: AccountFees;
23
+ /** An account's spot rates from Hyperliquid's `userFees` answer; `null` when it is not one, or its referral discount is over 100%. */
24
+ export declare function parseUserFees(value: unknown): AccountFees | null;
25
+ /** One market's fee multipliers from Hyperliquid's outcome metadata, in decimal text: the venue's global scale and its creator's (an omitted creator scale is "0"). */
26
+ export type MarketFeeScale = {
27
+ readonly global: string;
28
+ readonly creator: string;
29
+ };
30
+ /** What turning one market's shares back into USDC costs one account: taking liquidity, or resting as a maker. Buying pays neither. */
31
+ export type OutcomeFees = {
32
+ readonly taker: FeeRate;
33
+ readonly maker: FeeRate;
34
+ };
35
+ /**
36
+ * Hyperliquid's outcome fee: the account's rate less its referral discount,
37
+ * times the global scale and the creator's `s + max(s, 1)`. Selling,
38
+ * settling and cashing in pairs pay it; buying does not.
39
+ */
40
+ export declare function closingFees(account: AccountFees, market: MarketFeeScale): OutcomeFees;
41
+ /**
42
+ * What whole shares pay out if their side resolves, in USDC base units: a
43
+ * dollar a share less the settlement fee at the taker rate. The fee rounds
44
+ * up and the rest floors to the cent, so it never exceeds what lands.
45
+ */
46
+ export declare function settledPayout(shares: bigint, fees: OutcomeFees): bigint;
47
+ /** What cashing in Yes and No pairs lands: a dollar a pair, paid as two half-dollar legs each charged the taker rate. */
48
+ export declare function pairPayout(pairs: bigint, fees: OutcomeFees): bigint;
49
+ /** The rate a sale is forecast at: a market order takes liquidity; a limit may take or rest, so the larger of the two. */
50
+ export declare const saleRate: (fees: OutcomeFees, market: boolean) => FeeRate;
51
+ /** What a sale of `gross` (USDC base units) lands in cash: less the venue fee at `charged` and the builder fee in decibps, floored to the cent, never below 0. */
52
+ export declare function saleProceeds(gross: bigint, charged: FeeRate, builderDecibps: number): bigint;
53
+ /** What a buy of `amount` takes with the builder fee (decibps) added, rounded up so the cost stated is never less than what leaves. Any unit. */
54
+ export declare function withBuilderFee(amount: bigint, builderDecibps: number): bigint;
55
+ /** The most a buy can cost so that `withBuilderFee` of it still fits in `amount`. Any unit. */
56
+ export declare function beforeBuilderFee(amount: bigint, builderDecibps: number): bigint;
@@ -0,0 +1,70 @@
1
+ import { ceilDiv, centFloor, decimalParts } from "./money.js";
2
+ const usdcUnit = 1000000n;
3
+ /**
4
+ * Hyperliquid's base spot schedule: 7 bps taker, 4 maker, no discount. A
5
+ * visitor with no account to read pays it, and no volume tier, staking or
6
+ * referral discount charges more, so it bounds what any account pays.
7
+ */
8
+ export const guestFees = { taker: "0.0007", maker: "0.0004", referral: "0" };
9
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10
+ /** An account's spot rates from Hyperliquid's `userFees` answer; `null` when it is not one, or its referral discount is over 100%. */
11
+ export function parseUserFees(value) {
12
+ if (!isRecord(value))
13
+ return null;
14
+ const { userSpotCrossRate: taker, userSpotAddRate: maker, activeReferralDiscount: referral } = value;
15
+ if (typeof taker !== "string" || typeof maker !== "string" || typeof referral !== "string")
16
+ return null;
17
+ const unsigned = /^\d+(\.\d+)?$/;
18
+ if (!unsigned.test(taker) || !/^-?\d+(\.\d+)?$/.test(maker) || !unsigned.test(referral))
19
+ return null;
20
+ const discount = rate(referral);
21
+ return discount.value <= discount.scale ? { taker, maker, referral } : null;
22
+ }
23
+ const rate = (text) => {
24
+ const decimals = text.split(".")[1]?.length ?? 0;
25
+ return { value: decimalParts(text, decimals), scale: 10n ** BigInt(decimals) };
26
+ };
27
+ const times = (left, right) => ({ value: left.value * right.value, scale: left.scale * right.scale });
28
+ const noFee = { value: 0n, scale: 1n };
29
+ /**
30
+ * Hyperliquid's outcome fee: the account's rate less its referral discount,
31
+ * times the global scale and the creator's `s + max(s, 1)`. Selling,
32
+ * settling and cashing in pairs pay it; buying does not.
33
+ */
34
+ export function closingFees(account, market) {
35
+ const referral = rate(account.referral);
36
+ const creator = rate(market.creator);
37
+ const multiplier = { value: creator.value + (creator.value > creator.scale ? creator.value : creator.scale), scale: creator.scale };
38
+ const scaled = times(times({ value: referral.scale - referral.value, scale: referral.scale }, rate(market.global)), multiplier);
39
+ const maker = rate(account.maker);
40
+ return { taker: times(rate(account.taker), scaled), maker: times(maker.value < 0n ? noFee : maker, scaled) };
41
+ }
42
+ const fee = (amount, charged) => ceilDiv(amount * charged.value, charged.scale);
43
+ /**
44
+ * What whole shares pay out if their side resolves, in USDC base units: a
45
+ * dollar a share less the settlement fee at the taker rate. The fee rounds
46
+ * up and the rest floors to the cent, so it never exceeds what lands.
47
+ */
48
+ export function settledPayout(shares, fees) {
49
+ const gross = shares * usdcUnit;
50
+ return centFloor(gross - fee(gross, fees.taker));
51
+ }
52
+ /** What cashing in Yes and No pairs lands: a dollar a pair, paid as two half-dollar legs each charged the taker rate. */
53
+ export function pairPayout(pairs, fees) {
54
+ return centFloor(pairs * usdcUnit - 2n * fee(pairs * (usdcUnit / 2n), fees.taker));
55
+ }
56
+ /** The rate a sale is forecast at: a market order takes liquidity; a limit may take or rest, so the larger of the two. */
57
+ export const saleRate = (fees, market) => market || fees.taker.value * fees.maker.scale >= fees.maker.value * fees.taker.scale ? fees.taker : fees.maker;
58
+ /** What a sale of `gross` (USDC base units) lands in cash: less the venue fee at `charged` and the builder fee in decibps, floored to the cent, never below 0. */
59
+ export function saleProceeds(gross, charged, builderDecibps) {
60
+ const net = gross - fee(gross, charged) - ceilDiv(gross * BigInt(builderDecibps), 100000n);
61
+ return net > 0n ? centFloor(net) : 0n;
62
+ }
63
+ /** What a buy of `amount` takes with the builder fee (decibps) added, rounded up so the cost stated is never less than what leaves. Any unit. */
64
+ export function withBuilderFee(amount, builderDecibps) {
65
+ return amount + ceilDiv(amount * BigInt(builderDecibps), 100000n);
66
+ }
67
+ /** The most a buy can cost so that `withBuilderFee` of it still fits in `amount`. Any unit. */
68
+ export function beforeBuilderFee(amount, builderDecibps) {
69
+ return (amount * 100000n) / (100000n + BigInt(builderDecibps));
70
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * What a control showed and when, so a press never takes terms worse than
3
+ * the user saw while deciding. Keep one per control, in the flow that owns
4
+ * it, and pass every time from one monotonic clock (ms).
5
+ */
6
+ /** How far before a press began (before its activation when no start was seen) the values on screen still count. */
7
+ export declare const shownLookbackMs = 500;
8
+ export type ShownValue = {
9
+ readonly subject: string;
10
+ readonly value: bigint;
11
+ readonly from: number;
12
+ readonly to: number | null;
13
+ };
14
+ export declare class ShownHistory {
15
+ private shown;
16
+ private pressedAt;
17
+ /** `value` is on screen for `subject` from `now`; `null` shows nothing. */
18
+ show(subject: string, value: bigint | null, now: number): void;
19
+ /** A press began: pointer or key down. */
20
+ pressed(now: number): void;
21
+ /** What was on screen for a press at `now`: every value shown since `shownLookbackMs` before the press began, each kept `settle` ms past its replacement. Ends the press. */
22
+ press(now: number, settle?: number): ShownValue[];
23
+ }
24
+ /**
25
+ * The least a press at `now` may take for `subject`: the most `history`
26
+ * showed (exact amounts, any unit) in the press window, all of it for this
27
+ * subject; `null` when it showed nothing, or something for another subject.
28
+ * Ends the press; keep the floor for any retry of this press.
29
+ */
30
+ export declare function shownFloor(history: ShownHistory, subject: string, now: number): bigint | null;
31
+ /**
32
+ * The limit to sign for a press at `now`: `price`, or the best limit
33
+ * `history` showed for `subject` in the press window when that is better for
34
+ * the user (lower to buy, higher to sell). Show limits as `priceUnits`. Apply
35
+ * it to the final limit just before signing, and state `maxCost`,
36
+ * `minProceeds` and `orderCoreNeed` from the limit it returns; the size
37
+ * stays, so a better limit may fill only in part. Ends the press.
38
+ */
39
+ export declare function boundLimit(history: ShownHistory, subject: string, buy: boolean, price: string, now: number): string;
package/dist/shown.js ADDED
@@ -0,0 +1,70 @@
1
+ import { priceUnits } from "./book-walk.js";
2
+ /**
3
+ * What a control showed and when, so a press never takes terms worse than
4
+ * the user saw while deciding. Keep one per control, in the flow that owns
5
+ * it, and pass every time from one monotonic clock (ms).
6
+ */
7
+ /** How far before a press began (before its activation when no start was seen) the values on screen still count. */
8
+ export const shownLookbackMs = 500;
9
+ // An amount stays on screen this long after it is replaced, while the button's label fades.
10
+ const labelSettleMs = 300;
11
+ const keepMs = 60_000;
12
+ export class ShownHistory {
13
+ shown = [];
14
+ pressedAt = null;
15
+ /** `value` is on screen for `subject` from `now`; `null` shows nothing. */
16
+ show(subject, value, now) {
17
+ const last = this.shown.at(-1);
18
+ if (last?.to === null && last.subject === subject && last.value === value)
19
+ return;
20
+ if (last?.to === null)
21
+ last.to = now;
22
+ this.shown = this.shown.filter((entry) => entry.to === null || now - entry.to < keepMs);
23
+ if (value !== null)
24
+ this.shown.push({ subject, value, from: now, to: null });
25
+ }
26
+ /** A press began: pointer or key down. */
27
+ pressed(now) {
28
+ this.pressedAt = now;
29
+ }
30
+ /** What was on screen for a press at `now`: every value shown since `shownLookbackMs` before the press began, each kept `settle` ms past its replacement. Ends the press. */
31
+ press(now, settle = 0) {
32
+ const start = (this.pressedAt ?? now) - shownLookbackMs;
33
+ this.pressedAt = null;
34
+ return this.shown.filter((entry) => entry.from <= now && (entry.to === null || entry.to + settle >= start));
35
+ }
36
+ }
37
+ /**
38
+ * The least a press at `now` may take for `subject`: the most `history`
39
+ * showed (exact amounts, any unit) in the press window, all of it for this
40
+ * subject; `null` when it showed nothing, or something for another subject.
41
+ * Ends the press; keep the floor for any retry of this press.
42
+ */
43
+ export function shownFloor(history, subject, now) {
44
+ const seen = history.press(now, labelSettleMs);
45
+ if (seen.length === 0 || seen.some((entry) => entry.subject !== subject))
46
+ return null;
47
+ return seen.reduce((most, entry) => (entry.value > most ? entry.value : most), 0n);
48
+ }
49
+ /**
50
+ * The limit to sign for a press at `now`: `price`, or the best limit
51
+ * `history` showed for `subject` in the press window when that is better for
52
+ * the user (lower to buy, higher to sell). Show limits as `priceUnits`. Apply
53
+ * it to the final limit just before signing, and state `maxCost`,
54
+ * `minProceeds` and `orderCoreNeed` from the limit it returns; the size
55
+ * stays, so a better limit may fill only in part. Ends the press.
56
+ */
57
+ export function boundLimit(history, subject, buy, price, now) {
58
+ const seen = history.press(now);
59
+ const current = priceUnits(price);
60
+ if (current === null)
61
+ return price;
62
+ let best = current;
63
+ for (const entry of seen)
64
+ if (entry.subject === subject && (buy ? entry.value < best : entry.value > best))
65
+ best = entry.value;
66
+ if (best === current)
67
+ return price;
68
+ const fraction = (best % 100000000n).toString().padStart(8, "0").replace(/0+$/, "");
69
+ return `${best / 100000000n}.${fraction}`;
70
+ }