@totalis/hip4-client 0.84.1 → 0.85.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,9 +1,9 @@
1
1
  // Generated by scripts/generate.mjs; do not edit.
2
- export const sdkVersion = "211.0.0-golden-live-fives";
3
- export const openapiSha256 = "d8b937fb26fe71ab2eef6812b630b15eefbb66702c72d2a192a77f1e0095463b";
2
+ export const sdkVersion = "212.0.0-suggested-categories";
3
+ export const openapiSha256 = "7dfe6c962d2acc85b455fa7cbd1b4d8a6cec4b2dabf96550219fb483d3d71224";
4
4
  export const realtimeSha256 = "f4f1078418b5302417babe1380b85b0c4f89cb0fdfaff3a46154dd2018625c07";
5
5
  export const jsonSchemaSha256 = {
6
- "account.schema.json": "5106e2d53abef190990eff113f6692dd27df5848439cf5a80a42c11e89f2bef6",
6
+ "account.schema.json": "96c6f76d10567b00bff122e31eca177b3879eec78628113832d00bc9ea6db891",
7
7
  "comments.schema.json": "18f4addcfa4e31c2c833fce8b8beca61d2e2ee5b6318c2ed0b479698ff56b65e",
8
8
  "common.schema.json": "04f51deb3cbea448e59195e26ede3212598d58a7940fe67eb2123fd9161c5edb",
9
9
  "core-exit.schema.json": "c7f617e815225cdcac95c236f8b73fbe288ee5713ff444c3be90eb915fc3a401",
@@ -15,7 +15,7 @@ export const jsonSchemaSha256 = {
15
15
  "maker-telemetry.schema.json": "85b111ce0f4935299d1116071b43de12e775bef4e0c283c12f19046d34374a9c",
16
16
  "market-data.schema.json": "85db33fac6a29b0fa87a500bfda947d0ab3913b13f1c26663d4a7c0484c35786",
17
17
  "product-metadata.schema.json": "7c8ffbde878a0aedaed16814fcfd2e80038054b140886cc8736bb7b508042631",
18
- "quote.schema.json": "5616260d399d022bde2d0130cc9f8a09f71a3dc877276adf796c7a174d21b59a",
18
+ "quote.schema.json": "7b3dc6197c37d9e58440dccd109208205d380797506f4dc5ae07caf49a6276da",
19
19
  "realtime.schema.json": "f4f1078418b5302417babe1380b85b0c4f89cb0fdfaff3a46154dd2018625c07"
20
20
  };
21
21
  export const operations = {
@@ -25,6 +25,7 @@ export const operations = {
25
25
  "activeCoreExits",
26
26
  "admitOwnMaker",
27
27
  "admitPartnerWallet",
28
+ "approveWallet",
28
29
  "bindEmbeddedWallet",
29
30
  "cancelRfq",
30
31
  "confirmComboCopyAgent",
@@ -96,6 +97,7 @@ export const operations = {
96
97
  "getUsernameAvailability",
97
98
  "getVaultAgents",
98
99
  "getVolumeLeaderboard",
100
+ "getWalletApproval",
99
101
  "getWithdrawal",
100
102
  "grantComboCopyAgent",
101
103
  "grantVaultAgent",
package/dist/maker.js CHANGED
@@ -3,7 +3,7 @@ import { ApiError, randomBytes32, resendable, sendOnce, singleFetch, sleep, unwr
3
3
  import { toTotalisSigner } from "./signer.js";
4
4
  import { items } from "./pagination.js";
5
5
  import { TotalisStream } from "./stream.js";
6
- import { follow } from "./totalis.js";
6
+ import { follow, terminalOperationStatuses } from "./totalis.js";
7
7
  import { address, cashoutTransferTypedData, hashTypedData, quoteTypedData, sellBackTypedData } from "./typed-data.js";
8
8
  import { calldata, controllerTransactions } from "./controller.js";
9
9
  export { controllerTransactions, encodeCall, openMakerVaultTransaction } from "./controller.js";
@@ -522,7 +522,7 @@ export function createMaker(options) {
522
522
  */
523
523
  const withdrawal = async () => unwrap(await client.GET("/v1/makers/{maker_id}/withdrawal", { params: { path: { maker_id: makerId } } }));
524
524
  const settled = new Set(["NO_IMPROVEMENT", "FAILED"]);
525
- const operationDone = new Set(["COMMITTED", "REVERTED", "EXPIRED_UNEXECUTED"]);
525
+ const operationDone = terminalOperationStatuses;
526
526
  /**
527
527
  * Ask for a collateral reduction and follow the job on the maker stream until
528
528
  * it needs nothing more from the maker: NO_IMPROVEMENT, FAILED, or DURABLE
package/dist/totalis.d.ts CHANGED
@@ -2,7 +2,7 @@ import { issueApiKey, rotateApiKey } from "./api-keys.js";
2
2
  import { type AccessToken, type ApiClientOptions, type PublicEnvironment } from "./base.js";
3
3
  import type { paths } from "./generated/client.js";
4
4
  import { type BridgedCash, type CoreAccountMode, type HypercoreAnswer, type HypercoreTransport, type HyperliquidInfo, type SignedSendAsset } from "./hypercore.js";
5
- import { BalanceUnknownError, EntryError, ExitUnavailableError } from "./flow-errors.js";
5
+ import { BalanceUnknownError, EntryError, ExitUnavailableError, WalletApprovalError } from "./flow-errors.js";
6
6
  import { ApiError, NetworkError, type RetryPolicy } from "./request.js";
7
7
  import { type SignerInput } from "./signer.js";
8
8
  import { TotalisStream, type StreamEvent, type StreamOptions, type StreamSubscription } from "./stream.js";
@@ -69,6 +69,44 @@ export type EntryCash = {
69
69
  readonly wallet: Amount | null;
70
70
  };
71
71
  export type DepositAccepted = Ok<"/v1/me/deposits", "post", 202>;
72
+ /** The account wallet's USDC approval to WalletAccept and its permit nonce, read at one block (`readWalletApproval`); `approved`, `nonce` and `block` are `null` when unread, never 0. */
73
+ export type WalletApproval = Ok<"/v1/me/wallet-approval", "get">;
74
+ /** A permit request as the venue holds it: its operation's status, and `failure_reason` once it changed nothing. */
75
+ export type WalletApprovalRequest = Ok<"/v1/me/wallet-approval", "post", 202>;
76
+ /**
77
+ * A signed USDC permit setting the account wallet's approval to WalletAccept,
78
+ * plain JSON. Persist it before `sendWalletApproval`: after a lost answer or a
79
+ * restart, `recoverWalletApproval` resends the same body under the same key,
80
+ * never a new signature. `body.nonce` is the permit nonce it was signed with.
81
+ */
82
+ export type SignedWalletApproval = {
83
+ readonly kind: "WALLET_APPROVAL";
84
+ readonly version: 1;
85
+ readonly requestId: string;
86
+ readonly account: Hex;
87
+ readonly chainId: string;
88
+ readonly vault: Hex;
89
+ readonly token: Hex;
90
+ readonly spender: Hex;
91
+ readonly body: CommandOf<"/v1/me/wallet-approval">;
92
+ };
93
+ /** A permit this client signed, with the request the venue answered once it landed. */
94
+ export type LandedWalletApproval = {
95
+ readonly signed: SignedWalletApproval;
96
+ readonly landed: WalletApprovalRequest;
97
+ };
98
+ /** An approval the caller already holds: a `WalletApproval` it just read, or a permit that just landed. */
99
+ export type KnownWalletApproval = WalletApproval | LandedWalletApproval;
100
+ /** Awaited with a signed permit before it is first sent; persist it to recover. */
101
+ export type ApprovalListener = (record: SignedWalletApproval) => void | Promise<void>;
102
+ /**
103
+ * Where an entry's shortfall comes from: `"wallet"` (default) signs a USDC
104
+ * authorization for it; `"approval"` draws it from the wallet's approval to
105
+ * WalletAccept, asking a permit only when the approval left is short.
106
+ */
107
+ export type EntryFunding = "wallet" | "approval";
108
+ /** The approval asked when the approval left falls short: 10,000 USDC, or the shortfall when it is larger. */
109
+ export declare const defaultWalletApproval = 10000000000n;
72
110
  /**
73
111
  * What one Combo can stake, from the venue balances and the account's
74
112
  * HyperCore cash, in USDC base units (`readComboCash`). `vault` and `wallet`
@@ -191,15 +229,17 @@ export type AcceptanceResult = {
191
229
  * `DEADLINE_BEFORE_CLAIM` when the venue reached it too late; nothing traded
192
230
  * and its cash stayed where it was.
193
231
  */
194
- export type EntryFailure = "CORE_MOVE_MISSED" | NonNullable<Operation["failure_reason"]>;
232
+ export type EntryFailure = "CORE_MOVE_MISSED" | "INSUFFICIENT_APPROVAL" | NonNullable<Operation["failure_reason"]>;
195
233
  /**
196
234
  * An entry's `EntryFailure`; undefined unless its operation ended with a
197
235
  * `failure_reason`. Pass the record as `onRecord` last handed it back (or
198
236
  * `openPosition`'s `record`): only `LANDED` shows the Core cash moved before
199
237
  * `fund_by`. `PROCESSED` only says the nonce is spent, which a refused or
200
- * expired send also does, so it does not show the move.
238
+ * expired send also does, so it does not show the move. For a `"approval"`
239
+ * entry pass its acceptance too (`outcome`): `INSUFFICIENT_APPROVAL` when the
240
+ * wallet's approval to WalletAccept was below the shortfall.
201
241
  */
202
- export declare function entryFailure(record: SignedEntry | LegacySignedEntry, operation: Pick<Operation, "failure_reason">): EntryFailure | undefined;
242
+ export declare function entryFailure(record: SignedEntry | LegacySignedEntry, operation: Pick<Operation, "failure_reason">, acceptance?: Acceptance | NotAdmitted): EntryFailure | undefined;
203
243
  /** When an entry quote stops being acceptable, in ms on the venue clock: its `accept_before`. A quote without a readable one never is. */
204
244
  export declare function acceptBefore(quote: EntryQuote): number;
205
245
  /**
@@ -239,6 +279,8 @@ export type TotalisOptions = Omit<ApiClientOptions, "accessToken"> & {
239
279
  }>, "type">;
240
280
  };
241
281
  };
282
+ /** The operation statuses that never change again; only COMMITTED executed. */
283
+ export declare const terminalOperationStatuses: ReadonlySet<string>;
242
284
  /**
243
285
  * Follow a resource: read it, then read again only when the stream says it
244
286
  * changed (`wake`) or after a reconnect, until `done`. Reads made while the
@@ -290,8 +332,20 @@ export declare function createTotalis(options: TotalisOptions): {
290
332
  readonly choose?: Chooser<EntryQuote>;
291
333
  /** How long quotes may keep arriving after the first one `choose` would take, before it picks; 0 takes it at once. Time spent signing the funding counts. */
292
334
  readonly collectMs?: number;
293
- /** `"wallet"` (default) plans the shortfall from the wallet and `core`; `"none"` never funds; or pass a funding command. */
294
- readonly funding?: "wallet" | "none" | Funding;
335
+ /**
336
+ * `"wallet"` (default) plans the shortfall from the wallet and `core`
337
+ * with a USDC authorization; `"approval"` plans it the same way but draws
338
+ * the wallet's part from its approval to WalletAccept (`prepareEntryFunding`),
339
+ * reusing it, and an unsent bridge's exact bytes, on each refresh;
340
+ * `"none"` never funds; or pass a funding command.
341
+ */
342
+ readonly funding?: EntryFunding | "none" | Funding;
343
+ /** With `"approval"`: a `WalletApproval` just read, or a permit request that just landed, used instead of reading the approval again (see `prepareEntryFunding`). */
344
+ readonly approval?: KnownWalletApproval;
345
+ /** With `"approval"`: the approval a permit asks when one is needed, or `null` to never ask one (see `prepareEntryFunding`). */
346
+ readonly approvalValue?: Amount | null;
347
+ /** With `"approval"`: awaited with a permit before it is first sent; persist it to `recoverWalletApproval`. */
348
+ readonly onApproval?: ApprovalListener;
295
349
  /** Core USDC offered for a bridge, in USDC base units; `null` when unread (see `signEntry`). */
296
350
  readonly core?: Amount | null;
297
351
  readonly sourceDex?: "spot" | "";
@@ -351,6 +405,12 @@ export declare function createTotalis(options: TotalisOptions): {
351
405
  readonly cash?: EntryCash | undefined;
352
406
  readonly sourceDex?: "spot" | "" | undefined;
353
407
  readonly hypercoreNonce?: number | undefined;
408
+ readonly funding?: EntryFunding | undefined;
409
+ /** With `"approval"`: a `WalletApproval` just read, or a permit this client signed with its landed request, used instead of reading the approval again; it must be this wallet's, on this deployment, for its USDC. */
410
+ readonly approval?: KnownWalletApproval | undefined;
411
+ /** The approval a permit asks when one is needed; default the larger of `defaultWalletApproval` and the shortfall; `null` never asks one. */
412
+ readonly approvalValue?: Amount | null | undefined;
413
+ readonly onApproval?: ApprovalListener | undefined;
354
414
  readonly signal?: AbortSignal | undefined;
355
415
  }) => Promise<PreparedEntryFunding>;
356
416
  signEntry: (request: {
@@ -361,6 +421,7 @@ export declare function createTotalis(options: TotalisOptions): {
361
421
  readonly acceptanceId?: string;
362
422
  readonly hypercoreNonce?: number;
363
423
  readonly prepared?: PreparedEntryFunding;
424
+ readonly funding?: EntryFunding;
364
425
  }) => Promise<SignedEntry>;
365
426
  signCashout: (request: {
366
427
  readonly quote: CashoutBid;
@@ -725,6 +786,27 @@ export declare function createTotalis(options: TotalisOptions): {
725
786
  readonly nonce: import("./generated/openapi.js").components["schemas"]["UInt64String"];
726
787
  readonly copy_agent: boolean;
727
788
  }, void, any>;
789
+ readWalletApproval: (signal?: AbortSignal) => Promise<WalletApproval>;
790
+ signWalletApproval: (request: {
791
+ readonly value: Amount;
792
+ readonly approval?: WalletApproval;
793
+ readonly requestId?: string;
794
+ readonly signal?: AbortSignal;
795
+ }) => Promise<SignedWalletApproval>;
796
+ sendWalletApproval: (signed: SignedWalletApproval) => Promise<WalletApprovalRequest>;
797
+ recoverWalletApproval: (signed: SignedWalletApproval, options?: {
798
+ readonly wait?: boolean;
799
+ readonly signal?: AbortSignal;
800
+ }) => Promise<WalletApprovalRequest>;
801
+ approveWallet: (request: {
802
+ readonly value: Amount;
803
+ readonly onSigned?: ApprovalListener;
804
+ readonly signal?: AbortSignal;
805
+ }) => Promise<WalletApprovalRequest>;
806
+ revokeWalletApproval: (request?: {
807
+ readonly onSigned?: ApprovalListener;
808
+ readonly signal?: AbortSignal;
809
+ }) => Promise<WalletApprovalRequest>;
728
810
  /** Render an RFQ's live quotes (entry or cash-out) from the stream; `[]` while the stream is down. */
729
811
  watchQuotes: (rfqId: string, listener: (quotes: readonly Quote[], serverNowMs: number) => void) => () => void;
730
812
  /** Issue a personal `ttk_` key; the signer must be the account wallet (embedded, or a wallet-only account's own). */
@@ -799,7 +881,7 @@ export declare function createTotalis(options: TotalisOptions): {
799
881
  close: () => void;
800
882
  };
801
883
  export type Totalis = ReturnType<typeof createTotalis>;
802
- export { BalanceUnknownError, EntryError, ExitUnavailableError };
884
+ export { BalanceUnknownError, EntryError, ExitUnavailableError, WalletApprovalError };
803
885
  export { ApiError, NetworkError };
804
886
  export type SignedCoreExit = Awaited<ReturnType<Totalis["signCoreExit"]>>;
805
887
  export type SignedDeposit = Awaited<ReturnType<Totalis["signDeposit"]>>;
package/dist/totalis.js CHANGED
@@ -2,13 +2,15 @@ import { keccak_256 } from "@noble/hashes/sha3";
2
2
  import { createApiKeyClient, issueApiKey, rotateApiKey } from "./api-keys.js";
3
3
  import { audienceClient, headerRecord } from "./base.js";
4
4
  import { bridgeAction, bridgeGasBuffer, hyperliquidExchange, hyperliquidNetwork, readCoreCash, settleHypercore, signSendAsset, usdcUnits, } from "./hypercore.js";
5
- import { BalanceUnknownError, EntryError, ExitUnavailableError, normalizeError } from "./flow-errors.js";
5
+ import { BalanceUnknownError, EntryError, ExitUnavailableError, normalizeError, WalletApprovalError } from "./flow-errors.js";
6
6
  import { comboAllowance, offeredCore, spendableCash } from "./money.js";
7
7
  import { ApiError, backoffDelay, envelope, NetworkError, randomBytes32, resendable, retryingFetch, sendOnce, singleFetch, sleep, unwrap, uuidv7 } from "./request.js";
8
8
  import { toTotalisSigner } from "./signer.js";
9
9
  import { TotalisStream } from "./stream.js";
10
10
  import { items } from "./pagination.js";
11
- import { address, agentGrantTypedData, cashoutTransferTypedData, exitTypedData, receiveWithAuthorizationTypedData, sellBackTypedData, takerAcceptTypedData, payoutNonce, transferWithAuthorizationTypedData, } from "./typed-data.js";
11
+ import { address, agentGrantTypedData, cashoutTransferTypedData, exitTypedData, receiveWithAuthorizationTypedData, sellBackTypedData, takerAcceptTypedData, payoutNonce, transferWithAuthorizationTypedData, walletPermitTypedData, } from "./typed-data.js";
12
+ /** The approval asked when the approval left falls short: 10,000 USDC, or the shortfall when it is larger. */
13
+ export const defaultWalletApproval = 10000000000n;
12
14
  /**
13
15
  * What an entry's bridge may have moved to its wallet, by its state: nothing
14
16
  * before it is sent, once discarded or refused. Only `LANDED` proves it
@@ -26,11 +28,15 @@ function bridgedCash(signed) {
26
28
  * `failure_reason`. Pass the record as `onRecord` last handed it back (or
27
29
  * `openPosition`'s `record`): only `LANDED` shows the Core cash moved before
28
30
  * `fund_by`. `PROCESSED` only says the nonce is spent, which a refused or
29
- * expired send also does, so it does not show the move.
31
+ * expired send also does, so it does not show the move. For a `"approval"`
32
+ * entry pass its acceptance too (`outcome`): `INSUFFICIENT_APPROVAL` when the
33
+ * wallet's approval to WalletAccept was below the shortfall.
30
34
  */
31
- export function entryFailure(record, operation) {
35
+ export function entryFailure(record, operation, acceptance) {
32
36
  if (operation.failure_reason !== "INSUFFICIENT_CASH")
33
37
  return operation.failure_reason;
38
+ if (acceptance !== undefined && acceptance.status !== "NOT_ADMITTED" && acceptance.funding_failure_reason === "INSUFFICIENT_APPROVAL")
39
+ return "INSUFFICIENT_APPROVAL";
34
40
  if (record.bridge === undefined || "version" in record && record.bridgeState === "LANDED")
35
41
  return "INSUFFICIENT_CASH";
36
42
  return "CORE_MOVE_MISSED";
@@ -117,6 +123,11 @@ function callData(signature, ...words) {
117
123
  return `0x${selector}${words.map((word) => (typeof word === "bigint" ? word.toString(16) : word.slice(2)).padStart(64, "0")).join("")}`;
118
124
  }
119
125
  const idempotency = (key = uuidv7()) => ({ "Idempotency-Key": key });
126
+ /** The operation statuses that never change again; only COMMITTED executed. */
127
+ export const terminalOperationStatuses = new Set(["COMMITTED", "REVERTED", "EXPIRED_UNEXECUTED"]);
128
+ /** How long a signed permit may wait to be submitted; not how long the approval lasts. */
129
+ const permitLifeSeconds = 30 * 60;
130
+ const approvalFunding = { kind: "WALLET_APPROVAL" };
120
131
  function withTimeout(signal, ms) {
121
132
  return signal === undefined ? AbortSignal.timeout(ms) : AbortSignal.any([signal, AbortSignal.timeout(ms)]);
122
133
  }
@@ -459,6 +470,144 @@ export function createTotalis(options) {
459
470
  const authorization_signature = await (await requireSigner()).signTypedData(receiveWithAuthorizationTypedData(chain, { account, from: account, ...authorization }));
460
471
  return { kind: "WALLET", ...authorization, authorization_signature };
461
472
  }
473
+ /** The account wallet's USDC approval to WalletAccept and its permit nonce, read at one block (`WalletApproval`). */
474
+ async function readWalletApproval(signal) {
475
+ return unwrap(await client.GET("/v1/me/wallet-approval", signal === undefined ? {} : { signal }));
476
+ }
477
+ /** An approval the caller holds counts only for this wallet, deployment, vault and USDC; a landed permit only once committed. */
478
+ function requireApprovalScope(known, wallet, chain) {
479
+ const account = wallet.toLowerCase();
480
+ const usdc = chain.usdc.address.toLowerCase();
481
+ const vault = chain.vault_address.toLowerCase();
482
+ const scoped = "signed" in known
483
+ ? known.signed.account === account && known.signed.chainId === chain.chain_id && known.signed.vault === vault && known.signed.token === usdc
484
+ && known.landed.request_id === known.signed.requestId && known.landed.status === "COMMITTED"
485
+ : known.account.toLowerCase() === account && known.chain_id === chain.chain_id && known.vault.toLowerCase() === vault && known.token.toLowerCase() === usdc;
486
+ if (!scoped)
487
+ throw new Error("the approval is for another wallet, deployment, vault or token, or its permit has not landed");
488
+ }
489
+ /**
490
+ * Sign a USDC permit setting the account wallet's approval to WalletAccept
491
+ * to `value` (0 revokes) without sending it, at the nonce of `approval`, a
492
+ * `readWalletApproval` read now when left out. It can be submitted for 30
493
+ * minutes. Persist the record, then `sendWalletApproval` it.
494
+ */
495
+ async function signWalletApproval(request) {
496
+ const signer = await requireSigner();
497
+ const account = address((await signer.address()).toLowerCase());
498
+ const value = BigInt(request.value);
499
+ if (value < 0n || value >= 1n << 256n)
500
+ throw new RangeError("the approval must be a uint256");
501
+ const [chain, approval] = await Promise.all([deployment(), request.approval ?? readWalletApproval(request.signal)]);
502
+ requireApprovalScope(approval, account, chain);
503
+ if (approval.nonce === null)
504
+ throw new WalletApprovalError("APPROVAL_UNKNOWN", "the wallet's permit nonce is unknown; read the approval again");
505
+ const spender = address(approval.spender.toLowerCase());
506
+ const permit = { owner: account, spender, value: value.toString(), nonce: approval.nonce, deadline: String(now() + permitLifeSeconds) };
507
+ const signature = await signer.signTypedData(walletPermitTypedData(chain, permit));
508
+ return {
509
+ kind: "WALLET_APPROVAL", version: 1, requestId: request.requestId ?? uuidv7(), account, chainId: chain.chain_id,
510
+ vault: address(approval.vault.toLowerCase()), token: address(approval.token.toLowerCase()), spender, body: { value: permit.value, nonce: permit.nonce, deadline: permit.deadline, signature },
511
+ };
512
+ }
513
+ /**
514
+ * POST a signed permit under its request ID, resending the same bytes on a
515
+ * lost answer. The 202 is the request as it stands; `recoverWalletApproval`
516
+ * follows it. The chain judges the deadline: a permit sent after it passed
517
+ * is admitted like any other and ends `PERMIT_EXPIRED`.
518
+ */
519
+ async function sendWalletApproval(signed) {
520
+ const account = signer === undefined ? unwrap(await client.GET("/v1/me")).wallet : await signer.address();
521
+ if (account.toLowerCase() !== signed.account || (await deployment()).chain_id !== signed.chainId) {
522
+ throw new Error("this permit was signed by another wallet or on another deployment");
523
+ }
524
+ return sendOnce(() => client.POST("/v1/me/wallet-approval", { params: { header: idempotency(signed.requestId) }, body: signed.body }));
525
+ }
526
+ /** Follow a sent permit until its operation ends: resolves it COMMITTED, else throws `WalletApprovalError` with its `failure_reason`. */
527
+ async function settleWalletApproval(signed, sent, signal) {
528
+ let request = sent;
529
+ if (!terminalOperationStatuses.has(request.status)) {
530
+ await waitForOperation(request.operation_id, signal);
531
+ request = await sendWalletApproval(signed);
532
+ }
533
+ if (request.status === "COMMITTED")
534
+ return request;
535
+ const reason = request.failure_reason ?? "PERMIT_REVERTED";
536
+ throw new WalletApprovalError(reason, `the permit setting the approval to ${request.value} changed nothing (${reason})`);
537
+ }
538
+ /**
539
+ * Finish a stored permit after a lost answer or a restart, signing nothing:
540
+ * resend its body under its request ID, which answers with the request as
541
+ * it stands (or admits it if the first send never arrived), then follow it
542
+ * until it ends, unless `wait` is false. Resolves it COMMITTED, else throws
543
+ * `WalletApprovalError`.
544
+ */
545
+ async function recoverWalletApproval(signed, options = {}) {
546
+ const request = await sendWalletApproval(signed);
547
+ return options.wait === false ? request : settleWalletApproval(signed, request, options.signal);
548
+ }
549
+ /**
550
+ * Set the account wallet's approval to WalletAccept to `value` and wait
551
+ * until it lands: sign a permit at the current nonce, hand the record to
552
+ * `onSigned` to persist, send it and follow it. Resolves the COMMITTED
553
+ * request; throws `WalletApprovalError` when it changed nothing. After a
554
+ * restart, `recoverWalletApproval` the stored record instead.
555
+ */
556
+ async function approveWallet(request) {
557
+ const signed = await signWalletApproval({ value: request.value, ...(request.signal === undefined ? {} : { signal: request.signal }) });
558
+ await request.onSigned?.(signed);
559
+ return settleWalletApproval(signed, await sendWalletApproval(signed), request.signal);
560
+ }
561
+ /** `approveWallet` with value 0. The approval stands until this resolves: only a landed revoke ended it. */
562
+ function revokeWalletApproval(request = {}) {
563
+ return approveWallet({ ...request, value: 0n });
564
+ }
565
+ /** An entry signed without `prepareEntryFunding` sends no permit: the approval left must already cover `need`. */
566
+ async function approvalCovers(need) {
567
+ const { approved } = await readWalletApproval();
568
+ if (approved === null)
569
+ throw new WalletApprovalError("APPROVAL_UNKNOWN", "the wallet's approval is unknown; read it again");
570
+ if (BigInt(approved) < need)
571
+ throw new WalletApprovalError("INSUFFICIENT_APPROVAL", `the approval left, ${approved}, is below the ${need} this entry needs; approveWallet first`);
572
+ }
573
+ /**
574
+ * Make the approval left cover `need` for a `"approval"` entry: a landed
575
+ * approval that covers it is reused; otherwise a permit for `approvalValue`
576
+ * (default the larger of `defaultWalletApproval` and `need`) is signed,
577
+ * handed to `onApproval`, sent and followed until it lands. With
578
+ * `approvalValue: null` no permit is asked: a short approval throws
579
+ * `INSUFFICIENT_APPROVAL`. A permit whose nonce another one used ends well
580
+ * only if the approval read after it covers `need`. `approval`, one the
581
+ * caller just read or a permit request that just landed, stands in for the
582
+ * first read.
583
+ */
584
+ async function ensureApproval(need, request) {
585
+ const covered = (approval) => {
586
+ if (approval.approved === null)
587
+ throw new WalletApprovalError("APPROVAL_UNKNOWN", "the wallet's approval is unknown; read it again");
588
+ return BigInt(approval.approved) >= need;
589
+ };
590
+ const known = request.fresh === true ? undefined : request.approval;
591
+ if (known !== undefined && "signed" in known && BigInt(known.landed.value) >= need)
592
+ return;
593
+ const approval = known !== undefined && !("signed" in known) ? known : await readWalletApproval(request.signal);
594
+ if (covered(approval))
595
+ return;
596
+ if (request.approvalValue === null)
597
+ throw new WalletApprovalError("INSUFFICIENT_APPROVAL", `the approval left, ${approval.approved}, is below the ${need} this entry needs; approveWallet first`);
598
+ const value = request.approvalValue === undefined ? (need > defaultWalletApproval ? need : defaultWalletApproval) : BigInt(request.approvalValue);
599
+ if (value < need)
600
+ throw new RangeError(`an approval of ${value} does not cover the ${need} this entry needs`);
601
+ const signed = await signWalletApproval({ value, approval, ...(request.signal === undefined ? {} : { signal: request.signal }) });
602
+ await request.onApproval?.(signed);
603
+ try {
604
+ await settleWalletApproval(signed, await sendWalletApproval(signed), request.signal);
605
+ }
606
+ catch (error) {
607
+ if (!(error instanceof WalletApprovalError) || error.code !== "PERMIT_NONCE_USED" || !covered(await readWalletApproval(request.signal)))
608
+ throw error;
609
+ }
610
+ }
462
611
  /**
463
612
  * Settle an acceptance whose accept response was lost, or a stored record
464
613
  * after a restart: read it, and while the held request is still waiting for
@@ -677,20 +826,32 @@ export function createTotalis(options) {
677
826
  * USDC authorization and any bridge from `core`, planned from `cash` or a
678
827
  * fresh balances read as `signEntry` plans them. Neither names a quote, so
679
828
  * once one is chosen `signEntry({ quote, prepared })` signs only the quote
680
- * and the accept can go straight out.
829
+ * and the accept can go straight out. With `funding: "approval"` no USDC
830
+ * authorization is signed: the shortfall comes from the wallet's approval
831
+ * to WalletAccept, and when the approval left is short a permit is signed,
832
+ * handed to `onApproval` to persist, and followed until it lands, so this
833
+ * resolves only with an approval that covered the shortfall when read.
834
+ * The approval is read beside the bridge signature, unless `approval`
835
+ * passes one just read or a permit request that just landed.
681
836
  */
682
837
  async function prepareEntryFunding(request) {
683
838
  const { signer, account, chain, scope } = await recordScope();
839
+ if (request.approval !== undefined)
840
+ requireApprovalScope(request.approval, account, chain);
684
841
  const stake = BigInt(request.stake);
685
842
  const core = request.core === undefined || request.core === null ? request.core : BigInt(request.core);
686
843
  const plan = planEntry(stake, core, request.cash ?? await readSpendableCash(request.signal));
844
+ // A bridge can't be undone, so with one the approval is read fresh beside
845
+ // its signature (no added wait), whatever the caller passed.
687
846
  const [bridge, funding] = await Promise.all([
688
847
  signBridge(signer, chain, plan.bridge, request),
689
- plan.wallet > 0n ? depositAuthorization(chain, account, plan.wallet) : undefined,
848
+ plan.wallet <= 0n ? undefined
849
+ : request.funding === "approval" ? ensureApproval(plan.wallet, { ...request, fresh: plan.bridge > 0n }).then(() => approvalFunding)
850
+ : depositAuthorization(chain, account, plan.wallet),
690
851
  ]);
691
852
  return { stake: stake.toString(), ...scope, ...(funding === undefined ? {} : { funding }), ...(bridge === undefined ? {} : { bridge }) };
692
853
  }
693
- async function signEntryWith(request, funding) {
854
+ async function signEntryWith(request, funding, route = "wallet") {
694
855
  const { quote, cash, prepared } = request;
695
856
  const { signer, vaultSigner, account, chain, scope } = await recordScope();
696
857
  if (quote.entry.taker.toLowerCase() !== account)
@@ -725,7 +886,9 @@ export function createTotalis(options) {
725
886
  const [taker_signature, bridge, walletFunding] = await Promise.all([
726
887
  signing,
727
888
  signBridge(signer, chain, bridgeAmount, request),
728
- walletAmount > 0n ? depositAuthorization(chain, account, walletAmount) : undefined,
889
+ walletAmount <= 0n ? undefined
890
+ : route === "approval" ? approvalCovers(walletAmount).then(() => approvalFunding)
891
+ : depositAuthorization(chain, account, walletAmount),
729
892
  ]);
730
893
  const fundingCommand = plan === undefined ? (funding === "none" || funding === "plan" ? undefined : funding) : walletFunding;
731
894
  return record(taker_signature, fundingCommand, bridge);
@@ -745,10 +908,14 @@ export function createTotalis(options) {
745
908
  * Persist the record, then `sendAcceptance` it; after a restart,
746
909
  * `recoverAcceptance` it. Pass `hypercoreNonce` if your app reserves
747
910
  * Hyperliquid nonces itself. With `prepared` (`prepareEntryFunding`), only
748
- * the quote is signed, and its funding is the prepared one.
911
+ * the quote is signed, and its funding is the prepared one. `funding:
912
+ * "approval"` draws the wallet's part from its approval to WalletAccept
913
+ * instead of a USDC authorization; signing sends nothing, so without
914
+ * `prepared` the approval left must already cover it (`WalletApprovalError`
915
+ * `INSUFFICIENT_APPROVAL` otherwise).
749
916
  */
750
917
  function signEntry(request) {
751
- return signEntryWith(request, "plan");
918
+ return signEntryWith(request, "plan", request.funding);
752
919
  }
753
920
  /** Sign a cash-out quote as the position's owner without sending it: the same SellBack or CashoutTransfer digest the maker signs. */
754
921
  async function signCashout(request) {
@@ -873,7 +1040,8 @@ export function createTotalis(options) {
873
1040
  */
874
1041
  async function openPosition(request) {
875
1042
  const { legs, stake, choose = bestQuote(), collectMs = defaultCollectMs, funding = "wallet", intent, quoteTimeoutMs = 20_000, refreshMs = defaultRefreshMs, maxAttempts = defaultMaxAttempts, signal } = request;
876
- const reading = funding === "wallet" && request.cash === undefined ? readSpendableCash(signal) : undefined;
1043
+ const planned = funding === "wallet" || funding === "approval";
1044
+ const reading = planned && request.cash === undefined ? readSpendableCash(signal) : undefined;
877
1045
  reading?.catch(() => undefined);
878
1046
  const account = await (await requireSigner()).address();
879
1047
  await deployment();
@@ -890,17 +1058,22 @@ export function createTotalis(options) {
890
1058
  !refused.has(quote.quote_id) && (floor === undefined || BigInt(quote.entry.payout) >= floor);
891
1059
  // Counted from the first choice, not from its signature, so a slow wallet cannot stretch the window.
892
1060
  let refreshUntil;
1061
+ // An approval entry's funding names no quote and its bridge was never sent unless the record says so, so a refresh reuses both.
1062
+ let reusable;
893
1063
  const take = () => signedOrCancel(rfqId, async () => {
894
- const prepared = funding === "wallet"
895
- ? await prepareEntryFunding({ stake: wanted.stake, core: request.core, cash: request.cash ?? await (refreshUntil === undefined ? reading : readSpendableCash(signal)), sourceDex: request.sourceDex, signal })
896
- : undefined;
1064
+ const prepared = !planned ? undefined : reusable ?? await prepareEntryFunding({
1065
+ stake: wanted.stake, core: request.core, cash: request.cash ?? await (refreshUntil === undefined ? reading : readSpendableCash(signal)),
1066
+ sourceDex: request.sourceDex, funding, approval: request.approval, approvalValue: request.approvalValue, onApproval: request.onApproval, signal,
1067
+ });
1068
+ if (funding === "approval")
1069
+ reusable = prepared;
897
1070
  const selected = refreshUntil === undefined
898
1071
  ? await awaitOffer(rfqId, offered, choose, Math.max(0, Math.round(collectMs - (performance.now() - createdAt))), quoteTimeoutMs, signal)
899
1072
  : await awaitOffer(rfqId, offered, choose, 0, Math.max(0, Math.round(refreshUntil - performance.now())), signal);
900
1073
  refreshUntil ??= performance.now() + refreshMs;
901
1074
  if (!offered(selected))
902
1075
  throw new Error("the chosen quote is not for the requested position");
903
- const signed = await signEntryWith({ quote: selected, prepared }, funding === "wallet" ? "plan" : funding);
1076
+ const signed = await signEntryWith({ quote: selected, prepared }, planned ? "plan" : funding);
904
1077
  await request.onSigned?.(signed);
905
1078
  return { selected, signed };
906
1079
  });
@@ -934,6 +1107,8 @@ export function createTotalis(options) {
934
1107
  await request.onSigned?.(record);
935
1108
  }
936
1109
  refused.add(signed.quoteId);
1110
+ if (record.bridge !== undefined && record.bridgeState !== undefined && record.bridgeState !== "DISCARDED")
1111
+ reusable = undefined;
937
1112
  const last = record;
938
1113
  const end = async () => {
939
1114
  if (record !== last) {
@@ -1020,7 +1195,7 @@ export function createTotalis(options) {
1020
1195
  * words it for an entry).
1021
1196
  */
1022
1197
  function waitForOperation(operationId, signal) {
1023
- const terminal = new Set(["COMMITTED", "REVERTED", "EXPIRED_UNEXECUTED"]);
1198
+ const terminal = terminalOperationStatuses;
1024
1199
  return followSent(stream, async (stop) => unwrap(await client.GET("/v1/me/operations/{operation_id}", { params: { path: { operation_id: operationId } }, signal: stop, fetch: recoveryFetch })).operation, (operation) => terminal.has(operation.status), (event) => event.event_type === "VAULT_BALANCE_CHANGED" ||
1025
1200
  (event.event_type === "OPERATION_UPDATED" && event.payload.operation_id === operationId && terminal.has(event.payload.status)), signal, retry);
1026
1201
  }
@@ -1408,6 +1583,12 @@ export function createTotalis(options) {
1408
1583
  grantVaultAgent,
1409
1584
  revokeVaultAgent,
1410
1585
  vaultAgents,
1586
+ readWalletApproval,
1587
+ signWalletApproval,
1588
+ sendWalletApproval,
1589
+ recoverWalletApproval,
1590
+ approveWallet,
1591
+ revokeWalletApproval,
1411
1592
  /** Render an RFQ's live quotes (entry or cash-out) from the stream; `[]` while the stream is down. */
1412
1593
  watchQuotes,
1413
1594
  /** Issue a personal `ttk_` key; the signer must be the account wallet (embedded, or a wallet-only account's own). */
@@ -1416,5 +1597,5 @@ export function createTotalis(options) {
1416
1597
  close: () => stream.close(),
1417
1598
  };
1418
1599
  }
1419
- export { BalanceUnknownError, EntryError, ExitUnavailableError };
1600
+ export { BalanceUnknownError, EntryError, ExitUnavailableError, WalletApprovalError };
1420
1601
  export { ApiError, NetworkError };
@@ -333,6 +333,49 @@ export type PayoutAuthorization = {
333
333
  };
334
334
  /** USDC TransferWithAuthorization for a Totalis withdrawal payout, under the deployment's USDC domain. */
335
335
  export declare function transferWithAuthorizationTypedData(deployment: UsdcDeployment, payout: PayoutAuthorization): UsdcTypedData<"TransferWithAuthorization">;
336
+ /** A USDC EIP-2612 permit setting the account wallet's approval to WalletAccept (`GET /v1/me/wallet-approval` `spender`) to `value`; 0 revokes it. */
337
+ export type WalletPermit = {
338
+ readonly owner: string;
339
+ readonly spender: string;
340
+ readonly value: string;
341
+ readonly nonce: string;
342
+ readonly deadline: string;
343
+ };
344
+ /** USDC Permit(owner, spender, value, nonce, deadline) under the deployment's USDC domain, for `POST /v1/me/wallet-approval`. */
345
+ export declare function walletPermitTypedData(deployment: UsdcDeployment, permit: WalletPermit): {
346
+ domain: {
347
+ readonly name: "USDC";
348
+ readonly version: "2";
349
+ readonly chainId: bigint;
350
+ readonly verifyingContract: Hex;
351
+ };
352
+ types: {
353
+ Permit: readonly [{
354
+ readonly name: "owner";
355
+ readonly type: "address";
356
+ }, {
357
+ readonly name: "spender";
358
+ readonly type: "address";
359
+ }, {
360
+ readonly name: "value";
361
+ readonly type: "uint256";
362
+ }, {
363
+ readonly name: "nonce";
364
+ readonly type: "uint256";
365
+ }, {
366
+ readonly name: "deadline";
367
+ readonly type: "uint256";
368
+ }];
369
+ };
370
+ primaryType: "Permit";
371
+ message: {
372
+ owner: `0x${string}`;
373
+ spender: `0x${string}`;
374
+ value: bigint;
375
+ nonce: bigint;
376
+ deadline: bigint;
377
+ };
378
+ };
336
379
  /** Any EIP-712 signer. `toTotalisSigner` in `./signer` adapts viem, EIP-1193 and ethers signers. */
337
380
  export type TypedDataSigner = {
338
381
  signTypedData(typedData: TypedData): Promise<Hex>;
@@ -317,6 +317,23 @@ export function transferWithAuthorizationTypedData(deployment, payout) {
317
317
  },
318
318
  };
319
319
  }
320
+ const permitFields = [
321
+ { name: "owner", type: "address" },
322
+ { name: "spender", type: "address" },
323
+ { name: "value", type: "uint256" },
324
+ { name: "nonce", type: "uint256" },
325
+ { name: "deadline", type: "uint256" },
326
+ ];
327
+ /** USDC Permit(owner, spender, value, nonce, deadline) under the deployment's USDC domain, for `POST /v1/me/wallet-approval`. */
328
+ export function walletPermitTypedData(deployment, permit) {
329
+ return {
330
+ domain: usdcDomain(deployment), types: { Permit: permitFields }, primaryType: "Permit",
331
+ message: {
332
+ owner: address(permit.owner), spender: address(permit.spender), value: BigInt(permit.value),
333
+ nonce: BigInt(permit.nonce), deadline: BigInt(permit.deadline),
334
+ },
335
+ };
336
+ }
320
337
  /** Lowercase hex with v in {27, 28}: the venue rejects v = 0/1. Longer ERC-1271 signatures pass through. */
321
338
  export function canonicalSignature(signature) {
322
339
  const lower = signature.toLowerCase();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totalis/hip4-client",
3
- "version": "0.84.1",
3
+ "version": "0.85.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": [