@esseyonsui/sui-sdk-v3 0.1.7 → 0.1.9

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 (39) hide show
  1. package/README.md +7 -0
  2. package/dist/errors.d.ts +4 -0
  3. package/dist/errors.d.ts.map +1 -1
  4. package/dist/essey.d.ts +55 -7
  5. package/dist/essey.d.ts.map +1 -1
  6. package/dist/essey.js +252 -49
  7. package/dist/index.d.ts +2 -1
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/v3/collateral/health.d.ts +2 -0
  10. package/dist/v3/collateral/health.d.ts.map +1 -1
  11. package/dist/v3/collateral/health.js +6 -0
  12. package/dist/v3/collateral/local-health.d.ts +3 -2
  13. package/dist/v3/collateral/local-health.d.ts.map +1 -1
  14. package/dist/v3/collateral/local-health.js +2 -6
  15. package/dist/v3/index.d.ts +1 -0
  16. package/dist/v3/index.d.ts.map +1 -1
  17. package/dist/v3/index.js +1 -0
  18. package/dist/v3/notes/denominations.d.ts +4 -0
  19. package/dist/v3/notes/denominations.d.ts.map +1 -1
  20. package/dist/v3/notes/denominations.js +23 -7
  21. package/dist/v3/notes/opening.d.ts +4 -1
  22. package/dist/v3/notes/opening.d.ts.map +1 -1
  23. package/dist/v3/notes/opening.js +6 -2
  24. package/dist/v3/notes/withdraw.d.ts +7 -0
  25. package/dist/v3/notes/withdraw.d.ts.map +1 -1
  26. package/dist/v3/notes/withdraw.js +47 -0
  27. package/dist/v3/pace.d.ts +43 -0
  28. package/dist/v3/pace.d.ts.map +1 -0
  29. package/dist/v3/pace.js +42 -0
  30. package/dist/v3/relay/client.d.ts +0 -8
  31. package/dist/v3/relay/client.d.ts.map +1 -1
  32. package/dist/v3/relay/client.js +0 -17
  33. package/dist/v3/stage1.d.ts +2 -2
  34. package/dist/v3/stage1.d.ts.map +1 -1
  35. package/dist/v3/stage1.js +4 -4
  36. package/dist/v3/time-grid.d.ts +5 -0
  37. package/dist/v3/time-grid.d.ts.map +1 -0
  38. package/dist/v3/time-grid.js +15 -0
  39. package/package.json +1 -1
package/dist/essey.js CHANGED
@@ -16,7 +16,8 @@ import { DOM_LBLIND, DOM_TSALT, R } from "./v3/domains.js";
16
16
  import { MODE_OPEN, MODE_TOPUP, NO_ADDRESS, collLockExt } from "./v3/ext.js";
17
17
  import { defaultExt, faultExt, heartbeatExt, liquidateExt, openExt, releaseExt, topupByBorrowerExt, topupExt, } from "./v3/collateral/ext.js";
18
18
  import { claimDefault as claimDefaultBody, faultLiquidate as faultLiquidateBody, heartbeat as heartbeatBody, liquidate as liquidateBody, release as releaseBody, topup as topupBody, topupBorrower as topupBorrowerBody, } from "./v3/collateral/bodies.js";
19
- import { heartbeatFloor } from "./v3/collateral/math.js";
19
+ import { GRACE_S, heartbeatFloor } from "./v3/collateral/math.js";
20
+ import { heartbeatHour, settleNowS } from "./v3/time-grid.js";
20
21
  /**
21
22
  * The Seal servers dry-run `keeper::check_loan` and answer "does not have access" when it aborts: a heartbeat still
22
23
  * covers the loan at this price, the loan is not active, or the pass or badge does not match.
@@ -31,7 +32,9 @@ function keeperRefusal(err) {
31
32
  const HB_GAP_MS = 3000000n;
32
33
  const HB_GAP_STANDIN_MS = 120000n;
33
34
  const H_MAX_MS = 86400000n;
34
- import { MODE, NO_TERMS, health, lenderAmount, loanRisk, seizeSplit } from "./v3/collateral/health.js";
35
+ const FIND_LOAN_TRIES = 15;
36
+ const FIND_LOAN_PAUSE_MS = 1_500;
37
+ import { MODE, NO_TERMS, health, lenderAmount, loanRisk, seizeIsLast, seizeSplit, } from "./v3/collateral/health.js";
35
38
  import { collLockPk, collNote, outputBlind, requestCommit, termsCommit, } from "./v3/collateral/openings.js";
36
39
  import { fetchKeeperPlaintext, keeperKeyId, openingOf, rollTo } from "./v3/collateral/seal.js";
37
40
  import { localHealth } from "./v3/collateral/local-health.js";
@@ -46,7 +49,7 @@ import { LOAN_REFI_KIND, loanRefi } from "./v3/loans/refi-plan.js";
46
49
  import { LOAN_OFFER_KIND, decodeRequest, lock4, lockField, loanExt, loanOffer, offerKeyId, offerPlaintext, offerRoom, sealListingBind, } from "./v3/loans/offer-plan.js";
47
50
  import { badgeRecipient, proveBadge } from "./v3/badge.js";
48
51
  import { proveFaucet } from "./v3/faucet.js";
49
- import { ecdhBlind, feeOf, treasuryPoint, verifyFeeOpening, } from "./v3/fees.js";
52
+ import { ecdhBlind, feeCommit, feeOf, treasuryPoint, verifyFeeOpening, } from "./v3/fees.js";
50
53
  import { JS4_LEVELS, deposit as depositInput, js4, membership, } from "./v3/inputs.js";
51
54
  import { marketRates } from "./v3/market.js";
52
55
  import { afterPage, assertLoanOpen, assertRoomMatches, assertSaleOpen, coinByPool, listPositions, openPosition, poolId, requireSale, summarizeLoan, summarizeRoom, viewLoanObject, viewPosition, viewRoomObject, } from "./v3/stage1.js";
@@ -67,13 +70,18 @@ import { noteCommitment, noteNullifier, notePk } from "./v3/notes/keys.js";
67
70
  import { fillerEnc, sealOpening } from "./v3/notes/opening.js";
68
71
  import { orderedLeaves, ownNotes, ownOpenings, usedIndices, } from "./v3/notes/scan.js";
69
72
  import { poolTree } from "./v3/notes/tree.js";
70
- import { exitValue, pickInputs, refuseLinkedAmount, transferValue, withdrawCost, } from "./v3/notes/withdraw.js";
73
+ import { exitKept, exitPieces, exitValue, piecePayees, pickInputs, refuseLinkedAmount, refuseUncovered, transferValue, withdrawCost, withdrawPieces, } from "./v3/notes/withdraw.js";
74
+ import { paceDelay } from "./v3/pace.js";
71
75
  import { proofBytes } from "./v3/proof-bytes.js";
72
76
  import { RelayClient, failure, } from "./v3/relay/client.js";
73
77
  import { provePossession } from "./v3/relay/possession.js";
74
- const FOLLOW_POLLS = 60;
78
+ /** A ticket lives 15 min (`services/relayer-v3/src/tickets.ts:7`); a minute past it the relayer answers "expired". */
79
+ const FOLLOW_CAP_MS = 16 * 60_000;
80
+ /** Times a seize output's collect waits again while nothing has landed after the seizure. */
81
+ const SEIZE_REWAITS = 3;
75
82
  /** The relayer's 202 after its wait cap can carry an etaMs near 0 (LOAD-02), which would spend every poll in seconds. */
76
83
  const FOLLOW_MIN_GAP_MS = 2_000;
84
+ const SPENT_POLLS = 60;
77
85
  const MAX_USED_SENDERS = 64;
78
86
  const EPH_SHIFT = 3n;
79
87
  const NO_RELAYER = "no relayer url: the deployment record names none yet; nothing was sent";
@@ -501,6 +509,18 @@ function relayerUrl(choice, config) {
501
509
  throw new EsseyError("ONION_UNAVAILABLE", "refused: this build has no Tor transport; nothing was sent");
502
510
  return choice === "clear" ? config.relayer.url : choice;
503
511
  }
512
+ function pacingOf(delays) {
513
+ if (delays === undefined || delays === "default")
514
+ return true;
515
+ if (delays === "off")
516
+ return false;
517
+ throw new EsseyError("INVALID_ARGUMENT", 'delays must be "default" or "off"');
518
+ }
519
+ /** From maturity plus grace a default may be claimed (`src/v3/collateral/health.ts:174`); `repay.move` reads no clock. */
520
+ const repayDeadline = (terms) => ({
521
+ atMs: Number((terms.maturityS + GRACE_S) * 1000n),
522
+ soft: true,
523
+ });
504
524
  /**
505
525
  * A deposit answered a digest for an earlier piece, or left a stranded record. Depositing the whole amount
506
526
  * again repeats them. A digest is not confirmation the note is in the pool.
@@ -548,6 +568,33 @@ function payee(to) {
548
568
  throw new EsseyError("INVALID_ARGUMENT", NO_TO);
549
569
  return recipient;
550
570
  }
571
+ const listOf = (to) => (Array.isArray(to) ? to : [to]);
572
+ function onePayee(to) {
573
+ const list = listOf(to);
574
+ if (list.length !== 1)
575
+ throw new EsseyError("INVALID_ARGUMENT", "refused: force: true, or a coin without denominations, pays one exact withdraw to one address; give one to; nothing was sent");
576
+ return list[0];
577
+ }
578
+ /** Pieces already paid are public and final; the error lists them so none is paid twice. */
579
+ function payoutStopped(error, paid, pieces) {
580
+ if (paid.length === 0)
581
+ return error;
582
+ const at = paid.length + 1;
583
+ const inner = isEsseyError(error) ? error : undefined;
584
+ const why = inner
585
+ ? [inner.code, inner.detail?.error].filter(Boolean).join(" ")
586
+ : error instanceof Error
587
+ ? error.message
588
+ : "it threw";
589
+ const stopped = new EsseyError(inner?.code ?? "RELAY_FAILED", `withdraw stopped at piece ${at} of ${pieces.length}: ${why}. Pieces paid before it: ${paid.length}, listed in detail.landed; do not pay them again`, {
590
+ ...inner?.detail,
591
+ landed: paid.map((p) => ({ digest: p.digest, value: p.amount.toString(), to: p.to })),
592
+ stopped: pieces[paid.length].toString(),
593
+ untried: pieces.slice(at).map(String),
594
+ });
595
+ stopped.cause = error;
596
+ return stopped;
597
+ }
551
598
  /**
552
599
  * LOAN-01: close_ms is public, so an exact close publishes the caller's chosen window. It rounds up to a whole
553
600
  * `step` (an hour unless the deployment sets `closeStepMs`), or down one step when up would pass the chain's
@@ -574,6 +621,7 @@ export class Essey {
574
621
  relay;
575
622
  relayerBase;
576
623
  seedOption;
624
+ pacing;
577
625
  credential;
578
626
  fees;
579
627
  relayer;
@@ -583,7 +631,9 @@ export class Essey {
583
631
  /** D-SPEC §6.2:598-600. Sealed sale rooms. */
584
632
  sales;
585
633
  keeper;
586
- constructor(config, statePath, apiOrigin, fetch, io, relay, relayerBase, seedOption) {
634
+ /** Each pass over the fee room carries the same tag, so one fetch per coin per commit is all v3api sees. */
635
+ feeOpenings = new Map();
636
+ constructor(config, statePath, apiOrigin, fetch, io, relay, relayerBase, seedOption, pacing) {
587
637
  this.config = config;
588
638
  this.statePath = statePath;
589
639
  this.apiOrigin = apiOrigin;
@@ -592,6 +642,10 @@ export class Essey {
592
642
  this.relay = relay;
593
643
  this.relayerBase = relayerBase;
594
644
  this.seedOption = seedOption;
645
+ this.pacing = pacing;
646
+ const closeOf = (loan) => () => this.roundDeadline(loan, "close_ms");
647
+ const settleByOf = (loan) => () => this.roundDeadline(loan, "settle_by_ms");
648
+ const coverOf = (loan) => () => this.coverDeadline(loan);
595
649
  this.credential = {
596
650
  obtain: (o) => this.obtain(o?.invite, o?.role ?? "member"),
597
651
  status: () => this.info(readState(this.statePath).credential),
@@ -612,6 +666,7 @@ export class Essey {
612
666
  request: (id) => this.readRequest(id),
613
667
  lend: async (p) => {
614
668
  const send = async () => {
669
+ await this.pause("offer", p.loan, closeOf(p.loan));
615
670
  const { body, record, seq } = await this.planOffer(p.loan, BigInt(p.rateBps));
616
671
  return {
617
672
  seq,
@@ -628,30 +683,30 @@ export class Essey {
628
683
  return (await send()).sent;
629
684
  }
630
685
  },
631
- collect: (p) => this.collect(p.loan, p.offer),
632
- collectSeized: (p) => this.collectSeized(p.loan, p.offer),
633
- collectSurplus: (p) => this.collectSurplus(p),
634
- accept: async (id) => {
686
+ collect: (p) => this.paced("collect", p.loan, null, () => this.collect(p.loan, p.offer)),
687
+ collectSeized: (p) => this.paced("collect_seized", p.loan, null, () => this.collectSeized(p.loan, p.offer)),
688
+ collectSurplus: (p) => this.paced("collect_surplus", p.loan, null, () => this.collectSurplus(p)),
689
+ accept: (id) => this.paced("settle", id, settleByOf(id), async () => {
635
690
  const { body, rateBps, terms, borrowerPk, collAmt } = await this.planSettle(id);
636
691
  return { ...(await this.freeLoan(settleLoan, body)), rateBps, terms, borrowerPk, collAmt };
637
- },
638
- release: (p) => this.releaseCollateral(p.loan, p.terms, p.borrowerPk, p.collAmt),
692
+ }),
693
+ release: (p) => this.paced("release", p.loan, null, () => this.releaseCollateral(p.loan, p.terms, p.borrowerPk, p.collAmt)),
639
694
  cancelOwn: (id) => this.cancelOwn(id),
640
695
  slash: (p) => this.slashOffer(p.loan, BigInt(p.seq)),
641
- fault: (p) => this.ctFault(p.loan, p.via),
696
+ fault: (p) => this.paced("fault", p.loan, null, () => this.ctFault(p.loan, p.via)),
642
697
  openRefi: (p) => this.openRefi(p),
643
698
  cancelRefi: (id) => this.cancelRefiOwn(id),
644
- settleRefi: (p) => this.settleRefiOwn(p),
645
- reclaimOffer: (p) => this.reclaimOffer(p.loan, p.offer, p.round),
646
- heartbeat: (p) => this.heartbeatOwn(p),
647
- topup: (p) => this.topupOwn(p),
648
- liquidate: (p) => this.borrowerSeize(p, MODE.LIQUIDATE),
649
- seizeDefault: (p) => this.borrowerSeize(p, MODE.DEFAULT),
650
- faultLiquidate: (p) => this.faultLiquidate(p.loan, p.offer),
651
- keeperLiquidate: (p) => this.keeperLiquidate(p.loan, p.via),
652
- reclaimCollateral: (p) => this.reclaimOwnCollateral(p.loan, p.collAmt),
699
+ settleRefi: (p) => this.paced("settle", p.loan, settleByOf(p.loan), () => this.settleRefiOwn(p)),
700
+ reclaimOffer: (p) => this.paced("reclaim_offer", p.loan, null, () => this.reclaimOffer(p.loan, p.offer, p.round)),
701
+ heartbeat: (p) => this.paced("heartbeat", p.loan, coverOf(p.loan), () => this.heartbeatOwn(p)),
702
+ topup: (p) => this.paced("topup", p.loan, coverOf(p.loan), () => this.topupOwn(p)),
703
+ liquidate: (p) => this.paced("liquidate", p.loan, null, () => this.borrowerSeize(p, MODE.LIQUIDATE)),
704
+ seizeDefault: (p) => this.paced("liquidate", p.loan, null, () => this.borrowerSeize(p, MODE.DEFAULT)),
705
+ faultLiquidate: (p) => this.paced("liquidate", p.loan, null, () => this.faultLiquidate(p.loan, p.offer)),
706
+ keeperLiquidate: (p) => this.paced("liquidate", p.loan, null, () => this.keeperLiquidate(p.loan, p.via)),
707
+ reclaimCollateral: (p) => this.paced("reclaim_collateral", p.loan, null, () => this.reclaimOwnCollateral(p.loan, p.collAmt)),
653
708
  recover: (p) => this.recoverOwnLoan(p.loan),
654
- payBack: async (p) => this.paidLoan(repayLoan, await this.planRepay(p.loan, p.terms, p.borrowerPk)),
709
+ payBack: (p) => this.paced("repay", p.loan, async () => repayDeadline(p.terms), async () => this.paidLoan(repayLoan, await this.planRepay(p.loan, p.terms, p.borrowerPk))),
655
710
  settle: (p) => this.freeLoan(settleLoan, p),
656
711
  repay: (p) => this.paidLoan(repayLoan, p),
657
712
  reclaim: (p) => this.paidLoan(reclaimLoan, p),
@@ -668,21 +723,24 @@ export class Essey {
668
723
  open: (coin, index) => this.openNote(coin, index),
669
724
  list: (coin) => this.listNotes(coin),
670
725
  view: (coin, index) => this.viewNote(coin, index),
671
- withdraw: (coin, amount, to, o) => this.withdraw(coin, amount, to, o),
726
+ withdraw: async (coin, amount, to, o = {}) => {
727
+ const plan = this.withdrawPlan(coin, amount, to, o);
728
+ return this.paced("withdraw", `${coin}:${amount}:${to}`, null, () => this.withdraw(coin, plan, o));
729
+ },
672
730
  receiveAddress: () => this.receiveAddress(),
673
- transfer: (coin, amount, to) => this.transfer(coin, amount, to),
674
- exit: (coin, to, o) => this.exit(coin, to, o),
731
+ transfer: (coin, amount, to) => this.paced("transfer", `${coin}:${amount}:${to}`, null, () => this.transfer(coin, amount, to)),
732
+ exit: (coin, to, o) => this.paced("exit", `${coin}:${to}`, null, () => this.exit(coin, to, o)),
675
733
  recoverStranded: () => this.recoverStranded(),
676
734
  };
677
735
  this.sales = {
678
736
  open: (p) => this.openSale(p),
679
737
  list: () => this.listSales(),
680
738
  view: (id) => this.viewSale(id),
681
- bid: (p) => this.placeBid(p.room, p.v, p.amount),
739
+ bid: (p) => this.paced("bid", p.room, async () => ({ atMs: Number((await this.saleRoom(p.room)).closeMs) }), () => this.placeBid(p.room, p.v, p.amount)),
682
740
  finish: (p) => this.finishSale(p),
683
741
  slash: (p) => this.slashBid(p.room, p.seq),
684
742
  expire: (p) => this.expireSale(p.room, p.vault),
685
- reclaim: (p) => this.reclaimBid(p.room, p.bid, p.what ?? "lock"),
743
+ reclaim: (p) => this.paced("sale_reclaim", p.room, null, () => this.reclaimBid(p.room, p.bid, p.what ?? "lock")),
686
744
  claim: (p) => this.claimItem(p),
687
745
  cancel: (p) => this.cancelSale(p.room, p.vault),
688
746
  badgeGrant: (to) => this.badgeGrant(to),
@@ -702,9 +760,39 @@ export class Essey {
702
760
  readState(o.statePath);
703
761
  const { config, apiOrigin } = await loadConfig(o.config, fetch);
704
762
  const url = relayerUrl(o.relayer ?? "clear", config);
705
- const relay = url === null ? null : new RelayClient({ url, fetch, submitDelayMs: o.submitDelayMs });
763
+ const relay = url === null ? null : new RelayClient({ url, fetch });
706
764
  const relayerBase = url === null ? null : serviceUrl(url, "relayer url").origin;
707
- return new Essey(config, o.statePath, apiOrigin, fetch, io, relay, relayerBase, o.seed && Uint8Array.from(o.seed));
765
+ return new Essey(config, o.statePath, apiOrigin, fetch, io, relay, relayerBase, o.seed && Uint8Array.from(o.seed), pacingOf(o.delays));
766
+ }
767
+ paced(action, subject, deadline, run) {
768
+ return this.pause(action, subject, deadline).then(run);
769
+ }
770
+ /** Runs before the action reads anything its proof binds, so a long wait never stales a Merkle root or `now_s`. */
771
+ async pause(action, subject, deadline) {
772
+ if (!this.pacing)
773
+ return;
774
+ const at = deadline ? await deadline() : null;
775
+ const nowMs = (this.io.now ?? Date.now)();
776
+ const delayMs = paceDelay(action, nowMs, at, Number(CLOSE_MARGIN_MS));
777
+ const wait = this.io.pace ?? ((p) => this.sleep(p.delayMs));
778
+ await wait({ action, subject, delayMs, notBeforeMs: nowMs + delayMs });
779
+ }
780
+ sleep(ms) {
781
+ return (this.io.sleep ?? ((t) => new Promise((resolve) => setTimeout(resolve, t))))(ms);
782
+ }
783
+ /** The current round's `close_ms` (offers, `loan.move:339`) or `settle_by_ms` (settles, `settle.move:132`). */
784
+ async roundDeadline(loanId, field) {
785
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
786
+ const row = await read(address(loanId, "loan id"));
787
+ const at = row?.round?.[field];
788
+ return at === undefined ? null : { atMs: Number(at) };
789
+ }
790
+ /** The stored heartbeat expiry, past which a keeper may liquidate (`keeper.move:204`); none before a first heartbeat. */
791
+ async coverDeadline(loanId) {
792
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
793
+ const row = await read(address(loanId, "loan id"));
794
+ const at = Number(row?.json?.coll?.hb_expiry_ms ?? 0);
795
+ return at > 0 ? { atMs: at, soft: true } : null;
708
796
  }
709
797
  relayClient() {
710
798
  return this.relay ?? notSetUp(NO_RELAYER);
@@ -785,6 +873,9 @@ export class Essey {
785
873
  notSetUp("no credential: call credential.obtain first");
786
874
  const prover = this.io.prover ?? this.missingProver("membership");
787
875
  const readFeeCommit = this.io.readFeeCommit ?? notSetUp("no chain reader: the FeeConfig objects are not published yet");
876
+ const held = this.feeOpenings.get(coin);
877
+ if (held && feeCommit(held) === (await readFeeCommit(coin)))
878
+ return held;
788
879
  const challenge = await getJson(this.fetch, `${api}/v3/fee-params/challenge`);
789
880
  const nonce = challenge.body.nonce;
790
881
  if (challenge.status !== 200 || typeof nonce !== "string")
@@ -805,7 +896,9 @@ export class Essey {
805
896
  });
806
897
  if (reply.status !== 200 || reply.body.ok !== true || reply.body.coin !== coin)
807
898
  throw refusedBy("v3api", reply);
808
- return verifyFeeOpening(reply.body, await readFeeCommit(coin));
899
+ const params = verifyFeeOpening(reply.body, await readFeeCommit(coin));
900
+ this.feeOpenings.set(coin, params);
901
+ return params;
809
902
  }
810
903
  async rates(market) {
811
904
  const id = address(market, "market");
@@ -1214,15 +1307,78 @@ export class Essey {
1214
1307
  }
1215
1308
  return summary;
1216
1309
  }
1217
- async withdraw(coin, amount, to, o = {}) {
1310
+ /** Every refusal that needs no chain read, so a bad call is refused before its wait rather than after it. */
1311
+ withdrawPlan(coin, amount, to, o) {
1218
1312
  if (amount <= 0n)
1219
1313
  throw new EsseyError("INVALID_ARGUMENT", "amount must be above 0");
1220
- return this.spend(coin, { to }, (owned, rates, relayerFee) => {
1314
+ const list = this.config.denominations[coinOf(coin)];
1315
+ if (list === undefined || o.force === true)
1316
+ return { amount, exact: onePayee(to) };
1317
+ const payees = listOf(to).map(payee);
1318
+ const pieces = withdrawPieces(amount, list);
1319
+ return { amount, pieces, sendTo: piecePayees(pieces.length, payees) };
1320
+ }
1321
+ async withdraw(coin, plan, o) {
1322
+ if ("exact" in plan)
1323
+ return [await this.withdrawExact(coin, plan.amount, plan.exact, o)];
1324
+ const { fee, relayerFee, owned } = await this.payoutPlan(coin);
1325
+ refuseUncovered(owned, plan.pieces, fee, relayerFee);
1326
+ refuseLinkedAmount(plan.amount, faucetGrant(coin), owned, fee, relayerFee);
1327
+ return this.payPieces(coin, plan.pieces, plan.sendTo, fee);
1328
+ }
1329
+ async withdrawExact(coin, amount, to, o) {
1330
+ const landed = await this.spend(coin, { to }, (owned, rates, relayerFee) => {
1221
1331
  const inputs = pickInputs(owned, withdrawCost(amount, rates, relayerFee));
1222
1332
  if (o.force !== true)
1223
1333
  refuseLinkedAmount(amount, faucetGrant(coin), owned, rates, relayerFee);
1224
1334
  return { value: amount, inputs };
1225
1335
  });
1336
+ return { ...landed, amount, to: payee(to) };
1337
+ }
1338
+ /** The same reads and set-up checks `spend` makes, once for every piece of a split payout. */
1339
+ async payoutPlan(coin) {
1340
+ this.relayClient();
1341
+ this.relayerAddress();
1342
+ this.prover();
1343
+ const relayerFee = this.coinFee(coin);
1344
+ const fee = await this.feeParams(coin);
1345
+ const { owned } = await this.owned(coin);
1346
+ return { fee, relayerFee, owned };
1347
+ }
1348
+ /** The one loop over a payout's pieces, where a wait between them belongs. Each reads the pool after the last is seen spent. */
1349
+ async payPieces(coin, pieces, to, fee) {
1350
+ const paid = [];
1351
+ let spent = [];
1352
+ for (const [i, amount] of pieces.entries()) {
1353
+ try {
1354
+ if (i > 0)
1355
+ await this.pause("withdraw_piece", `${coin}:${to[i]}`, null);
1356
+ await this.awaitSpent(coin, spent);
1357
+ const landed = await this.spend(coin, { to: to[i] }, (owned, rates, relayerFee) => {
1358
+ spent = pickInputs(owned, withdrawCost(amount, rates, relayerFee));
1359
+ return { value: amount, inputs: spent };
1360
+ }, [], fee);
1361
+ paid.push({ ...landed, amount, to: to[i] });
1362
+ }
1363
+ catch (error) {
1364
+ throw payoutStopped(error, paid, pieces);
1365
+ }
1366
+ }
1367
+ return paid;
1368
+ }
1369
+ async awaitSpent(coin, spent) {
1370
+ if (spent.length === 0)
1371
+ return;
1372
+ const sleep = this.io.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1373
+ for (let i = 0; i < SPENT_POLLS; i++) {
1374
+ const { owned } = await this.owned(coin);
1375
+ if (!owned.some((n) => spent.some((s) => s.index === n.index)))
1376
+ return;
1377
+ await sleep(FOLLOW_MIN_GAP_MS);
1378
+ }
1379
+ throw new EsseyError("RELAY_FAILED", "the pool read does not show the last piece spent yet; the next is unsent", {
1380
+ error: "NOT_INDEXED",
1381
+ });
1226
1382
  }
1227
1383
  receiveAddress() {
1228
1384
  const seed = this.seed();
@@ -1240,25 +1396,47 @@ export class Essey {
1240
1396
  }));
1241
1397
  }
1242
1398
  async exit(coin, to, o = {}) {
1243
- return this.spend(coin, { to }, (owned, rates, relayerFee) => {
1399
+ const list = this.config.denominations[coinOf(coin)];
1400
+ if (list === undefined || o.force === true)
1401
+ return this.exitExact(coin, onePayee(to), o);
1402
+ const payees = listOf(to).map(payee);
1403
+ const { fee, relayerFee, owned } = await this.payoutPlan(coin);
1404
+ if (owned.length > 2)
1405
+ throw new EsseyError("INVALID_ARGUMENT", "refused: exit spends at most two notes");
1406
+ const total = owned.reduce((sum, n) => sum + n.value, 0n);
1407
+ const pieces = exitPieces(total, list, fee, relayerFee);
1408
+ const sendTo = piecePayees(pieces.length, payees);
1409
+ refuseUncovered(owned, pieces, fee, relayerFee);
1410
+ const value = pieces.reduce((sum, piece) => sum + piece, 0n);
1411
+ refuseLinkedAmount(value, faucetGrant(coin), owned, fee, relayerFee);
1412
+ const payouts = await this.payPieces(coin, pieces, sendTo, fee);
1413
+ return { payouts, kept: exitKept(total, pieces, fee, relayerFee) };
1414
+ }
1415
+ async exitExact(coin, to, o) {
1416
+ let value = 0n;
1417
+ let kept = 0n;
1418
+ const landed = await this.spend(coin, { to }, (owned, rates, relayerFee) => {
1244
1419
  if (owned.length > 2)
1245
1420
  throw new EsseyError("INVALID_ARGUMENT", "refused: exit spends at most two notes");
1246
- const value = exitValue(owned.reduce((sum, n) => sum + n.value, 0n), rates, relayerFee);
1421
+ const total = owned.reduce((sum, n) => sum + n.value, 0n);
1422
+ value = exitValue(total, rates, relayerFee);
1247
1423
  if (value === 0n)
1248
1424
  throw new EsseyError("INVALID_ARGUMENT", "refused: nothing to exit after fees");
1249
1425
  if (o.force !== true)
1250
1426
  refuseLinkedAmount(value, faucetGrant(coin), owned, rates, relayerFee);
1427
+ kept = total - withdrawCost(value, rates, relayerFee);
1251
1428
  return { value, inputs: owned };
1252
1429
  });
1430
+ return { payouts: [{ ...landed, amount: value, to: payee(to) }], kept };
1253
1431
  }
1254
1432
  /** js4 with the withdraw field (`src/v3/inputs.ts:39`); the change note's index is on disk before the body leaves. */
1255
- async spend(coin, dest, choose, extra = []) {
1433
+ async spend(coin, dest, choose, extra = [], known) {
1256
1434
  const recipient = "to" in dest ? payee(dest.to) : undefined;
1257
1435
  const relayerFee = decimal(this.config.relayerFee[coinOf(coin)], "config relayerFee");
1258
1436
  const relay = this.relayClient();
1259
1437
  const relayer = this.relayerAddress();
1260
1438
  const prover = this.prover();
1261
- const fee = await this.feeParams(coin);
1439
+ const fee = known ?? (await this.feeParams(coin));
1262
1440
  const { events, owned, seed } = await this.owned(coin);
1263
1441
  const { value, inputs } = choose([...owned, ...extra], fee, relayerFee);
1264
1442
  const tree = poolTree(orderedLeaves(events));
@@ -1306,9 +1484,9 @@ export class Essey {
1306
1484
  }
1307
1485
  /** A 202 carries no digest (`src/v3/relay/client.ts:100`): the ticket is followed until it lands. */
1308
1486
  async follow(relay, queued, what) {
1309
- const sleep = this.io.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1310
- for (let i = 0; i < FOLLOW_POLLS; i++) {
1311
- await sleep(Math.max(queued.etaMs, FOLLOW_MIN_GAP_MS));
1487
+ const gap = Math.max(queued.etaMs, FOLLOW_MIN_GAP_MS);
1488
+ for (let waited = 0; waited < FOLLOW_CAP_MS; waited += gap) {
1489
+ await this.sleep(gap);
1312
1490
  const s = await relay.status(queued.ticket);
1313
1491
  if (s.state === "landed" && s.digest)
1314
1492
  return { digest: s.digest, ticket: queued.ticket };
@@ -1391,15 +1569,36 @@ export class Essey {
1391
1569
  if (this.config.relayer.url === null)
1392
1570
  notSetUp("missing config: the deployment record names no relayer");
1393
1571
  const plan = this.io.planLoanOpen ?? ((q) => this.planOpen(q));
1394
- const read = this.io.readCreated ?? notSetUp("missing config: no loan reader");
1572
+ if (!this.io.readLoans)
1573
+ notSetUp("missing config: no loan reader");
1395
1574
  const proved = await plan(p);
1396
1575
  if (proved.pool !== p.loanCoin)
1397
1576
  wrongCoinObject();
1398
1577
  const landed = await this.paidLoan(openLoan, { ...proved, wait: true });
1399
- const id = await read(landed.digest);
1400
- if (typeof id !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(id))
1401
- unknownObject("the digest created no loan");
1402
- return { ...landed, id: address(id, "loan id") };
1578
+ return { ...landed, id: await this.loanByKey(proved.loanKey) };
1579
+ }
1580
+ /** PRV-07: the new loan is found among all loans by the key the borrower chose, not by its own digest. */
1581
+ async loanByKey(loanKey) {
1582
+ const read = this.io.readLoans ?? notSetUp("missing config: no loan reader");
1583
+ for (let attempt = 0; attempt < FIND_LOAN_TRIES; attempt++) {
1584
+ if (attempt > 0)
1585
+ await this.sleep(FIND_LOAN_PAUSE_MS);
1586
+ let cursor = null;
1587
+ let pages = 0;
1588
+ for (;;) {
1589
+ const page = await read(cursor);
1590
+ pages += 1;
1591
+ const row = page.loans.find((l) => l.json?.loan_key?.toString() === `${loanKey}`);
1592
+ if (row && !/^0x[0-9a-fA-F]{64}$/.test(row.id))
1593
+ unknownObject("the listed loan id is not an object id");
1594
+ if (row)
1595
+ return address(row.id, "loan id");
1596
+ cursor = afterPage(page.next, pages);
1597
+ if (cursor === null)
1598
+ break;
1599
+ }
1600
+ }
1601
+ return unknownObject("the open landed, but no listed loan carries its key yet");
1403
1602
  }
1404
1603
  /**
1405
1604
  * The borrower's `loan_open`: a CollLock spend of up to two own notes into the lock, the Health OPEN rows, the
@@ -2082,7 +2281,7 @@ export class Essey {
2082
2281
  await this.keys();
2083
2282
  const noteIndex = this.reserve("notes");
2084
2283
  const mine = deriveNoteKey(seed, noteIndex);
2085
- const nowS = BigInt(Math.floor((this.io.now ?? Date.now)() / 1000));
2284
+ const nowS = settleNowS((this.io.now ?? Date.now)(), q.closeMs);
2086
2285
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2087
2286
  const plan = (extHash) => loanSettle({
2088
2287
  slots,
@@ -2391,10 +2590,14 @@ export class Essey {
2391
2590
  throw new EsseyError("INVALID_ARGUMENT", "refused: the seizure left this side nothing");
2392
2591
  const note = { value, sk: opened.sk, blinding: outputBlind(opened.blinding, out, seizeNonce) };
2393
2592
  const commitment = noteCommitment(note.value, notePk(note.sk), note.blinding);
2394
- const events = await pools(C);
2593
+ let events = await pools(C);
2395
2594
  const leaf = events.commitments.find((c) => BigInt(c.commitment) === commitment);
2396
2595
  if (!leaf)
2397
2596
  unknownObject("no seized note of this side is in the pool: another offer won, or the loan was topped up");
2597
+ for (let i = 0; i < SEIZE_REWAITS && this.pacing && seizeIsLast(BigInt(events.commitments.length), leaf.index, out); i++) {
2598
+ await this.pause(out === 0 ? "collect_seized" : "collect_surplus", loan, null);
2599
+ events = await pools(C);
2600
+ }
2398
2601
  return this.claimLeaf(C, events, { ...note, index: Number(leaf.index) });
2399
2602
  }
2400
2603
  /** The seed index whose key is `pk`: the borrower key of a loan this seed opened. */
@@ -2608,7 +2811,7 @@ export class Essey {
2608
2811
  const noteIndex = this.reserve("notes");
2609
2812
  const mine = deriveNoteKey(seed, noteIndex);
2610
2813
  const padKey = deriveNoteKey(seed, this.reserve("notes"));
2611
- const nowS = BigInt(Math.floor((this.io.now ?? Date.now)() / 1000));
2814
+ const nowS = settleNowS((this.io.now ?? Date.now)(), q.closeMs);
2612
2815
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2613
2816
  const plan = (extHash) => loanRefi({
2614
2817
  slots,
@@ -2973,7 +3176,7 @@ export class Essey {
2973
3176
  const wait = (last + gap - now + 999n) / 1000n;
2974
3177
  throw new EsseyError("INVALID_ARGUMENT", `the last heartbeat is under one gap old; retry in ${wait} s`);
2975
3178
  }
2976
- const hour = now + 3600000n;
3179
+ const hour = heartbeatHour(now);
2977
3180
  const expiry = asked ?? (stored > hour ? stored : hour);
2978
3181
  if (expiry < now + gap || expiry > now + H_MAX_MS)
2979
3182
  throw new EsseyError("INVALID_ARGUMENT", "the expiry must be at least one gap and at most 24 h ahead");
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  export { COINS, parseConfig, type CoinKey, type V3Config } from "./config.ts";
2
2
  export { ESSEY_ERROR_CODES, EsseyError, isEsseyError, type EsseyErrorCode } from "./errors.ts";
3
- export { Essey, type ConnectOptions, type CredentialInfo, type EsseyIo, type OpenQuote, type Recovered, type Renewal, type SaleOpenTx, type SaleRecord, type SpendOptions, } from "./essey.ts";
3
+ export { Essey, type ConnectOptions, type CredentialInfo, type EsseyIo, type ExitResult, type OpenQuote, type Payees, type Payout, type Recovered, type Renewal, type SaleOpenTx, type SaleRecord, type SpendOptions, } from "./essey.ts";
4
4
  export type { KeeperActions, KeeperBadge, KeeperIo, KeeperQueue, KeeperSection, KeeperVerdict, KeeperVia, Unjudged, } from "./keeper.ts";
5
5
  export type { Landed, Queued, RelayerInfo, TicketState } from "./v3/relay/client.ts";
6
6
  export type { NoteSummary, PoolCommitment, PoolEvents } from "./v3/notes/scan.ts";
7
+ export type { PacedAction, Pause } from "./v3/pace.ts";
7
8
  export type { LoanOpening, LoanOpenParams, MyLoanView, MySaleView, OpenRequest, OpenSale, PoolPosition, PoolView, PublicLoanStatus, PublicLoanView, SaleOpenParams, } from "./v3/stage1.ts";
8
9
  export * as v3 from "./v3/index.ts";
9
10
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,aAAa,CAAC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,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,YAAY,GAClB,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,aAAa,EACb,WAAW,EACX,QAAQ,EACR,WAAW,EACX,aAAa,EACb,aAAa,EACb,SAAS,EACT,QAAQ,GACT,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACrF,YAAY,EAAE,WAAW,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAClF,YAAY,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACvD,YAAY,EACV,WAAW,EACX,cAAc,EACd,UAAU,EACV,UAAU,EACV,WAAW,EACX,QAAQ,EACR,YAAY,EACZ,QAAQ,EACR,gBAAgB,EAChB,cAAc,EACd,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,MAAM,eAAe,CAAC"}
@@ -78,6 +78,8 @@ export type Health = {
78
78
  export declare const NO_TERMS: KeeperTerms;
79
79
  /** What the lender reads out of a TOPUP's `delivery[3..6]` with the key behind `lenderEnc`: the re-locked amount. */
80
80
  export declare function lenderAmount(encSk: bigint, [lEx, lEy, lCt]: [bigint, bigint, bigint]): Promise<bigint>;
81
+ /** Whether the pool's last leaf is still the one closing the seize that inserted output `out` at `index`. */
82
+ export declare function seizeIsLast(leafCount: bigint, index: bigint, out: 0 | 1): boolean;
81
83
  /**
82
84
  * A seizure's split of the lock (B §5.5, `health.circom:303-346`): what the seizer proves, and what the lender and the
83
85
  * borrower recompute afterwards from the claimed `p_spot` the seizing call took. FAULT seizes the whole lock and runs
@@ -1 +1 @@
1
- {"version":3,"file":"health.d.ts","sourceRoot":"","sources":["../../../src/v3/collateral/health.ts"],"names":[],"mappings":"AAKA,OAAO,EAA6D,KAAK,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5G,OAAO,KAAK,EAAE,YA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cAAc,EAAE,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC,CAAC;IACjD,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;;;;;;;;;;;;;EASA;AAED,0GAA0G;AAC1G,wBAAgB,QAAQ,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,CAKzG;AAuDD,4FAA4F;AAC5F,wBAAsB,MAAM,CAAC,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC,CAwI7D"}
@@ -43,6 +43,12 @@ export async function lenderAmount(encSk, [lEx, lEy, lCt]) {
43
43
  const { sx } = await ecdhBlind(lEx, lEy, encSk);
44
44
  return (lCt - lenderMask(sx) + R) % R;
45
45
  }
46
+ /** A seize inserts `[out 0, out 3, out 1, out 2]` (`move/v3/loan/sources/liquidation.move:445-446`). */
47
+ const SEIZE_LEAF_AT = { 0: 0, 1: 2 };
48
+ /** Whether the pool's last leaf is still the one closing the seize that inserted output `out` at `index`. */
49
+ export function seizeIsLast(leafCount, index, out) {
50
+ return leafCount === index - BigInt(SEIZE_LEAF_AT[out]) + 4n;
51
+ }
46
52
  /**
47
53
  * A seizure's split of the lock (B §5.5, `health.circom:303-346`): what the seizer proves, and what the lender and the
48
54
  * borrower recompute afterwards from the claimed `p_spot` the seizing call took. FAULT seizes the whole lock and runs
@@ -8,7 +8,8 @@ export type LineRisk = {
8
8
  /**
9
9
  * `underwater` is the LIQUIDATE statement: over the line at both spot and EMA (`health.circom:282-283`).
10
10
  * `liquidationPrice` is the lowest price not over the line (`value.circom:33-34,124,244-253`), null when none is.
11
- * `bestBucketK` is the deepest floor of `liquidation.move:451-455` still healthy (`health.circom:281`), or null.
11
+ * `coveredAtDefaultK` is whether the k 1 floor of `liquidation.move:451-455` is healthy (`health.circom:281`). A
12
+ * deeper healthy k is not computed: a finer bucket publishes more of the loan's LTV band (LOAN-06).
12
13
  * `ltvBps` is floor(owed · 10000 / value) at min(spot, EMA), the cap `open_price_ok` puts on an OPEN's price
13
14
  * (`move/v3/market/sources/market.move:241-245`), null at value 0. It is on owed and no on-chain line computes
14
15
  * it: `health.circom:271-281` compares principal, at OPEN only.
@@ -17,7 +18,7 @@ export type LocalHealth = {
17
18
  ltvBps: bigint | null;
18
19
  underwater: boolean;
19
20
  liquidationPrice: bigint | null;
20
- bestBucketK: number | null;
21
+ coveredAtDefaultK: boolean;
21
22
  };
22
23
  export declare function localHealth(collAmt: bigint, owed: bigint, risk: LineRisk, r: Reading): LocalHealth;
23
24
  //# sourceMappingURL=local-health.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"local-health.d.ts","sourceRoot":"","sources":["../../../src/v3/collateral/local-health.ts"],"names":[],"mappings":"AAEA,OAAO,EAAmD,KAAK,OAAO,EAAE,MAAM,WAAW,CAAC;AAE1F,oEAAoE;AACpE,MAAM,MAAM,QAAQ,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtE;;;;;;;GAOG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,UAAU,EAAE,OAAO,CAAC;IACpB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B,CAAC;AAWF,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,EAAE,OAAO,GAAG,WAAW,CAclG"}
1
+ {"version":3,"file":"local-health.d.ts","sourceRoot":"","sources":["../../../src/v3/collateral/local-health.ts"],"names":[],"mappings":"AAEA,OAAO,EAAqC,KAAK,OAAO,EAAE,MAAM,WAAW,CAAC;AAE5E,oEAAoE;AACpE,MAAM,MAAM,QAAQ,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtE;;;;;;;;GAQG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,UAAU,EAAE,OAAO,CAAC;IACpB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,iBAAiB,EAAE,OAAO,CAAC;CAC5B,CAAC;AAWF,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,EAAE,OAAO,GAAG,WAAW,CAWlG"}
@@ -1,5 +1,5 @@
1
1
  import { BPS_DENOM } from "../fees.js";
2
- import { K_MAX, K_MIN, heartbeatFloor, overLine, valueAt } from "./math.js";
2
+ import { heartbeatFloor, overLine, valueAt } from "./math.js";
3
3
  const ceilDiv = (a, b) => (a + b - 1n) / b;
4
4
  function healthyFrom(collAmt, owed, risk, expo) {
5
5
  if (owed === 0n)
@@ -14,14 +14,10 @@ export function localHealth(collAmt, owed, risk, r) {
14
14
  const over = (price) => overLine(valueAt(collAmt, price, scale).q, owed, risk.liqBps);
15
15
  const low = r.spot < r.ema ? r.spot : r.ema;
16
16
  const value = valueAt(collAmt, low, scale).q;
17
- let bestBucketK = null;
18
- for (let k = K_MAX; k >= K_MIN && bestBucketK === null; k--)
19
- if (!over(heartbeatFloor(r, k)))
20
- bestBucketK = k;
21
17
  return {
22
18
  ltvBps: value === 0n ? null : (owed * BPS_DENOM) / value,
23
19
  underwater: over(r.spot) && over(r.ema),
24
20
  liquidationPrice: healthyFrom(collAmt, owed, risk, r.expo),
25
- bestBucketK,
21
+ coveredAtDefaultK: !over(heartbeatFloor(r, 1)),
26
22
  };
27
23
  }
@@ -16,6 +16,7 @@ export * from "./kinds.ts";
16
16
  export * from "./market.ts";
17
17
  export * from "./notes/keys.ts";
18
18
  export * as notes from "./notes/index.ts";
19
+ export * from "./pace.ts";
19
20
  export * from "./proof-bytes.ts";
20
21
  export * from "./prover.ts";
21
22
  export { credentialSigned, epochEnd, expiryAllowed, parseCredential, type Role, type Slot, } from "./credential/issue.ts";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/v3/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,cAAc,aAAa,CAAC;AAC5B,OAAO,KAAK,UAAU,MAAM,uBAAuB,CAAC;AACpD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAC3C,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,OAAO,KAAK,KAAK,MAAM,kBAAkB,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,YAAY,CAAC;AAC3B,cAAc,4BAA4B,CAAC;AAC3C,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,qBAAqB,CAAC;AACpC,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAChC,OAAO,KAAK,KAAK,MAAM,kBAAkB,CAAC;AAC1C,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC;AAC5B,OAAO,EACL,gBAAgB,EAChB,QAAQ,EACR,aAAa,EACb,eAAe,EACf,KAAK,IAAI,EACT,KAAK,IAAI,GACV,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,KAAK,MAAM,EAAE,KAAK,MAAM,EAAE,KAAK,WAAW,EAAE,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC9G,OAAO,EACL,iBAA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