@esseyonsui/sui-sdk-v3 0.2.1 → 0.3.2

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 +113 -23
  2. package/dist/essey.d.ts.map +1 -1
  3. package/dist/essey.js +512 -179
  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 +15 -0
  56. package/dist/v3/sales/package-gate.d.ts.map +1 -0
  57. package/dist/v3/sales/package-gate.js +25 -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,42 @@ 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
+ * `previous.cutoverMs` of the record that made R1 current (`deployments/essey-v3.testnet.json:349`). A retired
118
+ * generation cut over later is R1, retired by Z1, and keeps the shapes this SDK builds for a current object; one cut
119
+ * over at or before it, or with no cutover, is pre-R1 (Erik 2026-12-01 item 3, A).
120
+ */
121
+ const R1_CUTOVER_MS = 1_796_079_087_974;
122
+ /** The record's `previous` and `previous2` (`services/v3api/src/config-route.ts` `previousSlots`), for `pkg`. */
123
+ function retiredOf(config, pkg) {
124
+ const record = config;
125
+ return [record.previous, record.previous2].flatMap((slot) => {
126
+ const origin = slot?.packageOrigins?.[pkg];
127
+ if (typeof origin !== "string")
128
+ return [];
129
+ const latest = slot.packages?.[pkg];
130
+ const registry = slot.objects?.keeperRegistry?.id;
131
+ const cutover = slot.cutoverMs;
132
+ return [
133
+ {
134
+ origin: normalizeSuiAddress(origin),
135
+ latest: typeof latest === "string" ? latest : origin,
136
+ preR1: !(typeof cutover === "number" && cutover > R1_CUTOVER_MS),
137
+ ...(typeof registry === "string" ? { keeperRegistry: registry } : {}),
138
+ },
139
+ ];
140
+ });
141
+ }
142
+ function retiredFor(config, pkg, type) {
143
+ const address = type?.split("::")[0];
144
+ if (!address)
145
+ return undefined;
146
+ return retiredOf(config, pkg).find((g) => g.origin === normalizeSuiAddress(address));
147
+ }
148
+ /** `loan.move` `E_CLOSE_GRID`: the open landed a step later than its close was chosen for; a fresh close lands. */
149
+ const E_CLOSE_GRID = 42_046;
150
+ const lateClose = (err) => (isEsseyError(err, "RELAY_FAILED") || isEsseyError(err, "RELAY_REFUSED")) &&
151
+ err.detail?.abort?.code === E_CLOSE_GRID;
114
152
  function readRequestPlain(plain) {
115
153
  try {
116
154
  return decodeRequest(plain);
@@ -514,15 +552,22 @@ function sweepTemps(path) {
514
552
  }
515
553
  const blake2b256 = (bytes) => blake2b(bytes, { dkLen: 32 });
516
554
  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) {
555
+ /** A Move `Option<u256>` or `Option<u64>` read as JSON: null, the value, or `{ vec: [] | [value] }`. */
556
+ function optionU256(raw, what = "the vault claim") {
519
557
  const inner = raw && typeof raw === "object" ? raw.vec?.[0] : raw;
520
558
  if (inner === null || inner === undefined)
521
559
  return null;
522
560
  if (typeof inner !== "string" && typeof inner !== "number")
523
- unknownObject("the vault claim is not a u256");
561
+ unknownObject(`${what} is not a number`);
524
562
  return BigInt(inner);
525
563
  }
564
+ /** A Move `Option<vector<u8>>` read as JSON, base64 inside as `readRoom` gives `bids[i].sealed`; UNVERIFIED shape. */
565
+ function optionBytes(raw) {
566
+ const inner = raw && typeof raw === "object" ? raw.vec?.[0] : raw;
567
+ return typeof inner === "string" ? Uint8Array.from(Buffer.from(inner, "base64")) : undefined;
568
+ }
569
+ /** PRV-23 A: the round's `pick` (`loan.move:108`), null until `pick::pick` lands and after a slash clears it. */
570
+ const pickOf = (round) => optionU256(round?.pick, "the round's pick");
526
571
  function asInvalid(run) {
527
572
  try {
528
573
  return run();
@@ -675,16 +720,6 @@ function payoutStopped(error, paid, rest) {
675
720
  stopped.cause = error;
676
721
  return stopped;
677
722
  }
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
723
  function refusedBy(service, reply) {
689
724
  const error = typeof reply.body.error === "string" ? reply.body.error : undefined;
690
725
  return new EsseyError("SERVICE_REFUSED", `${service} refused: ${error ?? reply.status}`, {
@@ -753,7 +788,7 @@ export class Essey {
753
788
  await this.refuseOffGridClose(p.loan);
754
789
  const send = async () => {
755
790
  await this.pause("offer", p.loan, closeOf(p.loan));
756
- const { body, record, seq } = await this.planOffer(p.loan, BigInt(p.rateBps));
791
+ const { body, record, seq } = await this.planOffer(p.loan);
757
792
  return {
758
793
  seq,
759
794
  sent: this.paidLoan(offerLoan, body).then((landed) => ({ ...landed, offer: record })),
@@ -797,6 +832,7 @@ export class Essey {
797
832
  keeperLiquidate: (p) => this.paced("liquidate", p.loan, null, () => this.keeperLiquidate(p.loan, p.via)),
798
833
  reclaimCollateral: (p) => this.paced("reclaim_collateral", p.loan, null, () => this.reclaimOwnCollateral(p.loan, p.collAmt)),
799
834
  recover: (p) => this.recoverOwnLoan(p.loan),
835
+ recoverRecords: () => this.recoverRecords(),
800
836
  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
837
  settle: (p) => this.freeLoan(settleLoan, p),
802
838
  repay: (p) => this.paidLoan(repayLoan, p),
@@ -837,9 +873,9 @@ export class Essey {
837
873
  open: (p) => this.openSale(p),
838
874
  list: () => this.listSales(),
839
875
  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)),
876
+ 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
877
  finish: (p) => this.finishSale(p),
842
- slash: (p) => this.slashBid(p.room, p.seq),
878
+ slash: (p) => this.slashBid(p.room),
843
879
  expire: (p) => this.expireSale(p.room, p.vault),
844
880
  reclaim: (p) => this.paced("sale_reclaim", p.room, null, () => this.reclaimBid(p.room, p.bid, p.what ?? "lock")),
845
881
  claim: (p) => this.claimItem(p),
@@ -1854,10 +1890,13 @@ export class Essey {
1854
1890
  const plan = this.io.planLoanOpen ?? ((q) => this.planOpen(q));
1855
1891
  if (!this.io.readLoans)
1856
1892
  notSetUp("missing config: no loan reader");
1857
- const proved = await plan(p);
1858
- if (proved.pool !== p.loanCoin)
1859
- wrongCoinObject();
1860
- const landed = await this.paidLoan(openLoan, { ...proved, wait: true });
1893
+ const send = async () => {
1894
+ const proved = await plan(p);
1895
+ if (proved.pool !== p.loanCoin)
1896
+ wrongCoinObject();
1897
+ return { proved, landed: await this.paidLoan(openLoan, { ...proved, wait: true }) };
1898
+ };
1899
+ const { proved, landed } = await send().catch((err) => (lateClose(err) ? send() : Promise.reject(err)));
1861
1900
  const read = this.io.readLoans;
1862
1901
  const row = await this.listedByKey("loan", "loan_key", proved.loanKey, async (c) => {
1863
1902
  const page = await read(c);
@@ -1922,7 +1961,8 @@ export class Essey {
1922
1961
  pathElements: tree.path(n.index),
1923
1962
  }));
1924
1963
  await this.keys();
1925
- const own = deriveNoteKey(seed, this.reserve("notes"));
1964
+ const ownIndex = this.reserve("notes");
1965
+ const own = deriveNoteKey(seed, ownIndex);
1926
1966
  const changeIndex = this.reserve("notes");
1927
1967
  const change = deriveNoteKey(seed, changeIndex);
1928
1968
  const borrowerPk = notePk(own.sk);
@@ -1935,17 +1975,6 @@ export class Essey {
1935
1975
  termMs: BigInt(p.termMs),
1936
1976
  salt: poseidonHash([own.sk, own.blinding, 2n]),
1937
1977
  };
1938
- const closeMs = this.loanClose(p.offerWindowMs);
1939
- const reqSealed = await seal({
1940
- id: requestKeyId(loanKey),
1941
- data: requestPlaintext({
1942
- ...request,
1943
- borrowerPk,
1944
- closeMs,
1945
- market,
1946
- coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
1947
- }),
1948
- });
1949
1978
  const keeperCt = await seal({
1950
1979
  id: keeperKeyId(loanKey, 0n),
1951
1980
  data: encodeKeeperPayload({
@@ -1988,7 +2017,33 @@ export class Essey {
1988
2017
  request,
1989
2018
  });
1990
2019
  const reqCommit = requestCommit(request, borrowerPk, note);
1991
- const passN0 = openAction(loanKey, { reqCommit, reqSealed, closeMs, market, collateralCommit: note });
2020
+ const proved = async (circuit, input, publics) => ({
2021
+ proof: (await prover.prove(circuit, input)).proof,
2022
+ publicSignals: publics.map(String),
2023
+ });
2024
+ const lockProved = await proved("coll_lock", lock.input, lock.publics);
2025
+ const healthProved = await proved("health", open.input, open.publics);
2026
+ // The close goes last, after the slow proofs, so the open lands in the step it was chosen in (42_046).
2027
+ const closeMs = await this.loanClose(p.offerWindowMs);
2028
+ const reqSealed = await seal({
2029
+ id: requestKeyId(loanKey),
2030
+ data: requestPlaintext({
2031
+ ...request,
2032
+ borrowerPk,
2033
+ closeMs,
2034
+ market,
2035
+ coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
2036
+ }),
2037
+ });
2038
+ const memo = sealMemo(memoKey(seed), { kind: MEMO_KIND.request, key: loanKey, round: 0n }, requestMemoBody({ keyIndex: ownIndex, collAmt: p.collateral, borrowerPk }));
2039
+ const passN0 = openAction(loanKey, {
2040
+ reqCommit,
2041
+ reqSealed,
2042
+ closeMs,
2043
+ market,
2044
+ collateralCommit: note,
2045
+ memo,
2046
+ });
1992
2047
  const pass = membership({
1993
2048
  secrets: member,
1994
2049
  credential: credential,
@@ -1996,10 +2051,6 @@ export class Essey {
1996
2051
  room: keyId(loanKey),
1997
2052
  bind: keyId(passN0),
1998
2053
  });
1999
- const proved = async (circuit, input, publics) => ({
2000
- proof: (await prover.prove(circuit, input)).proof,
2001
- publicSignals: publics.map(String),
2002
- });
2003
2054
  return {
2004
2055
  pool: L,
2005
2056
  pass: {
@@ -2008,12 +2059,13 @@ export class Essey {
2008
2059
  expiryMs: credential.expiryMs,
2009
2060
  n0: passN0,
2010
2061
  },
2011
- collLock: await proved("coll_lock", lock.input, lock.publics),
2012
- health: await proved("health", open.input, open.publics),
2062
+ collLock: lockProved,
2063
+ health: healthProved,
2013
2064
  market,
2014
2065
  loanKey,
2015
2066
  reqCommit,
2016
2067
  reqSealed,
2068
+ memo,
2017
2069
  closeMs,
2018
2070
  collateralCommit: note,
2019
2071
  lock: lock.spend,
@@ -2024,11 +2076,46 @@ export class Essey {
2024
2076
  priceUpdate: await update(market),
2025
2077
  };
2026
2078
  }
2027
- /** The coins of the market a loan names, as `C/L` in the deployment record. */
2028
- loanClose(offerWindowMs) {
2029
- const nowMs = (this.io.now ?? Date.now)();
2030
- return BigInt(stepClose(nowMs + offerWindowMs, nowMs, LOAN_MAX_WINDOW_MS, this.config.closeStepMs));
2079
+ saleGate(kind, type) {
2080
+ const current = this.config.packageOrigins.sale ?? notSetUp("the sale package is not published yet");
2081
+ const retired = retiredOf(this.config, "sale");
2082
+ const previous = retired.filter((g) => g.preR1).map((g) => g.origin);
2083
+ const drained = retired.filter((g) => !g.preR1).map((g) => g.origin);
2084
+ const gate = asInvalid(() => saleKindGate(kind, type, { current, previous, drained }));
2085
+ const r1 = retiredFor(this.config, "sale", type);
2086
+ return r1 && !r1.preR1 ? { ...gate, drained: r1 } : gate;
2087
+ }
2088
+ /** A pre-R1 loan: its heartbeat takes bucket `k` at the pre-R1 floor. */
2089
+ retired(row) {
2090
+ return retiredFor(this.config, "loan", row?.type)?.preR1 === true;
2091
+ }
2092
+ /** An R1 loan under the Z1 record: R1's keeper policy and Seal namespace, and the shapes of a current loan. */
2093
+ drainedLoan(row) {
2094
+ const g = retiredFor(this.config, "loan", row?.type);
2095
+ return g && !g.preR1 ? g : undefined;
2031
2096
  }
2097
+ sealOrigin(row) {
2098
+ const drained = this.drainedLoan(row);
2099
+ return drained ? { origin: drained.origin } : {};
2100
+ }
2101
+ /**
2102
+ * A draining loan takes no opening kind (request read, offer, refi open) and none whose call changed shape in R1
2103
+ * (pick, settle, refi settle); it still cancels, repays, releases, reclaims, collects, tops up and heartbeats.
2104
+ */
2105
+ refuseRetired(row) {
2106
+ if (retiredFor(this.config, "loan", row?.type))
2107
+ 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");
2108
+ }
2109
+ /** PRV-27 (b): past a step boundary nearer than the landing margin first, then the close `loan::check_close` takes. */
2110
+ async loanClose(offerWindowMs) {
2111
+ const step = this.config.closeStepMs ?? HOUR_MS;
2112
+ const now = () => (this.io.now ?? Date.now)();
2113
+ const wait = closeWaitMs(now(), step, Number(CLOSE_MARGIN_MS));
2114
+ if (wait > 0)
2115
+ await this.sleep(wait);
2116
+ return gridClose(now(), offerWindowMs, step);
2117
+ }
2118
+ /** The coins of the market a loan names, as `C/L` in the deployment record. */
2032
2119
  pairOf(market) {
2033
2120
  const want = address(market, "market");
2034
2121
  const hit = Object.entries(this.config.objects.markets).find(([, id]) => id && address(id, "market") === want);
@@ -2047,6 +2134,7 @@ export class Essey {
2047
2134
  const row = await read(loan);
2048
2135
  if (!row)
2049
2136
  unknownObject("no loan with this id");
2137
+ this.refuseRetired(row);
2050
2138
  const json = row.json;
2051
2139
  const round = row.round;
2052
2140
  const refi = Number(json.state) === 8;
@@ -2120,15 +2208,17 @@ export class Essey {
2120
2208
  const offers = row?.round?.offers;
2121
2209
  return offers !== undefined && BigInt(offers.length) > seq;
2122
2210
  }
2123
- /** The lender's `loan_offer`: the principal locked to the round from up to two own notes, its sealed terms pinned. */
2124
- async planOffer(loanId, rateBps) {
2211
+ /**
2212
+ * The lender's `loan_offer`: the principal locked to the round from up to two own notes, its sealed terms pinned.
2213
+ * PRV-23 A, SCOPE-R1-MOVE-BATCH D10: the rate is the posted one, so offers differ in nothing the winner draw weighs.
2214
+ */
2215
+ async planOffer(loanId) {
2125
2216
  const q = await this.readRequest(loanId, true);
2126
2217
  assertRequestTerm(q.termMs, this.config.closeStepMs ?? HOUR_MS);
2127
2218
  const L = q.pair[1];
2128
2219
  if (poolId(this.config, L) !== q.poolL)
2129
2220
  wrongCoinObject();
2130
- if (rateBps > q.maxRateBps)
2131
- throw new EsseyError("INVALID_ARGUMENT", "the rate is above the request's maximum");
2221
+ const rateBps = q.maxRateBps;
2132
2222
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2133
2223
  const { member, credential } = readState(this.statePath, this.stateKey);
2134
2224
  const relayer = this.relayerAddress();
@@ -2174,7 +2264,15 @@ export class Essey {
2174
2264
  const changeValue = spent[0].amount + spent[1].amount - q.principal - relayerFee;
2175
2265
  const encChange = bytesOf(sealOpening({ value: changeValue, blinding: change.blinding, index: changeIndex }, noteEncKey(seed).encPub));
2176
2266
  const encFee = bytesOf(fillerEnc());
2177
- const extHash = loanExt(LOAN_OFFER_KIND, q.loan, q.poolL, q.round, relayer, [encChange, encFee], blake2b256(sealed));
2267
+ const record = {
2268
+ noteIndex: offerIndex,
2269
+ principal: q.principal,
2270
+ rateBps,
2271
+ termMs: q.termMs,
2272
+ borrowerPk: q.borrowerPk,
2273
+ };
2274
+ const memo = sealMemo(memoKey(seed), { kind: MEMO_KIND.offer, key: q.loanKey, round: q.round }, offerMemoBody(record));
2275
+ const extHash = loanExt(LOAN_OFFER_KIND, q.loan, q.poolL, q.round, relayer, [encChange, encFee], blake2b256(Uint8Array.from([...sealed, ...memo])));
2178
2276
  const witness = await loanOffer({
2179
2277
  root: tree.root,
2180
2278
  ins: spent,
@@ -2203,13 +2301,6 @@ export class Essey {
2203
2301
  publicSignals: publics.map(String),
2204
2302
  });
2205
2303
  const { spend } = witness;
2206
- const record = {
2207
- noteIndex: offerIndex,
2208
- principal: q.principal,
2209
- rateBps,
2210
- termMs: q.termMs,
2211
- borrowerPk: q.borrowerPk,
2212
- };
2213
2304
  return {
2214
2305
  record,
2215
2306
  seq: q.seq,
@@ -2232,6 +2323,7 @@ export class Essey {
2232
2323
  feeCt: spend.feeCt,
2233
2324
  commit: witness.commit,
2234
2325
  sealed,
2326
+ memo,
2235
2327
  encChange,
2236
2328
  encFee,
2237
2329
  },
@@ -2295,6 +2387,8 @@ export class Essey {
2295
2387
  const offer = offers?.[Number(seq)];
2296
2388
  if (!offer?.active)
2297
2389
  throw new EsseyError("INVALID_ARGUMENT", "seq is not an active offer of this round");
2390
+ if (pickOf(row.round) !== seq)
2391
+ throw new EsseyError("INVALID_ARGUMENT", "refused: only the round's pick can be slashed (offer::slash aborts 42_050); nothing was sent");
2298
2392
  const approve = this.offerApprove(loan, loanKey, round, seq, pair);
2299
2393
  const sealed = Uint8Array.from(Buffer.from(offer.sealed, "base64"));
2300
2394
  const plain = await decrypt({ sealed, approve }).catch(() => undefined);
@@ -2303,6 +2397,58 @@ export class Essey {
2303
2397
  const derived = await derive({ id: offerKeyId(loanKey, round, seq), approve });
2304
2398
  return this.freeLoan(slashLoan, { pool: pair[1], loan, round, seq, keys: this.pinnedKeys(derived) });
2305
2399
  }
2400
+ /**
2401
+ * PRV-23 A: the round's pick, drawn first when none is stored, opened through Seal: the one offer key the borrower
2402
+ * reads. A pick that does not open its commit and lock is slashed, which clears it, and drawn again (DOS-02). The
2403
+ * slots carry the pick alone as active, the one-slot witness `loan::settle_rows` folds (`loan.move:507-513`).
2404
+ */
2405
+ async pickedSlots(q) {
2406
+ const field = lockField(q.loanKey, q.round);
2407
+ const slashed = new Set();
2408
+ for (let draw = 0; draw < SETTLE_SLOTS; draw++) {
2409
+ const round = await this.untilPicked(q, slashed);
2410
+ const pick = pickOf(round);
2411
+ const o = round.offers[Number(pick)];
2412
+ const sealed = Uint8Array.from(Buffer.from(o.sealed, "base64"));
2413
+ const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
2414
+ const approve = this.offerApprove(q.loan, q.loanKey, q.round, pick, q.pair);
2415
+ const plain = await decrypt({ sealed, approve });
2416
+ if (offerOpens(plain, field, BigInt(o.commit), BigInt(o.lock)))
2417
+ return round.offers.map((s, i) => ({
2418
+ commit: BigInt(s.commit),
2419
+ lock: BigInt(s.lock),
2420
+ active: BigInt(i) === pick,
2421
+ open: BigInt(i) === pick ? decodeOffer(plain) : undefined,
2422
+ }));
2423
+ await this.slashOffer(q.loan, pick);
2424
+ slashed.add(pick);
2425
+ }
2426
+ throw new EsseyError("INVALID_ARGUMENT", "refused: no offer of this round opens its commit and lock");
2427
+ }
2428
+ /**
2429
+ * The round once a pick shows that is none of `slashed`. With no pick, `loan_pick` goes once, alone: `pick::pick`
2430
+ * takes `Random` and must end its PTB (`move/v3/loan/sources/pick.move:1-3`). The reader may trail both writes.
2431
+ */
2432
+ async untilPicked(q, slashed) {
2433
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2434
+ let sent = false;
2435
+ for (let i = 0; i < SETTLE_READS; i++) {
2436
+ const round = (await read(q.loan))?.round;
2437
+ if (!round)
2438
+ unknownObject("the loan's round is missing");
2439
+ const pick = pickOf(round);
2440
+ const trailing = [...slashed].some((s) => round.offers[Number(s)]?.active) || (pick !== null && slashed.has(pick));
2441
+ if (!trailing && pick !== null)
2442
+ return round;
2443
+ if (!trailing && !sent) {
2444
+ await this.freeLoan(pickLoan, { pool: q.pair[1], loan: q.loan });
2445
+ sent = true;
2446
+ continue;
2447
+ }
2448
+ await this.sleep(SETTLE_READ_MS);
2449
+ }
2450
+ throw new EsseyError("STATE_REFUSED", "the loan read does not show the round's pick yet");
2451
+ }
2306
2452
  /** Threshold many derived keys, each with its server's slot in `config.seal.servers` (`seal_servers::public_keys` order). */
2307
2453
  pinnedKeys(derived) {
2308
2454
  const servers = this.config.seal.servers.map((s) => s.objectId);
@@ -2320,12 +2466,12 @@ export class Essey {
2320
2466
  */
2321
2467
  async ctFault(loanId, via) {
2322
2468
  const derive = this.io.sealDerivedKeys ?? notSetUp("missing config: no Seal key deriver");
2323
- const { loan, json } = await this.activeLoan(loanId);
2469
+ const { loan, json, drained } = await this.activeLoan(loanId);
2324
2470
  const retained = json.coll?.borrower_ct;
2325
2471
  if (!retained)
2326
2472
  throw new EsseyError("INVALID_ARGUMENT", "the loan holds no borrower ciphertext");
2327
2473
  const id = keeperKeyId(BigInt(json.loan_key), BigInt(retained.version));
2328
- const approval = await this.keeperApproval(json, loan, id, via);
2474
+ const approval = await this.keeperApproval(json, loan, id, via, drained);
2329
2475
  if (await this.retainedOpens(json, loan, approval))
2330
2476
  throw new EsseyError("INVALID_ARGUMENT", "refused: the ciphertext opens its lock and terms (prove_ct_fault aborts 43_212)");
2331
2477
  const derived = await derive({ id, ...approval });
@@ -2366,15 +2512,26 @@ export class Essey {
2366
2512
  const row = await read(loan);
2367
2513
  if (!row)
2368
2514
  unknownObject("no loan with this id");
2515
+ if (this.retired(row))
2516
+ this.refuseRetired(row);
2369
2517
  const json = row.json;
2370
2518
  if (Number(json.state) !== 2 && Number(json.state) !== 8)
2371
2519
  throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
2372
- return { loan, json };
2520
+ const drained = this.drainedLoan(row);
2521
+ return drained ? { loan, json, drained } : { loan, json };
2373
2522
  }
2374
- /** Either policy entry for key id `id`; the badge one carries the signer its Seal session must be made by. */
2375
- async keeperApproval(json, loan, id, via = "pass") {
2523
+ /**
2524
+ * Either policy entry for key id `id`; the badge one carries the signer its Seal session must be made by. An R1 loan
2525
+ * under the Z1 record is read through R1's own keeper policy and registry, and a badge is of the current registry.
2526
+ */
2527
+ async keeperApproval(json, loan, id, via = "pass", drained) {
2376
2528
  const market = address(json.market_id, "market");
2377
2529
  const pair = this.pairOf(json.market_id);
2530
+ if (drained) {
2531
+ if (via !== "pass")
2532
+ throw new EsseyError("INVALID_ARGUMENT", "refused: an R1 loan is read with a keeper pass, not a badge");
2533
+ return { approve: await this.keeperApprove(loan, market, id, pair, drained), origin: drained.origin };
2534
+ }
2378
2535
  if (via === "pass")
2379
2536
  return { approve: await this.keeperApprove(loan, market, id, pair) };
2380
2537
  const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
@@ -2446,7 +2603,8 @@ export class Essey {
2446
2603
  proof: `0x${Buffer.from(proof).toString("hex")}`,
2447
2604
  };
2448
2605
  const digest = await this.sponsoredSend(signer, txKindB64, wire, relayer);
2449
- const row = await this.listedByKey("badge", "tag", pass.publics[0], async (c) => {
2606
+ // PRV-16: a badge keeps no pass tag (keeper.move:53-60); the fresh holder this mint alone used finds it.
2607
+ const row = await this.listedByKey("badge", "holder", holder, async (c) => {
2450
2608
  const page = await readBadges(c);
2451
2609
  return { rows: page.badges, next: page.next };
2452
2610
  });
@@ -2475,24 +2633,33 @@ export class Essey {
2475
2633
  });
2476
2634
  }
2477
2635
  /** `keeper::seal_approve_keeper_proof`: a KEEPER pass for the deployment's keeper registry, bound to the viewer. */
2478
- async keeperApprove(loan, market, id, pair) {
2479
- const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
2636
+ async keeperApprove(loan, market, id, pair, drained) {
2637
+ const current = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
2638
+ // Z1's registry takes R1's pass key (`git show 57deb997b:scripts/v3/publish-leaves.ts`:215); only the registry differs.
2639
+ const registry = drained
2640
+ ? (drained.keeperRegistry ?? notSetUp("the record names no keeper registry for this loan's package"))
2641
+ : current.registry.id;
2642
+ const keeper = { passKey: current.passKey, registry: { id: registry } };
2643
+ const pkg = drained ? drained.latest : this.config.packages.loan;
2480
2644
  const { member, credential } = readState(this.statePath, this.stateKey);
2481
2645
  if (!member || credential?.role !== "keeper")
2482
2646
  notSetUp("no keeper credential");
2483
2647
  const { price, standin } = await this.keeperFeed(market);
2484
2648
  const prover = this.prover();
2485
2649
  return async (viewer) => {
2650
+ // 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).
2651
+ const nonce = drawSecret();
2486
2652
  const pass = membership({
2487
2653
  secrets: member,
2488
2654
  credential: credential,
2489
2655
  domain: DOMAIN_KEEPER,
2490
2656
  room: keeper.registry.id,
2491
2657
  bind: viewer,
2658
+ nonce,
2492
2659
  });
2493
2660
  const proved = await prover.prove("membership", pass.input);
2494
2661
  return {
2495
- target: `${this.config.packages.loan}::keeper::seal_approve_keeper_proof${standin ? "_standin" : ""}`,
2662
+ target: `${pkg}::keeper::seal_approve_keeper_proof${standin ? "_standin" : ""}`,
2496
2663
  typeArguments: pair.map((c) => this.config.coins[c].type),
2497
2664
  args: [
2498
2665
  { pure: "vector<u8>", value: `0x${Buffer.from(id).toString("hex")}` },
@@ -2504,6 +2671,7 @@ export class Essey {
2504
2671
  { pure: "u256", value: pass.publics[0].toString() },
2505
2672
  { pure: "u64", value: credential.expiryMs.toString() },
2506
2673
  { pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
2674
+ { pure: "u256", value: nonce.toString() },
2507
2675
  { object: "0x6" },
2508
2676
  ],
2509
2677
  };
@@ -2534,13 +2702,7 @@ export class Essey {
2534
2702
  }
2535
2703
  return notSetUp("no Pyth market in the deployment");
2536
2704
  }
2537
- /** The borrower's read of offer `seq` after close (`seal_policy::seal_approve_offer`): pass nonce 0 is its open tag. */
2538
- async openOffer(loan, loanKey, round, seq, sealed, pair) {
2539
- const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
2540
- const plain = await decrypt({ sealed, approve: this.offerApprove(loan, loanKey, round, seq, pair) });
2541
- return decodeOffer(plain);
2542
- }
2543
- /** The borrower's `loan_settle` on round 0: the lowest eligible offer wins, keeper ciphertext v1 carries its terms. */
2705
+ /** The borrower's `loan_settle` on round 0: the round's pick wins, keeper ciphertext v1 carries its terms. */
2544
2706
  async planSettle(id, collAmt) {
2545
2707
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2546
2708
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
@@ -2548,19 +2710,12 @@ export class Essey {
2548
2710
  // settle.move:131-135 refuses a settle until now_s * 1000 reaches close_ms.
2549
2711
  if (BigInt(Math.floor((this.io.now ?? Date.now)() / 1000)) * 1000n < q.closeMs)
2550
2712
  throw new EsseyError("INVALID_ARGUMENT", "refused: the offer window is still open");
2551
- const row = await read(q.loan);
2552
- const json = row.json;
2553
2713
  const seed = this.seed();
2554
- const { opening } = this.ownOpening(seed, json, q.borrowerPk, collAmt);
2555
- const round = row.round;
2556
- const slots = [];
2557
- for (const [i, o] of round.offers.entries()) {
2558
- const sealed = Uint8Array.from(Buffer.from(o.sealed, "base64"));
2559
- const open = o.active
2560
- ? await this.openOffer(q.loan, q.loanKey, q.round, BigInt(i), sealed, q.pair)
2561
- : undefined;
2562
- slots.push({ commit: BigInt(o.commit), lock: BigInt(o.lock), active: o.active, open });
2563
- }
2714
+ const first = (await read(q.loan)).json;
2715
+ this.ownOpening(seed, first, q.borrowerPk, collAmt);
2716
+ const slots = await this.pickedSlots(q);
2717
+ const json = (await read(q.loan)).json;
2718
+ const { opening, index: keyIndex } = this.ownOpening(seed, json, q.borrowerPk, collAmt);
2564
2719
  const { member, credential } = readState(this.statePath, this.stateKey);
2565
2720
  const L = q.pair[1];
2566
2721
  const prover = this.prover();
@@ -2602,6 +2757,12 @@ export class Essey {
2602
2757
  if (w.termsCommit !== draft.termsCommit)
2603
2758
  throw new EsseyError("INVALID_ARGUMENT", "refused: the terms moved between drafts");
2604
2759
  const settleProof = await prover.prove("loan_settle", w.input);
2760
+ const memo = this.settleMemo(seed, q.loanKey, q.round, {
2761
+ keyIndex,
2762
+ collAmt: opening.amount,
2763
+ borrowerPk: q.borrowerPk,
2764
+ terms: w.terms,
2765
+ });
2605
2766
  const args = settleArgs({
2606
2767
  loan: q.loan,
2607
2768
  poolL: q.poolL,
@@ -2617,6 +2778,7 @@ export class Essey {
2617
2778
  keeperCt,
2618
2779
  encs,
2619
2780
  nowS,
2781
+ memo,
2620
2782
  });
2621
2783
  const n0 = actionHash(blake2b256, q.loanKey, BigInt(json.nonce), "settle", args);
2622
2784
  const room = keyId(q.loanKey);
@@ -2655,9 +2817,13 @@ export class Essey {
2655
2817
  encPrincipal,
2656
2818
  encFee,
2657
2819
  nowS,
2820
+ memo,
2658
2821
  },
2659
2822
  };
2660
2823
  }
2824
+ settleMemo(seed, loanKey, round, record) {
2825
+ return sealMemo(memoKey(seed), { kind: MEMO_KIND.settle, key: loanKey, round }, settleMemoBody(record));
2826
+ }
2661
2827
  /** The borrower's `loan_repay`: `owed` to the lender's note by ECDH on its enc key, change back to own key. */
2662
2828
  async planRepay(loanId, terms, borrowerPk) {
2663
2829
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
@@ -3044,6 +3210,7 @@ export class Essey {
3044
3210
  const row = await read(loan);
3045
3211
  if (!row)
3046
3212
  unknownObject("no loan with this id");
3213
+ this.refuseRetired(row);
3047
3214
  const json = row.json;
3048
3215
  if (Number(json.state) !== 2)
3049
3216
  throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
@@ -3061,20 +3228,24 @@ export class Essey {
3061
3228
  salt: poseidonHash([own.sk, own.blinding, 2n, round]),
3062
3229
  };
3063
3230
  const reqCommit = requestCommit(request, p.borrowerPk, collNote(opening));
3064
- const closeMs = this.loanClose(p.offerWindowMs);
3065
- const reqSealed = await seal({
3066
- id: requestKeyId(opening.loanKey),
3067
- data: requestPlaintext({
3068
- ...request,
3069
- borrowerPk: p.borrowerPk,
3070
- closeMs,
3071
- market,
3072
- coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
3073
- }),
3074
- });
3075
- const pass = await this.borrowerPass(json, "refi", openRefiArgs({ loan, poolL, reqCommit, reqSealed, closeMs }));
3076
- const landed = await this.freeLoan(refinanceLoan, { pool: L, loan, pass, reqCommit, reqSealed, closeMs });
3077
- return { ...landed, round, closeMs };
3231
+ const send = async () => {
3232
+ const closeMs = await this.loanClose(p.offerWindowMs);
3233
+ const reqSealed = await seal({
3234
+ id: requestKeyId(opening.loanKey),
3235
+ data: requestPlaintext({
3236
+ ...request,
3237
+ borrowerPk: p.borrowerPk,
3238
+ closeMs,
3239
+ market,
3240
+ coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
3241
+ }),
3242
+ });
3243
+ const args = openRefiArgs({ loan, poolL, reqCommit, reqSealed, closeMs });
3244
+ const pass = await this.borrowerPass(json, "refi", args);
3245
+ const body = { pool: L, loan, pass, reqCommit, reqSealed, closeMs };
3246
+ return { ...(await this.freeLoan(refinanceLoan, body)), round, closeMs };
3247
+ };
3248
+ return send().catch((err) => (lateClose(err) ? send() : Promise.reject(err)));
3078
3249
  }
3079
3250
  /**
3080
3251
  * `refi::settle_refi`: the round's offers opened as `planSettle` opens them, the request read back through Seal, the
@@ -3086,23 +3257,17 @@ export class Essey {
3086
3257
  const readReading = this.io.readReading ?? notSetUp("missing config: no reading reader");
3087
3258
  const update = this.io.priceUpdate ?? notSetUp("missing config: no price update source");
3088
3259
  const q = await this.readRequest(p.loan);
3089
- const row = await read(q.loan);
3090
- const json = row.json;
3091
- if (termsCommit(p.terms, p.borrowerPk) !== BigInt(json.terms_commit))
3260
+ if (BigInt((this.io.now ?? Date.now)()) < q.closeMs)
3261
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the offer window is still open");
3262
+ const opened = (await read(q.loan)).json;
3263
+ if (termsCommit(p.terms, p.borrowerPk) !== BigInt(opened.terms_commit))
3092
3264
  throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
3093
- const round = row.round;
3094
- const slots = [];
3095
- for (const [i, o] of round.offers.entries()) {
3096
- const sealed = Uint8Array.from(Buffer.from(o.sealed, "base64"));
3097
- const open = o.active
3098
- ? await this.openOffer(q.loan, q.loanKey, q.round, BigInt(i), sealed, q.pair)
3099
- : undefined;
3100
- slots.push({ commit: BigInt(o.commit), lock: BigInt(o.lock), active: o.active, open });
3101
- }
3265
+ const slots = await this.pickedSlots(q);
3266
+ const json = (await read(q.loan)).json;
3102
3267
  const [C, L] = q.pair;
3103
3268
  const market = address(json.market_id, "market");
3104
3269
  const seed = this.seed();
3105
- const { opening } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
3270
+ const { opening, index: keyIndex } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
3106
3271
  const r = await readReading(market);
3107
3272
  const pClaim = r.spot < r.ema ? r.spot : r.ema;
3108
3273
  const rates = await this.rates(market);
@@ -3160,6 +3325,12 @@ export class Essey {
3160
3325
  if (w.termsCommit !== draft.termsCommit)
3161
3326
  throw new EsseyError("INVALID_ARGUMENT", "refused: the terms moved between drafts");
3162
3327
  const refiProof = await this.prover().prove("loan_refi", w.input);
3328
+ const memo = this.settleMemo(seed, q.loanKey, q.round, {
3329
+ keyIndex,
3330
+ collAmt: opening.amount,
3331
+ borrowerPk: p.borrowerPk,
3332
+ terms: w.terms,
3333
+ });
3163
3334
  const args = settleRefiArgs({
3164
3335
  loan: q.loan,
3165
3336
  poolL: q.poolL,
@@ -3182,6 +3353,7 @@ export class Essey {
3182
3353
  encs,
3183
3354
  encsP,
3184
3355
  nowS,
3356
+ memo,
3185
3357
  });
3186
3358
  const pass = await this.borrowerPass(json, "settle_refi", args);
3187
3359
  const landed = await this.freeLoan(settleRefiLoan, {
@@ -3206,6 +3378,7 @@ export class Essey {
3206
3378
  encs,
3207
3379
  encsP,
3208
3380
  nowS,
3381
+ memo,
3209
3382
  priceUpdate: await update(market),
3210
3383
  });
3211
3384
  return { ...landed, rateBps: w.terms.rateBps, terms: w.terms };
@@ -3316,6 +3489,48 @@ export class Essey {
3316
3489
  }
3317
3490
  throw new EsseyError("CT_MISMATCH", "refused: no spend of own notes opens the locked note");
3318
3491
  }
3492
+ /**
3493
+ * SCOPE-R1-MEMO D6: every listed loan's memos trial-opened under this seed's memo key. The AAD names the loan key,
3494
+ * round and slot, so a memo sealed for another seed, or copied into another loan, does not open.
3495
+ */
3496
+ async recoverRecords() {
3497
+ const readLoans = this.io.readLoans ?? notSetUp("missing config: no loan reader");
3498
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
3499
+ const key = memoKey(this.seed());
3500
+ const out = { loans: [], offers: [] };
3501
+ const bytes = (v) => typeof v === "string" ? Uint8Array.from(Buffer.from(v, "base64")) : new Uint8Array();
3502
+ let cursor = null;
3503
+ let pages = 0;
3504
+ for (;;) {
3505
+ const page = await readLoans(cursor);
3506
+ pages += 1;
3507
+ for (const row of page.loans) {
3508
+ const loan = address(row.id, "loan id");
3509
+ const json = row.json;
3510
+ const loanKey = BigInt(json.loan_key);
3511
+ const last = BigInt(json.round ?? 0);
3512
+ let record = null;
3513
+ for (let r = 0n; r <= last; r++) {
3514
+ const round = (r === last && row.round !== undefined ? row.round : (await read(loan, r))?.round);
3515
+ if (!round)
3516
+ continue;
3517
+ if (r === 0n)
3518
+ record = openRequestMemo(key, loanKey, bytes(round.req_memo)) ?? record;
3519
+ record = openSettleMemo(key, loanKey, r, bytes(round.settle_memo)) ?? record;
3520
+ (round.offers ?? []).forEach((o, seq) => {
3521
+ const offer = openOfferMemo(key, loanKey, r, bytes(o.memo));
3522
+ if (offer)
3523
+ out.offers.push({ loan, round: r, seq, record: offer });
3524
+ });
3525
+ }
3526
+ if (record)
3527
+ out.loans.push({ loan, record });
3528
+ }
3529
+ cursor = afterPage(page.next, pages);
3530
+ if (cursor === null)
3531
+ return out;
3532
+ }
3533
+ }
3319
3534
  /** `reclaim::reclaim`: the lender's Lock4 among the round's resolved locks, refunded to a fresh own note. */
3320
3535
  async reclaimOffer(loanId, offer, roundArg) {
3321
3536
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
@@ -3418,9 +3633,9 @@ export class Essey {
3418
3633
  const market = address(json.market_id, "market");
3419
3634
  const expiryMs = await this.heartbeatExpiry(json, market, p.terms.maturityS, p.expiryMs);
3420
3635
  const { opening } = this.ownOpening(this.seed(), json, p.borrowerPk, p.collAmt);
3421
- const k = p.k ?? 1;
3422
3636
  const reading = await readPrice(market);
3423
- const floor = heartbeatFloor(reading, k);
3637
+ const retired = this.retired(row);
3638
+ const floor = retired ? legacyHeartbeatFloor(reading) : heartbeatFloor(reading);
3424
3639
  const fee = await this.loanFee(C, json.coll_fee_commit);
3425
3640
  const rates = {
3426
3641
  ltvBps: BigInt(json.ltv_bps),
@@ -3455,9 +3670,9 @@ export class Essey {
3455
3670
  statement: h.statement,
3456
3671
  wait: true,
3457
3672
  encs,
3458
- k,
3459
3673
  expiryMs,
3460
3674
  priceUpdate: await update(market),
3675
+ retired,
3461
3676
  }));
3462
3677
  return { ...landed, expiryMs };
3463
3678
  }
@@ -3509,11 +3724,13 @@ export class Essey {
3509
3724
  const fresh = coverExpiry(now, maturityS);
3510
3725
  if (asked === undefined && fresh < now + gap)
3511
3726
  throw new EsseyError("INVALID_ARGUMENT", "the loan is under one gap from maturity plus grace");
3512
- const expiry = asked ?? (stored > fresh ? stored : fresh);
3727
+ const expiry = asked ?? coverOverStored(fresh, stored);
3513
3728
  if (expiry < now + gap || expiry > now + H_MAX_MS)
3514
3729
  throw new EsseyError("INVALID_ARGUMENT", "the expiry must be at least one gap and at most 24 h ahead");
3515
3730
  if (expiry < stored)
3516
3731
  throw new EsseyError("INVALID_ARGUMENT", "the expiry cannot be earlier than the loan's current heartbeat expiry");
3732
+ if (expiry % COVER_STEP_MS !== 0n)
3733
+ throw new EsseyError("INVALID_ARGUMENT", "the expiry must be on the 5-minute cover step");
3517
3734
  return expiry;
3518
3735
  }
3519
3736
  /**
@@ -3577,6 +3794,7 @@ export class Essey {
3577
3794
  nonceAtCt: opening.nonce + 1n,
3578
3795
  terms: p.terms,
3579
3796
  }),
3797
+ ...this.sealOrigin(row),
3580
3798
  });
3581
3799
  const encs = [bytesOf(fillerEnc()), bytesOf(fillerEnc())];
3582
3800
  const decimals = {
@@ -3683,18 +3901,18 @@ export class Essey {
3683
3901
  }
3684
3902
  /** The keeper reads the current keeper ciphertext under its pass or badge, rolls the opening to the lock's nonce and seizes. */
3685
3903
  keeperLiquidate(loanId, via) {
3686
- return this.seize(loanId, MODE.LIQUIDATE, (json, _seed, loan) => this.keeperOpening(json, loan, via));
3904
+ return this.seize(loanId, MODE.LIQUIDATE, (json, _seed, loan, drained) => this.keeperOpening(json, loan, via, drained));
3687
3905
  }
3688
3906
  /** Any read that does not open the lock and the terms commit throws CT_MISMATCH. */
3689
- async keeperOpening(json, loan, via) {
3907
+ async keeperOpening(json, loan, via, drained) {
3690
3908
  const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
3691
3909
  const readCt = this.io.readKeeperCt ?? notSetUp("missing config: no keeper ciphertext reader");
3692
3910
  const loanKey = BigInt(json.loan_key);
3693
3911
  const version = BigInt(json.coll.keeper_ct_version);
3694
- const { approve, signer } = await this.keeperApproval(json, loan, keeperKeyId(loanKey, version), via);
3912
+ const approval = await this.keeperApproval(json, loan, keeperKeyId(loanKey, version), via, drained);
3695
3913
  const sealed = { loan, loanKey, keeperCt: await readCt(loan), keeperCtVersion: version };
3696
3914
  const payload = await fetchKeeperPlaintext(sealed, {
3697
- decrypt: (r) => decrypt({ sealed: r.sealed, approve, signer }).catch(keeperRefusal),
3915
+ decrypt: (r) => decrypt({ sealed: r.sealed, ...approval }).catch(keeperRefusal),
3698
3916
  });
3699
3917
  if (!payload.terms)
3700
3918
  throw new EsseyError("CT_MISMATCH", "refused: the keeper plaintext carries no terms");
@@ -3710,10 +3928,10 @@ export class Essey {
3710
3928
  */
3711
3929
  async judge(loanId, via) {
3712
3930
  const readPrice = this.io.readPrice ?? notSetUp("missing config: no price reader");
3713
- const { loan, json } = await this.activeLoan(loanId);
3931
+ const { loan, json, drained } = await this.activeLoan(loanId);
3714
3932
  let opened;
3715
3933
  try {
3716
- opened = await this.keeperOpening(json, loan, via);
3934
+ opened = await this.keeperOpening(json, loan, via, drained);
3717
3935
  }
3718
3936
  catch (err) {
3719
3937
  if (!isEsseyError(err, "CT_MISMATCH"))
@@ -3745,7 +3963,7 @@ export class Essey {
3745
3963
  if (Number(json.state) !== 2 && Number(json.state) !== 8)
3746
3964
  throw new EsseyError("INVALID_ARGUMENT", "the loan is not seizable");
3747
3965
  const seed = this.seed();
3748
- const { terms, borrowerPk, opening } = await open(json, seed, loan);
3966
+ const { terms, borrowerPk, opening } = await open(json, seed, loan, this.drainedLoan(row));
3749
3967
  if (termsCommit(terms, borrowerPk) !== BigInt(json.terms_commit))
3750
3968
  throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
3751
3969
  const [C, L] = this.pairOf(json.market_id);
@@ -3848,20 +4066,10 @@ export class Essey {
3848
4066
  });
3849
4067
  }
3850
4068
  /** The seller keys and bounds salt of the sale opened at note index `index`, so the seed alone reopens them. */
3851
- saleOpening(seed, index) {
3852
- const own = deriveNoteKey(seed, index);
3853
- const tagged = (t) => poseidonHash([own.sk, own.blinding, t]);
3854
- return { sellerSk: own.sk, sellerSecret: tagged(7n), boundsSalt: tagged(8n) };
3855
- }
3856
4069
  /** D-SPEC §6.2:599. The seller pass over `sale_room::open_args`, at action nonce 0; the relayer or the callback pays. */
3857
4070
  async openSale(p) {
3858
- const asked = assertSaleOpen(p);
3859
- assertSaleGrid(asked, this.config.closeStepMs ?? HOUR_MS);
3860
- const nowMs = (this.io.now ?? Date.now)();
3861
- const open = {
3862
- ...asked,
3863
- closeMs: stepClose(nowMs + asked.bidWindowMs, nowMs, SALE_MAX_WINDOW_MS, this.config.closeStepMs),
3864
- };
4071
+ const open = assertSaleOpen(p);
4072
+ await this.saleWindow(open);
3865
4073
  requireSale(this.config);
3866
4074
  const pool = poolId(this.config, open.coin);
3867
4075
  const item = { id: address(open.itemId, "itemId"), type: open.itemType };
@@ -3869,22 +4077,26 @@ export class Essey {
3869
4077
  const submit = (open.sponsored ?? this.sponsoring() !== null)
3870
4078
  ? await this.saleSponsor(pool, item.id)
3871
4079
  : (this.io.submitSaleOpen ?? notSetUp("missing config: sale open has no submitter"));
3872
- const closeMs = BigInt(open.closeMs);
3873
- const finishByMs = closeMs + BigInt(open.finishWindowMs);
3874
- const typeName = asInvalid(() => {
3875
- assertFinishWindow(closeMs, finishByMs);
3876
- return typeNameOf(open.itemType);
3877
- });
3878
- const shape = { pool, item: { id: item.id, typeName }, closeMs, finishByMs, maxBids: open.maxBids };
4080
+ const typeName = asInvalid(() => typeNameOf(open.itemType));
4081
+ const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
3879
4082
  const { secrets, credential } = this.member();
3880
4083
  const prover = this.prover();
3881
4084
  const seed = await this.keys();
3882
4085
  const noteIndex = this.reserve("notes");
3883
- const { boundsSalt, ...seller } = this.saleOpening(seed, noteIndex);
3884
- const bounds = { lo: open.minPrice, hi: open.maxPrice, salt: boundsSalt };
3885
- const commits = openCommits({ ...seller, boundsSalt }, bounds);
4086
+ const s = saleSecrets(deriveNoteKey(seed, noteIndex));
4087
+ const commits = openCommits(s, open.price);
4088
+ const bounds = { lo: open.price, hi: open.price, salt: s.boundsSalt };
3886
4089
  const saleKey = drawSecret();
3887
- const n0 = actionHash(blake2b256, saleKey, 0n, "open", openArgs({ ...shape, ...commits, saleKey }));
4090
+ const listing = await seal({
4091
+ id: listingKeyId(saleKey),
4092
+ data: listingPlaintext({ price: open.price, salt: s.postedSalt }),
4093
+ pkg: "sale",
4094
+ });
4095
+ const memo = sealSaleMemo(memoKey(seed), saleKey, { noteIndex, price: open.price });
4096
+ const t = await this.saleWindow(open);
4097
+ const { closeMs, finishByMs } = t;
4098
+ const shape = { pool, item: { id: item.id, typeName }, closeMs, finishByMs, maxBids: open.maxBids };
4099
+ const n0 = actionHash(blake2b256, saleKey, 0n, "open", openArgs({ ...shape, ...commits, listing, memo, saleKey }));
3888
4100
  const pass = membership({
3889
4101
  secrets,
3890
4102
  credential,
@@ -3893,11 +4105,14 @@ export class Essey {
3893
4105
  bind: keyId(n0),
3894
4106
  });
3895
4107
  const proved = await prover.prove("membership", pass.input);
4108
+ await this.untilLandable(t);
3896
4109
  const landed = await submit({
3897
4110
  coin: open.coin,
3898
4111
  item,
3899
4112
  saleKey,
3900
4113
  ...commits,
4114
+ listing,
4115
+ memo,
3901
4116
  closeMs,
3902
4117
  finishByMs,
3903
4118
  maxBids: open.maxBids,
@@ -3915,7 +4130,8 @@ export class Essey {
3915
4130
  const page = await readRooms(c);
3916
4131
  return { rows: page.rooms, next: page.next };
3917
4132
  });
3918
- assertRoomMatches(this.config, open, { id, json });
4133
+ assertRoomMatches(this.config, { ...open, closeMs: Number(closeMs) }, { id, json });
4134
+ const seller = { sellerSk: s.sellerSk, sellerSecret: s.sellerSecret };
3919
4135
  return {
3920
4136
  id,
3921
4137
  digest: landed.digest,
@@ -3923,6 +4139,20 @@ export class Essey {
3923
4139
  sale: { room: id, noteIndex, seller, bounds },
3924
4140
  };
3925
4141
  }
4142
+ /** PRV-27 (b), `sale_room::check_grid` (44_041): the close and finish a sale opening about now must carry. */
4143
+ async saleWindow(open) {
4144
+ const nowMs = (this.io.now ?? Date.now)();
4145
+ const asked = { nowMs, bidWindowMs: open.bidWindowMs, finishWindowMs: open.finishWindowMs };
4146
+ return asInvalid(() => saleTimes({ ...asked, marginMs: SALE_LAND_MARGIN_MS }));
4147
+ }
4148
+ /** An open landing outside `[landFromMs, landByMs]` aborts 44_041: wait for the start, refuse past the end. */
4149
+ async untilLandable(t) {
4150
+ const now = BigInt((this.io.now ?? Date.now)());
4151
+ if (now < t.landFromMs)
4152
+ await this.sleep(Number(t.landFromMs - now));
4153
+ if (BigInt((this.io.now ?? Date.now)()) > t.landByMs)
4154
+ 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");
4155
+ }
3926
4156
  /**
3927
4157
  * The sponsored open (E-34): a fresh seed-derived sender signs `from_proof` and `open` while the relayer pays gas.
3928
4158
  * PRV-35: an item at one of this seed's `itemAddress()` holders opens from that holder with no hand-over; any other
@@ -4015,16 +4245,33 @@ export class Essey {
4015
4245
  const bounds = this.io.roomBounds ? await this.io.roomBounds(key) : null;
4016
4246
  return viewRoomObject(this.config, { id: key, json: row.json }, bounds);
4017
4247
  }
4018
- async saleRoom(id) {
4248
+ /**
4249
+ * The room, refused for `kind` when its type names a retired sale package that does not take it
4250
+ * (DECISION-R1-MIGRATION A, `sales/package-gate.ts`). `legacy`: such a room's `finish` opens every active bid.
4251
+ */
4252
+ async saleRoom(id, kind) {
4019
4253
  requireSale(this.config);
4020
4254
  const read = this.io.readRoom ?? notSetUp("missing config: no room reader");
4021
4255
  const room = address(id, "room id");
4022
4256
  const row = await read(room);
4023
4257
  if (!row)
4024
4258
  unknownObject("no room with this id");
4259
+ const { legacy, drained } = row.type
4260
+ ? this.saleGate(kind, row.type)
4261
+ : { legacy: false, drained: undefined };
4262
+ // A retired room's Seal policy is its own package's; an old package id stays callable (DECISION-R1-MIGRATION).
4263
+ const policyPkg = legacy ? salePackageOf(row.type) : (drained?.latest ?? this.config.packages.sale);
4025
4264
  const json = row.json;
4026
4265
  const bids = (json.bids ?? []);
4266
+ const pick = optionU256(json.pick, "the room's pick");
4027
4267
  return {
4268
+ legacy,
4269
+ drained: !!drained,
4270
+ policyPkg,
4271
+ ...(drained ? { origin: drained.origin } : {}),
4272
+ pick: pick === null ? null : Number(pick),
4273
+ postedCommit: BigInt(json.posted_commit ?? 0),
4274
+ listing: optionBytes(json.listing),
4028
4275
  id: room,
4029
4276
  coin: coinByPool(this.config, String(json.pool_id)),
4030
4277
  saleKey: BigInt(json.sale_key),
@@ -4063,16 +4310,72 @@ export class Essey {
4063
4310
  if (this.nowMs() + CLOSE_MARGIN_MS > closeMs)
4064
4311
  throw new EsseyError("INVALID_ARGUMENT", `${what} has closed or closes within 2 minutes, too soon to prove and land; nothing was sent`);
4065
4312
  }
4066
- async placeBid(roomId, v, amount) {
4067
- if (typeof v !== "bigint" || typeof amount !== "bigint" || v <= 0n || v > amount)
4068
- throw new EsseyError("INVALID_ARGUMENT", "the bid must be above 0 and at most the deposit");
4069
- const room = await this.saleRoom(roomId);
4313
+ /**
4314
+ * `sale_room::seal_approve_listing`: a SEAL pass under a fresh non-zero nonce, bound to the viewer, as the loan
4315
+ * request read takes (`readRequest`), so two reads show two tags.
4316
+ */
4317
+ async readRoomListing(room) {
4318
+ const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
4319
+ const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
4320
+ const { member, credential } = readState(this.statePath, this.stateKey);
4321
+ if (!member || !credential)
4322
+ notSetUp("no credential: call credential.obtain first");
4323
+ if (!room.listing)
4324
+ unknownObject("the room holds no sealed listing");
4325
+ const scope = keyId(room.saleKey);
4326
+ const prover = this.prover();
4327
+ return decrypt({
4328
+ sealed: room.listing,
4329
+ pkg: "sale",
4330
+ approve: async (viewer) => {
4331
+ const nonce = drawSecret();
4332
+ const bind = `0x${Buffer.from(sealListingBind(scope, viewer)).toString("hex")}`;
4333
+ const pass = membership({
4334
+ secrets: member,
4335
+ credential: credential,
4336
+ domain: DOMAIN_SENDER,
4337
+ room: scope,
4338
+ bind,
4339
+ nonce,
4340
+ });
4341
+ const proved = await prover.prove("membership", pass.input);
4342
+ return {
4343
+ target: `${this.config.packages.sale}::sale_room::seal_approve_listing`,
4344
+ typeArguments: [this.config.coins[room.coin].type],
4345
+ args: [
4346
+ { pure: "vector<u8>", value: `0x${Buffer.from(listingKeyId(room.saleKey)).toString("hex")}` },
4347
+ { object: room.id },
4348
+ { object: passKey.id },
4349
+ { pure: "u256", value: pass.publics[0].toString() },
4350
+ { pure: "u256", value: nonce.toString() },
4351
+ { pure: "u64", value: credential.expiryMs.toString() },
4352
+ { pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
4353
+ { object: "0x6" },
4354
+ ],
4355
+ };
4356
+ },
4357
+ });
4358
+ }
4359
+ async placeBid(roomId, maxPrice, asked) {
4360
+ if (typeof maxPrice !== "bigint" || maxPrice <= 0n || (asked !== undefined && typeof asked !== "bigint"))
4361
+ throw new EsseyError("INVALID_ARGUMENT", "maxPrice must be above 0 and amount a bigint");
4362
+ const room = await this.saleRoom(roomId, "bid");
4070
4363
  if (room.state !== SALE_STATE.open)
4071
4364
  throw new EsseyError("INVALID_ARGUMENT", "the room is not taking bids");
4072
4365
  this.assertBeforeClose(room.closeMs, "the room");
4073
4366
  const seq = room.bids.length;
4074
4367
  if (seq >= room.maxBids)
4075
4368
  throw new EsseyError("INVALID_ARGUMENT", "the room is full");
4369
+ const plain = await this.readRoomListing(room);
4370
+ const listing = asInvalid(() => readListing(plain, room.postedCommit));
4371
+ if (!listing)
4372
+ throw new EsseyError("CT_MISMATCH", "refused: the listing does not open the room's posted price");
4373
+ const v = listing.price;
4374
+ if (v > maxPrice)
4375
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the posted price is above maxPrice; nothing was sent");
4376
+ const amount = asked ?? v;
4377
+ if (amount < v)
4378
+ throw new EsseyError("INVALID_ARGUMENT", "the deposit must cover the posted price");
4076
4379
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
4077
4380
  const { member, credential } = readState(this.statePath, this.stateKey);
4078
4381
  if (!member || !credential)
@@ -4097,7 +4400,8 @@ export class Essey {
4097
4400
  const record = { room: room.id, noteIndex: this.reserve("notes"), v, amount };
4098
4401
  const changeIndex = this.reserve("notes");
4099
4402
  const change = deriveNoteKey(seed, changeIndex);
4100
- const secrets = this.bidSecrets(seed, record);
4403
+ const secrets = { ...this.bidSecrets(seed, record), s: listing.salt };
4404
+ const memo = sealBidMemo(memoKey(seed), room.saleKey, record);
4101
4405
  const sealed = await seal({
4102
4406
  id: bidKeyId(room.saleKey, BigInt(seq)),
4103
4407
  data: bidPlaintext(secrets),
@@ -4110,12 +4414,13 @@ export class Essey {
4110
4414
  const w = await lockBid({
4111
4415
  root: tree.root,
4112
4416
  ins: spent,
4113
- room: { id: room.id, saleKey: room.saleKey, seq },
4417
+ room: { id: room.id, saleKey: room.saleKey, seq, postedCommit: room.postedCommit },
4114
4418
  bid: secrets,
4115
4419
  change: { pk: notePk(change.sk), blinding: change.blinding },
4116
4420
  relayer,
4117
4421
  relayerFee,
4118
4422
  sealed,
4423
+ memo,
4119
4424
  encs,
4120
4425
  fee,
4121
4426
  eph: drawEph(),
@@ -4142,6 +4447,7 @@ export class Essey {
4142
4447
  proved: await proved("lock_bid", w.input, w.publics),
4143
4448
  statement: w.statement,
4144
4449
  sealed,
4450
+ memo,
4145
4451
  encs,
4146
4452
  });
4147
4453
  return { ...landed, bid: record };
@@ -4165,7 +4471,7 @@ export class Essey {
4165
4471
  });
4166
4472
  const proved = await prover.prove("membership", pass.input);
4167
4473
  return {
4168
- target: `${this.config.packages.sale}::sale_room::seal_approve_bid`,
4474
+ target: `${room.policyPkg}::sale_room::seal_approve_bid`,
4169
4475
  typeArguments: [this.config.coins[room.coin].type],
4170
4476
  args: [
4171
4477
  {
@@ -4184,17 +4490,19 @@ export class Essey {
4184
4490
  };
4185
4491
  }
4186
4492
  /** `seal_approve_bid` releases keys from close until `finish_by_ms`, for an active bid (`sale_room.move:337-341`). */
4187
- async closedRoom(roomId) {
4188
- const room = await this.saleRoom(roomId);
4493
+ async closedRoom(roomId, kind) {
4494
+ const room = await this.saleRoom(roomId, kind);
4189
4495
  const now = this.nowMs();
4190
4496
  if (room.state !== SALE_STATE.open || now < room.closeMs || now >= room.finishByMs)
4191
4497
  throw new EsseyError("INVALID_ARGUMENT", "the room is not between close and its finish deadline");
4192
4498
  return room;
4193
4499
  }
4194
- async slashBid(roomId, seq) {
4195
- const room = await this.closedRoom(roomId);
4196
- if (!Number.isInteger(seq) || !room.bids[seq]?.active)
4197
- throw new EsseyError("INVALID_ARGUMENT", "seq is not an active bid of this room");
4500
+ /** PRV-24 A: only the room's pick is slashed (44_039); a slash clears it, so `finish` draws again. */
4501
+ async slashBid(roomId) {
4502
+ const room = await this.closedRoom(roomId, "slash");
4503
+ const seq = room.pick;
4504
+ if (seq === null || !room.bids[seq]?.active)
4505
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the room has no pick to slash; nothing was sent");
4198
4506
  const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
4199
4507
  const derive = this.io.sealDerivedKeys ?? notSetUp("missing config: no Seal key deriver");
4200
4508
  const bid = room.bids[seq];
@@ -4214,23 +4522,28 @@ export class Essey {
4214
4522
  });
4215
4523
  }
4216
4524
  async finishSale(p) {
4217
- const room = await this.closedRoom(p.room);
4525
+ const room = await this.pickedRoom(p.room);
4218
4526
  const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
4527
+ const opened = (i) => (room.legacy ? room.bids[i].active : i === room.pick);
4219
4528
  const plains = [];
4220
4529
  for (const [i, b] of room.bids.entries()) {
4221
- if (b.active && typeof b.sealed !== "string")
4530
+ if (opened(i) && typeof b.sealed !== "string")
4222
4531
  notSetUp("the room reader gave no sealed bid");
4223
- const sealed = b.active ? Uint8Array.from(Buffer.from(b.sealed, "base64")) : undefined;
4224
- plains.push(sealed && (await decrypt({ sealed, approve: this.bidApprove(room, i), pkg: "sale" })));
4532
+ const sealed = opened(i) ? Uint8Array.from(Buffer.from(b.sealed, "base64")) : undefined;
4533
+ const origin = room.origin ? { origin: room.origin } : {};
4534
+ plains.push(sealed && (await decrypt({ sealed, approve: this.bidApprove(room, i), pkg: "sale", ...origin })));
4225
4535
  }
4226
4536
  const seed = this.seed();
4227
4537
  const sellerIndex = this.indexOfSellerKey(seed, p.seller.sellerSk);
4228
4538
  const fee = await this.feeParams(room.coin);
4229
4539
  const eph = drawEph();
4230
- const planFor = (encs) => settlePlan({ room, plains, seller: p.seller, bounds: p.bounds, encs, fee, eph });
4540
+ const planRoom = { ...room, pick: room.legacy ? "legacy" : room.pick };
4541
+ const planFor = (encs) => settlePlan({ room: planRoom, plains, seller: p.seller, bounds: p.bounds, encs, fee, eph });
4231
4542
  const draft = await planFor([new Uint8Array(128), new Uint8Array(128)]);
4232
- if (draft.slash.length > 0)
4233
- throw new EsseyError("INVALID_ARGUMENT", `refused: slash bids ${draft.slash.join(", ")} first`);
4543
+ if (draft.slash.length > 0) {
4544
+ const which = room.legacy ? `bids ${draft.slash.join(", ")}` : `bid ${draft.slash[0]}`;
4545
+ throw new EsseyError("INVALID_ARGUMENT", `refused: slash ${which} first`);
4546
+ }
4234
4547
  const encSeller = sealOpening({ ...draft.sellerNote, index: sellerIndex }, noteEncKey(seed).encPub);
4235
4548
  const encs = [hexBytes(encSeller), hexBytes(fillerEnc())];
4236
4549
  const w = await planFor(encs);
@@ -4244,6 +4557,26 @@ export class Essey {
4244
4557
  encs,
4245
4558
  });
4246
4559
  }
4560
+ /**
4561
+ * PRV-24 A: a closed room with an active bid and no pick draws one first (`sale_pick`, alone: `sale_room::pick`
4562
+ * takes `Random`), then the room is read until the pick shows. A retired room, or one with no active bid, has none.
4563
+ */
4564
+ async pickedRoom(roomId) {
4565
+ let room = await this.closedRoom(roomId, "finish");
4566
+ if (room.legacy || room.pick !== null || !room.bids.some((b) => b.active))
4567
+ return room;
4568
+ if (room.drained)
4569
+ throw new EsseyError("STATE_REFUSED", "refused: an R1 room takes no pick after the Z1 cutover; with no pick it ends by expire; nothing was sent");
4570
+ await this.freeLoan(pickBody, { pool: room.coin, room: room.id });
4571
+ for (let i = 0; i < SETTLE_READS && room.pick === null; i++) {
4572
+ if (i > 0)
4573
+ await this.sleep(SETTLE_READ_MS);
4574
+ room = await this.closedRoom(roomId, "finish");
4575
+ }
4576
+ if (room.pick === null)
4577
+ throw new EsseyError("STATE_REFUSED", "the room read does not show its pick yet");
4578
+ return room;
4579
+ }
4247
4580
  indexOfSellerKey(seed, sellerSk) {
4248
4581
  const n = readState(this.statePath, this.stateKey).notes ?? 0;
4249
4582
  for (let i = n - 1; i >= 0; i--)
@@ -4252,13 +4585,13 @@ export class Essey {
4252
4585
  return notSetUp("refused: sellerSk is not a note key of this seed, so the proceeds would not scan");
4253
4586
  }
4254
4587
  async expireSale(roomId, vault) {
4255
- const room = await this.saleRoom(roomId);
4588
+ const room = await this.saleRoom(roomId, "expire");
4256
4589
  if (room.state !== SALE_STATE.open || this.nowMs() < room.finishByMs)
4257
4590
  throw new EsseyError("INVALID_ARGUMENT", "the room is not past its finish deadline");
4258
4591
  return this.freeLoan(expireBody, { pool: room.coin, room: room.id, vault });
4259
4592
  }
4260
4593
  async cancelSale(roomId, vault) {
4261
- const room = await this.saleRoom(roomId);
4594
+ const room = await this.saleRoom(roomId, "cancel");
4262
4595
  if (room.state !== SALE_STATE.open || room.bids.length > 0)
4263
4596
  throw new EsseyError("INVALID_ARGUMENT", "only an open room with no bid cancels");
4264
4597
  // `sale_room::action_hash` is `loan::action_hash`'s encoding over `sale_key` (`sale_room.move:528-529`).
@@ -4266,7 +4599,7 @@ export class Essey {
4266
4599
  return this.freeLoan(cancelBody, { pool: room.coin, room: room.id, vault, pass });
4267
4600
  }
4268
4601
  async reclaimBid(roomId, record, what) {
4269
- const room = await this.saleRoom(roomId);
4602
+ const room = await this.saleRoom(roomId, "reclaim");
4270
4603
  if (room.state !== SALE_STATE.settled && room.state !== SALE_STATE.expired)
4271
4604
  throw new EsseyError("INVALID_ARGUMENT", "the room has not ended");
4272
4605
  const seed = this.seed();
@@ -4314,7 +4647,7 @@ export class Essey {
4314
4647
  const claim = optionU256(json.claim);
4315
4648
  if (claim === null)
4316
4649
  throw new EsseyError("INVALID_ARGUMENT", "the vault holds no claim yet");
4317
- const room = await this.saleRoom(String(json.room_id));
4650
+ const room = await this.saleRoom(String(json.room_id), "claim");
4318
4651
  let holder;
4319
4652
  if (p.bid) {
4320
4653
  const own = this.bidSecrets(this.seed(), p.bid);