@esseyonsui/sui-sdk-v3 0.2.0 → 0.3.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 (70) hide show
  1. package/dist/essey.d.ts +106 -21
  2. package/dist/essey.d.ts.map +1 -1
  3. package/dist/essey.js +456 -164
  4. package/dist/index.d.ts +1 -1
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/v3/collateral/bodies.d.ts +2 -1
  7. package/dist/v3/collateral/bodies.d.ts.map +1 -1
  8. package/dist/v3/collateral/bodies.js +5 -5
  9. package/dist/v3/collateral/local-health.d.ts +2 -2
  10. package/dist/v3/collateral/local-health.js +1 -1
  11. package/dist/v3/collateral/math.d.ts +8 -9
  12. package/dist/v3/collateral/math.d.ts.map +1 -1
  13. package/dist/v3/collateral/math.js +65 -13
  14. package/dist/v3/index.d.ts +1 -0
  15. package/dist/v3/index.d.ts.map +1 -1
  16. package/dist/v3/index.js +1 -0
  17. package/dist/v3/kinds.d.ts +5 -2
  18. package/dist/v3/kinds.d.ts.map +1 -1
  19. package/dist/v3/kinds.js +7 -1
  20. package/dist/v3/loans/bodies.d.ts +16 -0
  21. package/dist/v3/loans/bodies.d.ts.map +1 -1
  22. package/dist/v3/loans/bodies.js +13 -0
  23. package/dist/v3/loans/open-plan.d.ts +2 -0
  24. package/dist/v3/loans/open-plan.d.ts.map +1 -1
  25. package/dist/v3/loans/open-plan.js +1 -1
  26. package/dist/v3/loans/refi-plan.d.ts.map +1 -1
  27. package/dist/v3/loans/refi-plan.js +2 -4
  28. package/dist/v3/loans/settle-plan.d.ts +7 -2
  29. package/dist/v3/loans/settle-plan.d.ts.map +1 -1
  30. package/dist/v3/loans/settle-plan.js +15 -15
  31. package/dist/v3/memo.d.ts +68 -0
  32. package/dist/v3/memo.d.ts.map +1 -0
  33. package/dist/v3/memo.js +147 -0
  34. package/dist/v3/sales/auctioneer.d.ts +8 -3
  35. package/dist/v3/sales/auctioneer.d.ts.map +1 -1
  36. package/dist/v3/sales/auctioneer.js +22 -5
  37. package/dist/v3/sales/bid.d.ts +3 -0
  38. package/dist/v3/sales/bid.d.ts.map +1 -1
  39. package/dist/v3/sales/bid.js +3 -0
  40. package/dist/v3/sales/bodies.d.ts +14 -2
  41. package/dist/v3/sales/bodies.d.ts.map +1 -1
  42. package/dist/v3/sales/bodies.js +11 -2
  43. package/dist/v3/sales/index.d.ts +3 -0
  44. package/dist/v3/sales/index.d.ts.map +1 -1
  45. package/dist/v3/sales/index.js +3 -0
  46. package/dist/v3/sales/listing.d.ts +19 -0
  47. package/dist/v3/sales/listing.d.ts.map +1 -0
  48. package/dist/v3/sales/listing.js +41 -0
  49. package/dist/v3/sales/memo.d.ts +4 -0
  50. package/dist/v3/sales/memo.d.ts.map +1 -0
  51. package/dist/v3/sales/memo.js +6 -0
  52. package/dist/v3/sales/open-kind.d.ts +4 -1
  53. package/dist/v3/sales/open-kind.d.ts.map +1 -1
  54. package/dist/v3/sales/open-kind.js +4 -3
  55. package/dist/v3/sales/package-gate.d.ts +14 -0
  56. package/dist/v3/sales/package-gate.d.ts.map +1 -0
  57. package/dist/v3/sales/package-gate.js +24 -0
  58. package/dist/v3/sales/rows.d.ts +1 -0
  59. package/dist/v3/sales/rows.d.ts.map +1 -1
  60. package/dist/v3/sales/rows.js +3 -1
  61. package/dist/v3/sales/seller.d.ts +34 -10
  62. package/dist/v3/sales/seller.d.ts.map +1 -1
  63. package/dist/v3/sales/seller.js +43 -16
  64. package/dist/v3/stage1.d.ts +3 -3
  65. package/dist/v3/stage1.d.ts.map +1 -1
  66. package/dist/v3/stage1.js +3 -4
  67. package/dist/v3/time-grid.d.ts +12 -1
  68. package/dist/v3/time-grid.d.ts.map +1 -1
  69. package/dist/v3/time-grid.js +17 -2
  70. package/package.json +1 -1
package/dist/essey.js CHANGED
@@ -13,13 +13,14 @@ import { address, assertTestnet, decimal, fixedHeaders, getJson, postJson, servi
13
13
  import { credentialSigned, parseCredential, renewOpensAt, requestCredential, solveChallenge, } from "./v3/credential/issue.js";
14
14
  import { DOMAIN_KEEPER, DOMAIN_SENDER, DOMAIN_SPEND, FEE_PARAMS_ROOM, feeNonceLane, memberCommitment, } from "./v3/credential/membership.js";
15
15
  import { passProof, transfer as transferBody, withdraw as withdrawBody, } from "./v3/bodies.js";
16
- import { cancel as cancelLoan, slash as slashLoan, ctFault as ctFaultLoan, cancelRefi as cancelRefiLoan, claimDefault as claimDefaultLoan, offer as offerLoan, open as openLoan, reclaim as reclaimLoan, reclaimColl as reclaimCollLoan, refinance as refinanceLoan, settleRefi as settleRefiLoan, repay as repayLoan, settle as settleLoan, } from "./v3/loans/bodies.js";
16
+ import { cancel as cancelLoan, slash as slashLoan, ctFault as ctFaultLoan, cancelRefi as cancelRefiLoan, claimDefault as claimDefaultLoan, offer as offerLoan, open as openLoan, pick as pickLoan, reclaim as reclaimLoan, reclaimColl as reclaimCollLoan, refinance as refinanceLoan, settleRefi as settleRefiLoan, repay as repayLoan, settle as settleLoan, } from "./v3/loans/bodies.js";
17
17
  import { DOM_LBLIND, DOM_TSALT, R } from "./v3/domains.js";
18
18
  import { MODE_OPEN, MODE_TOPUP, NO_ADDRESS, collLockExt } from "./v3/ext.js";
19
19
  import { defaultExt, faultExt, heartbeatExt, liquidateExt, openExt, releaseExt, topupByBorrowerExt, topupExt, } from "./v3/collateral/ext.js";
20
20
  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";
21
- import { GRACE_S, coverExpiry, heartbeatFloor } from "./v3/collateral/math.js";
22
- import { assertLoanGrid, assertRequestClose, assertRequestTerm, assertSaleGrid, defaultNowS, settleNowS, } from "./v3/time-grid.js";
21
+ import { COVER_STEP_MS, GRACE_S, coverExpiry, coverOverStored, heartbeatFloor, legacyHeartbeatFloor, } from "./v3/collateral/math.js";
22
+ import { assertLoanGrid, assertRequestClose, assertRequestTerm, closeWaitMs, defaultNowS, gridClose, settleNowS, } from "./v3/time-grid.js";
23
+ import { MEMO_KIND, memoKey, offerMemoBody, openOfferMemo, openRequestMemo, openSettleMemo, requestMemoBody, sealBidMemo, sealMemo, sealSaleMemo, settleMemoBody, } from "./v3/memo.js";
23
24
  /**
24
25
  * The Seal servers dry-run `keeper::check_loan` and answer "does not have access" when it aborts: a heartbeat still
25
26
  * covers the loan at this price, the loan is not active, or the pass or badge does not match.
@@ -46,7 +47,7 @@ import { KEEPER_LAYOUT_VERSION, encodeKeeperPayload } from "./v3/keeper-payload.
46
47
  import { LOAN_REPAY_KIND, loanRepay } from "./v3/loans/repay-plan.js";
47
48
  import { reclaimColl, reclaimLock } from "./v3/loans/reclaim-plan.js";
48
49
  import { collLock, keyId, openAction, requestKeyId, requestPlaintext } from "./v3/loans/open-plan.js";
49
- import { LOAN_SETTLE_KIND, actionHash, decodeOffer, interest, loanSettle, offerOpens, sealOfferBind, settleArgs, openRefiArgs, readingBytes, settleRefiArgs, cancelRefiArgs, topupArgs, } from "./v3/loans/settle-plan.js";
50
+ import { LOAN_SETTLE_KIND, SETTLE_SLOTS, actionHash, decodeOffer, interest, loanSettle, offerOpens, sealOfferBind, settleArgs, openRefiArgs, readingBytes, settleRefiArgs, cancelRefiArgs, topupArgs, } from "./v3/loans/settle-plan.js";
50
51
  import { lockRound } from "./v3/loans/lock-round.js";
51
52
  import { LOAN_REFI_KIND, loanRefi } from "./v3/loans/refi-plan.js";
52
53
  import { LOAN_OFFER_KIND, decodeRequest, lock4, lockField, loanExt, loanOffer, offerKeyId, offerPlaintext, offerRoom, sealListingBind, } from "./v3/loans/offer-plan.js";
@@ -58,13 +59,15 @@ import { marketRates } from "./v3/market.js";
58
59
  import { afterPage, assertLoanOpen, assertRoomMatches, assertSaleOpen, coinByPool, openPosition, poolId, requireSale, summarizeLoan, summarizeRoom, viewLoanObject, viewPosition, viewRoomObject, } from "./v3/stage1.js";
59
60
  import { plan as settlePlan } from "./v3/sales/auctioneer.js";
60
61
  import { lockBid } from "./v3/sales/bid.js";
61
- import { bidBody, cancelBody, claimBody, expireBody, finishBody, reclaimBody, slashBody, } from "./v3/sales/bodies.js";
62
+ import { bidBody, cancelBody, claimBody, expireBody, finishBody, pickBody, reclaimBody, slashBody, } from "./v3/sales/bodies.js";
62
63
  import { itemClaim } from "./v3/sales/claim.js";
64
+ import { listingKeyId, listingPlaintext, readListing } from "./v3/sales/listing.js";
63
65
  import { saleOpenKind } from "./v3/sales/open-kind.js";
64
66
  import { SALE_STATE } from "./v3/sales/outcome.js";
67
+ import { saleKindGate, salePackageOf } from "./v3/sales/package-gate.js";
65
68
  import { reclaim as saleReclaim } from "./v3/sales/reclaim.js";
66
69
  import { bidAad, bidKeyId, bidPlaintext, openBid, sealBidBind } from "./v3/sales/rows.js";
67
- import { assertFinishWindow, openArgs, openCommits, typeNameOf } from "./v3/sales/seller.js";
70
+ import { openArgs, openCommits, saleSecrets, saleTimes, typeNameOf } from "./v3/sales/seller.js";
68
71
  import { splitDenominations } from "./v3/notes/denominations.js";
69
72
  import { DEPOSIT_ROOM, carriesKind, depositKind, executeSponsored, sponsor, } from "./v3/notes/deposit.js";
70
73
  import { SEED_BYTES, deriveNoteKey, depositSigner, itemHolder, noteEncKey, receiveKey, } from "./v3/notes/derive.js";
@@ -95,9 +98,8 @@ const POSSESSION_TTL_MS = 5 * 60_000;
95
98
  /** NEEDS-BORIS: the relayer's default `sponsorWindowMs` (`services/relayer-v3/src/config.ts:261`); it serves no route that names its own. */
96
99
  const SPONSOR_WINDOW_MS = 10 * 60_000;
97
100
  const HOUR_MS = 3_600_000;
98
- /** `MAX_BIDDING_MS` (move/v3/loan/sources/loan.move:42) and `MAX_OPEN_MS` (move/v3/sale/sources/sale_room.move:68). */
99
- const LOAN_MAX_WINDOW_MS = 7 * 86_400_000;
100
- const SALE_MAX_WINDOW_MS = 30 * 86_400_000;
101
+ /** Lane SDK-B's allowance from choosing a sale's close to its open landing (`R1-SDKB-ESSEY-CALLSITES.md` §3). */
102
+ const SALE_LAND_MARGIN_MS = 60_000;
101
103
  /** Measured offer submit-to-land on testnet: median 56 s, p95 83 s. A later send aborts at close, after its proofs. */
102
104
  const CLOSE_MARGIN_MS = 120000n;
103
105
  const NO_TO = "no to address: the zero address is nobody's; nothing was sent";
@@ -111,6 +113,19 @@ function unknownObject(what) {
111
113
  function wrongCoinObject() {
112
114
  throw new EsseyError("INVALID_ARGUMENT", "wrong coin: the envelope pool is not the loan coin");
113
115
  }
116
+ /**
117
+ * The original ids of the retired `pkg`, the address in its objects' types: the record's optional
118
+ * `previous.packageOrigins` (`services/v3api/src/config-route.ts` `PreviousPackages`).
119
+ */
120
+ function previousOrigins(config, pkg) {
121
+ const record = config;
122
+ const id = record.previous?.packageOrigins?.[pkg];
123
+ return typeof id === "string" ? [normalizeSuiAddress(id)] : [];
124
+ }
125
+ /** `loan.move` `E_CLOSE_GRID`: the open landed a step later than its close was chosen for; a fresh close lands. */
126
+ const E_CLOSE_GRID = 42_046;
127
+ const lateClose = (err) => (isEsseyError(err, "RELAY_FAILED") || isEsseyError(err, "RELAY_REFUSED")) &&
128
+ err.detail?.abort?.code === E_CLOSE_GRID;
114
129
  function readRequestPlain(plain) {
115
130
  try {
116
131
  return decodeRequest(plain);
@@ -514,15 +529,22 @@ function sweepTemps(path) {
514
529
  }
515
530
  const blake2b256 = (bytes) => blake2b(bytes, { dkLen: 32 });
516
531
  const hexBytes = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
517
- /** A Move `Option<u256>` read as JSON: null, the value, or `{ vec: [] | [value] }`. */
518
- function optionU256(raw) {
532
+ /** A Move `Option<u256>` or `Option<u64>` read as JSON: null, the value, or `{ vec: [] | [value] }`. */
533
+ function optionU256(raw, what = "the vault claim") {
519
534
  const inner = raw && typeof raw === "object" ? raw.vec?.[0] : raw;
520
535
  if (inner === null || inner === undefined)
521
536
  return null;
522
537
  if (typeof inner !== "string" && typeof inner !== "number")
523
- unknownObject("the vault claim is not a u256");
538
+ unknownObject(`${what} is not a number`);
524
539
  return BigInt(inner);
525
540
  }
541
+ /** A Move `Option<vector<u8>>` read as JSON, base64 inside as `readRoom` gives `bids[i].sealed`; UNVERIFIED shape. */
542
+ function optionBytes(raw) {
543
+ const inner = raw && typeof raw === "object" ? raw.vec?.[0] : raw;
544
+ return typeof inner === "string" ? Uint8Array.from(Buffer.from(inner, "base64")) : undefined;
545
+ }
546
+ /** PRV-23 A: the round's `pick` (`loan.move:108`), null until `pick::pick` lands and after a slash clears it. */
547
+ const pickOf = (round) => optionU256(round?.pick, "the round's pick");
526
548
  function asInvalid(run) {
527
549
  try {
528
550
  return run();
@@ -675,16 +697,6 @@ function payoutStopped(error, paid, rest) {
675
697
  stopped.cause = error;
676
698
  return stopped;
677
699
  }
678
- /**
679
- * LOAN-01: close_ms is public, so an exact close publishes the caller's chosen window. It rounds up to a whole
680
- * `step` (an hour unless the deployment sets `closeStepMs`), or down one step when up would pass the chain's
681
- * longest window, which is still far above its shortest.
682
- */
683
- function stepClose(closeMs, nowMs, maxWindowMs, step = HOUR_MS) {
684
- const up = Math.ceil(closeMs / step) * step;
685
- const over = up - nowMs > maxWindowMs && closeMs - nowMs <= maxWindowMs;
686
- return over ? up - step : up;
687
- }
688
700
  function refusedBy(service, reply) {
689
701
  const error = typeof reply.body.error === "string" ? reply.body.error : undefined;
690
702
  return new EsseyError("SERVICE_REFUSED", `${service} refused: ${error ?? reply.status}`, {
@@ -753,7 +765,7 @@ export class Essey {
753
765
  await this.refuseOffGridClose(p.loan);
754
766
  const send = async () => {
755
767
  await this.pause("offer", p.loan, closeOf(p.loan));
756
- const { body, record, seq } = await this.planOffer(p.loan, BigInt(p.rateBps));
768
+ const { body, record, seq } = await this.planOffer(p.loan);
757
769
  return {
758
770
  seq,
759
771
  sent: this.paidLoan(offerLoan, body).then((landed) => ({ ...landed, offer: record })),
@@ -797,6 +809,7 @@ export class Essey {
797
809
  keeperLiquidate: (p) => this.paced("liquidate", p.loan, null, () => this.keeperLiquidate(p.loan, p.via)),
798
810
  reclaimCollateral: (p) => this.paced("reclaim_collateral", p.loan, null, () => this.reclaimOwnCollateral(p.loan, p.collAmt)),
799
811
  recover: (p) => this.recoverOwnLoan(p.loan),
812
+ recoverRecords: () => this.recoverRecords(),
800
813
  payBack: (p) => this.paced("repay", p.loan, async () => repayDeadline(p.terms), async () => this.paidLoan(repayLoan, await this.planRepay(p.loan, p.terms, p.borrowerPk))),
801
814
  settle: (p) => this.freeLoan(settleLoan, p),
802
815
  repay: (p) => this.paidLoan(repayLoan, p),
@@ -837,9 +850,9 @@ export class Essey {
837
850
  open: (p) => this.openSale(p),
838
851
  list: () => this.listSales(),
839
852
  view: (id) => this.viewSale(id),
840
- bid: (p) => this.paced("bid", p.room, async () => ({ atMs: Number((await this.saleRoom(p.room)).closeMs) }), () => this.placeBid(p.room, p.v, p.amount)),
853
+ bid: (p) => this.paced("bid", p.room, async () => ({ atMs: Number((await this.saleRoom(p.room, "bid")).closeMs) }), () => this.placeBid(p.room, p.maxPrice, p.amount)),
841
854
  finish: (p) => this.finishSale(p),
842
- slash: (p) => this.slashBid(p.room, p.seq),
855
+ slash: (p) => this.slashBid(p.room),
843
856
  expire: (p) => this.expireSale(p.room, p.vault),
844
857
  reclaim: (p) => this.paced("sale_reclaim", p.room, null, () => this.reclaimBid(p.room, p.bid, p.what ?? "lock")),
845
858
  claim: (p) => this.claimItem(p),
@@ -1015,10 +1028,28 @@ export class Essey {
1015
1028
  if (held && feeCommit(held) === (await readFeeCommit(coin, lane)))
1016
1029
  return held;
1017
1030
  const body = await this.feePass("/v3/fee-params", { coin, ...(lane === "edge" ? { lane } : {}) });
1018
- const params = verifyFeeOpening(body, await readFeeCommit(coin, lane));
1031
+ const params = await this.servedOrStaged(coin, body, await readFeeCommit(coin, lane));
1019
1032
  this.feeOpenings.set(key, params);
1020
1033
  return params;
1021
1034
  }
1035
+ /**
1036
+ * PRV-02 O5: across a `fee_config::update` the book's current row trails the chain, and the opening the chain now
1037
+ * holds is a staged `next` row, filed by commit (`services/v3api/src/fee-archive.ts:60-82`).
1038
+ */
1039
+ async servedOrStaged(coin, served, onChain) {
1040
+ try {
1041
+ return verifyFeeOpening(served, onChain);
1042
+ }
1043
+ catch (mismatch) {
1044
+ try {
1045
+ return await this.loanFee(coin, onChain);
1046
+ }
1047
+ catch (error) {
1048
+ const unknown = isEsseyError(error, "SERVICE_REFUSED") && error.detail?.error === "FEE_OPENING_UNKNOWN";
1049
+ throw unknown ? mismatch : error;
1050
+ }
1051
+ }
1052
+ }
1022
1053
  /**
1023
1054
  * PRV-02: a loan step folds the loan's own snapshot (`loan.move:141-143`), not the config as it stands, so its
1024
1055
  * opening is fetched by that commit (v3api's archive) and must hash to it.
@@ -1836,10 +1867,13 @@ export class Essey {
1836
1867
  const plan = this.io.planLoanOpen ?? ((q) => this.planOpen(q));
1837
1868
  if (!this.io.readLoans)
1838
1869
  notSetUp("missing config: no loan reader");
1839
- const proved = await plan(p);
1840
- if (proved.pool !== p.loanCoin)
1841
- wrongCoinObject();
1842
- const landed = await this.paidLoan(openLoan, { ...proved, wait: true });
1870
+ const send = async () => {
1871
+ const proved = await plan(p);
1872
+ if (proved.pool !== p.loanCoin)
1873
+ wrongCoinObject();
1874
+ return { proved, landed: await this.paidLoan(openLoan, { ...proved, wait: true }) };
1875
+ };
1876
+ const { proved, landed } = await send().catch((err) => (lateClose(err) ? send() : Promise.reject(err)));
1843
1877
  const read = this.io.readLoans;
1844
1878
  const row = await this.listedByKey("loan", "loan_key", proved.loanKey, async (c) => {
1845
1879
  const page = await read(c);
@@ -1904,7 +1938,8 @@ export class Essey {
1904
1938
  pathElements: tree.path(n.index),
1905
1939
  }));
1906
1940
  await this.keys();
1907
- const own = deriveNoteKey(seed, this.reserve("notes"));
1941
+ const ownIndex = this.reserve("notes");
1942
+ const own = deriveNoteKey(seed, ownIndex);
1908
1943
  const changeIndex = this.reserve("notes");
1909
1944
  const change = deriveNoteKey(seed, changeIndex);
1910
1945
  const borrowerPk = notePk(own.sk);
@@ -1917,17 +1952,6 @@ export class Essey {
1917
1952
  termMs: BigInt(p.termMs),
1918
1953
  salt: poseidonHash([own.sk, own.blinding, 2n]),
1919
1954
  };
1920
- const closeMs = this.loanClose(p.offerWindowMs);
1921
- const reqSealed = await seal({
1922
- id: requestKeyId(loanKey),
1923
- data: requestPlaintext({
1924
- ...request,
1925
- borrowerPk,
1926
- closeMs,
1927
- market,
1928
- coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
1929
- }),
1930
- });
1931
1955
  const keeperCt = await seal({
1932
1956
  id: keeperKeyId(loanKey, 0n),
1933
1957
  data: encodeKeeperPayload({
@@ -1970,7 +1994,33 @@ export class Essey {
1970
1994
  request,
1971
1995
  });
1972
1996
  const reqCommit = requestCommit(request, borrowerPk, note);
1973
- const passN0 = openAction(loanKey, { reqCommit, reqSealed, closeMs, market, collateralCommit: note });
1997
+ const proved = async (circuit, input, publics) => ({
1998
+ proof: (await prover.prove(circuit, input)).proof,
1999
+ publicSignals: publics.map(String),
2000
+ });
2001
+ const lockProved = await proved("coll_lock", lock.input, lock.publics);
2002
+ const healthProved = await proved("health", open.input, open.publics);
2003
+ // The close goes last, after the slow proofs, so the open lands in the step it was chosen in (42_046).
2004
+ const closeMs = await this.loanClose(p.offerWindowMs);
2005
+ const reqSealed = await seal({
2006
+ id: requestKeyId(loanKey),
2007
+ data: requestPlaintext({
2008
+ ...request,
2009
+ borrowerPk,
2010
+ closeMs,
2011
+ market,
2012
+ coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
2013
+ }),
2014
+ });
2015
+ const memo = sealMemo(memoKey(seed), { kind: MEMO_KIND.request, key: loanKey, round: 0n }, requestMemoBody({ keyIndex: ownIndex, collAmt: p.collateral, borrowerPk }));
2016
+ const passN0 = openAction(loanKey, {
2017
+ reqCommit,
2018
+ reqSealed,
2019
+ closeMs,
2020
+ market,
2021
+ collateralCommit: note,
2022
+ memo,
2023
+ });
1974
2024
  const pass = membership({
1975
2025
  secrets: member,
1976
2026
  credential: credential,
@@ -1978,10 +2028,6 @@ export class Essey {
1978
2028
  room: keyId(loanKey),
1979
2029
  bind: keyId(passN0),
1980
2030
  });
1981
- const proved = async (circuit, input, publics) => ({
1982
- proof: (await prover.prove(circuit, input)).proof,
1983
- publicSignals: publics.map(String),
1984
- });
1985
2031
  return {
1986
2032
  pool: L,
1987
2033
  pass: {
@@ -1990,12 +2036,13 @@ export class Essey {
1990
2036
  expiryMs: credential.expiryMs,
1991
2037
  n0: passN0,
1992
2038
  },
1993
- collLock: await proved("coll_lock", lock.input, lock.publics),
1994
- health: await proved("health", open.input, open.publics),
2039
+ collLock: lockProved,
2040
+ health: healthProved,
1995
2041
  market,
1996
2042
  loanKey,
1997
2043
  reqCommit,
1998
2044
  reqSealed,
2045
+ memo,
1999
2046
  closeMs,
2000
2047
  collateralCommit: note,
2001
2048
  lock: lock.spend,
@@ -2006,11 +2053,34 @@ export class Essey {
2006
2053
  priceUpdate: await update(market),
2007
2054
  };
2008
2055
  }
2009
- /** The coins of the market a loan names, as `C/L` in the deployment record. */
2010
- loanClose(offerWindowMs) {
2011
- const nowMs = (this.io.now ?? Date.now)();
2012
- return BigInt(stepClose(nowMs + offerWindowMs, nowMs, LOAN_MAX_WINDOW_MS, this.config.closeStepMs));
2056
+ saleGate(kind, type) {
2057
+ const current = this.config.packageOrigins.sale ?? notSetUp("the sale package is not published yet");
2058
+ const previous = previousOrigins(this.config, "sale");
2059
+ return asInvalid(() => saleKindGate(kind, type, { current, previous }));
2060
+ }
2061
+ /** DECISION-R1-MIGRATION A: a loan whose type names `previous.packageOrigins.loan` is draining. */
2062
+ retired(row) {
2063
+ const pkg = row?.type?.split("::")[0];
2064
+ return pkg !== undefined && previousOrigins(this.config, "loan").includes(normalizeSuiAddress(pkg));
2065
+ }
2066
+ /**
2067
+ * A draining loan takes no opening kind (request read, offer, refi open) and none whose call changed shape in R1
2068
+ * (pick, settle, refi settle); it still cancels, repays, releases, reclaims, collects, tops up and heartbeats.
2069
+ */
2070
+ refuseRetired(row) {
2071
+ if (this.retired(row))
2072
+ throw new EsseyError("INVALID_ARGUMENT", "refused: this loan is on a retired loan package and only finishes there (cancel, repay, release, reclaim, collect, top up, heartbeat); nothing was sent");
2073
+ }
2074
+ /** PRV-27 (b): past a step boundary nearer than the landing margin first, then the close `loan::check_close` takes. */
2075
+ async loanClose(offerWindowMs) {
2076
+ const step = this.config.closeStepMs ?? HOUR_MS;
2077
+ const now = () => (this.io.now ?? Date.now)();
2078
+ const wait = closeWaitMs(now(), step, Number(CLOSE_MARGIN_MS));
2079
+ if (wait > 0)
2080
+ await this.sleep(wait);
2081
+ return gridClose(now(), offerWindowMs, step);
2013
2082
  }
2083
+ /** The coins of the market a loan names, as `C/L` in the deployment record. */
2014
2084
  pairOf(market) {
2015
2085
  const want = address(market, "market");
2016
2086
  const hit = Object.entries(this.config.objects.markets).find(([, id]) => id && address(id, "market") === want);
@@ -2029,6 +2099,7 @@ export class Essey {
2029
2099
  const row = await read(loan);
2030
2100
  if (!row)
2031
2101
  unknownObject("no loan with this id");
2102
+ this.refuseRetired(row);
2032
2103
  const json = row.json;
2033
2104
  const round = row.round;
2034
2105
  const refi = Number(json.state) === 8;
@@ -2102,15 +2173,17 @@ export class Essey {
2102
2173
  const offers = row?.round?.offers;
2103
2174
  return offers !== undefined && BigInt(offers.length) > seq;
2104
2175
  }
2105
- /** The lender's `loan_offer`: the principal locked to the round from up to two own notes, its sealed terms pinned. */
2106
- async planOffer(loanId, rateBps) {
2176
+ /**
2177
+ * The lender's `loan_offer`: the principal locked to the round from up to two own notes, its sealed terms pinned.
2178
+ * PRV-23 A, SCOPE-R1-MOVE-BATCH D10: the rate is the posted one, so offers differ in nothing the winner draw weighs.
2179
+ */
2180
+ async planOffer(loanId) {
2107
2181
  const q = await this.readRequest(loanId, true);
2108
2182
  assertRequestTerm(q.termMs, this.config.closeStepMs ?? HOUR_MS);
2109
2183
  const L = q.pair[1];
2110
2184
  if (poolId(this.config, L) !== q.poolL)
2111
2185
  wrongCoinObject();
2112
- if (rateBps > q.maxRateBps)
2113
- throw new EsseyError("INVALID_ARGUMENT", "the rate is above the request's maximum");
2186
+ const rateBps = q.maxRateBps;
2114
2187
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2115
2188
  const { member, credential } = readState(this.statePath, this.stateKey);
2116
2189
  const relayer = this.relayerAddress();
@@ -2156,7 +2229,15 @@ export class Essey {
2156
2229
  const changeValue = spent[0].amount + spent[1].amount - q.principal - relayerFee;
2157
2230
  const encChange = bytesOf(sealOpening({ value: changeValue, blinding: change.blinding, index: changeIndex }, noteEncKey(seed).encPub));
2158
2231
  const encFee = bytesOf(fillerEnc());
2159
- const extHash = loanExt(LOAN_OFFER_KIND, q.loan, q.poolL, q.round, relayer, [encChange, encFee], blake2b256(sealed));
2232
+ const record = {
2233
+ noteIndex: offerIndex,
2234
+ principal: q.principal,
2235
+ rateBps,
2236
+ termMs: q.termMs,
2237
+ borrowerPk: q.borrowerPk,
2238
+ };
2239
+ const memo = sealMemo(memoKey(seed), { kind: MEMO_KIND.offer, key: q.loanKey, round: q.round }, offerMemoBody(record));
2240
+ const extHash = loanExt(LOAN_OFFER_KIND, q.loan, q.poolL, q.round, relayer, [encChange, encFee], blake2b256(Uint8Array.from([...sealed, ...memo])));
2160
2241
  const witness = await loanOffer({
2161
2242
  root: tree.root,
2162
2243
  ins: spent,
@@ -2185,13 +2266,6 @@ export class Essey {
2185
2266
  publicSignals: publics.map(String),
2186
2267
  });
2187
2268
  const { spend } = witness;
2188
- const record = {
2189
- noteIndex: offerIndex,
2190
- principal: q.principal,
2191
- rateBps,
2192
- termMs: q.termMs,
2193
- borrowerPk: q.borrowerPk,
2194
- };
2195
2269
  return {
2196
2270
  record,
2197
2271
  seq: q.seq,
@@ -2214,6 +2288,7 @@ export class Essey {
2214
2288
  feeCt: spend.feeCt,
2215
2289
  commit: witness.commit,
2216
2290
  sealed,
2291
+ memo,
2217
2292
  encChange,
2218
2293
  encFee,
2219
2294
  },
@@ -2277,6 +2352,8 @@ export class Essey {
2277
2352
  const offer = offers?.[Number(seq)];
2278
2353
  if (!offer?.active)
2279
2354
  throw new EsseyError("INVALID_ARGUMENT", "seq is not an active offer of this round");
2355
+ if (pickOf(row.round) !== seq)
2356
+ throw new EsseyError("INVALID_ARGUMENT", "refused: only the round's pick can be slashed (offer::slash aborts 42_050); nothing was sent");
2280
2357
  const approve = this.offerApprove(loan, loanKey, round, seq, pair);
2281
2358
  const sealed = Uint8Array.from(Buffer.from(offer.sealed, "base64"));
2282
2359
  const plain = await decrypt({ sealed, approve }).catch(() => undefined);
@@ -2285,6 +2362,58 @@ export class Essey {
2285
2362
  const derived = await derive({ id: offerKeyId(loanKey, round, seq), approve });
2286
2363
  return this.freeLoan(slashLoan, { pool: pair[1], loan, round, seq, keys: this.pinnedKeys(derived) });
2287
2364
  }
2365
+ /**
2366
+ * PRV-23 A: the round's pick, drawn first when none is stored, opened through Seal: the one offer key the borrower
2367
+ * reads. A pick that does not open its commit and lock is slashed, which clears it, and drawn again (DOS-02). The
2368
+ * slots carry the pick alone as active, the one-slot witness `loan::settle_rows` folds (`loan.move:507-513`).
2369
+ */
2370
+ async pickedSlots(q) {
2371
+ const field = lockField(q.loanKey, q.round);
2372
+ const slashed = new Set();
2373
+ for (let draw = 0; draw < SETTLE_SLOTS; draw++) {
2374
+ const round = await this.untilPicked(q, slashed);
2375
+ const pick = pickOf(round);
2376
+ const o = round.offers[Number(pick)];
2377
+ const sealed = Uint8Array.from(Buffer.from(o.sealed, "base64"));
2378
+ const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
2379
+ const approve = this.offerApprove(q.loan, q.loanKey, q.round, pick, q.pair);
2380
+ const plain = await decrypt({ sealed, approve });
2381
+ if (offerOpens(plain, field, BigInt(o.commit), BigInt(o.lock)))
2382
+ return round.offers.map((s, i) => ({
2383
+ commit: BigInt(s.commit),
2384
+ lock: BigInt(s.lock),
2385
+ active: BigInt(i) === pick,
2386
+ open: BigInt(i) === pick ? decodeOffer(plain) : undefined,
2387
+ }));
2388
+ await this.slashOffer(q.loan, pick);
2389
+ slashed.add(pick);
2390
+ }
2391
+ throw new EsseyError("INVALID_ARGUMENT", "refused: no offer of this round opens its commit and lock");
2392
+ }
2393
+ /**
2394
+ * The round once a pick shows that is none of `slashed`. With no pick, `loan_pick` goes once, alone: `pick::pick`
2395
+ * takes `Random` and must end its PTB (`move/v3/loan/sources/pick.move:1-3`). The reader may trail both writes.
2396
+ */
2397
+ async untilPicked(q, slashed) {
2398
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2399
+ let sent = false;
2400
+ for (let i = 0; i < SETTLE_READS; i++) {
2401
+ const round = (await read(q.loan))?.round;
2402
+ if (!round)
2403
+ unknownObject("the loan's round is missing");
2404
+ const pick = pickOf(round);
2405
+ const trailing = [...slashed].some((s) => round.offers[Number(s)]?.active) || (pick !== null && slashed.has(pick));
2406
+ if (!trailing && pick !== null)
2407
+ return round;
2408
+ if (!trailing && !sent) {
2409
+ await this.freeLoan(pickLoan, { pool: q.pair[1], loan: q.loan });
2410
+ sent = true;
2411
+ continue;
2412
+ }
2413
+ await this.sleep(SETTLE_READ_MS);
2414
+ }
2415
+ throw new EsseyError("STATE_REFUSED", "the loan read does not show the round's pick yet");
2416
+ }
2288
2417
  /** Threshold many derived keys, each with its server's slot in `config.seal.servers` (`seal_servers::public_keys` order). */
2289
2418
  pinnedKeys(derived) {
2290
2419
  const servers = this.config.seal.servers.map((s) => s.objectId);
@@ -2348,6 +2477,7 @@ export class Essey {
2348
2477
  const row = await read(loan);
2349
2478
  if (!row)
2350
2479
  unknownObject("no loan with this id");
2480
+ this.refuseRetired(row);
2351
2481
  const json = row.json;
2352
2482
  if (Number(json.state) !== 2 && Number(json.state) !== 8)
2353
2483
  throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
@@ -2428,7 +2558,8 @@ export class Essey {
2428
2558
  proof: `0x${Buffer.from(proof).toString("hex")}`,
2429
2559
  };
2430
2560
  const digest = await this.sponsoredSend(signer, txKindB64, wire, relayer);
2431
- const row = await this.listedByKey("badge", "tag", pass.publics[0], async (c) => {
2561
+ // PRV-16: a badge keeps no pass tag (keeper.move:53-60); the fresh holder this mint alone used finds it.
2562
+ const row = await this.listedByKey("badge", "holder", holder, async (c) => {
2432
2563
  const page = await readBadges(c);
2433
2564
  return { rows: page.badges, next: page.next };
2434
2565
  });
@@ -2465,12 +2596,15 @@ export class Essey {
2465
2596
  const { price, standin } = await this.keeperFeed(market);
2466
2597
  const prover = this.prover();
2467
2598
  return async (viewer) => {
2599
+ // PRV-16: nonce 0 is the badge mint's; a read takes a fresh one, so no two reads show one tag (keeper.move:255-256).
2600
+ const nonce = drawSecret();
2468
2601
  const pass = membership({
2469
2602
  secrets: member,
2470
2603
  credential: credential,
2471
2604
  domain: DOMAIN_KEEPER,
2472
2605
  room: keeper.registry.id,
2473
2606
  bind: viewer,
2607
+ nonce,
2474
2608
  });
2475
2609
  const proved = await prover.prove("membership", pass.input);
2476
2610
  return {
@@ -2486,6 +2620,7 @@ export class Essey {
2486
2620
  { pure: "u256", value: pass.publics[0].toString() },
2487
2621
  { pure: "u64", value: credential.expiryMs.toString() },
2488
2622
  { pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
2623
+ { pure: "u256", value: nonce.toString() },
2489
2624
  { object: "0x6" },
2490
2625
  ],
2491
2626
  };
@@ -2516,13 +2651,7 @@ export class Essey {
2516
2651
  }
2517
2652
  return notSetUp("no Pyth market in the deployment");
2518
2653
  }
2519
- /** The borrower's read of offer `seq` after close (`seal_policy::seal_approve_offer`): pass nonce 0 is its open tag. */
2520
- async openOffer(loan, loanKey, round, seq, sealed, pair) {
2521
- const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
2522
- const plain = await decrypt({ sealed, approve: this.offerApprove(loan, loanKey, round, seq, pair) });
2523
- return decodeOffer(plain);
2524
- }
2525
- /** The borrower's `loan_settle` on round 0: the lowest eligible offer wins, keeper ciphertext v1 carries its terms. */
2654
+ /** The borrower's `loan_settle` on round 0: the round's pick wins, keeper ciphertext v1 carries its terms. */
2526
2655
  async planSettle(id, collAmt) {
2527
2656
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2528
2657
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
@@ -2530,19 +2659,12 @@ export class Essey {
2530
2659
  // settle.move:131-135 refuses a settle until now_s * 1000 reaches close_ms.
2531
2660
  if (BigInt(Math.floor((this.io.now ?? Date.now)() / 1000)) * 1000n < q.closeMs)
2532
2661
  throw new EsseyError("INVALID_ARGUMENT", "refused: the offer window is still open");
2533
- const row = await read(q.loan);
2534
- const json = row.json;
2535
2662
  const seed = this.seed();
2536
- const { opening } = this.ownOpening(seed, json, q.borrowerPk, collAmt);
2537
- const round = row.round;
2538
- const slots = [];
2539
- for (const [i, o] of round.offers.entries()) {
2540
- const sealed = Uint8Array.from(Buffer.from(o.sealed, "base64"));
2541
- const open = o.active
2542
- ? await this.openOffer(q.loan, q.loanKey, q.round, BigInt(i), sealed, q.pair)
2543
- : undefined;
2544
- slots.push({ commit: BigInt(o.commit), lock: BigInt(o.lock), active: o.active, open });
2545
- }
2663
+ const first = (await read(q.loan)).json;
2664
+ this.ownOpening(seed, first, q.borrowerPk, collAmt);
2665
+ const slots = await this.pickedSlots(q);
2666
+ const json = (await read(q.loan)).json;
2667
+ const { opening, index: keyIndex } = this.ownOpening(seed, json, q.borrowerPk, collAmt);
2546
2668
  const { member, credential } = readState(this.statePath, this.stateKey);
2547
2669
  const L = q.pair[1];
2548
2670
  const prover = this.prover();
@@ -2584,6 +2706,12 @@ export class Essey {
2584
2706
  if (w.termsCommit !== draft.termsCommit)
2585
2707
  throw new EsseyError("INVALID_ARGUMENT", "refused: the terms moved between drafts");
2586
2708
  const settleProof = await prover.prove("loan_settle", w.input);
2709
+ const memo = this.settleMemo(seed, q.loanKey, q.round, {
2710
+ keyIndex,
2711
+ collAmt: opening.amount,
2712
+ borrowerPk: q.borrowerPk,
2713
+ terms: w.terms,
2714
+ });
2587
2715
  const args = settleArgs({
2588
2716
  loan: q.loan,
2589
2717
  poolL: q.poolL,
@@ -2599,6 +2727,7 @@ export class Essey {
2599
2727
  keeperCt,
2600
2728
  encs,
2601
2729
  nowS,
2730
+ memo,
2602
2731
  });
2603
2732
  const n0 = actionHash(blake2b256, q.loanKey, BigInt(json.nonce), "settle", args);
2604
2733
  const room = keyId(q.loanKey);
@@ -2637,9 +2766,13 @@ export class Essey {
2637
2766
  encPrincipal,
2638
2767
  encFee,
2639
2768
  nowS,
2769
+ memo,
2640
2770
  },
2641
2771
  };
2642
2772
  }
2773
+ settleMemo(seed, loanKey, round, record) {
2774
+ return sealMemo(memoKey(seed), { kind: MEMO_KIND.settle, key: loanKey, round }, settleMemoBody(record));
2775
+ }
2643
2776
  /** The borrower's `loan_repay`: `owed` to the lender's note by ECDH on its enc key, change back to own key. */
2644
2777
  async planRepay(loanId, terms, borrowerPk) {
2645
2778
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
@@ -3026,6 +3159,7 @@ export class Essey {
3026
3159
  const row = await read(loan);
3027
3160
  if (!row)
3028
3161
  unknownObject("no loan with this id");
3162
+ this.refuseRetired(row);
3029
3163
  const json = row.json;
3030
3164
  if (Number(json.state) !== 2)
3031
3165
  throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
@@ -3043,20 +3177,24 @@ export class Essey {
3043
3177
  salt: poseidonHash([own.sk, own.blinding, 2n, round]),
3044
3178
  };
3045
3179
  const reqCommit = requestCommit(request, p.borrowerPk, collNote(opening));
3046
- const closeMs = this.loanClose(p.offerWindowMs);
3047
- const reqSealed = await seal({
3048
- id: requestKeyId(opening.loanKey),
3049
- data: requestPlaintext({
3050
- ...request,
3051
- borrowerPk: p.borrowerPk,
3052
- closeMs,
3053
- market,
3054
- coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
3055
- }),
3056
- });
3057
- const pass = await this.borrowerPass(json, "refi", openRefiArgs({ loan, poolL, reqCommit, reqSealed, closeMs }));
3058
- const landed = await this.freeLoan(refinanceLoan, { pool: L, loan, pass, reqCommit, reqSealed, closeMs });
3059
- return { ...landed, round, closeMs };
3180
+ const send = async () => {
3181
+ const closeMs = await this.loanClose(p.offerWindowMs);
3182
+ const reqSealed = await seal({
3183
+ id: requestKeyId(opening.loanKey),
3184
+ data: requestPlaintext({
3185
+ ...request,
3186
+ borrowerPk: p.borrowerPk,
3187
+ closeMs,
3188
+ market,
3189
+ coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
3190
+ }),
3191
+ });
3192
+ const args = openRefiArgs({ loan, poolL, reqCommit, reqSealed, closeMs });
3193
+ const pass = await this.borrowerPass(json, "refi", args);
3194
+ const body = { pool: L, loan, pass, reqCommit, reqSealed, closeMs };
3195
+ return { ...(await this.freeLoan(refinanceLoan, body)), round, closeMs };
3196
+ };
3197
+ return send().catch((err) => (lateClose(err) ? send() : Promise.reject(err)));
3060
3198
  }
3061
3199
  /**
3062
3200
  * `refi::settle_refi`: the round's offers opened as `planSettle` opens them, the request read back through Seal, the
@@ -3068,23 +3206,17 @@ export class Essey {
3068
3206
  const readReading = this.io.readReading ?? notSetUp("missing config: no reading reader");
3069
3207
  const update = this.io.priceUpdate ?? notSetUp("missing config: no price update source");
3070
3208
  const q = await this.readRequest(p.loan);
3071
- const row = await read(q.loan);
3072
- const json = row.json;
3073
- if (termsCommit(p.terms, p.borrowerPk) !== BigInt(json.terms_commit))
3209
+ if (BigInt((this.io.now ?? Date.now)()) < q.closeMs)
3210
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the offer window is still open");
3211
+ const opened = (await read(q.loan)).json;
3212
+ if (termsCommit(p.terms, p.borrowerPk) !== BigInt(opened.terms_commit))
3074
3213
  throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
3075
- const round = row.round;
3076
- const slots = [];
3077
- for (const [i, o] of round.offers.entries()) {
3078
- const sealed = Uint8Array.from(Buffer.from(o.sealed, "base64"));
3079
- const open = o.active
3080
- ? await this.openOffer(q.loan, q.loanKey, q.round, BigInt(i), sealed, q.pair)
3081
- : undefined;
3082
- slots.push({ commit: BigInt(o.commit), lock: BigInt(o.lock), active: o.active, open });
3083
- }
3214
+ const slots = await this.pickedSlots(q);
3215
+ const json = (await read(q.loan)).json;
3084
3216
  const [C, L] = q.pair;
3085
3217
  const market = address(json.market_id, "market");
3086
3218
  const seed = this.seed();
3087
- const { opening } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
3219
+ const { opening, index: keyIndex } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
3088
3220
  const r = await readReading(market);
3089
3221
  const pClaim = r.spot < r.ema ? r.spot : r.ema;
3090
3222
  const rates = await this.rates(market);
@@ -3142,6 +3274,12 @@ export class Essey {
3142
3274
  if (w.termsCommit !== draft.termsCommit)
3143
3275
  throw new EsseyError("INVALID_ARGUMENT", "refused: the terms moved between drafts");
3144
3276
  const refiProof = await this.prover().prove("loan_refi", w.input);
3277
+ const memo = this.settleMemo(seed, q.loanKey, q.round, {
3278
+ keyIndex,
3279
+ collAmt: opening.amount,
3280
+ borrowerPk: p.borrowerPk,
3281
+ terms: w.terms,
3282
+ });
3145
3283
  const args = settleRefiArgs({
3146
3284
  loan: q.loan,
3147
3285
  poolL: q.poolL,
@@ -3164,6 +3302,7 @@ export class Essey {
3164
3302
  encs,
3165
3303
  encsP,
3166
3304
  nowS,
3305
+ memo,
3167
3306
  });
3168
3307
  const pass = await this.borrowerPass(json, "settle_refi", args);
3169
3308
  const landed = await this.freeLoan(settleRefiLoan, {
@@ -3188,6 +3327,7 @@ export class Essey {
3188
3327
  encs,
3189
3328
  encsP,
3190
3329
  nowS,
3330
+ memo,
3191
3331
  priceUpdate: await update(market),
3192
3332
  });
3193
3333
  return { ...landed, rateBps: w.terms.rateBps, terms: w.terms };
@@ -3298,6 +3438,48 @@ export class Essey {
3298
3438
  }
3299
3439
  throw new EsseyError("CT_MISMATCH", "refused: no spend of own notes opens the locked note");
3300
3440
  }
3441
+ /**
3442
+ * SCOPE-R1-MEMO D6: every listed loan's memos trial-opened under this seed's memo key. The AAD names the loan key,
3443
+ * round and slot, so a memo sealed for another seed, or copied into another loan, does not open.
3444
+ */
3445
+ async recoverRecords() {
3446
+ const readLoans = this.io.readLoans ?? notSetUp("missing config: no loan reader");
3447
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
3448
+ const key = memoKey(this.seed());
3449
+ const out = { loans: [], offers: [] };
3450
+ const bytes = (v) => typeof v === "string" ? Uint8Array.from(Buffer.from(v, "base64")) : new Uint8Array();
3451
+ let cursor = null;
3452
+ let pages = 0;
3453
+ for (;;) {
3454
+ const page = await readLoans(cursor);
3455
+ pages += 1;
3456
+ for (const row of page.loans) {
3457
+ const loan = address(row.id, "loan id");
3458
+ const json = row.json;
3459
+ const loanKey = BigInt(json.loan_key);
3460
+ const last = BigInt(json.round ?? 0);
3461
+ let record = null;
3462
+ for (let r = 0n; r <= last; r++) {
3463
+ const round = (r === last && row.round !== undefined ? row.round : (await read(loan, r))?.round);
3464
+ if (!round)
3465
+ continue;
3466
+ if (r === 0n)
3467
+ record = openRequestMemo(key, loanKey, bytes(round.req_memo)) ?? record;
3468
+ record = openSettleMemo(key, loanKey, r, bytes(round.settle_memo)) ?? record;
3469
+ (round.offers ?? []).forEach((o, seq) => {
3470
+ const offer = openOfferMemo(key, loanKey, r, bytes(o.memo));
3471
+ if (offer)
3472
+ out.offers.push({ loan, round: r, seq, record: offer });
3473
+ });
3474
+ }
3475
+ if (record)
3476
+ out.loans.push({ loan, record });
3477
+ }
3478
+ cursor = afterPage(page.next, pages);
3479
+ if (cursor === null)
3480
+ return out;
3481
+ }
3482
+ }
3301
3483
  /** `reclaim::reclaim`: the lender's Lock4 among the round's resolved locks, refunded to a fresh own note. */
3302
3484
  async reclaimOffer(loanId, offer, roundArg) {
3303
3485
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
@@ -3400,9 +3582,9 @@ export class Essey {
3400
3582
  const market = address(json.market_id, "market");
3401
3583
  const expiryMs = await this.heartbeatExpiry(json, market, p.terms.maturityS, p.expiryMs);
3402
3584
  const { opening } = this.ownOpening(this.seed(), json, p.borrowerPk, p.collAmt);
3403
- const k = p.k ?? 1;
3404
3585
  const reading = await readPrice(market);
3405
- const floor = heartbeatFloor(reading, k);
3586
+ const retired = this.retired(row);
3587
+ const floor = retired ? legacyHeartbeatFloor(reading) : heartbeatFloor(reading);
3406
3588
  const fee = await this.loanFee(C, json.coll_fee_commit);
3407
3589
  const rates = {
3408
3590
  ltvBps: BigInt(json.ltv_bps),
@@ -3437,9 +3619,9 @@ export class Essey {
3437
3619
  statement: h.statement,
3438
3620
  wait: true,
3439
3621
  encs,
3440
- k,
3441
3622
  expiryMs,
3442
3623
  priceUpdate: await update(market),
3624
+ retired,
3443
3625
  }));
3444
3626
  return { ...landed, expiryMs };
3445
3627
  }
@@ -3491,11 +3673,13 @@ export class Essey {
3491
3673
  const fresh = coverExpiry(now, maturityS);
3492
3674
  if (asked === undefined && fresh < now + gap)
3493
3675
  throw new EsseyError("INVALID_ARGUMENT", "the loan is under one gap from maturity plus grace");
3494
- const expiry = asked ?? (stored > fresh ? stored : fresh);
3676
+ const expiry = asked ?? coverOverStored(fresh, stored);
3495
3677
  if (expiry < now + gap || expiry > now + H_MAX_MS)
3496
3678
  throw new EsseyError("INVALID_ARGUMENT", "the expiry must be at least one gap and at most 24 h ahead");
3497
3679
  if (expiry < stored)
3498
3680
  throw new EsseyError("INVALID_ARGUMENT", "the expiry cannot be earlier than the loan's current heartbeat expiry");
3681
+ if (expiry % COVER_STEP_MS !== 0n)
3682
+ throw new EsseyError("INVALID_ARGUMENT", "the expiry must be on the 5-minute cover step");
3499
3683
  return expiry;
3500
3684
  }
3501
3685
  /**
@@ -3830,20 +4014,10 @@ export class Essey {
3830
4014
  });
3831
4015
  }
3832
4016
  /** The seller keys and bounds salt of the sale opened at note index `index`, so the seed alone reopens them. */
3833
- saleOpening(seed, index) {
3834
- const own = deriveNoteKey(seed, index);
3835
- const tagged = (t) => poseidonHash([own.sk, own.blinding, t]);
3836
- return { sellerSk: own.sk, sellerSecret: tagged(7n), boundsSalt: tagged(8n) };
3837
- }
3838
4017
  /** D-SPEC §6.2:599. The seller pass over `sale_room::open_args`, at action nonce 0; the relayer or the callback pays. */
3839
4018
  async openSale(p) {
3840
- const asked = assertSaleOpen(p);
3841
- assertSaleGrid(asked, this.config.closeStepMs ?? HOUR_MS);
3842
- const nowMs = (this.io.now ?? Date.now)();
3843
- const open = {
3844
- ...asked,
3845
- closeMs: stepClose(nowMs + asked.bidWindowMs, nowMs, SALE_MAX_WINDOW_MS, this.config.closeStepMs),
3846
- };
4019
+ const open = assertSaleOpen(p);
4020
+ await this.saleWindow(open);
3847
4021
  requireSale(this.config);
3848
4022
  const pool = poolId(this.config, open.coin);
3849
4023
  const item = { id: address(open.itemId, "itemId"), type: open.itemType };
@@ -3851,22 +4025,26 @@ export class Essey {
3851
4025
  const submit = (open.sponsored ?? this.sponsoring() !== null)
3852
4026
  ? await this.saleSponsor(pool, item.id)
3853
4027
  : (this.io.submitSaleOpen ?? notSetUp("missing config: sale open has no submitter"));
3854
- const closeMs = BigInt(open.closeMs);
3855
- const finishByMs = closeMs + BigInt(open.finishWindowMs);
3856
- const typeName = asInvalid(() => {
3857
- assertFinishWindow(closeMs, finishByMs);
3858
- return typeNameOf(open.itemType);
3859
- });
3860
- const shape = { pool, item: { id: item.id, typeName }, closeMs, finishByMs, maxBids: open.maxBids };
4028
+ const typeName = asInvalid(() => typeNameOf(open.itemType));
4029
+ const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
3861
4030
  const { secrets, credential } = this.member();
3862
4031
  const prover = this.prover();
3863
4032
  const seed = await this.keys();
3864
4033
  const noteIndex = this.reserve("notes");
3865
- const { boundsSalt, ...seller } = this.saleOpening(seed, noteIndex);
3866
- const bounds = { lo: open.minPrice, hi: open.maxPrice, salt: boundsSalt };
3867
- const commits = openCommits({ ...seller, boundsSalt }, bounds);
4034
+ const s = saleSecrets(deriveNoteKey(seed, noteIndex));
4035
+ const commits = openCommits(s, open.price);
4036
+ const bounds = { lo: open.price, hi: open.price, salt: s.boundsSalt };
3868
4037
  const saleKey = drawSecret();
3869
- const n0 = actionHash(blake2b256, saleKey, 0n, "open", openArgs({ ...shape, ...commits, saleKey }));
4038
+ const listing = await seal({
4039
+ id: listingKeyId(saleKey),
4040
+ data: listingPlaintext({ price: open.price, salt: s.postedSalt }),
4041
+ pkg: "sale",
4042
+ });
4043
+ const memo = sealSaleMemo(memoKey(seed), saleKey, { noteIndex, price: open.price });
4044
+ const t = await this.saleWindow(open);
4045
+ const { closeMs, finishByMs } = t;
4046
+ const shape = { pool, item: { id: item.id, typeName }, closeMs, finishByMs, maxBids: open.maxBids };
4047
+ const n0 = actionHash(blake2b256, saleKey, 0n, "open", openArgs({ ...shape, ...commits, listing, memo, saleKey }));
3870
4048
  const pass = membership({
3871
4049
  secrets,
3872
4050
  credential,
@@ -3875,11 +4053,14 @@ export class Essey {
3875
4053
  bind: keyId(n0),
3876
4054
  });
3877
4055
  const proved = await prover.prove("membership", pass.input);
4056
+ await this.untilLandable(t);
3878
4057
  const landed = await submit({
3879
4058
  coin: open.coin,
3880
4059
  item,
3881
4060
  saleKey,
3882
4061
  ...commits,
4062
+ listing,
4063
+ memo,
3883
4064
  closeMs,
3884
4065
  finishByMs,
3885
4066
  maxBids: open.maxBids,
@@ -3897,7 +4078,8 @@ export class Essey {
3897
4078
  const page = await readRooms(c);
3898
4079
  return { rows: page.rooms, next: page.next };
3899
4080
  });
3900
- assertRoomMatches(this.config, open, { id, json });
4081
+ assertRoomMatches(this.config, { ...open, closeMs: Number(closeMs) }, { id, json });
4082
+ const seller = { sellerSk: s.sellerSk, sellerSecret: s.sellerSecret };
3901
4083
  return {
3902
4084
  id,
3903
4085
  digest: landed.digest,
@@ -3905,6 +4087,20 @@ export class Essey {
3905
4087
  sale: { room: id, noteIndex, seller, bounds },
3906
4088
  };
3907
4089
  }
4090
+ /** PRV-27 (b), `sale_room::check_grid` (44_041): the close and finish a sale opening about now must carry. */
4091
+ async saleWindow(open) {
4092
+ const nowMs = (this.io.now ?? Date.now)();
4093
+ const asked = { nowMs, bidWindowMs: open.bidWindowMs, finishWindowMs: open.finishWindowMs };
4094
+ return asInvalid(() => saleTimes({ ...asked, marginMs: SALE_LAND_MARGIN_MS }));
4095
+ }
4096
+ /** An open landing outside `[landFromMs, landByMs]` aborts 44_041: wait for the start, refuse past the end. */
4097
+ async untilLandable(t) {
4098
+ const now = BigInt((this.io.now ?? Date.now)());
4099
+ if (now < t.landFromMs)
4100
+ await this.sleep(Number(t.landFromMs - now));
4101
+ if (BigInt((this.io.now ?? Date.now)()) > t.landByMs)
4102
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the open's proofs took past its close step, so it would land off the grid (44_041); nothing was sent");
4103
+ }
3908
4104
  /**
3909
4105
  * The sponsored open (E-34): a fresh seed-derived sender signs `from_proof` and `open` while the relayer pays gas.
3910
4106
  * PRV-35: an item at one of this seed's `itemAddress()` holders opens from that holder with no hand-over; any other
@@ -3997,16 +4193,29 @@ export class Essey {
3997
4193
  const bounds = this.io.roomBounds ? await this.io.roomBounds(key) : null;
3998
4194
  return viewRoomObject(this.config, { id: key, json: row.json }, bounds);
3999
4195
  }
4000
- async saleRoom(id) {
4196
+ /**
4197
+ * The room, refused for `kind` when its type names a retired sale package that does not take it
4198
+ * (DECISION-R1-MIGRATION A, `sales/package-gate.ts`). `legacy`: such a room's `finish` opens every active bid.
4199
+ */
4200
+ async saleRoom(id, kind) {
4001
4201
  requireSale(this.config);
4002
4202
  const read = this.io.readRoom ?? notSetUp("missing config: no room reader");
4003
4203
  const room = address(id, "room id");
4004
4204
  const row = await read(room);
4005
4205
  if (!row)
4006
4206
  unknownObject("no room with this id");
4207
+ const { legacy } = row.type ? this.saleGate(kind, row.type) : { legacy: false };
4208
+ // A retired room's Seal policy is its own package's; an old package id stays callable (DECISION-R1-MIGRATION).
4209
+ const policyPkg = legacy ? salePackageOf(row.type) : this.config.packages.sale;
4007
4210
  const json = row.json;
4008
4211
  const bids = (json.bids ?? []);
4212
+ const pick = optionU256(json.pick, "the room's pick");
4009
4213
  return {
4214
+ legacy,
4215
+ policyPkg,
4216
+ pick: pick === null ? null : Number(pick),
4217
+ postedCommit: BigInt(json.posted_commit ?? 0),
4218
+ listing: optionBytes(json.listing),
4010
4219
  id: room,
4011
4220
  coin: coinByPool(this.config, String(json.pool_id)),
4012
4221
  saleKey: BigInt(json.sale_key),
@@ -4045,16 +4254,72 @@ export class Essey {
4045
4254
  if (this.nowMs() + CLOSE_MARGIN_MS > closeMs)
4046
4255
  throw new EsseyError("INVALID_ARGUMENT", `${what} has closed or closes within 2 minutes, too soon to prove and land; nothing was sent`);
4047
4256
  }
4048
- async placeBid(roomId, v, amount) {
4049
- if (typeof v !== "bigint" || typeof amount !== "bigint" || v <= 0n || v > amount)
4050
- throw new EsseyError("INVALID_ARGUMENT", "the bid must be above 0 and at most the deposit");
4051
- const room = await this.saleRoom(roomId);
4257
+ /**
4258
+ * `sale_room::seal_approve_listing`: a SEAL pass under a fresh non-zero nonce, bound to the viewer, as the loan
4259
+ * request read takes (`readRequest`), so two reads show two tags.
4260
+ */
4261
+ async readRoomListing(room) {
4262
+ const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
4263
+ const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
4264
+ const { member, credential } = readState(this.statePath, this.stateKey);
4265
+ if (!member || !credential)
4266
+ notSetUp("no credential: call credential.obtain first");
4267
+ if (!room.listing)
4268
+ unknownObject("the room holds no sealed listing");
4269
+ const scope = keyId(room.saleKey);
4270
+ const prover = this.prover();
4271
+ return decrypt({
4272
+ sealed: room.listing,
4273
+ pkg: "sale",
4274
+ approve: async (viewer) => {
4275
+ const nonce = drawSecret();
4276
+ const bind = `0x${Buffer.from(sealListingBind(scope, viewer)).toString("hex")}`;
4277
+ const pass = membership({
4278
+ secrets: member,
4279
+ credential: credential,
4280
+ domain: DOMAIN_SENDER,
4281
+ room: scope,
4282
+ bind,
4283
+ nonce,
4284
+ });
4285
+ const proved = await prover.prove("membership", pass.input);
4286
+ return {
4287
+ target: `${this.config.packages.sale}::sale_room::seal_approve_listing`,
4288
+ typeArguments: [this.config.coins[room.coin].type],
4289
+ args: [
4290
+ { pure: "vector<u8>", value: `0x${Buffer.from(listingKeyId(room.saleKey)).toString("hex")}` },
4291
+ { object: room.id },
4292
+ { object: passKey.id },
4293
+ { pure: "u256", value: pass.publics[0].toString() },
4294
+ { pure: "u256", value: nonce.toString() },
4295
+ { pure: "u64", value: credential.expiryMs.toString() },
4296
+ { pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
4297
+ { object: "0x6" },
4298
+ ],
4299
+ };
4300
+ },
4301
+ });
4302
+ }
4303
+ async placeBid(roomId, maxPrice, asked) {
4304
+ if (typeof maxPrice !== "bigint" || maxPrice <= 0n || (asked !== undefined && typeof asked !== "bigint"))
4305
+ throw new EsseyError("INVALID_ARGUMENT", "maxPrice must be above 0 and amount a bigint");
4306
+ const room = await this.saleRoom(roomId, "bid");
4052
4307
  if (room.state !== SALE_STATE.open)
4053
4308
  throw new EsseyError("INVALID_ARGUMENT", "the room is not taking bids");
4054
4309
  this.assertBeforeClose(room.closeMs, "the room");
4055
4310
  const seq = room.bids.length;
4056
4311
  if (seq >= room.maxBids)
4057
4312
  throw new EsseyError("INVALID_ARGUMENT", "the room is full");
4313
+ const plain = await this.readRoomListing(room);
4314
+ const listing = asInvalid(() => readListing(plain, room.postedCommit));
4315
+ if (!listing)
4316
+ throw new EsseyError("CT_MISMATCH", "refused: the listing does not open the room's posted price");
4317
+ const v = listing.price;
4318
+ if (v > maxPrice)
4319
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the posted price is above maxPrice; nothing was sent");
4320
+ const amount = asked ?? v;
4321
+ if (amount < v)
4322
+ throw new EsseyError("INVALID_ARGUMENT", "the deposit must cover the posted price");
4058
4323
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
4059
4324
  const { member, credential } = readState(this.statePath, this.stateKey);
4060
4325
  if (!member || !credential)
@@ -4079,7 +4344,8 @@ export class Essey {
4079
4344
  const record = { room: room.id, noteIndex: this.reserve("notes"), v, amount };
4080
4345
  const changeIndex = this.reserve("notes");
4081
4346
  const change = deriveNoteKey(seed, changeIndex);
4082
- const secrets = this.bidSecrets(seed, record);
4347
+ const secrets = { ...this.bidSecrets(seed, record), s: listing.salt };
4348
+ const memo = sealBidMemo(memoKey(seed), room.saleKey, record);
4083
4349
  const sealed = await seal({
4084
4350
  id: bidKeyId(room.saleKey, BigInt(seq)),
4085
4351
  data: bidPlaintext(secrets),
@@ -4092,12 +4358,13 @@ export class Essey {
4092
4358
  const w = await lockBid({
4093
4359
  root: tree.root,
4094
4360
  ins: spent,
4095
- room: { id: room.id, saleKey: room.saleKey, seq },
4361
+ room: { id: room.id, saleKey: room.saleKey, seq, postedCommit: room.postedCommit },
4096
4362
  bid: secrets,
4097
4363
  change: { pk: notePk(change.sk), blinding: change.blinding },
4098
4364
  relayer,
4099
4365
  relayerFee,
4100
4366
  sealed,
4367
+ memo,
4101
4368
  encs,
4102
4369
  fee,
4103
4370
  eph: drawEph(),
@@ -4124,6 +4391,7 @@ export class Essey {
4124
4391
  proved: await proved("lock_bid", w.input, w.publics),
4125
4392
  statement: w.statement,
4126
4393
  sealed,
4394
+ memo,
4127
4395
  encs,
4128
4396
  });
4129
4397
  return { ...landed, bid: record };
@@ -4147,7 +4415,7 @@ export class Essey {
4147
4415
  });
4148
4416
  const proved = await prover.prove("membership", pass.input);
4149
4417
  return {
4150
- target: `${this.config.packages.sale}::sale_room::seal_approve_bid`,
4418
+ target: `${room.policyPkg}::sale_room::seal_approve_bid`,
4151
4419
  typeArguments: [this.config.coins[room.coin].type],
4152
4420
  args: [
4153
4421
  {
@@ -4166,17 +4434,19 @@ export class Essey {
4166
4434
  };
4167
4435
  }
4168
4436
  /** `seal_approve_bid` releases keys from close until `finish_by_ms`, for an active bid (`sale_room.move:337-341`). */
4169
- async closedRoom(roomId) {
4170
- const room = await this.saleRoom(roomId);
4437
+ async closedRoom(roomId, kind) {
4438
+ const room = await this.saleRoom(roomId, kind);
4171
4439
  const now = this.nowMs();
4172
4440
  if (room.state !== SALE_STATE.open || now < room.closeMs || now >= room.finishByMs)
4173
4441
  throw new EsseyError("INVALID_ARGUMENT", "the room is not between close and its finish deadline");
4174
4442
  return room;
4175
4443
  }
4176
- async slashBid(roomId, seq) {
4177
- const room = await this.closedRoom(roomId);
4178
- if (!Number.isInteger(seq) || !room.bids[seq]?.active)
4179
- throw new EsseyError("INVALID_ARGUMENT", "seq is not an active bid of this room");
4444
+ /** PRV-24 A: only the room's pick is slashed (44_039); a slash clears it, so `finish` draws again. */
4445
+ async slashBid(roomId) {
4446
+ const room = await this.closedRoom(roomId, "slash");
4447
+ const seq = room.pick;
4448
+ if (seq === null || !room.bids[seq]?.active)
4449
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the room has no pick to slash; nothing was sent");
4180
4450
  const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
4181
4451
  const derive = this.io.sealDerivedKeys ?? notSetUp("missing config: no Seal key deriver");
4182
4452
  const bid = room.bids[seq];
@@ -4196,23 +4466,27 @@ export class Essey {
4196
4466
  });
4197
4467
  }
4198
4468
  async finishSale(p) {
4199
- const room = await this.closedRoom(p.room);
4469
+ const room = await this.pickedRoom(p.room);
4200
4470
  const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
4471
+ const opened = (i) => (room.legacy ? room.bids[i].active : i === room.pick);
4201
4472
  const plains = [];
4202
4473
  for (const [i, b] of room.bids.entries()) {
4203
- if (b.active && typeof b.sealed !== "string")
4474
+ if (opened(i) && typeof b.sealed !== "string")
4204
4475
  notSetUp("the room reader gave no sealed bid");
4205
- const sealed = b.active ? Uint8Array.from(Buffer.from(b.sealed, "base64")) : undefined;
4476
+ const sealed = opened(i) ? Uint8Array.from(Buffer.from(b.sealed, "base64")) : undefined;
4206
4477
  plains.push(sealed && (await decrypt({ sealed, approve: this.bidApprove(room, i), pkg: "sale" })));
4207
4478
  }
4208
4479
  const seed = this.seed();
4209
4480
  const sellerIndex = this.indexOfSellerKey(seed, p.seller.sellerSk);
4210
4481
  const fee = await this.feeParams(room.coin);
4211
4482
  const eph = drawEph();
4212
- const planFor = (encs) => settlePlan({ room, plains, seller: p.seller, bounds: p.bounds, encs, fee, eph });
4483
+ const planRoom = { ...room, pick: room.legacy ? "legacy" : room.pick };
4484
+ const planFor = (encs) => settlePlan({ room: planRoom, plains, seller: p.seller, bounds: p.bounds, encs, fee, eph });
4213
4485
  const draft = await planFor([new Uint8Array(128), new Uint8Array(128)]);
4214
- if (draft.slash.length > 0)
4215
- throw new EsseyError("INVALID_ARGUMENT", `refused: slash bids ${draft.slash.join(", ")} first`);
4486
+ if (draft.slash.length > 0) {
4487
+ const which = room.legacy ? `bids ${draft.slash.join(", ")}` : `bid ${draft.slash[0]}`;
4488
+ throw new EsseyError("INVALID_ARGUMENT", `refused: slash ${which} first`);
4489
+ }
4216
4490
  const encSeller = sealOpening({ ...draft.sellerNote, index: sellerIndex }, noteEncKey(seed).encPub);
4217
4491
  const encs = [hexBytes(encSeller), hexBytes(fillerEnc())];
4218
4492
  const w = await planFor(encs);
@@ -4226,6 +4500,24 @@ export class Essey {
4226
4500
  encs,
4227
4501
  });
4228
4502
  }
4503
+ /**
4504
+ * PRV-24 A: a closed room with an active bid and no pick draws one first (`sale_pick`, alone: `sale_room::pick`
4505
+ * takes `Random`), then the room is read until the pick shows. A retired room, or one with no active bid, has none.
4506
+ */
4507
+ async pickedRoom(roomId) {
4508
+ let room = await this.closedRoom(roomId, "finish");
4509
+ if (room.legacy || room.pick !== null || !room.bids.some((b) => b.active))
4510
+ return room;
4511
+ await this.freeLoan(pickBody, { pool: room.coin, room: room.id });
4512
+ for (let i = 0; i < SETTLE_READS && room.pick === null; i++) {
4513
+ if (i > 0)
4514
+ await this.sleep(SETTLE_READ_MS);
4515
+ room = await this.closedRoom(roomId, "finish");
4516
+ }
4517
+ if (room.pick === null)
4518
+ throw new EsseyError("STATE_REFUSED", "the room read does not show its pick yet");
4519
+ return room;
4520
+ }
4229
4521
  indexOfSellerKey(seed, sellerSk) {
4230
4522
  const n = readState(this.statePath, this.stateKey).notes ?? 0;
4231
4523
  for (let i = n - 1; i >= 0; i--)
@@ -4234,13 +4526,13 @@ export class Essey {
4234
4526
  return notSetUp("refused: sellerSk is not a note key of this seed, so the proceeds would not scan");
4235
4527
  }
4236
4528
  async expireSale(roomId, vault) {
4237
- const room = await this.saleRoom(roomId);
4529
+ const room = await this.saleRoom(roomId, "expire");
4238
4530
  if (room.state !== SALE_STATE.open || this.nowMs() < room.finishByMs)
4239
4531
  throw new EsseyError("INVALID_ARGUMENT", "the room is not past its finish deadline");
4240
4532
  return this.freeLoan(expireBody, { pool: room.coin, room: room.id, vault });
4241
4533
  }
4242
4534
  async cancelSale(roomId, vault) {
4243
- const room = await this.saleRoom(roomId);
4535
+ const room = await this.saleRoom(roomId, "cancel");
4244
4536
  if (room.state !== SALE_STATE.open || room.bids.length > 0)
4245
4537
  throw new EsseyError("INVALID_ARGUMENT", "only an open room with no bid cancels");
4246
4538
  // `sale_room::action_hash` is `loan::action_hash`'s encoding over `sale_key` (`sale_room.move:528-529`).
@@ -4248,7 +4540,7 @@ export class Essey {
4248
4540
  return this.freeLoan(cancelBody, { pool: room.coin, room: room.id, vault, pass });
4249
4541
  }
4250
4542
  async reclaimBid(roomId, record, what) {
4251
- const room = await this.saleRoom(roomId);
4543
+ const room = await this.saleRoom(roomId, "reclaim");
4252
4544
  if (room.state !== SALE_STATE.settled && room.state !== SALE_STATE.expired)
4253
4545
  throw new EsseyError("INVALID_ARGUMENT", "the room has not ended");
4254
4546
  const seed = this.seed();
@@ -4296,7 +4588,7 @@ export class Essey {
4296
4588
  const claim = optionU256(json.claim);
4297
4589
  if (claim === null)
4298
4590
  throw new EsseyError("INVALID_ARGUMENT", "the vault holds no claim yet");
4299
- const room = await this.saleRoom(String(json.room_id));
4591
+ const room = await this.saleRoom(String(json.room_id), "claim");
4300
4592
  let holder;
4301
4593
  if (p.bid) {
4302
4594
  const own = this.bidSecrets(this.seed(), p.bid);