@totalis/hip4-client 0.124.0 → 0.126.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +389 -0
  2. package/README.md +9 -5
  3. package/dist/api-keys.d.ts +21 -2
  4. package/dist/api-keys.js +12 -10
  5. package/dist/audience-contract.d.ts +1 -2
  6. package/dist/client.d.ts +1 -1
  7. package/dist/client.js +1 -1
  8. package/dist/flow-errors.d.ts +1 -1
  9. package/dist/flow-errors.js +1 -1
  10. package/dist/generated/account-read.d.ts +150 -126
  11. package/dist/generated/api-keys.d.ts +19 -10
  12. package/dist/generated/browse.d.ts +12 -12
  13. package/dist/generated/client.d.ts +5 -2
  14. package/dist/generated/errors.d.ts +15 -8
  15. package/dist/generated/errors.js +47 -35
  16. package/dist/generated/maker.d.ts +3 -4
  17. package/dist/generated/openapi.d.ts +833 -893
  18. package/dist/generated/realtime.d.ts +66 -93
  19. package/dist/generated/vault-abi.d.ts +57 -0
  20. package/dist/generated/vault-abi.js +77 -0
  21. package/dist/generated/version.d.ts +16 -16
  22. package/dist/generated/version.js +20 -18
  23. package/dist/maker.d.ts +134 -54
  24. package/dist/maker.js +257 -147
  25. package/dist/money.d.ts +8 -6
  26. package/dist/money.js +7 -7
  27. package/dist/partner.d.ts +2 -0
  28. package/dist/partner.js +2 -1
  29. package/dist/request.d.ts +11 -2
  30. package/dist/request.js +7 -2
  31. package/dist/totalis.d.ts +147 -232
  32. package/dist/totalis.js +290 -269
  33. package/dist/typed-data.d.ts +6 -0
  34. package/dist/typed-data.js +8 -0
  35. package/dist/ui.d.ts +6 -10
  36. package/dist/ui.js +15 -13
  37. package/dist/vault-reads.d.ts +46 -0
  38. package/dist/vault-reads.js +72 -0
  39. package/examples/browser-wallet.mjs +1 -1
  40. package/examples/node-bot.mjs +15 -12
  41. package/package.json +1 -1
package/dist/totalis.js CHANGED
@@ -4,7 +4,7 @@ import { audienceClient, headerRecord } from "./base.js";
4
4
  import { bridgeAction, bridgeGasBuffer, hyperliquidExchange, hyperliquidNetwork, readCoreCash, settleHypercore, signSendAsset, usdcUnits, } from "./hypercore.js";
5
5
  import { BalanceUnknownError, EntryError, ExitUnavailableError, normalizeError, WalletApprovalError } from "./flow-errors.js";
6
6
  import { comboAllowance, offeredCore, spendableCash } from "./money.js";
7
- import { ApiError, backoffDelay, envelope, NetworkError, randomBytes32, resendable, retryingFetch, sendOnce, singleFetch, sleep, unwrap, uuidv7 } from "./request.js";
7
+ import { ApiError, backoffDelay, NetworkError, randomBytes32, resendable, retryingFetch, rfqLegsInOrder, sendOnce, singleFetch, sleep, unwrap, uuidv7 } from "./request.js";
8
8
  import { abortReason, anySignal, timeoutSignal } from "./runtime.js";
9
9
  import { toTotalisSigner } from "./signer.js";
10
10
  import { TotalisStream } from "./stream.js";
@@ -26,17 +26,17 @@ function bridgedCash(signed) {
26
26
  }
27
27
  /**
28
28
  * An entry's `EntryFailure`; undefined unless its operation ended with a
29
- * `failure_reason`. Pass the record as `onRecord` last handed it back (or
30
- * `openPosition`'s `record`): only `LANDED` shows the Core cash moved before
31
- * `fund_by`. `PROCESSED` only says the nonce is spent, which a refused or
32
- * expired send also does, so it does not show the move. For a `"approval"`
33
- * entry pass its acceptance too (`outcome`): `INSUFFICIENT_APPROVAL` when the
34
- * wallet's approval to WalletAccept was below the shortfall.
29
+ * `reason`. Pass the record as `onRecord` last handed it back (or
30
+ * `openPosition`'s `record`): only `LANDED` shows the Core cash moved in
31
+ * time. `PROCESSED` only says the nonce is spent, which a refused or
32
+ * expired send also does, so it does not show the move. For an entry the
33
+ * wallet funds pass its acceptance too (`outcome`): `INSUFFICIENT_APPROVAL`
34
+ * when the wallet's approval to WalletAccept was below the shortfall.
35
35
  */
36
36
  export function entryFailure(record, operation, acceptance) {
37
- if (operation.failure_reason !== "INSUFFICIENT_CASH")
38
- return operation.failure_reason;
39
- if (acceptance !== undefined && acceptance.status !== "NOT_ADMITTED" && acceptance.funding_failure_reason === "INSUFFICIENT_APPROVAL")
37
+ if (operation.reason !== "INSUFFICIENT_CASH")
38
+ return operation.reason;
39
+ if (acceptance !== undefined && acceptance.status !== "NOT_ADMITTED" && acceptance.reason === "INSUFFICIENT_APPROVAL")
40
40
  return "INSUFFICIENT_APPROVAL";
41
41
  if (record.bridge === undefined || "version" in record && record.bridgeState === "LANDED")
42
42
  return "INSUFFICIENT_CASH";
@@ -44,46 +44,25 @@ export function entryFailure(record, operation, acceptance) {
44
44
  }
45
45
  const answered = { ok: "LANDED", processed: "PROCESSED", refused: "REFUSED" };
46
46
  const defaultTransport = hyperliquidExchange();
47
- /** The acceptance's `fund_by` in ms: until then a WALLET-funded entry may move its Core cash. */
48
- function fundBy(outcome) {
49
- if (outcome.status === "NOT_ADMITTED" || outcome.fund_by === undefined)
50
- return undefined;
51
- const ms = Date.parse(outcome.fund_by);
52
- return Number.isNaN(ms) ? undefined : ms;
53
- }
54
47
  /**
55
- * The latest the venue clock can read, from responses' `server_time`. The
56
- * venue stamps a response after its request left, so now on the venue is at
57
- * most that stamp plus the time since sending. A stamp alone, judged at
58
- * receipt, reads early by the response's delay. Elapsed time is the larger of
59
- * the monotonic clock's (which may pause while the device sleeps) and the
60
- * wall clock's (which may step back). `Infinity` before any response.
48
+ * A flow's clock: milliseconds since it began, the larger of the monotonic
49
+ * clock's (which may pause while the device sleeps) and the wall clock's
50
+ * (which may step back).
61
51
  */
62
- function venueClock() {
63
- const samples = [];
64
- return {
65
- /** Call as a request leaves; call the result with its response's `server_time`. */
66
- sending() {
67
- const mono = performance.now();
68
- const wall = Date.now();
69
- return (serverTime) => {
70
- const server = Date.parse(serverTime);
71
- if (!Number.isNaN(server))
72
- samples.push({ server, mono, wall });
73
- };
74
- },
75
- latest() {
76
- const mono = performance.now();
77
- const wall = Date.now();
78
- return Math.min(...samples.map((sample) => sample.server + Math.max(mono - sample.mono, wall - sample.wall)));
79
- },
80
- };
81
- }
82
- /** When an entry quote stops being acceptable, in ms on the venue clock: its `accept_before`. A quote without a readable one never is. */
83
- export function acceptBefore(quote) {
84
- const ms = Date.parse(quote.accept_before);
85
- return Number.isNaN(ms) ? -Infinity : ms;
52
+ function flowClock() {
53
+ const mono = performance.now();
54
+ const wall = Date.now();
55
+ return { now: () => Math.max(performance.now() - mono, Date.now() - wall) };
86
56
  }
57
+ /**
58
+ * How long after sending an accept its bridge from HyperCore may still go.
59
+ * An accept that draws the wallet waits at least six seconds from its arrival
60
+ * for wallet USDC still landing, and it arrives after it was sent, so a bridge
61
+ * sent within four seconds of the send keeps two to land, however long the
62
+ * maker or the answer took. A bridge never goes later: that cash would reach
63
+ * the wallet after the trade gave up on it.
64
+ */
65
+ export const fundWindowMs = 4_000;
87
66
  /** How often a pending acceptance with an unsent bridge is read, and how long past the maker's deadline. */
88
67
  const watchMs = 250;
89
68
  const watchGraceMs = 2000;
@@ -94,29 +73,24 @@ const minimumDeposit = 1000000n;
94
73
  * best of them win instead of the fastest.
95
74
  */
96
75
  const defaultCollectMs = 1_000;
97
- const defaultRefreshMs = 10_000;
98
76
  const defaultMaxAttempts = 4;
99
- /** Accept refusals that mean the chosen quote went away before the accept, not that the position cannot open. */
100
- const refreshCodes = new Set(["QUOTE_EXPIRED", "QUOTE_REPLACED"]);
77
+ /** Accept refusals that mean the chosen quote left the book just before the accept (its maker or the venue replaced it), not that the position cannot open. */
78
+ const goneCodes = new Set(["QUOTE_EXPIRED", "QUOTE_REPLACED"]);
101
79
  const passedOn = new Set(["DECLINED", "TIMED_OUT"]);
102
80
  const timerSlackMs = 250;
103
81
  function termsOf(quote) {
104
- return quote.kind === "ENTRY" ? quote.entry : quote.sell_back;
82
+ return quote.kind === "ENTRY" ? quote.signing.entry : quote.signing.sell_back;
105
83
  }
106
- /** The highest payout among quotes still before their `accept_before` (ties go to the earliest). */
84
+ /** The highest payout (ties go to the earliest). */
107
85
  export function bestQuote() {
108
- return (quotes, now) => quotes
109
- .filter((quote) => acceptBefore(quote) > now)
110
- .reduce((best, quote) => best === undefined || BigInt(quote.entry.payout) > BigInt(best.entry.payout) ? quote : best, undefined);
86
+ return (quotes) => quotes
87
+ .reduce((best, quote) => best === undefined || BigInt(quote.payout) > BigInt(best.payout) ? quote : best, undefined);
111
88
  }
112
- /**
113
- * The highest price with at least `minLifeSeconds` left (execution needs 20 s
114
- * after confirmation) and, given `minPrice` in USDC base units, no lower than it.
115
- */
116
- export function bestBid(minLifeSeconds = 25, minPrice) {
117
- return (bids, now) => bids
118
- .filter((bid) => Number(termsOf(bid).expiry) * 1000 - now >= minLifeSeconds * 1000 && (minPrice === undefined || BigInt(termsOf(bid).price) >= minPrice))
119
- .reduce((best, bid) => best === undefined || BigInt(termsOf(bid).price) > BigInt(termsOf(best).price) ? bid : best, undefined);
89
+ /** The highest price and, given `minPrice` in USDC base units, no lower than it. */
90
+ export function bestBid(minPrice) {
91
+ return (bids) => bids
92
+ .filter((bid) => minPrice === undefined || BigInt(bid.price) >= minPrice)
93
+ .reduce((best, bid) => best === undefined || BigInt(bid.price) > BigInt(best.price) ? bid : best, undefined);
120
94
  }
121
95
  /** ABI calldata for a call whose arguments are all static words (addresses and integers). */
122
96
  function callData(signature, ...words) {
@@ -128,7 +102,6 @@ const idempotency = (key = uuidv7()) => ({ "Idempotency-Key": key });
128
102
  export const terminalOperationStatuses = new Set(["COMMITTED", "REVERTED", "EXPIRED_UNEXECUTED"]);
129
103
  /** How long a signed permit may wait to be submitted; not how long the approval lasts. */
130
104
  const permitLifeSeconds = 30 * 60;
131
- const approvalFunding = { kind: "WALLET_APPROVAL" };
132
105
  function withTimeout(signal, ms) {
133
106
  return signal === undefined ? timeoutSignal(ms) : anySignal([signal, timeoutSignal(ms)]);
134
107
  }
@@ -264,10 +237,16 @@ function followUntil(stream, read, done, wake, recheckMs, signal, retry, command
264
237
  // An RFQ that ends drops its quotes too, so rendered quotes empty with it.
265
238
  const rfqEnded = (event) => event.event_type === "RFQ_CANCELLED" || event.event_type === "RFQ_FAILED" || event.event_type === "RFQ_ACCEPTED" || event.event_type === "RFQ_DECLINED";
266
239
  const quotesChanged = (rfqId) => (event) => (event.event_type === "QUOTE_CREATED" || event.event_type === "QUOTE_REMOVED" || rfqEnded(event)) && event.payload.rfq_id === rfqId;
267
- /** The venue refuses to accept a cash-out quote with this much signed life left or less. */
268
- const cashoutAcceptLifeMs = 22_000;
269
- /** When the quote stops being acceptable, in ms on the venue clock. */
270
- const acceptableUntil = (offer) => offer.kind === "ENTRY" ? acceptBefore(offer) : Number(termsOf(offer).expiry) * 1000 - cashoutAcceptLifeMs;
240
+ /**
241
+ * Until when, in ms on the venue clock, the venue lists a quote: an entry
242
+ * until 14 s before its signed expiry (when it stops being acceptable), a bid
243
+ * until 22 s before. A quote the venue renews is replaced before then; one it
244
+ * stops listing sends no event.
245
+ */
246
+ const listedUntil = (offer) => {
247
+ const until = Number(termsOf(offer).expiry) * 1000 - (offer.kind === "ENTRY" ? 14_000 : 22_000);
248
+ return Number.isNaN(until) ? -Infinity : until;
249
+ };
271
250
  /**
272
251
  * The account's live quotes, kept from the stream: the snapshot's `quotes`,
273
252
  * then QUOTE_CREATED and QUOTE_REMOVED. The quotes GET is read only for an RFQ
@@ -311,9 +290,9 @@ function streamQuotes(stream, read) {
311
290
  });
312
291
  return {
313
292
  /**
314
- * The acceptable quotes on an RFQ, oldest first. Expiry sends no event, so
315
- * quotes past their accept life are dropped here. After a truncated
316
- * snapshot the RFQ's quotes are read once from the quotes GET.
293
+ * The quotes on an RFQ's book, oldest first, as the venue lists them.
294
+ * After a truncated snapshot the RFQ's quotes are read once from the
295
+ * quotes GET.
317
296
  */
318
297
  async offers(rfqId, signal) {
319
298
  if (truncated && !recovered.has(rfqId)) {
@@ -324,7 +303,7 @@ function streamQuotes(stream, read) {
324
303
  const book = books.get(rfqId);
325
304
  const now = stream.serverNow();
326
305
  for (const [quoteId, offer] of book ?? [])
327
- if (acceptableUntil(offer) <= now)
306
+ if (listedUntil(offer) <= now)
328
307
  book.delete(quoteId);
329
308
  return [...(book?.values() ?? [])].sort((a, b) => a.sequence - b.sequence);
330
309
  },
@@ -341,7 +320,7 @@ export function createTotalis(options) {
341
320
  const keys = createApiKeyClient(environment, { ...clientOptions, accessToken });
342
321
  const stream = new TotalisStream({
343
322
  environment, accessToken, headers: headerRecord(clientOptions.headers), ...streamOptions,
344
- subscription: { ...streamOptions?.subscription, type: "account" },
323
+ subscription: { ...streamOptions?.subscription, kind: "account" },
345
324
  ...(clientOptions.baseUrl === undefined ? {} : { baseUrl: clientOptions.baseUrl }),
346
325
  ...(streamBaseUrl === undefined ? {} : { streamBaseUrl }),
347
326
  });
@@ -381,7 +360,7 @@ export function createTotalis(options) {
381
360
  throw error;
382
361
  }));
383
362
  async function cancelRfq(rfqId) {
384
- await client.POST("/v1/rfqs/{rfq_id}/cancel", { params: { path: { rfq_id: rfqId }, header: idempotency() } }).catch(() => undefined);
363
+ await client.POST("/v1/rfqs/{rfq_id}/cancel", { params: { path: { rfq_id: rfqId } } }).catch(() => undefined);
385
364
  }
386
365
  const book = streamQuotes(stream, async (rfqId, signal) => unwrap(await client.GET("/v1/rfqs/{rfq_id}/quotes", { params: { path: { rfq_id: rfqId } }, ...(signal === undefined ? {} : { signal, fetch: recoveryFetch }) })).quotes);
387
366
  async function createRfq(command) {
@@ -390,23 +369,22 @@ export function createTotalis(options) {
390
369
  }
391
370
  async function createCashout(positionId) {
392
371
  const header = idempotency();
393
- return (await sendOnce(() => client.POST("/v1/me/positions/{position_id}/cashout", { params: { path: { position_id: positionId }, header }, body: {} }))).rfq_id;
372
+ return (await sendOnce(() => client.POST("/v1/me/positions/{position_id}/cashout", { params: { path: { position_id: positionId }, header } }))).rfq_id;
394
373
  }
395
374
  /** The live quotes rendered for a UI: `[]` while the stream is not live (stale). */
396
375
  function watchQuotes(rfqId, listener) {
397
376
  let stopped = false;
398
- let expiry;
377
+ let unlisted;
399
378
  const refresh = async () => {
400
379
  const offers = stream.status === "live" ? await book.offers(rfqId) : [];
401
380
  if (stopped)
402
381
  return;
403
- const now = stream.serverNow();
404
- listener(stream.status === "live" ? offers : [], now);
405
- // Re-render when the soonest quote stops being acceptable; that sends no event.
406
- clearTimeout(expiry);
407
- const next = Math.min(...offers.map(acceptableUntil));
382
+ listener(stream.status === "live" ? offers : []);
383
+ // The venue stops listing a quote it did not renew without an event.
384
+ clearTimeout(unlisted);
385
+ const next = Math.min(...offers.map(listedUntil));
408
386
  if (Number.isFinite(next))
409
- expiry = setTimeout(() => void refresh().catch(() => undefined), Math.max(0, next - now) + 1);
387
+ unlisted = setTimeout(() => void refresh().catch(() => undefined), Math.max(0, next - stream.serverNow()) + 1);
410
388
  };
411
389
  const offs = [
412
390
  stream.on("event", (event) => void (quotesChanged(rfqId)(event) && refresh().catch(() => undefined))),
@@ -416,7 +394,7 @@ export function createTotalis(options) {
416
394
  void refresh().catch(() => undefined);
417
395
  return () => {
418
396
  stopped = true;
419
- clearTimeout(expiry);
397
+ clearTimeout(unlisted);
420
398
  for (const off of offs)
421
399
  off();
422
400
  };
@@ -424,23 +402,19 @@ export function createTotalis(options) {
424
402
  /**
425
403
  * The quote `choose` picks once quotes have had `collectMs` to arrive after
426
404
  * the first one it would take, re-chosen on every change to the RFQ's quotes
427
- * and when the window ends. The window ends sooner when waiting would lose
428
- * the quote `choose` picks now (it ages past `choose`'s rules or the venue's
429
- * accept floor) or run past `timeoutMs`, so collecting never ends worse.
405
+ * and when the window ends. The window ends sooner when the venue would stop
406
+ * listing that quote first, and never runs past `timeoutMs`.
430
407
  */
431
408
  function awaitOffer(rfqId, eligible, choose, collectMs, timeoutMs, signal) {
432
409
  const giveUpAt = performance.now() + timeoutMs - timerSlackMs;
433
410
  let firstAt;
434
411
  const pick = async (stop) => {
435
- const offers = (await book.offers(rfqId, stop)).filter(eligible);
436
- const now = stream.serverNow();
437
- const offer = choose(offers, now);
412
+ const offer = choose((await book.offers(rfqId, stop)).filter(eligible));
438
413
  if (offer === undefined)
439
414
  return { offer, waitMs: undefined };
440
415
  firstAt ??= performance.now();
441
416
  const waitMs = Math.max(Math.min(firstAt + collectMs, giveUpAt) - performance.now(), 0);
442
- const later = offers.filter((candidate) => acceptableUntil(candidate) > now + waitMs);
443
- return { offer, waitMs: waitMs === 0 || choose(later, now + waitMs)?.quote_id !== offer.quote_id ? 0 : waitMs };
417
+ return { offer, waitMs: listedUntil(offer) - stream.serverNow() <= waitMs ? 0 : waitMs };
444
418
  };
445
419
  return followUntil(stream, pick, (picked) => picked.offer !== undefined && picked.waitMs === 0, quotesChanged(rfqId), (picked) => picked.waitMs, withTimeout(signal, timeoutMs), retry)
446
420
  .then(({ offer }) => offer);
@@ -449,7 +423,7 @@ export function createTotalis(options) {
449
423
  async function readSpendableCash(signal) {
450
424
  return spendableCash(unwrap(await client.GET("/v1/me/balances", signal === undefined ? {} : { signal })));
451
425
  }
452
- /** A fresh `GET /v1/me/account-value`: what the account holds at Totalis, every amount read at one block; all null when `state` is `UNKNOWN`. */
426
+ /** A fresh `GET /v1/me/account-value`: what the account holds at Totalis, every amount read at one block; all null when `freshness` is `UNKNOWN`. */
453
427
  async function readAccountValue(signal) {
454
428
  return unwrap(await client.GET("/v1/me/account-value", signal === undefined ? {} : { signal }));
455
429
  }
@@ -474,10 +448,12 @@ export function createTotalis(options) {
474
448
  };
475
449
  }
476
450
  /** The wallet's USDC authorization of `value` into the vault; the venue fills `account` and `from` with the same wallet. */
451
+ /** The body names the signed ReceiveWithAuthorization's `value` `amount`. */
477
452
  async function depositAuthorization(chain, account, value) {
478
- const authorization = { value: value.toString(), valid_after: String(now() - 60), valid_before: String(now() + 600), salt: randomBytes32() };
479
- const authorization_signature = await (await requireSigner()).signTypedData(receiveWithAuthorizationTypedData(chain, { account, from: account, ...authorization }));
480
- return { kind: "WALLET", ...authorization, authorization_signature };
453
+ const amount = value.toString();
454
+ const authorization = { valid_after: String(now() - 60), valid_before: String(now() + 600), salt: randomBytes32() };
455
+ const authorization_signature = await (await requireSigner()).signTypedData(receiveWithAuthorizationTypedData(chain, { account, from: account, value: amount, ...authorization }));
456
+ return { amount, ...authorization, authorization_signature };
481
457
  }
482
458
  /** The account wallet's USDC approval to WalletAccept and its permit nonce, read at one block (`WalletApproval`). */
483
459
  async function readWalletApproval(signal) {
@@ -516,7 +492,7 @@ export function createTotalis(options) {
516
492
  const signature = await signer.signTypedData(walletPermitTypedData(chain, permit));
517
493
  return {
518
494
  kind: "WALLET_APPROVAL", version: 1, requestId: request.requestId ?? uuidv7(), account, chainId: chain.chain_id,
519
- vault: address(approval.vault.toLowerCase()), token: address(approval.token.toLowerCase()), spender, body: { value: permit.value, nonce: permit.nonce, deadline: permit.deadline, signature },
495
+ vault: address(approval.vault.toLowerCase()), token: address(approval.token.toLowerCase()), spender, body: { amount: permit.value, nonce: permit.nonce, deadline: permit.deadline, signature },
520
496
  };
521
497
  }
522
498
  /**
@@ -532,7 +508,7 @@ export function createTotalis(options) {
532
508
  }
533
509
  return sendOnce(() => client.POST("/v1/me/wallet-approval", { params: { header: idempotency(signed.requestId) }, body: signed.body }));
534
510
  }
535
- /** Follow a sent permit until its operation ends: resolves it COMMITTED, else throws `WalletApprovalError` with its `failure_reason`. */
511
+ /** Follow a sent permit until its operation ends: resolves it COMMITTED, else throws `WalletApprovalError` with its `reason`. */
536
512
  async function settleWalletApproval(signed, sent, signal) {
537
513
  let request = sent;
538
514
  if (!terminalOperationStatuses.has(request.status)) {
@@ -541,8 +517,8 @@ export function createTotalis(options) {
541
517
  }
542
518
  if (request.status === "COMMITTED")
543
519
  return request;
544
- const reason = request.failure_reason ?? "PERMIT_REVERTED";
545
- throw new WalletApprovalError(reason, `the permit setting the approval to ${request.value} changed nothing (${reason})`);
520
+ const reason = request.reason ?? "PERMIT_REVERTED";
521
+ throw new WalletApprovalError(reason, `the permit setting the approval to ${request.amount} changed nothing (${reason})`);
546
522
  }
547
523
  /**
548
524
  * Finish a stored permit after a lost answer or a restart, signing nothing:
@@ -580,7 +556,7 @@ export function createTotalis(options) {
580
556
  throw new WalletApprovalError("INSUFFICIENT_APPROVAL", `the approval left, ${approved}, is below the ${need} this entry needs; approveWallet first`);
581
557
  }
582
558
  /**
583
- * Make the approval left cover `need` for a `"approval"` entry: a landed
559
+ * Make the approval left cover `need` for an entry the wallet funds: a landed
584
560
  * approval that covers it is reused; otherwise a permit for `approvalValue`
585
561
  * (default the larger of `defaultWalletApproval` and `need`) is signed,
586
562
  * handed to `onApproval`, sent and followed until it lands. With
@@ -597,7 +573,7 @@ export function createTotalis(options) {
597
573
  return BigInt(approval.approved) >= need;
598
574
  };
599
575
  const known = request.fresh === true ? undefined : request.approval;
600
- if (known !== undefined && "signed" in known && BigInt(known.landed.value) >= need)
576
+ if (known !== undefined && "signed" in known && BigInt(known.landed.amount) >= need)
601
577
  return;
602
578
  const approval = known !== undefined && !("signed" in known) ? known : await readWalletApproval(request.signal);
603
579
  if (covered(approval))
@@ -623,19 +599,20 @@ export function createTotalis(options) {
623
599
  * the maker, read once more after its deadline (the read retires an
624
600
  * unanswered acceptance), unless `wait` is false. While `watching` the
625
601
  * deadline, it reads every `watchMs` instead, so an early answer is seen
626
- * before its `fund_by` passes. `absent` handles an accept the venue never
602
+ * while its bridge may still go. `absent` handles an accept the venue never
627
603
  * received.
628
604
  */
629
- async function settleAcceptance(lost, read, absent, wait = true, watching) {
605
+ async function settleAcceptance(lost, read, absent, clock, wait = true, watch = false) {
630
606
  for (;;) {
631
607
  // If the recovery read is lost too, surface the original command's error and its resend().
632
608
  const acceptance = await read().catch((error) => Promise.reject(error instanceof NetworkError ? lost ?? error : error));
633
609
  if (acceptance === "absent")
634
610
  return absent();
635
- if (!wait || acceptance.status !== "PENDING_CONFIRM" || acceptance.deadline === undefined)
611
+ if (!wait || acceptance.status !== "PENDING_CONFIRM" || acceptance.confirm_within_ms === undefined)
636
612
  return acceptance;
637
- const deadline = Date.parse(acceptance.deadline);
638
- await sleep(watching?.(deadline) ? watchMs : Math.max(0, deadline - Date.now()) + 1000);
613
+ // Reading again late is harmless, so the maker's time counts from the answer's arrival.
614
+ const until = clock.now() + acceptance.confirm_within_ms;
615
+ await sleep(watch && clock.now() < until + watchGraceMs ? watchMs : Math.max(0, until - clock.now()) + 1000);
639
616
  }
640
617
  }
641
618
  /** A read whose 404 means the resource does not exist (yet). */
@@ -649,25 +626,21 @@ export function createTotalis(options) {
649
626
  * taker's. `STATE_CONFLICT` leaves the RFQ open: the acceptance is read
650
627
  * once more, and still absent throws that error rather than `NOT_ADMITTED`.
651
628
  * With `watch`, a pending acceptance is read every `watchMs` until its
652
- * deadline plus `watchGraceMs` on the venue clock.
629
+ * `confirm_within_ms` plus `watchGraceMs` pass.
653
630
  */
654
631
  function fenceAcceptance(signed, clock, lost, wait = true, watch = false) {
655
632
  const { rfqId, quoteId } = signed;
656
- const watching = watch ? (deadline) => clock.latest() < deadline + watchGraceMs : undefined;
657
633
  const read = async () => {
658
- const stamped = clock.sending();
659
634
  const acceptance = orAbsent(await client.GET("/v1/quotes/{quote_id}/acceptance", { params: { path: { quote_id: quoteId } } }));
660
635
  if (acceptance === "absent")
661
636
  return acceptance;
662
637
  checkEcho(signed, acceptance, false);
663
- stamped(acceptance.server_time);
664
638
  return acceptance;
665
639
  };
666
640
  return settleAcceptance(lost, read, async () => {
667
- const header = idempotency();
668
641
  let open;
669
642
  try {
670
- await sendOnce(() => client.POST("/v1/rfqs/{rfq_id}/cancel", { params: { path: { rfq_id: rfqId }, header } }));
643
+ await sendOnce(() => client.POST("/v1/rfqs/{rfq_id}/cancel", { params: { path: { rfq_id: rfqId } } }));
671
644
  }
672
645
  catch (error) {
673
646
  if (error instanceof NetworkError)
@@ -682,17 +655,18 @@ export function createTotalis(options) {
682
655
  if (open !== undefined)
683
656
  throw open;
684
657
  return { status: "NOT_ADMITTED", quote_id: quoteId, rfq_id: rfqId };
685
- }, wait, watching);
686
- }, wait, watching);
658
+ }, clock, wait, watch);
659
+ }, clock, wait, watch);
687
660
  }
688
661
  /**
689
- * An acceptance must answer for this record's RFQ and quote; a direct accept
690
- * answer must also echo its acceptance ID. A read answers for the quote
691
- * whichever acceptance took it, as a quote has at most one.
662
+ * A read of the acceptance must answer for this record's RFQ and quote,
663
+ * whichever acceptance took it, as a quote has at most one. A direct accept
664
+ * answer names neither, but must echo the record's acceptance ID.
692
665
  */
693
666
  function checkEcho(signed, acceptance, direct) {
694
- if (acceptance.rfq_id !== signed.rfqId || acceptance.quote_id.toLowerCase() !== signed.quoteId.toLowerCase() || (direct && acceptance.acceptance_id !== signed.acceptanceId)) {
695
- throw new Error(`the venue answered for acceptance ${acceptance.acceptance_id} on quote ${acceptance.quote_id}, not this record's`);
667
+ const elsewhere = "quote_id" in acceptance && (acceptance.rfq_id !== signed.rfqId || acceptance.quote_id.toLowerCase() !== signed.quoteId.toLowerCase());
668
+ if (elsewhere || (direct && acceptance.acceptance_id !== signed.acceptanceId)) {
669
+ throw new Error(`the venue answered for acceptance ${acceptance.acceptance_id}${"quote_id" in acceptance ? ` on quote ${acceptance.quote_id}` : ""}, not this record's`);
696
670
  }
697
671
  }
698
672
  const resultOf = (signed, outcome, bridge) => {
@@ -704,7 +678,7 @@ export function createTotalis(options) {
704
678
  };
705
679
  return bridge.bridged?.() === undefined ? result : Object.defineProperty(result, "bridged", { get: bridge.bridged, enumerable: true });
706
680
  };
707
- /** A bridge this SDK signed and never sent, which may go only before `fund_by`. */
681
+ /** A bridge this SDK signed and never sent, which may go only within `fundWindowMs` of the accept. */
708
682
  const bridgeUnsent = (signed) => signed.kind === "ENTRY" && "version" in signed && signed.bridge !== undefined && signed.bridgeState === undefined;
709
683
  /** Record a never-sent bridge as discarded. Recovery derives the discard from the acceptance again, so a failed save loses nothing. */
710
684
  async function discardBridge(signed, onRecord) {
@@ -722,14 +696,16 @@ export function createTotalis(options) {
722
696
  }
723
697
  /**
724
698
  * Move an entry's bridge on from where its acceptance stands. Only this
725
- * record's own `ACCEPTED` acceptance, while `clock` proves its `fund_by`
726
- * is still ahead, sends it: first the record says `SENT`, then the same
727
- * bytes go out, resent while unanswered until `fund_by`. A bridge never sent is discarded
728
- * once the acceptance is answered any other way, another record's
729
- * acceptance took the quote, or `fund_by` passed before the first send; one
730
- * sent without an answer stays `SENT`. A legacy record is only read.
699
+ * record's own `ACCEPTED` acceptance, while `clock` is before `until`
700
+ * (`fundWindowMs` after this flow sent the accept), sends it: first the
701
+ * record says `SENT`, then the same bytes go out, resent while unanswered
702
+ * until `until`. A bridge never sent is discarded once the acceptance is
703
+ * answered any other way, another record's acceptance took the quote, or
704
+ * `until` passed before the first send, or is unknown because this flow sent
705
+ * no accept; one sent without an answer stays `SENT`. A legacy record is
706
+ * only read.
731
707
  */
732
- async function moveBridge(signed, outcome, clock, options) {
708
+ async function moveBridge(signed, outcome, clock, window, options) {
733
709
  if (signed.kind !== "ENTRY" || signed.bridge === undefined)
734
710
  return {};
735
711
  if (!("version" in signed))
@@ -740,8 +716,8 @@ export function createTotalis(options) {
740
716
  const ours = outcome.status === "NOT_ADMITTED" || outcome.acceptance_id === signed.acceptanceId;
741
717
  if (!ours && bridgeState === "SENT")
742
718
  return { bridged: () => bridgedCash(signed) };
743
- const until = ours && outcome.status === "ACCEPTED" ? fundBy(outcome) : undefined;
744
- if (until === undefined || clock.latest() >= until) {
719
+ const until = ours && outcome.status === "ACCEPTED" ? window : undefined;
720
+ if (until === undefined || clock.now() >= until) {
745
721
  if (ours && outcome.status === "PENDING_CONFIRM")
746
722
  return {};
747
723
  await discardBridge(signed, options.onRecord);
@@ -757,7 +733,7 @@ export function createTotalis(options) {
757
733
  unsent.catch(() => undefined);
758
734
  return { bridging: unsent };
759
735
  }
760
- if (clock.latest() >= until) {
736
+ if (clock.now() >= until) {
761
737
  await saveDiscard(signed, options.onRecord);
762
738
  return {};
763
739
  }
@@ -765,7 +741,7 @@ export function createTotalis(options) {
765
741
  const transport = options.transport ?? defaultTransport;
766
742
  let attempted = false;
767
743
  let latest = sent;
768
- const bridging = settleHypercore(bridge, { transport: (action, signal) => { attempted = true; return transport(action, signal); }, deadline: until, now: clock.latest })
744
+ const bridging = settleHypercore(bridge, { transport: (action, signal) => { attempted = true; return transport(action, signal); }, deadline: until, now: clock.now })
769
745
  .then(async (answer) => {
770
746
  if (answer.kind !== "unknown") {
771
747
  latest = { ...sent, bridgeState: answered[answer.kind] };
@@ -831,15 +807,14 @@ export function createTotalis(options) {
831
807
  })) : undefined;
832
808
  }
833
809
  /**
834
- * Plan and sign an entry's funding before choosing its quote: the wallet's
835
- * USDC authorization and any bridge from `core`, planned from `cash` or a
836
- * fresh balances read as `signEntry` plans them. Neither names a quote, so
837
- * once one is chosen `signEntry({ quote, prepared })` signs only the quote
838
- * and the accept can go straight out. With `funding: "approval"` no USDC
839
- * authorization is signed: the shortfall comes from the wallet's approval
840
- * to WalletAccept, and when the approval left is short a permit is signed,
841
- * handed to `onApproval` to persist, and followed until it lands, so this
842
- * resolves only with an approval that covered the shortfall when read.
810
+ * Ready an entry's funding before choosing its quote: the wallet's part and
811
+ * any bridge from `core`, planned from `cash` or a fresh balances read as
812
+ * `signEntry` plans them. Neither names a quote, so once one is chosen
813
+ * `signEntry({ quote, prepared })` signs only the quote and the accept can
814
+ * go straight out. The venue draws the wallet's part from the wallet's
815
+ * approval to WalletAccept; when the approval left is short a permit is
816
+ * signed, handed to `onApproval` to persist, and followed until it lands, so
817
+ * this resolves only with an approval that covered the shortfall when read.
843
818
  * The approval is read beside the bridge signature, unless `approval`
844
819
  * passes one just read or a permit request that just landed.
845
820
  */
@@ -852,36 +827,34 @@ export function createTotalis(options) {
852
827
  const plan = planEntry(stake, core, request.cash ?? await readSpendableCash(request.signal));
853
828
  // A bridge can't be undone, so with one the approval is read fresh beside
854
829
  // its signature (no added wait), whatever the caller passed.
855
- const [bridge, funding] = await Promise.all([
830
+ const [bridge] = await Promise.all([
856
831
  signBridge(signer, chain, plan.bridge, request),
857
- plan.wallet <= 0n ? undefined
858
- : request.funding === "approval" ? ensureApproval(plan.wallet, { ...request, fresh: plan.bridge > 0n }).then(() => approvalFunding)
859
- : depositAuthorization(chain, account, plan.wallet),
832
+ plan.wallet > 0n ? ensureApproval(plan.wallet, { ...request, fresh: plan.bridge > 0n }) : undefined,
860
833
  ]);
861
- return { stake: stake.toString(), ...scope, ...(funding === undefined ? {} : { funding }), ...(bridge === undefined ? {} : { bridge }) };
834
+ return { stake: stake.toString(), ...scope, ...(bridge === undefined ? {} : { bridge }) };
862
835
  }
863
- async function signEntryWith(request, funding, route = "wallet") {
836
+ async function signEntryWith(request) {
864
837
  const { quote, cash, prepared } = request;
865
- const { signer, vaultSigner, account, chain, scope } = await recordScope();
866
- if (quote.entry.taker.toLowerCase() !== account)
838
+ const { signer, vaultSigner, chain, scope } = await recordScope();
839
+ if (quote.signing.entry.taker.toLowerCase() !== scope.account)
867
840
  throw new Error("the quote is for another taker");
868
- const record = (taker_signature, fundingCommand, bridge) => ({
869
- kind: "ENTRY", version: 2, acceptanceId: request.acceptanceId ?? uuidv7(), rfqId: quote.rfq_id, quoteId: quote.quote_id, ...scope, expiry: quote.entry.expiry,
870
- command: { taker_signature, ...(fundingCommand === undefined ? {} : { funding: fundingCommand }) },
841
+ const record = (taker_signature, bridge) => ({
842
+ kind: "ENTRY", version: 2, acceptanceId: request.acceptanceId ?? uuidv7(), rfqId: quote.rfq_id, quoteId: quote.quote_id, ...scope, expiry: quote.signing.entry.expiry,
843
+ command: { taker_signature },
871
844
  ...(bridge === undefined ? {} : { bridge }),
872
845
  });
873
846
  if (prepared !== undefined) {
874
- if (prepared.stake !== quote.entry.stake || prepared.account !== scope.account || prepared.chainId !== scope.chainId || prepared.vault !== scope.vault) {
847
+ if (prepared.stake !== quote.signing.entry.stake || prepared.account !== scope.account || prepared.chainId !== scope.chainId || prepared.vault !== scope.vault) {
875
848
  throw new Error("the prepared funding is for another stake, account or deployment");
876
849
  }
877
- return record(await vaultSigner.signTypedData(takerAcceptTypedData(chain, quote.entry)), prepared.funding, prepared.bridge);
850
+ return record(await vaultSigner.signTypedData(takerAcceptTypedData(chain, quote.signing.entry)), prepared.bridge);
878
851
  }
879
- const stake = BigInt(quote.entry.stake);
852
+ const stake = BigInt(quote.signing.entry.stake);
880
853
  const core = request.core === undefined || request.core === null ? request.core : BigInt(request.core);
881
854
  // Known cash is planned before any prompt, so a plan that fails asks the wallet for nothing.
882
- let plan = funding === "plan" && cash !== undefined ? planEntry(stake, core, cash) : undefined;
883
- const signing = vaultSigner.signTypedData(takerAcceptTypedData(chain, quote.entry));
884
- if (funding === "plan" && cash === undefined) {
855
+ let plan = cash !== undefined ? planEntry(stake, core, cash) : undefined;
856
+ const signing = vaultSigner.signTypedData(takerAcceptTypedData(chain, quote.signing.entry));
857
+ if (plan === undefined) {
885
858
  // The quote signature names no amount, so the wallet signs it while the balances are read; a refusal stops the read and is the call's error.
886
859
  const reading = new AbortController();
887
860
  signing.catch((error) => reading.abort(error));
@@ -890,49 +863,43 @@ export function createTotalis(options) {
890
863
  throw error;
891
864
  });
892
865
  }
893
- const bridgeAmount = plan?.bridge ?? 0n;
894
- const walletAmount = plan?.wallet ?? 0n;
895
- const [taker_signature, bridge, walletFunding] = await Promise.all([
866
+ const [taker_signature, bridge] = await Promise.all([
896
867
  signing,
897
- signBridge(signer, chain, bridgeAmount, request),
898
- walletAmount <= 0n ? undefined
899
- : route === "approval" ? approvalCovers(walletAmount).then(() => approvalFunding)
900
- : depositAuthorization(chain, account, walletAmount),
868
+ signBridge(signer, chain, plan.bridge, request),
869
+ plan.wallet > 0n ? approvalCovers(plan.wallet) : undefined,
901
870
  ]);
902
- const fundingCommand = plan === undefined ? (funding === "none" || funding === "plan" ? undefined : funding) : walletFunding;
903
- return record(taker_signature, fundingCommand, bridge);
871
+ return record(taker_signature, bridge);
904
872
  }
905
873
  /**
906
874
  * Sign a Combo entry for a quote without sending it. Funding is planned
907
875
  * from `cash`, the free vault cash and available wallet USDC you already
908
876
  * read (`spendableCash`), or from a fresh balances read when it is left out:
909
- * free vault cash, then a USDC authorization from the wallet, then a bridge
910
- * of `core` (the Core USDC you offer, in USDC base units; `bridgeGasBuffer`
911
- * stays behind) to the wallet for the rest. Pass `core: null` when your Core
912
- * read failed: an entry that needs the bridge then throws `EntryError`
913
- * `BALANCE_UNKNOWN` instead of asking the wallet for it all. Leave `core`
914
- * out to fund from the wallet alone. The quote, the bridge and the wallet
915
- * authorization are asked of the signer at once; a wallet that prompts
916
- * shows them in turn. `sourceDex: ""` bridges from perps instead of spot.
877
+ * free vault cash, then the wallet, then a bridge of `core` (the Core USDC
878
+ * you offer, in USDC base units; `bridgeGasBuffer` stays behind) to the
879
+ * wallet for the rest. The venue draws the wallet's part from its approval
880
+ * to WalletAccept, which must already cover it (`WalletApprovalError`
881
+ * `INSUFFICIENT_APPROVAL` otherwise): signing sends nothing, so it cannot
882
+ * land a permit; `prepareEntryFunding` or `approveWallet` does. Pass
883
+ * `core: null` when your Core read failed: an entry that needs the bridge
884
+ * then throws `EntryError` `BALANCE_UNKNOWN` instead of asking the wallet
885
+ * for it all. Leave `core` out to fund from the wallet alone. The quote and
886
+ * the bridge are asked of the signer at once; a wallet that prompts shows
887
+ * them in turn. `sourceDex: ""` bridges from perps instead of spot.
917
888
  * Persist the record, then `sendAcceptance` it; after a restart,
918
889
  * `recoverAcceptance` it. Pass `hypercoreNonce` if your app reserves
919
890
  * Hyperliquid nonces itself. With `prepared` (`prepareEntryFunding`), only
920
- * the quote is signed, and its funding is the prepared one. `funding:
921
- * "approval"` draws the wallet's part from its approval to WalletAccept
922
- * instead of a USDC authorization; signing sends nothing, so without
923
- * `prepared` the approval left must already cover it (`WalletApprovalError`
924
- * `INSUFFICIENT_APPROVAL` otherwise).
891
+ * the quote is signed, and its bridge is the prepared one.
925
892
  */
926
893
  function signEntry(request) {
927
- return signEntryWith(request, "plan", request.funding);
894
+ return signEntryWith(request);
928
895
  }
929
896
  /** Sign a cash-out quote as the position's owner without sending it: the same SellBack digest the maker signs. */
930
897
  async function signCashout(request) {
931
898
  const { quote } = request;
932
899
  const { vaultSigner, account, chain, scope } = await recordScope();
933
- if (quote.sell_back.owner.toLowerCase() !== account)
900
+ if (quote.signing.sell_back.owner.toLowerCase() !== account)
934
901
  throw new Error("the quote sells another owner's position");
935
- const taker_signature = await vaultSigner.signTypedData(sellBackTypedData(chain, quote.sell_back));
902
+ const taker_signature = await vaultSigner.signTypedData(sellBackTypedData(chain, quote.signing.sell_back));
936
903
  return {
937
904
  kind: "CASHOUT", acceptanceId: request.acceptanceId ?? uuidv7(), rfqId: quote.rfq_id, quoteId: quote.quote_id, ...scope,
938
905
  positionId: termsOf(quote).position_id, command: { taker_signature },
@@ -942,8 +909,8 @@ export function createTotalis(options) {
942
909
  * Send a signed entry or cash-out: one synchronous accept under the
943
910
  * record's acceptance ID, whose answer must echo the record's acceptance,
944
911
  * RFQ and quote IDs; a lost answer is read and fenced, never resent blind.
945
- * An entry's bridge goes only after the accept answers `ACCEPTED` with a
946
- * `fund_by` still ahead, and never holds up the result (see `bridging`);
912
+ * An entry's bridge goes only after the accept answers `ACCEPTED`, within
913
+ * `fundWindowMs` of its send, and never holds up the result (see `bridging`);
947
914
  * an accept answered any other way discards it, so nothing moved.
948
915
  * `onRecord` is awaited with the record before the bridge is first sent,
949
916
  * and gets it again with Hyperliquid's answer or the discard. An entry
@@ -955,24 +922,16 @@ export function createTotalis(options) {
955
922
  await checkScope(signed);
956
923
  if (options.signal?.aborted)
957
924
  throw abortReason(options.signal);
958
- const clock = venueClock();
959
- if (signed.kind === "ENTRY" && signed.bridge !== undefined) {
960
- // The held accept's own stamp runs late by the maker's wait; a read sent alongside bounds the venue clock tightly.
961
- const probed = clock.sending();
962
- void client.GET("/v1/rfqs/{rfq_id}/quotes", { params: { path: { rfq_id: signed.rfqId } }, fetch: recoveryFetch }).then((read) => {
963
- if (read.data !== undefined)
964
- probed(read.data.server_time);
965
- }, () => undefined);
966
- }
925
+ const clock = flowClock();
967
926
  let outcome;
968
927
  let sends = 0;
969
928
  const fetch = countedFetch(() => { sends += 1; });
970
929
  const post = () => client.POST("/v1/quotes/{quote_id}/accept", { params: { path: { quote_id: signed.quoteId }, header: idempotency(signed.acceptanceId) }, body: signed.command, fetch });
930
+ // Counted from the first send, before any resend, so it never runs late.
931
+ const until = clock.now() + fundWindowMs;
971
932
  try {
972
- const stamped = clock.sending();
973
933
  const answer = await sendOnce(post);
974
934
  checkEcho(signed, answer, true);
975
- stamped(answer.server_time);
976
935
  outcome = answer;
977
936
  }
978
937
  catch (error) {
@@ -991,17 +950,16 @@ export function createTotalis(options) {
991
950
  throw failed;
992
951
  });
993
952
  }
994
- return resultOf(signed, outcome, await moveBridge(signed, outcome, clock, options));
953
+ return resultOf(signed, outcome, await moveBridge(signed, outcome, clock, until, options));
995
954
  }
996
955
  /**
997
956
  * Finish a stored record after a lost answer or a restart, signing nothing:
998
- * read the acceptance, fencing an absent one so it ends `NOT_ADMITTED`. An
999
- * entry's bridge never sent goes now only if the acceptance is `ACCEPTED`
1000
- * and its `fund_by` is still ahead, and is discarded otherwise; one sent
1001
- * without an answer is resent, the same bytes, within the same window. A
1002
- * record from SDK 0.63 or older is only read. One still `PENDING_CONFIRM`
1003
- * is read again after the maker's deadline, or every 250 ms until 2 s past
1004
- * it while a bridge is unsent; `wait: false` returns it as it stands instead.
957
+ * read the acceptance, fencing an absent one so it ends `NOT_ADMITTED`. It
958
+ * sends no bridge, since the accept it would fund went out in another flow
959
+ * and its `fundWindowMs` cannot be shown to be ahead: a bridge never sent is
960
+ * discarded, and one sent without an answer stays `SENT`. A record from SDK
961
+ * 0.63 or older is only read. One still `PENDING_CONFIRM` is read again
962
+ * after the maker's deadline; `wait: false` returns it as it stands instead.
1005
963
  * A record marked `refused` is `NOT_ADMITTED`, read from the record alone.
1006
964
  */
1007
965
  async function recoverAcceptance(signed, options = {}) {
@@ -1009,9 +967,9 @@ export function createTotalis(options) {
1009
967
  if (signed.kind === "ENTRY" && "refused" in signed && signed.refused !== undefined) {
1010
968
  return resultOf(signed, { status: "NOT_ADMITTED", quote_id: signed.quoteId, rfq_id: signed.rfqId }, {});
1011
969
  }
1012
- const clock = venueClock();
1013
- const outcome = await fenceAcceptance(signed, clock, undefined, options.wait ?? true, bridgeUnsent(signed));
1014
- return resultOf(signed, outcome, await moveBridge(signed, outcome, clock, options));
970
+ const clock = flowClock();
971
+ const outcome = await fenceAcceptance(signed, clock, undefined, options.wait ?? true);
972
+ return resultOf(signed, outcome, await moveBridge(signed, outcome, clock, undefined, options));
1015
973
  }
1016
974
  /** Cancel a fresh RFQ when its record fails before the accept is posted. */
1017
975
  async function signedOrCancel(rfqId, sign) {
@@ -1035,59 +993,56 @@ export function createTotalis(options) {
1035
993
  * under `positionId`, the quote's ID, once `waitForOperation(operationId)`
1036
994
  * resolves `COMMITTED`; pass its operation and the result's `record` to
1037
995
  * `entryFailure` to name a failure. Any vault shortfall is funded from the
1038
- * wallet, and from `core` by bridge, unless `funding` says otherwise.
996
+ * wallet, through its approval to WalletAccept, and from `core` by bridge.
1039
997
  *
1040
- * Makers replace their quotes as they renew them, so an accept can find its
1041
- * quote gone (`QUOTE_REPLACED`, `QUOTE_EXPIRED`); then `onSigned` gets the
1042
- * record marked `refused`. A maker can also turn its quote down (`DECLINED`)
1043
- * or not answer in time (`TIMED_OUT`). Either way nothing was admitted, so
1044
- * the best other quote paying at least `minPayout` is signed and sent,
1045
- * funding first, until one is taken, `refreshMs` has passed since the first
1046
- * quote was chosen, or `maxAttempts` accepts were sent. Then the last
998
+ * A quote stays takeable while it is on the book. An accept can still find
999
+ * its quote just replaced (`QUOTE_REPLACED`, `QUOTE_EXPIRED`); then
1000
+ * `onSigned` gets the record marked `refused`. A maker can also turn its
1001
+ * quote down (`DECLINED`) or not answer in time (`TIMED_OUT`). Either way
1002
+ * nothing was admitted, so the best other quote paying at least `minPayout`
1003
+ * is signed and sent, funding first, waiting up to `quoteTimeoutMs` for one,
1004
+ * until one is taken or `maxAttempts` accepts were sent. Then the last
1047
1005
  * refusal is thrown, or the last decline or timeout returned.
1048
1006
  */
1049
1007
  async function openPosition(request) {
1050
- const { legs, stake, choose = bestQuote(), collectMs = defaultCollectMs, funding = "wallet", intent, quoteTimeoutMs = 20_000, refreshMs = defaultRefreshMs, maxAttempts = defaultMaxAttempts, signal } = request;
1051
- const planned = funding === "wallet" || funding === "approval";
1052
- const reading = planned && request.cash === undefined ? readSpendableCash(signal) : undefined;
1008
+ const { legs, stake, choose = bestQuote(), collectMs = defaultCollectMs, quoteTimeoutMs = 20_000, maxAttempts = defaultMaxAttempts, signal } = request;
1009
+ const reading = request.cash === undefined ? readSpendableCash(signal) : undefined;
1053
1010
  reading?.catch(() => undefined);
1054
1011
  const account = await (await requireSigner()).address();
1055
1012
  await deployment();
1056
1013
  await stream.live(signal);
1057
- const wanted = { taker: account, stake: String(stake), legs: [...legs].sort((a, b) => Number(a.outcome_id) - Number(b.outcome_id)).map(({ outcome_id, side }) => ({ outcome_id, side })) };
1058
- const entry = { stake: wanted.stake, legs: wanted.legs };
1059
- const rfqId = await createRfq(intent === undefined ? entry : { ...entry, ...intent });
1014
+ const wanted = { taker: account, stake: String(stake), legs: rfqLegsInOrder(legs) };
1015
+ const rfqId = await createRfq({
1016
+ stake: wanted.stake, legs: wanted.legs,
1017
+ ...(request.builderCode === undefined ? {} : { builder_code: request.builderCode }),
1018
+ });
1060
1019
  const createdAt = performance.now();
1061
1020
  let floor = request.minPayout === undefined ? undefined : BigInt(request.minPayout);
1062
1021
  const refused = new Set();
1063
1022
  const offered = (quote) => quote.kind === "ENTRY" && quote.rfq_id === rfqId &&
1064
- quote.entry.taker.toLowerCase() === wanted.taker && quote.entry.stake === wanted.stake &&
1065
- JSON.stringify(quote.entry.legs.map(({ outcome_id, side }) => ({ outcome_id, side }))) === JSON.stringify(wanted.legs) &&
1066
- !refused.has(quote.quote_id) && (floor === undefined || BigInt(quote.entry.payout) >= floor);
1067
- // Counted from the first choice, not from its signature, so a slow wallet cannot stretch the window.
1068
- let refreshUntil;
1069
- // An approval entry's funding names no quote and its bridge was never sent unless the record says so, so a refresh reuses both.
1023
+ quote.signing.entry.taker.toLowerCase() === wanted.taker && quote.signing.entry.stake === wanted.stake &&
1024
+ JSON.stringify(quote.signing.entry.legs.map(({ outcome_id, side }) => ({ outcome_id, side }))) === JSON.stringify(wanted.legs) &&
1025
+ !refused.has(quote.quote_id) && (floor === undefined || BigInt(quote.signing.entry.payout) >= floor);
1026
+ let retrying = false;
1027
+ // An entry's funding names no quote and its bridge was never sent unless the record says so, so a refresh reuses both.
1070
1028
  let reusable;
1071
1029
  const take = () => signedOrCancel(rfqId, async () => {
1072
- const prepared = !planned ? undefined : reusable ?? await prepareEntryFunding({
1073
- stake: wanted.stake, core: request.core, cash: request.cash ?? await (refreshUntil === undefined ? reading : readSpendableCash(signal)),
1074
- sourceDex: request.sourceDex, funding, approval: request.approval, approvalValue: request.approvalValue, onApproval: request.onApproval, signal,
1030
+ const prepared = reusable ?? await prepareEntryFunding({
1031
+ stake: wanted.stake, core: request.core, cash: request.cash ?? await (retrying ? readSpendableCash(signal) : reading),
1032
+ sourceDex: request.sourceDex, approval: request.approval, approvalValue: request.approvalValue, onApproval: request.onApproval, signal,
1075
1033
  });
1076
- if (funding === "approval")
1077
- reusable = prepared;
1078
- const selected = refreshUntil === undefined
1079
- ? await awaitOffer(rfqId, offered, choose, Math.max(0, Math.round(collectMs - (performance.now() - createdAt))), quoteTimeoutMs, signal)
1080
- : await awaitOffer(rfqId, offered, choose, 0, Math.max(0, Math.round(refreshUntil - performance.now())), signal);
1081
- refreshUntil ??= performance.now() + refreshMs;
1034
+ reusable = prepared;
1035
+ const collect = retrying ? 0 : Math.max(0, Math.round(collectMs - (performance.now() - createdAt)));
1036
+ const selected = await awaitOffer(rfqId, offered, choose, collect, quoteTimeoutMs, signal);
1082
1037
  if (!offered(selected))
1083
1038
  throw new Error("the chosen quote is not for the requested position");
1084
- const signed = await signEntryWith({ quote: selected, prepared }, planned ? "plan" : funding);
1039
+ const signed = await signEntryWith({ quote: selected, prepared });
1085
1040
  await request.onSigned?.(signed);
1086
1041
  return { selected, signed };
1087
1042
  });
1088
1043
  let { selected, signed } = await take();
1089
- floor ??= BigInt(selected.entry.payout);
1090
- const refreshEnds = refreshUntil ?? 0;
1044
+ floor ??= BigInt(selected.signing.entry.payout);
1045
+ retrying = true;
1091
1046
  let record = signed;
1092
1047
  const send = () => sendAcceptance(signed, {
1093
1048
  ...(request.transport === undefined ? {} : { transport: request.transport }),
@@ -1107,7 +1062,7 @@ export function createTotalis(options) {
1107
1062
  return lost;
1108
1063
  }
1109
1064
  catch (error) {
1110
- if (!(error instanceof ApiError) || !refreshCodes.has(error.code))
1065
+ if (!(error instanceof ApiError) || !goneCodes.has(error.code))
1111
1066
  throw error;
1112
1067
  // Refused outright, so nothing was admitted and sendAcceptance discarded any bridge.
1113
1068
  lost = error;
@@ -1118,7 +1073,10 @@ export function createTotalis(options) {
1118
1073
  if (record.bridge !== undefined && record.bridgeState !== undefined && record.bridgeState !== "DISCARDED")
1119
1074
  reusable = undefined;
1120
1075
  const last = record;
1121
- const end = async () => {
1076
+ const end = async (cancelled = false) => {
1077
+ // Nothing was admitted: an RFQ left open would stay open while this stream is connected.
1078
+ if (!cancelled)
1079
+ await cancelRfq(rfqId);
1122
1080
  if (record !== last) {
1123
1081
  record = last;
1124
1082
  await request.onSigned?.(last);
@@ -1127,23 +1085,19 @@ export function createTotalis(options) {
1127
1085
  throw lost;
1128
1086
  return lost;
1129
1087
  };
1130
- if (attempt >= maxAttempts || performance.now() >= refreshEnds)
1088
+ if (attempt >= maxAttempts)
1131
1089
  return end();
1132
1090
  let next;
1133
1091
  try {
1134
1092
  next = await take();
1135
1093
  }
1136
1094
  catch (retried) {
1137
- // No fresh quote at or above the floor in time leaves this outcome standing.
1095
+ // No other quote at or above the floor in time leaves this outcome standing.
1096
+ // take() already cancelled the RFQ.
1138
1097
  if (retried instanceof Error && retried.name === "TimeoutError")
1139
- return end();
1098
+ return end(true);
1140
1099
  throw retried;
1141
1100
  }
1142
- // Signing and persisting can outlast the window: a record signed too late is never sent, and the last sent one is persisted again.
1143
- if (performance.now() >= refreshEnds) {
1144
- record = next.signed;
1145
- return end();
1146
- }
1147
1101
  ({ selected, signed } = next);
1148
1102
  record = signed;
1149
1103
  }
@@ -1152,7 +1106,7 @@ export function createTotalis(options) {
1152
1106
  const { bridged: _bridged, ...settled } = result;
1153
1107
  return {
1154
1108
  ...settled,
1155
- entry: selected.entry,
1109
+ entry: selected.signing.entry,
1156
1110
  /** As in `AcceptanceResult`, read as the bridge stands now. */
1157
1111
  get bridged() {
1158
1112
  return result.bridged;
@@ -1170,35 +1124,69 @@ export function createTotalis(options) {
1170
1124
  * `onSigned`, then `sendAcceptance`. `ACCEPTED` means the sell-back or
1171
1125
  * transfer is queued as `operationId` (follow it with `waitForOperation`);
1172
1126
  * otherwise the status says why not (`DECLINED`, `TIMED_OUT`, `CANCELLED`, `NOT_ADMITTED`).
1127
+ * A bid stays takeable while it is on the book; an accept that finds it
1128
+ * just replaced (`QUOTE_REPLACED`, `QUOTE_EXPIRED`) takes the next bid at
1129
+ * no lower a price, waiting up to `quoteTimeoutMs`, until `maxAttempts`
1130
+ * accepts were sent. Then that refusal is thrown.
1173
1131
  */
1174
1132
  async function cashOut(request) {
1175
- const { positionId, choose = bestBid(), collectMs = defaultCollectMs, quoteTimeoutMs = 20_000, signal } = request;
1133
+ const { positionId, choose = bestBid(), collectMs = defaultCollectMs, quoteTimeoutMs = 20_000, maxAttempts = defaultMaxAttempts, signal } = request;
1176
1134
  const owner = await (await requireSigner()).address();
1177
1135
  await deployment();
1178
1136
  await stream.live(signal);
1179
1137
  const rfqId = await createCashout(positionId);
1180
1138
  // Only quotes for this position, sold by this owner, are offered to the chooser and signed.
1139
+ const refused = new Set();
1140
+ // A later bid never pays less than the first one chosen.
1141
+ let floor;
1181
1142
  const matches = (quote) => {
1182
- if (quote.kind === "ENTRY" || quote.rfq_id !== rfqId)
1143
+ if (quote.kind === "ENTRY" || quote.rfq_id !== rfqId || refused.has(quote.quote_id))
1183
1144
  return false;
1184
- return quote.sell_back.position_id.toLowerCase() === positionId.toLowerCase() && quote.sell_back.owner === owner;
1145
+ if (floor !== undefined && BigInt(quote.signing.sell_back.price) < floor)
1146
+ return false;
1147
+ return quote.signing.sell_back.position_id.toLowerCase() === positionId.toLowerCase() && quote.signing.sell_back.owner === owner;
1185
1148
  };
1186
- const signed = await signedOrCancel(rfqId, async () => {
1187
- const bid = await awaitOffer(rfqId, matches, choose, collectMs, quoteTimeoutMs, signal);
1188
- if (!matches(bid))
1189
- throw new Error("the chosen quote is not for this position and owner");
1190
- const signed = await signCashout({ quote: bid });
1191
- await request.onSigned?.(signed);
1192
- return signed;
1193
- });
1194
- return { ...(await sendAcceptance(signed, signal === undefined ? {} : { signal })), positionId };
1149
+ // Nothing was admitted on a pass or a refusal: an RFQ left open would stay open while this stream is connected.
1150
+ let gone;
1151
+ for (let attempt = 1;; attempt += 1) {
1152
+ const signed = await signedOrCancel(rfqId, async () => {
1153
+ const bid = await awaitOffer(rfqId, matches, choose, attempt === 1 ? collectMs : 0, quoteTimeoutMs, signal);
1154
+ if (!matches(bid))
1155
+ throw new Error("the chosen quote is not for this position and owner");
1156
+ floor ??= BigInt(bid.signing.sell_back.price);
1157
+ const signed = await signCashout({ quote: bid });
1158
+ await request.onSigned?.(signed);
1159
+ return signed;
1160
+ }).catch((error) => {
1161
+ // No other bid in time: the refusal that sent it looking stands. signedOrCancel already cancelled the RFQ.
1162
+ throw gone !== undefined && error instanceof Error && error.name === "TimeoutError" ? gone : error;
1163
+ });
1164
+ let result;
1165
+ try {
1166
+ result = await sendAcceptance(signed, signal === undefined ? {} : { signal });
1167
+ }
1168
+ catch (error) {
1169
+ if (!(error instanceof ApiError) || !goneCodes.has(error.code))
1170
+ throw error;
1171
+ if (attempt >= maxAttempts) {
1172
+ await cancelRfq(rfqId);
1173
+ throw error;
1174
+ }
1175
+ refused.add(signed.quoteId);
1176
+ gone = error;
1177
+ continue;
1178
+ }
1179
+ if (passedOn.has(result.status))
1180
+ await cancelRfq(rfqId);
1181
+ return { ...result, positionId };
1182
+ }
1195
1183
  }
1196
1184
  /**
1197
1185
  * Follow an operation to a terminal status (COMMITTED, REVERTED or
1198
1186
  * EXPIRED_UNEXECUTED) from OPERATION_UPDATED, rereading it with
1199
1187
  * `GET /v1/me/operations/{operation_id}` on VAULT_BALANCE_CHANGED too.
1200
1188
  * Resolves at every terminal status: only COMMITTED executed, and a failed
1201
- * one's `failure_reason` says why when the venue knows (`entryFailure`
1189
+ * one's `reason` says why when the venue knows (`entryFailure`
1202
1190
  * words it for an entry).
1203
1191
  */
1204
1192
  function waitForOperation(operationId, signal) {
@@ -1382,7 +1370,8 @@ export function createTotalis(options) {
1382
1370
  // A minute inside the venue's maximum life absorbs clock skew.
1383
1371
  const exit = { amount: BigInt(request.amount).toString(), expiry: String(now() + Math.min(route.maximum_life_seconds - 60, 600)), salt: BigInt(randomBytes32()).toString() };
1384
1372
  const signature = await (agent ?? signer).signTypedData(exitTypedData(chain, { account, to, ...exit }));
1385
- const body = envelope({ account, to, ...exit, signature, purpose: request.purpose ?? "ORDER", ...(request.activationFeeAccepted ? { activation_fee_accepted: true } : {}) });
1373
+ // The venue takes the account from the credential and the router as to.
1374
+ const body = { ...exit, signature, purpose: request.purpose ?? "ORDER", ...(request.activationFeeAccepted ? { activation_fee_accepted: true } : {}) };
1386
1375
  return { exitId, account, body };
1387
1376
  }
1388
1377
  /**
@@ -1405,7 +1394,8 @@ export function createTotalis(options) {
1405
1394
  const claimId = request.claimId ?? uuidv7();
1406
1395
  const exit = { amount: cash.vault_free, expiry: String(now() + 600), salt: BigInt(randomBytes32()).toString() };
1407
1396
  const signature = await signer.signTypedData(exitTypedData(runOff, { account, to: account, ...exit }));
1408
- const body = envelope({ vault_address: address(cash.vault_address), account, to: account, ...exit, signature });
1397
+ // The venue takes the account, which is also to, from the credential.
1398
+ const body = { vault_address: address(cash.vault_address), ...exit, signature };
1409
1399
  return { claimId, account, body };
1410
1400
  }
1411
1401
  /** POST a signed run-off claim under its claim ID, resending the same bytes on a lost answer. The 202 is admission: follow `operation` with `waitForOperation`. */
@@ -1436,19 +1426,38 @@ export function createTotalis(options) {
1436
1426
  /**
1437
1427
  * Sign a sponsored deposit of wallet USDC into the vault without sending it:
1438
1428
  * a USDC ReceiveWithAuthorization to the vault, valid for 10 minutes, that
1439
- * Totalis relays and pays gas for. At least 1 USDC. Persist
1440
- * `{ depositId, body }`, then `sendDeposit` it.
1429
+ * Totalis relays and pays gas for. At least 1 USDC (0.10 from a Privy login
1430
+ * wallet). The signer must be the account wallet of the session or
1431
+ * participant API key (`funding:deposit` and `sponsorship:use`) the client
1432
+ * sends: the venue credits that account. Persist `{ depositId, body }`, then
1433
+ * `sendDeposit` it.
1441
1434
  */
1442
1435
  async function signDeposit(request) {
1443
1436
  const account = address((await (await requireSigner()).address()).toLowerCase());
1444
- const { kind: _kind, ...authorization } = await depositAuthorization(await deployment(), account, BigInt(request.amount));
1445
- const body = envelope({ account, from: account, ...authorization });
1446
- return { depositId: request.depositId ?? uuidv7(), account, body };
1437
+ const body = await depositAuthorization(await deployment(), account, BigInt(request.amount));
1438
+ return { depositId: request.depositId ?? uuidv7(), account, body: body };
1447
1439
  }
1448
1440
  /** POST a signed deposit under its ID, resending the same bytes on a lost answer. The 202 names the operation: follow it with `waitForOperation`. */
1449
1441
  function sendDeposit(signed) {
1450
1442
  return sendOnce(() => client.POST("/v1/me/deposits", { params: { header: { "Idempotency-Key": signed.depositId } }, body: signed.body }));
1451
1443
  }
1444
+ /**
1445
+ * Deposit wallet USDC into the vault in one call (`signDeposit`, then
1446
+ * `sendDeposit`); Totalis relays it and pays the gas. At least 1 USDC.
1447
+ * Resolves with the deposit's operation once it is `COMMITTED`, with the
1448
+ * cash in the vault, and throws if it ended any other way.
1449
+ */
1450
+ async function deposit(request) {
1451
+ await stream.live(request.signal);
1452
+ const { operation_id } = await sendDeposit(await signDeposit({ amount: request.amount }));
1453
+ const followed = waitForOperation(operation_id, request.signal);
1454
+ followed.catch(() => undefined);
1455
+ await request.onStarted?.(operation_id);
1456
+ const operation = await followed;
1457
+ if (operation.status !== "COMMITTED")
1458
+ throw new Error(`deposit ${operation_id} ended ${operation.status}; nothing reached the vault`);
1459
+ return operation;
1460
+ }
1452
1461
  /**
1453
1462
  * Sign the return of the account's Totalis cash to HyperCore without
1454
1463
  * sending it: a deposit of the available wallet USDC (when at least 1 USDC)
@@ -1532,6 +1541,16 @@ export function createTotalis(options) {
1532
1541
  function revokeVaultAgent(request) {
1533
1542
  return grantVaultAgent({ ...request, validUntil: 0 });
1534
1543
  }
1544
+ /**
1545
+ * Every market `GET /v1/markets` lists under `filters`, in outcome ID
1546
+ * order, as an async iterator. The filters apply after paging, so a page
1547
+ * can be short or empty while more follow: this reads on until `has_more`
1548
+ * is false. `for await (const market of sdk.listMarkets({ combo: "OPEN", eligibility: "ENABLED" }))`
1549
+ * walks the markets a Combo can include now.
1550
+ */
1551
+ function listMarkets(filters = {}, limit = 200) {
1552
+ return items((query) => client.GET("/v1/markets", { params: { query: { ...filters, ...query, limit } } }).then(unwrap), (page) => page.items);
1553
+ }
1535
1554
  /** The account's live vault agents, every page; `copy_agent` marks a Combo copy agent's key. */
1536
1555
  function vaultAgents(limit = 200) {
1537
1556
  return items((query) => client.GET("/v1/me/vault-agents", { params: { query: { ...query, limit } } }).then(unwrap), (page) => page.agents);
@@ -1560,6 +1579,7 @@ export function createTotalis(options) {
1560
1579
  /** The account stream. Flows start it on first use; `close()` it when done. */
1561
1580
  stream,
1562
1581
  deployment,
1582
+ listMarkets,
1563
1583
  /** Spendable Totalis cash from a fresh balances read (`spendableCash`): `{ vault, wallet, total }`, each `null` while unknown, never 0. */
1564
1584
  spendableCash: readSpendableCash,
1565
1585
  /** What the account holds at Totalis, every amount read at one block (`GET /v1/me/account-value`). */
@@ -1583,6 +1603,7 @@ export function createTotalis(options) {
1583
1603
  sendCoreExit,
1584
1604
  exitToCore,
1585
1605
  waitForCoreExit,
1606
+ deposit,
1586
1607
  signDeposit,
1587
1608
  sendDeposit,
1588
1609
  signReturnToCore,