@esseyonsui/sui-sdk-v3 0.3.2 → 0.4.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 (134) hide show
  1. package/dist/config.d.ts +3 -0
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/config.js +1 -0
  4. package/dist/errors.d.ts +3 -1
  5. package/dist/errors.d.ts.map +1 -1
  6. package/dist/errors.js +5 -0
  7. package/dist/essey.d.ts +157 -131
  8. package/dist/essey.d.ts.map +1 -1
  9. package/dist/essey.js +641 -823
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/network.d.ts +2 -0
  14. package/dist/network.d.ts.map +1 -1
  15. package/dist/network.js +17 -3
  16. package/dist/v3/collateral/bodies.d.ts +23 -14
  17. package/dist/v3/collateral/bodies.d.ts.map +1 -1
  18. package/dist/v3/collateral/bodies.js +42 -35
  19. package/dist/v3/collateral/ext.d.ts +18 -13
  20. package/dist/v3/collateral/ext.d.ts.map +1 -1
  21. package/dist/v3/collateral/ext.js +5 -6
  22. package/dist/v3/collateral/health.d.ts +16 -10
  23. package/dist/v3/collateral/health.d.ts.map +1 -1
  24. package/dist/v3/collateral/health.js +55 -30
  25. package/dist/v3/collateral/math.d.ts +0 -2
  26. package/dist/v3/collateral/math.d.ts.map +1 -1
  27. package/dist/v3/collateral/math.js +0 -5
  28. package/dist/v3/collateral/openings.d.ts +5 -1
  29. package/dist/v3/collateral/openings.d.ts.map +1 -1
  30. package/dist/v3/collateral/openings.js +7 -12
  31. package/dist/v3/credential/membership.d.ts +16 -2
  32. package/dist/v3/credential/membership.d.ts.map +1 -1
  33. package/dist/v3/credential/membership.js +36 -3
  34. package/dist/v3/domains.d.ts +9 -0
  35. package/dist/v3/domains.d.ts.map +1 -1
  36. package/dist/v3/domains.js +5 -0
  37. package/dist/v3/fees.d.ts +13 -1
  38. package/dist/v3/fees.d.ts.map +1 -1
  39. package/dist/v3/fees.js +32 -2
  40. package/dist/v3/funds.d.ts +34 -0
  41. package/dist/v3/funds.d.ts.map +1 -0
  42. package/dist/v3/funds.js +60 -0
  43. package/dist/v3/keeper-payload.d.ts +29 -7
  44. package/dist/v3/keeper-payload.d.ts.map +1 -1
  45. package/dist/v3/keeper-payload.js +33 -22
  46. package/dist/v3/kinds.d.ts +6 -6
  47. package/dist/v3/kinds.d.ts.map +1 -1
  48. package/dist/v3/kinds.js +5 -13
  49. package/dist/v3/loans/bodies.d.ts +40 -68
  50. package/dist/v3/loans/bodies.d.ts.map +1 -1
  51. package/dist/v3/loans/bodies.js +50 -73
  52. package/dist/v3/loans/offer-payload.d.ts +109 -0
  53. package/dist/v3/loans/offer-payload.d.ts.map +1 -0
  54. package/dist/v3/loans/offer-payload.js +207 -0
  55. package/dist/v3/loans/offer-plan.d.ts +8 -60
  56. package/dist/v3/loans/offer-plan.d.ts.map +1 -1
  57. package/dist/v3/loans/offer-plan.js +19 -95
  58. package/dist/v3/loans/open-plan.d.ts +15 -5
  59. package/dist/v3/loans/open-plan.d.ts.map +1 -1
  60. package/dist/v3/loans/open-plan.js +18 -7
  61. package/dist/v3/loans/reclaim-plan.d.ts +31 -15
  62. package/dist/v3/loans/reclaim-plan.d.ts.map +1 -1
  63. package/dist/v3/loans/reclaim-plan.js +63 -32
  64. package/dist/v3/loans/refi-plan.d.ts +8 -34
  65. package/dist/v3/loans/refi-plan.d.ts.map +1 -1
  66. package/dist/v3/loans/refi-plan.js +30 -111
  67. package/dist/v3/loans/repay-plan.d.ts.map +1 -1
  68. package/dist/v3/loans/repay-plan.js +2 -2
  69. package/dist/v3/loans/settle-plan.d.ts +88 -53
  70. package/dist/v3/loans/settle-plan.d.ts.map +1 -1
  71. package/dist/v3/loans/settle-plan.js +141 -150
  72. package/dist/v3/locks.d.ts +21 -0
  73. package/dist/v3/locks.d.ts.map +1 -0
  74. package/dist/v3/locks.js +15 -0
  75. package/dist/v3/memo.d.ts +14 -4
  76. package/dist/v3/memo.d.ts.map +1 -1
  77. package/dist/v3/memo.js +14 -7
  78. package/dist/v3/notes/derive.d.ts +5 -0
  79. package/dist/v3/notes/derive.d.ts.map +1 -1
  80. package/dist/v3/notes/derive.js +5 -0
  81. package/dist/v3/pace.d.ts +0 -1
  82. package/dist/v3/pace.d.ts.map +1 -1
  83. package/dist/v3/pace.js +0 -1
  84. package/dist/v3/pads.d.ts +15 -0
  85. package/dist/v3/pads.d.ts.map +1 -0
  86. package/dist/v3/pads.js +25 -0
  87. package/dist/v3/prover.d.ts +1 -1
  88. package/dist/v3/prover.d.ts.map +1 -1
  89. package/dist/v3/prover.js +1 -0
  90. package/dist/v3/relay/client.d.ts.map +1 -1
  91. package/dist/v3/relay/client.js +2 -2
  92. package/dist/v3/sales/auctioneer.d.ts +32 -27
  93. package/dist/v3/sales/auctioneer.d.ts.map +1 -1
  94. package/dist/v3/sales/auctioneer.js +67 -108
  95. package/dist/v3/sales/bid.d.ts +20 -49
  96. package/dist/v3/sales/bid.d.ts.map +1 -1
  97. package/dist/v3/sales/bid.js +28 -83
  98. package/dist/v3/sales/bodies.d.ts +4 -54
  99. package/dist/v3/sales/bodies.d.ts.map +1 -1
  100. package/dist/v3/sales/bodies.js +10 -52
  101. package/dist/v3/sales/claim.d.ts +0 -2
  102. package/dist/v3/sales/claim.d.ts.map +1 -1
  103. package/dist/v3/sales/claim.js +6 -8
  104. package/dist/v3/sales/index.d.ts +0 -1
  105. package/dist/v3/sales/index.d.ts.map +1 -1
  106. package/dist/v3/sales/index.js +0 -1
  107. package/dist/v3/sales/listing.d.ts +8 -6
  108. package/dist/v3/sales/listing.d.ts.map +1 -1
  109. package/dist/v3/sales/listing.js +27 -9
  110. package/dist/v3/sales/open-kind.d.ts +1 -3
  111. package/dist/v3/sales/open-kind.d.ts.map +1 -1
  112. package/dist/v3/sales/open-kind.js +2 -3
  113. package/dist/v3/sales/outcome.d.ts +5 -8
  114. package/dist/v3/sales/outcome.d.ts.map +1 -1
  115. package/dist/v3/sales/outcome.js +5 -9
  116. package/dist/v3/sales/package-gate.d.ts +3 -4
  117. package/dist/v3/sales/package-gate.d.ts.map +1 -1
  118. package/dist/v3/sales/package-gate.js +9 -7
  119. package/dist/v3/sales/rows.d.ts +9 -49
  120. package/dist/v3/sales/rows.d.ts.map +1 -1
  121. package/dist/v3/sales/rows.js +17 -91
  122. package/dist/v3/sales/seller.d.ts +2 -6
  123. package/dist/v3/sales/seller.d.ts.map +1 -1
  124. package/dist/v3/sales/seller.js +4 -11
  125. package/dist/v3/stage1.d.ts +8 -21
  126. package/dist/v3/stage1.d.ts.map +1 -1
  127. package/dist/v3/stage1.js +8 -76
  128. package/package.json +1 -1
  129. package/dist/v3/loans/lock-round.d.ts +0 -22
  130. package/dist/v3/loans/lock-round.d.ts.map +0 -1
  131. package/dist/v3/loans/lock-round.js +0 -20
  132. package/dist/v3/sales/reclaim.d.ts +0 -46
  133. package/dist/v3/sales/reclaim.d.ts.map +0 -1
  134. package/dist/v3/sales/reclaim.js +0 -57
package/dist/essey.js CHANGED
@@ -7,20 +7,21 @@ import { xchacha20poly1305 } from "@noble/ciphers/chacha.js";
7
7
  import { secp256k1 } from "@noble/curves/secp256k1.js";
8
8
  import { blake2b } from "@noble/hashes/blake2.js";
9
9
  import { COINS, loadConfig } from "./config.js";
10
- import { EsseyError, isEsseyError } from "./errors.js";
10
+ import { EsseyError, isEsseyError, RETIRED_GENERATION_PEERS } from "./errors.js";
11
11
  import { keeperSection, } from "./keeper.js";
12
12
  import { address, assertTestnet, decimal, fixedHeaders, getJson, postJson, serviceUrl, } from "./network.js";
13
13
  import { credentialSigned, parseCredential, renewOpensAt, requestCredential, solveChallenge, } from "./v3/credential/issue.js";
14
- import { DOMAIN_KEEPER, DOMAIN_SENDER, DOMAIN_SPEND, FEE_PARAMS_ROOM, feeNonceLane, memberCommitment, } from "./v3/credential/membership.js";
14
+ import { DOMAIN_KEEPER, DOMAIN_SENDER, DOMAIN_SPEND, FEE_PARAMS_ROOM, RateSlots, 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, 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
- import { DOM_LBLIND, DOM_TSALT, R } from "./v3/domains.js";
16
+ import { cancel as cancelLoan, ctFault as ctFaultLoan, cancelRefi as cancelRefiLoan, claimDefault as claimDefaultLoan, 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";
17
+ import { DOM_LBLIND, DOM_RBLIND, 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
+ import { drawDummySeed, padNote, padPair } from "./v3/pads.js";
20
21
  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 { 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";
22
+ import { COVER_STEP_MS, GRACE_S, coverExpiry, coverOverStored, heartbeatFloor, } from "./v3/collateral/math.js";
23
+ import { assertLoanGrid, assertRequestClose, assertRequestTerm, closeWaitMs, TERM_STEPS, defaultNowS, gridClose, settleNowS, } from "./v3/time-grid.js";
24
+ import { MEMO_KIND, memoKey, openRequestMemo, openSaleMemo, openSettleMemo, requestMemoBody, sealMemo, sealSaleMemo, settleMemoBody, } from "./v3/memo.js";
24
25
  /**
25
26
  * The Seal servers dry-run `keeper::check_loan` and answer "does not have access" when it aborts: a heartbeat still
26
27
  * covers the loan at this price, the loan is not active, or the pass or badge does not match.
@@ -38,39 +39,40 @@ const H_MAX_MS = 86400000n;
38
39
  const FIND_LISTED_TRIES = 15;
39
40
  const FIND_LISTED_PAUSE_MS = 1_500;
40
41
  const STALE_REQUEST_MS = 86_400_000;
41
- import { MODE, NO_TERMS, health, lenderAmount, loanRisk, seizeIsLast, seizeSplit, } from "./v3/collateral/health.js";
42
+ import { MODE, health, lenderAmount, loanRisk, seizeIsLast, seizeSplit } from "./v3/collateral/health.js";
42
43
  import { collLockPk, collNote, outputBlind, requestCommit, termsCommit, } from "./v3/collateral/openings.js";
43
44
  import { fetchKeeperPlaintext, keeperKeyId, openingOf, rollTo } from "./v3/collateral/seal.js";
44
45
  import { localHealth } from "./v3/collateral/local-health.js";
45
46
  import { badgeApprove, badgeOf, mintBadgeKind } from "./v3/keeper-badge.js";
46
- import { KEEPER_LAYOUT_VERSION, encodeKeeperPayload } from "./v3/keeper-payload.js";
47
+ import { KEEPER_LAYOUT_VERSION, NO_VIEW, encodeKeeperPayload, keeperView, viewCommit, viewTerms, } from "./v3/keeper-payload.js";
47
48
  import { LOAN_REPAY_KIND, loanRepay } from "./v3/loans/repay-plan.js";
48
49
  import { reclaimColl, reclaimLock } from "./v3/loans/reclaim-plan.js";
49
50
  import { collLock, keyId, openAction, requestKeyId, requestPlaintext } from "./v3/loans/open-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";
51
- import { lockRound } from "./v3/loans/lock-round.js";
51
+ import { LOAN_SETTLE_KIND, actionHash, interest, loanSettle, settleArgs, openRefiArgs, readingBytes, settleRefiArgs, cancelRefiArgs, topupArgs, } from "./v3/loans/settle-plan.js";
52
52
  import { LOAN_REFI_KIND, loanRefi } from "./v3/loans/refi-plan.js";
53
- import { LOAN_OFFER_KIND, decodeRequest, lock4, lockField, loanExt, loanOffer, offerKeyId, offerPlaintext, offerRoom, sealListingBind, } from "./v3/loans/offer-plan.js";
53
+ import { decodeRequest, loanExt, sealListingBind } from "./v3/loans/offer-plan.js";
54
+ import { bidOpen, lockEncs, offerKeys, offerOpen, packEncPoint, scanLocks, scanRecoveries, unlockAfter, unpackAmount, unpackEncPoint, } from "./v3/loans/offer-payload.js";
55
+ import { bidBlind, lock5, lockField, offerBlind } from "./v3/locks.js";
56
+ import { fundsFloor, fundsNote, fundsRead } from "./v3/funds.js";
54
57
  import { badgeRecipient, proveBadge } from "./v3/badge.js";
55
58
  import { proveFaucet } from "./v3/faucet.js";
56
- import { ecdhBlind, feeCommit, feeOf, treasuryPoint, verifyFeeOpening, } from "./v3/fees.js";
59
+ import { ecdhBlind, feeCommit, flatFeeOf, minHiddenBase, treasuryPoint, verifyFeeOpening, } from "./v3/fees.js";
57
60
  import { JS4_LEVELS, deposit as depositInput, js4, membership, } from "./v3/inputs.js";
58
61
  import { marketRates } from "./v3/market.js";
59
62
  import { afterPage, assertLoanOpen, assertRoomMatches, assertSaleOpen, coinByPool, openPosition, poolId, requireSale, summarizeLoan, summarizeRoom, viewLoanObject, viewPosition, viewRoomObject, } from "./v3/stage1.js";
60
63
  import { plan as settlePlan } from "./v3/sales/auctioneer.js";
61
- import { lockBid } from "./v3/sales/bid.js";
62
- import { bidBody, cancelBody, claimBody, expireBody, finishBody, pickBody, reclaimBody, slashBody, } from "./v3/sales/bodies.js";
64
+ import { bidLock } from "./v3/sales/bid.js";
65
+ import { cancelBody, claimBody, expireBody, finishBody } from "./v3/sales/bodies.js";
63
66
  import { itemClaim } from "./v3/sales/claim.js";
64
67
  import { listingKeyId, listingPlaintext, readListing } from "./v3/sales/listing.js";
65
68
  import { saleOpenKind } from "./v3/sales/open-kind.js";
66
69
  import { SALE_STATE } from "./v3/sales/outcome.js";
67
- import { saleKindGate, salePackageOf } from "./v3/sales/package-gate.js";
68
- import { reclaim as saleReclaim } from "./v3/sales/reclaim.js";
69
- import { bidAad, bidKeyId, bidPlaintext, openBid, sealBidBind } from "./v3/sales/rows.js";
70
+ import { saleKindGate } from "./v3/sales/package-gate.js";
71
+ import { bidSecrets } from "./v3/sales/rows.js";
70
72
  import { openArgs, openCommits, saleSecrets, saleTimes, typeNameOf } from "./v3/sales/seller.js";
71
73
  import { splitDenominations } from "./v3/notes/denominations.js";
72
74
  import { DEPOSIT_ROOM, carriesKind, depositKind, executeSponsored, sponsor, } from "./v3/notes/deposit.js";
73
- import { SEED_BYTES, deriveNoteKey, depositSigner, itemHolder, noteEncKey, receiveKey, } from "./v3/notes/derive.js";
75
+ import { SEED_BYTES, deriveNoteKey, depositSigner, itemHolder, noteEncKey, offerRecvKey, receiveKey, } from "./v3/notes/derive.js";
74
76
  import { faucetGrant } from "./v3/notes/faucet.js";
75
77
  import { noteCommitment, noteNullifier, notePk } from "./v3/notes/keys.js";
76
78
  import { fillerEnc, sealOpening, sealOpening2 } from "./v3/notes/opening.js";
@@ -110,40 +112,22 @@ function notSetUp(what) {
110
112
  function unknownObject(what) {
111
113
  throw new EsseyError("SERVICE_REFUSED", `unknown object: ${what}`);
112
114
  }
115
+ function refuseRetiredProof(what) {
116
+ throw new EsseyError("RETIRED_GENERATION", `refused: this ${what} is on a retired package; finish it with ${RETIRED_GENERATION_PEERS}; nothing was sent`);
117
+ }
113
118
  function wrongCoinObject() {
114
119
  throw new EsseyError("INVALID_ARGUMENT", "wrong coin: the envelope pool is not the loan coin");
115
120
  }
116
121
  /**
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).
122
+ * The original ids of each retired `pkg`, the address in its objects' types: the record's optional
123
+ * `previous.packageOrigins` and `previous2.packageOrigins` (`services/v3api/src/config-route.ts` `previousSlots`).
120
124
  */
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) {
125
+ function previousOrigins(config, pkg) {
124
126
  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));
127
+ return [record.previous, record.previous2]
128
+ .map((slot) => slot?.packageOrigins?.[pkg])
129
+ .filter((id) => typeof id === "string")
130
+ .map((id) => normalizeSuiAddress(id));
147
131
  }
148
132
  /** `loan.move` `E_CLOSE_GRID`: the open landed a step later than its close was chosen for; a fresh close lands. */
149
133
  const E_CLOSE_GRID = 42_046;
@@ -566,8 +550,6 @@ function optionBytes(raw) {
566
550
  const inner = raw && typeof raw === "object" ? raw.vec?.[0] : raw;
567
551
  return typeof inner === "string" ? Uint8Array.from(Buffer.from(inner, "base64")) : undefined;
568
552
  }
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");
571
553
  function asInvalid(run) {
572
554
  try {
573
555
  return run();
@@ -583,6 +565,8 @@ function drawSecret() {
583
565
  return n;
584
566
  }
585
567
  }
568
+ /** A Health output key for a note that is hashed but never inserted, so needs no reserved index. */
569
+ const randomPad = () => ({ pk: notePk(drawSecret()), blinding: drawSecret() });
586
570
  function drawEph() {
587
571
  for (;;) {
588
572
  const n = BigInt(`0x${randomBytes(32).toString("hex")}`) >> EPH_SHIFT;
@@ -751,6 +735,7 @@ export class Essey {
751
735
  feeOpenings = new Map();
752
736
  /** Loan snapshot openings by `coin:commit`, apart from `feeOpenings`, which follows the config as it stands. */
753
737
  snapshotOpenings = new Map();
738
+ feeLanes = new RateSlots();
754
739
  constructor(config, statePath, apiOrigin, fetch, io, relay, relayerBase, seedOption, pacing, stateKey) {
755
740
  this.config = config;
756
741
  this.statePath = statePath;
@@ -781,30 +766,14 @@ export class Essey {
781
766
  this.loans = {
782
767
  prepareOpen: (body) => this.prepareOpen(body),
783
768
  open: (p) => ("loanCoin" in p ? this.openRequest(p) : this.paidLoan(openLoan, p)),
784
- offer: (p) => this.paidLoan(offerLoan, p),
785
769
  request: (id) => this.readRequest(id),
786
770
  lend: async (p) => {
787
771
  await this.refuseStaleRequest(p.loan);
788
772
  await this.refuseOffGridClose(p.loan);
789
- const send = async () => {
790
- await this.pause("offer", p.loan, closeOf(p.loan));
791
- const { body, record, seq } = await this.planOffer(p.loan);
792
- return {
793
- seq,
794
- sent: this.paidLoan(offerLoan, body).then((landed) => ({ ...landed, offer: record })),
795
- };
796
- };
797
- const first = await send();
798
- try {
799
- return await first.sent;
800
- }
801
- catch (err) {
802
- if (!(await this.slotTaken(err, p.loan, first.seq)))
803
- throw err;
804
- return (await send()).sent;
805
- }
773
+ await this.pause("offer", p.loan, closeOf(p.loan));
774
+ return this.lend(p.loan);
806
775
  },
807
- collect: (p) => this.collecting("collect", p, (sweep) => this.collect(p.loan, p.offer, sweep)),
776
+ collect: (p) => this.collecting("collect", { loan: `${p.lock.coin}:${p.lock.noteIndex}`, sweep: p.sweep }, (sweep) => this.collect(p.lock, p.offer, sweep)),
808
777
  collectSeized: (p) => this.collecting("collect_seized", p, (sweep) => this.collectSeized(p.loan, p.offer, sweep)),
809
778
  collectSurplus: (p) => this.collecting("collect_surplus", p, (sweep) => this.collectSurplus(p, sweep)),
810
779
  accept: (p) => this.paced("settle", p.loan, settleByOf(p.loan), async () => {
@@ -815,7 +784,6 @@ export class Essey {
815
784
  }),
816
785
  release: (p) => this.paced("release", p.loan, null, () => this.releaseCollateral(p.loan, p.terms, p.borrowerPk, p.collAmt)),
817
786
  cancelOwn: (id) => this.cancelOwn(id),
818
- slash: (p) => this.slashOffer(p.loan, BigInt(p.seq)),
819
787
  fault: (p) => this.paced("fault", p.loan, null, () => this.ctFault(p.loan, p.via)),
820
788
  openRefi: (p) => this.openRefi(p),
821
789
  cancelRefi: (id) => this.cancelRefiOwn(id),
@@ -823,7 +791,7 @@ export class Essey {
823
791
  const settled = await this.settleRefiOwn(p);
824
792
  return { ...settled, cover: await this.firstCover({ ...p, terms: settled.terms }) };
825
793
  }),
826
- reclaimOffer: (p) => this.paced("reclaim_offer", p.loan, null, () => this.reclaimOffer(p.loan, p.offer, p.round)),
794
+ reclaimLock: (p) => this.paced("reclaim_offer", `${p.coin}:${p.noteIndex}`, null, () => this.reclaimOwnLock(p.coin, p.noteIndex)),
827
795
  heartbeat: (p) => this.paced("heartbeat", p.loan, coverOf(p.loan), () => this.heartbeatOwn(p)),
828
796
  topup: (p) => this.paced("topup", p.loan, coverOf(p.loan), () => this.topupOwn(p)),
829
797
  liquidate: (p) => this.paced("liquidate", p.loan, null, () => this.borrowerSeize(p, MODE.LIQUIDATE)),
@@ -875,9 +843,8 @@ export class Essey {
875
843
  view: (id) => this.viewSale(id),
876
844
  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)),
877
845
  finish: (p) => this.finishSale(p),
878
- slash: (p) => this.slashBid(p.room),
879
846
  expire: (p) => this.expireSale(p.room, p.vault),
880
- reclaim: (p) => this.paced("sale_reclaim", p.room, null, () => this.reclaimBid(p.room, p.bid, p.what ?? "lock")),
847
+ collectChange: (p) => this.collecting("collect", { loan: p.bid.room, sweep: p.sweep }, (sweep) => this.collectBidChange(p.bid, sweep)),
881
848
  claim: (p) => this.claimItem(p),
882
849
  itemAddress: () => this.itemAddress(),
883
850
  cancel: (p) => this.cancelSale(p.room, p.vault),
@@ -1095,6 +1062,7 @@ export class Essey {
1095
1062
  if (!member || !credential)
1096
1063
  notSetUp("no credential: call credential.obtain first");
1097
1064
  const prover = this.io.prover ?? this.missingProver("membership");
1065
+ const lane = this.feeLanes.take((this.io.now ?? Date.now)());
1098
1066
  const challenge = await getJson(this.fetch, `${api}/v3/fee-params/challenge`);
1099
1067
  const nonce = challenge.body.nonce;
1100
1068
  if (challenge.status !== 200 || typeof nonce !== "string")
@@ -1106,7 +1074,7 @@ export class Essey {
1106
1074
  domain: credential.role === "keeper" ? DOMAIN_KEEPER : DOMAIN_SENDER,
1107
1075
  room: FEE_PARAMS_ROOM,
1108
1076
  bind: nonce,
1109
- nonce: feeNonceLane(nonce),
1077
+ nonce: lane,
1110
1078
  });
1111
1079
  const reply = await postJson(this.fetch, `${api}${path}`, {
1112
1080
  ...fields,
@@ -1221,16 +1189,16 @@ export class Essey {
1221
1189
  if (this.io.prover)
1222
1190
  return this.io.prover;
1223
1191
  const ready = ["membership", "deposit", "js4"].every((name) => {
1224
- const row = this.config.circuits[name];
1192
+ const row = this.config.circuitsZ1[name];
1225
1193
  return typeof row?.wasm?.url === "string" && typeof row?.zkey?.url === "string";
1226
1194
  });
1227
1195
  if (ready)
1228
1196
  return notSetUp("no prover: circuit pins are in the config; build io.prover with v3.loadCircuitArtifacts and v3.groth16Prover");
1229
1197
  return notSetUp("no prover: the circuit artifacts are not in the config yet");
1230
1198
  }
1231
- /** Pins in the config still need a prover. An empty `circuits` object is the pre-bring-up record. */
1199
+ /** Pins in the config still need a prover. An empty `circuitsZ1` object is the pre-bring-up record. */
1232
1200
  missingProver(circuit) {
1233
- const row = this.config.circuits[circuit];
1201
+ const row = this.config.circuitsZ1[circuit];
1234
1202
  if (typeof row?.wasm?.url === "string" && typeof row.zkey?.url === "string")
1235
1203
  return notSetUp(`no prover: ${circuit} pins are in the config; build io.prover with v3.loadCircuitArtifacts and v3.groth16Prover`);
1236
1204
  return notSetUp(`no prover: ${circuit} artifacts are not in the config yet`);
@@ -1766,7 +1734,9 @@ export class Essey {
1766
1734
  ins: [ins[0], ins[1] ?? dummyInput()],
1767
1735
  out0: "payTo" in dest
1768
1736
  ? { amount: value, pk: dest.payTo.pk, blinding: paidBlinding }
1769
- : { amount: 0n, pk: notePk(drawSecret()), blinding: drawSecret() },
1737
+ : "lock" in dest
1738
+ ? { amount: value, pk: dest.lock.pk, blinding: dest.lock.blinding }
1739
+ : { amount: 0n, pk: notePk(drawSecret()), blinding: drawSecret() },
1770
1740
  out1: { pk: notePk(change.sk), blinding: change.blinding },
1771
1741
  pad: { pk: notePk(drawSecret()), blinding: drawSecret() },
1772
1742
  ...(recipient ? { withdraw: { amount: value, recipient } } : {}),
@@ -1779,11 +1749,11 @@ export class Essey {
1779
1749
  const encChange = sealOpening({ value: changeValue, blinding: change.blinding, index }, noteEncKey(seed).encPub);
1780
1750
  const proved = await prover.prove("js4", js.input);
1781
1751
  const encPaid = "payTo" in dest ? sealPaid(dest.payTo, value, paidBlinding) : fillerEnc();
1782
- const body = ("payTo" in dest ? transferBody : withdrawBody)({
1752
+ const body = ("to" in dest ? withdrawBody : transferBody)({
1783
1753
  pool: coin,
1784
1754
  proved: { proof: proved.proof, publicSignals: js.publics.map(String) },
1785
1755
  statement: js.statement,
1786
- encs: [encPaid, encChange, fillerEnc(), fillerEnc()],
1756
+ encs: "lock" in dest ? dest.lock.encs(encChange) : [encPaid, encChange, fillerEnc(), fillerEnc()],
1787
1757
  relayerFee,
1788
1758
  wait: true,
1789
1759
  });
@@ -1987,6 +1957,7 @@ export class Essey {
1987
1957
  }),
1988
1958
  });
1989
1959
  const ids = { loan: keyId(loanKey), poolC, market };
1960
+ const lockPads = padPair(seed, () => this.reserve("notes"));
1990
1961
  const lock = await collLock({
1991
1962
  root: tree.root,
1992
1963
  ins: [ins[0], ins[1] ?? dummyInput()],
@@ -1997,23 +1968,27 @@ export class Essey {
1997
1968
  extHash: collLockExt(MODE_OPEN, ids.loan, poolC, market, relayer),
1998
1969
  fee,
1999
1970
  eph: drawEph(),
1971
+ pads: [lockPads[0], lockPads[1]],
2000
1972
  });
2001
1973
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2002
1974
  const encChange = bytesOf(sealOpening({ value: lock.changeAmount, blinding: change.blinding, index: changeIndex }, noteEncKey(seed).encPub));
2003
- const encFee = bytesOf(fillerEnc());
1975
+ const encs = [encChange, bytesOf(fillerEnc()), bytesOf(fillerEnc()), bytesOf(fillerEnc())];
2004
1976
  const decimals = {
2005
1977
  cDec: BigInt(this.config.coins[C].decimals),
2006
1978
  lDec: BigInt(this.config.coins[L].decimals),
2007
1979
  };
1980
+ // Health OPEN's out1/out2 are folded into hA but never inserted (Z1-LEAF-MAP.md, lock row): random keys, no index.
2008
1981
  const open = await health({
2009
1982
  mode: MODE.OPEN,
2010
1983
  opening,
2011
1984
  risk: loanRisk(rates.current, decimals, MODE.OPEN),
2012
1985
  price: { spot: pClaim, ema: pClaim, expo: reading.expo },
2013
1986
  timeS: 0n,
2014
- extHash: openExt(ids, keeperCt, encChange, encFee),
1987
+ extHash: openExt(ids, keeperCt, encs),
2015
1988
  fee,
2016
1989
  eph: drawEph(),
1990
+ pads: [randomPad(), randomPad()],
1991
+ dummySeeds: [drawDummySeed(), drawDummySeed()],
2017
1992
  request,
2018
1993
  });
2019
1994
  const reqCommit = requestCommit(request, borrowerPk, note);
@@ -2033,9 +2008,10 @@ export class Essey {
2033
2008
  closeMs,
2034
2009
  market,
2035
2010
  coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
2011
+ offerEncPub: offerRecvKey(seed, ownIndex).pub,
2036
2012
  }),
2037
2013
  });
2038
- const memo = sealMemo(memoKey(seed), { kind: MEMO_KIND.request, key: loanKey, round: 0n }, requestMemoBody({ keyIndex: ownIndex, collAmt: p.collateral, borrowerPk }));
2014
+ const memo = sealMemo(memoKey(seed), { kind: MEMO_KIND.request, key: loanKey, round: 0n }, requestMemoBody({ keyIndex: ownIndex, collAmt: p.collateral, borrowerPk, ...request }));
2039
2015
  const passN0 = openAction(loanKey, {
2040
2016
  reqCommit,
2041
2017
  reqSealed,
@@ -2069,7 +2045,7 @@ export class Essey {
2069
2045
  closeMs,
2070
2046
  collateralCommit: note,
2071
2047
  lock: lock.spend,
2072
- encs: [encChange, encFee],
2048
+ encs,
2073
2049
  keeperCt,
2074
2050
  pClaim,
2075
2051
  statement: open.statement,
@@ -2078,34 +2054,27 @@ export class Essey {
2078
2054
  }
2079
2055
  saleGate(kind, type) {
2080
2056
  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;
2057
+ const previous = previousOrigins(this.config, "sale");
2058
+ return asInvalid(() => saleKindGate(kind, type, { current, previous }));
2096
2059
  }
2097
- sealOrigin(row) {
2098
- const drained = this.drainedLoan(row);
2099
- return drained ? { origin: drained.origin } : {};
2060
+ /** DECISION-R1-MIGRATION A: a loan whose type names a `previous` or `previous2` loan origin is draining. */
2061
+ retired(row) {
2062
+ const pkg = row?.type?.split("::")[0];
2063
+ return pkg !== undefined && previousOrigins(this.config, "loan").includes(normalizeSuiAddress(pkg));
2100
2064
  }
2101
2065
  /**
2102
2066
  * A draining loan takes no opening kind (request read, offer, refi open) and none whose call changed shape in R1
2103
2067
  * (pick, settle, refi settle); it still cancels, repays, releases, reclaims, collects, tops up and heartbeats.
2104
2068
  */
2105
2069
  refuseRetired(row) {
2106
- if (retiredFor(this.config, "loan", row?.type))
2070
+ if (this.retired(row))
2107
2071
  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
2072
  }
2073
+ /** Erik ruling 3 (A): this SDK proves with `circuitsZ1` keys only, so a draining loan's proof is 0.3.x's to make. */
2074
+ refuseRetiredLoanProof(row) {
2075
+ if (this.retired(row))
2076
+ refuseRetiredProof("loan");
2077
+ }
2109
2078
  /** PRV-27 (b): past a step boundary nearer than the landing margin first, then the close `loan::check_close` takes. */
2110
2079
  async loanClose(offerWindowMs) {
2111
2080
  const step = this.config.closeStepMs ?? HOUR_MS;
@@ -2146,34 +2115,40 @@ export class Essey {
2146
2115
  this.assertBeforeClose(BigInt(round.close_ms), "the loan's offer round");
2147
2116
  const loanKey = BigInt(json.loan_key);
2148
2117
  const pair = this.pairOf(json.market_id);
2118
+ const poolL = address(json.pool_l, "pool_l");
2149
2119
  const room = keyId(loanKey);
2150
2120
  const prover = this.prover();
2151
2121
  const keyIdBytes = requestKeyId(loanKey);
2122
+ const funds = await this.fundsWitness(pair[1], await this.loanFee(pair[1], json.fee_commit));
2152
2123
  const plain = await decrypt({
2153
2124
  sealed: Uint8Array.from(Buffer.from(round.req_sealed, "base64")),
2154
2125
  approve: async (viewer) => {
2155
2126
  const nonce = drawSecret();
2156
- const bind = `0x${Buffer.from(sealListingBind(room, viewer)).toString("hex")}`;
2127
+ const sealBind = sealListingBind(room, viewer);
2157
2128
  const pass = membership({
2158
2129
  secrets: member,
2159
2130
  credential: credential,
2160
2131
  domain: DOMAIN_SENDER,
2161
2132
  room,
2162
- bind,
2133
+ bind: `0x${Buffer.from(sealBind).toString("hex")}`,
2163
2134
  nonce,
2164
2135
  });
2165
2136
  const proved = await prover.prove("membership", pass.input);
2137
+ const fundsProof = await funds.prove(sealBind, nonce);
2166
2138
  return {
2167
2139
  target: `${this.config.packages.loan}::seal_policy::seal_approve_request`,
2168
2140
  typeArguments: pair.map((c) => this.config.coins[c].type),
2169
2141
  args: [
2170
2142
  { pure: "vector<u8>", value: `0x${Buffer.from(keyIdBytes).toString("hex")}` },
2171
2143
  { object: loan },
2144
+ { object: poolL },
2172
2145
  { object: passKey.id },
2173
2146
  { pure: "u256", value: pass.publics[0].toString() },
2174
2147
  { pure: "u256", value: nonce.toString() },
2175
2148
  { pure: "u64", value: credential.expiryMs.toString() },
2176
2149
  { pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
2150
+ { pure: "u256", value: funds.root.toString() },
2151
+ { pure: "vector<u8>", value: `0x${Buffer.from(fundsProof).toString("hex")}` },
2177
2152
  { object: "0x6" },
2178
2153
  ],
2179
2154
  };
@@ -2188,266 +2163,178 @@ export class Essey {
2188
2163
  loan,
2189
2164
  loanKey,
2190
2165
  round: BigInt(json.round),
2191
- seq: BigInt(round.offers.length),
2192
2166
  pair,
2193
- poolL: address(json.pool_l, "pool_l"),
2167
+ poolL,
2194
2168
  ...request,
2195
2169
  borrowerPk: q.borrowerPk,
2196
2170
  collNote: note,
2197
2171
  closeMs: q.closeMs,
2172
+ settleByMs: BigInt(round.settle_by_ms),
2173
+ offerEncPub: q.offerEncPub,
2198
2174
  };
2199
2175
  }
2200
2176
  /**
2201
- * An offer is sealed to the slot it takes, `offers.length` when it lands (`loan.move` pin_offer). When another
2202
- * offer landed first, the relayer refuses or the chain fails it, and nothing was spent; one re-plan takes the next slot.
2177
+ * The borrower's own request, rebuilt with no Seal read and so no funds proof: round 0 from its request memo, which
2178
+ * this seed's memo key opens; a refi round from `refi` when given, else from that round's request memo
2179
+ * (`refi::open_refi`). The salt derives from the loan key's note index, the offer key from `offerRecvKey`. It must
2180
+ * open `req_commit`.
2203
2181
  */
2204
- async slotTaken(err, loan, seq) {
2205
- if (!isEsseyError(err, "RELAY_REFUSED") && !isEsseyError(err, "RELAY_FAILED"))
2206
- return false;
2207
- const row = await (this.io.readLoan ?? notSetUp("missing config: no loan reader"))(address(loan, "loan id"));
2208
- const offers = row?.round?.offers;
2209
- return offers !== undefined && BigInt(offers.length) > seq;
2182
+ async ownRequest(loanId, refi) {
2183
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2184
+ const loan = address(loanId, "loan id");
2185
+ const row = await read(loan);
2186
+ if (!row)
2187
+ unknownObject("no loan with this id");
2188
+ this.refuseRetired(row);
2189
+ const json = row.json;
2190
+ const round = row.round;
2191
+ const isRefi = Number(json.state) === 8;
2192
+ if (Number(json.state) !== 1 && !isRefi)
2193
+ throw new EsseyError("INVALID_ARGUMENT", "the loan is not bidding");
2194
+ if (!round)
2195
+ unknownObject("the loan's round is missing");
2196
+ const loanKey = BigInt(json.loan_key);
2197
+ const r = BigInt(json.round);
2198
+ const first = r === 0n ? row.round : (await read(loan, 0n))?.round;
2199
+ const memoOf = (at) => {
2200
+ const v = at?.req_memo;
2201
+ return typeof v === "string" ? Uint8Array.from(Buffer.from(v, "base64")) : new Uint8Array();
2202
+ };
2203
+ const seed = this.seed();
2204
+ const m = openRequestMemo(memoKey(seed), loanKey, memoOf(first));
2205
+ if (!m)
2206
+ unknownObject("this seed's request memo is not on the loan: not this seed's loan");
2207
+ const posted = isRefi ? (refi ?? openRequestMemo(memoKey(seed), loanKey, memoOf(row.round), r)) : m;
2208
+ if (!posted)
2209
+ unknownObject("this seed's request memo is not on the refi round");
2210
+ const own = deriveNoteKey(seed, m.keyIndex);
2211
+ const request = {
2212
+ principal: posted.principal,
2213
+ maxRateBps: posted.maxRateBps,
2214
+ termMs: posted.termMs,
2215
+ salt: poseidonHash(isRefi ? [own.sk, own.blinding, 2n, r] : [own.sk, own.blinding, 2n]),
2216
+ };
2217
+ const note = BigInt(isRefi ? json.coll.coll_note : json.collateral_commit);
2218
+ if (requestCommit(request, m.borrowerPk, note) !== BigInt(round.req_commit))
2219
+ throw new EsseyError("CT_MISMATCH", "refused: the own request does not open the loan's commit");
2220
+ return {
2221
+ loan,
2222
+ loanKey,
2223
+ round: r,
2224
+ pair: this.pairOf(json.market_id),
2225
+ poolL: address(json.pool_l, "pool_l"),
2226
+ ...request,
2227
+ borrowerPk: m.borrowerPk,
2228
+ collNote: note,
2229
+ closeMs: BigInt(round.close_ms),
2230
+ settleByMs: BigInt(round.settle_by_ms),
2231
+ offerEncPub: offerRecvKey(seed, m.keyIndex).pub,
2232
+ keyIndex: m.keyIndex,
2233
+ };
2234
+ }
2235
+ /**
2236
+ * PRV-22 (a), freeze D24: the funds proof a request or listing read needs, from the largest own note of `coin` at
2237
+ * the floor `10 * F` of `fee`. A member with none is refused before any proof or network call.
2238
+ */
2239
+ async fundsWitness(coin, fee) {
2240
+ const { events, owned } = await this.owned(coin);
2241
+ const floor = fundsFloor(fee);
2242
+ const note = fundsNote(owned, floor);
2243
+ if (!note)
2244
+ throw new EsseyError("FUNDS_BELOW_FLOOR", `refused: reading needs an own note of at least ${floor} in this coin (10 x the flat fee); nothing was sent`);
2245
+ const tree = poolTree(orderedLeaves(events));
2246
+ const prover = this.prover();
2247
+ return {
2248
+ root: tree.root,
2249
+ prove: async (sealBind, nonce) => {
2250
+ const w = fundsRead({
2251
+ note: { amount: note.value, sk: note.sk, blinding: note.blinding, index: note.index },
2252
+ path: tree.path(note.index),
2253
+ root: tree.root,
2254
+ fee,
2255
+ sealBind,
2256
+ nonce,
2257
+ });
2258
+ return proofBytes((await prover.prove("funds_read", w.input)).proof);
2259
+ },
2260
+ };
2210
2261
  }
2211
2262
  /**
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.
2263
+ * PRV-28 B+C: an offer is a plain `pool::transfer` whose first output is a Lock5 leaf under the round's field, with
2264
+ * fresh keys from a reserved note index (Erik's condition 2), the payload sealed to the request's offer key in slots
2265
+ * 0 and 2, and the recovery record sealed to this seed in slot 3 (condition 3). `unlock_s` is the first grid second
2266
+ * after the round's settle deadline (condition 4).
2214
2267
  */
2215
- async planOffer(loanId) {
2268
+ async lend(loanId) {
2216
2269
  const q = await this.readRequest(loanId, true);
2217
2270
  assertRequestTerm(q.termMs, this.config.closeStepMs ?? HOUR_MS);
2218
2271
  const L = q.pair[1];
2219
2272
  if (poolId(this.config, L) !== q.poolL)
2220
2273
  wrongCoinObject();
2221
- const rateBps = q.maxRateBps;
2222
- const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2223
- const { member, credential } = readState(this.statePath, this.stateKey);
2224
- const relayer = this.relayerAddress();
2225
- const relayerFee = this.coinFee(L);
2226
- const prover = this.prover();
2227
- const row = await (this.io.readLoan ?? notSetUp("missing config: no loan reader"))(q.loan);
2228
- const fee = await this.loanFee(L, row.json.fee_commit);
2229
- const { events, owned, seed } = await this.owned(L);
2230
- const inputs = pickInputs(owned, q.principal + relayerFee);
2231
- const tree = poolTree(orderedLeaves(events));
2232
- const ins = inputs.map((n) => ({
2233
- amount: n.value,
2234
- sk: n.sk,
2235
- blinding: n.blinding,
2236
- pathIndex: BigInt(n.index),
2237
- pathElements: tree.path(n.index),
2238
- }));
2239
- const spent = [ins[0], ins[1] ?? dummyInput()];
2240
- const n0 = noteNullifier(noteCommitment(spent[0].amount, notePk(spent[0].sk), spent[0].blinding), spent[0].sk, spent[0].pathIndex);
2274
+ if (!q.offerEncPub)
2275
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the request carries no offer key; nothing was sent");
2276
+ const seed = this.seed();
2241
2277
  await this.keys();
2242
- const offerIndex = this.reserve("notes");
2243
- const own = deriveNoteKey(seed, offerIndex);
2244
- const changeIndex = this.reserve("notes");
2245
- const change = deriveNoteKey(seed, changeIndex);
2246
- const enc = await treasuryPoint(poseidonHash([own.sk, own.blinding, 6n]) >> 2n);
2247
- const offer = {
2248
- rateBps,
2249
- salt: poseidonHash([own.sk, own.blinding, 5n]),
2250
- lenderPk: notePk(own.sk),
2251
- encX: enc.tx,
2252
- encY: enc.ty,
2253
- ns: poseidonHash([own.sk, own.blinding, 3n]),
2254
- b: poseidonHash([own.sk, own.blinding, 4n]),
2255
- amount: q.principal,
2278
+ const noteIndex = this.reserve("notes");
2279
+ const own = deriveNoteKey(seed, noteIndex);
2280
+ const keys = await offerKeys(own.sk, own.blinding);
2281
+ const unlockS = unlockAfter(q.settleByMs);
2282
+ const field = lockField(q.loanKey, q.round);
2283
+ const { lockPk } = lock5({ field, ...keys, amount: q.principal, unlockS });
2284
+ const payload = {
2285
+ ownerPk: keys.ownerPk,
2286
+ ns: keys.ns,
2287
+ aux: await packEncPoint(keys.encX, keys.encY),
2288
+ unlockS,
2256
2289
  };
2257
- const n0Le = Uint8Array.from(Buffer.from(n0.toString(16).padStart(64, "0"), "hex").reverse());
2258
- const sealed = await seal({
2259
- id: offerKeyId(q.loanKey, q.round, q.seq),
2260
- data: offerPlaintext(offer),
2261
- aad: n0Le,
2290
+ const recovery = { amount: q.principal, field, unlockS, index: BigInt(noteIndex) };
2291
+ const landed = await this.lockTransfer(L, q.principal, {
2292
+ pk: lockPk,
2293
+ blinding: keys.b,
2294
+ payload,
2295
+ recovery,
2296
+ counterpartyPub: q.offerEncPub,
2262
2297
  });
2263
- const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2264
- const changeValue = spent[0].amount + spent[1].amount - q.principal - relayerFee;
2265
- const encChange = bytesOf(sealOpening({ value: changeValue, blinding: change.blinding, index: changeIndex }, noteEncKey(seed).encPub));
2266
- const encFee = bytesOf(fillerEnc());
2267
- const record = {
2268
- noteIndex: offerIndex,
2298
+ const offer = {
2299
+ noteIndex,
2269
2300
  principal: q.principal,
2270
- rateBps,
2301
+ rateBps: q.maxRateBps,
2271
2302
  termMs: q.termMs,
2272
2303
  borrowerPk: q.borrowerPk,
2273
2304
  };
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])));
2276
- const witness = await loanOffer({
2277
- root: tree.root,
2278
- ins: spent,
2279
- request: { ...q, collNote: q.collNote },
2280
- loanKey: q.loanKey,
2281
- round: q.round,
2282
- offer,
2283
- change: { pk: notePk(change.sk), blinding: change.blinding },
2284
- relayerFee,
2285
- extHash,
2286
- fee,
2287
- eph: drawEph(),
2288
- });
2289
- if (witness.changeAmount !== changeValue)
2290
- throw new EsseyError("INVALID_ARGUMENT", "refused: the offer's fee lane is not free");
2291
- const passRoom = offerRoom(q.loanKey, q.round);
2292
- const pass = membership({
2293
- secrets: member,
2294
- credential: credential,
2295
- domain: DOMAIN_SPEND,
2296
- room: passRoom,
2297
- bind: keyId(n0),
2298
- });
2299
- const proved = async (circuit, input, publics) => ({
2300
- proof: (await prover.prove(circuit, input)).proof,
2301
- publicSignals: publics.map(String),
2302
- });
2303
- const { spend } = witness;
2304
- return {
2305
- record,
2306
- seq: q.seq,
2307
- body: {
2308
- pool: L,
2309
- loan: q.loan,
2310
- membership: await proved("membership", pass.input, pass.publics),
2311
- offer: await proved("loan_offer", witness.input, witness.publics),
2312
- tag: pass.publics[0],
2313
- expiryMs: credential.expiryMs,
2314
- passRoom,
2315
- root: spend.root,
2316
- nullifier0: spend.n0,
2317
- nullifier1: spend.n1,
2318
- lock: spend.note,
2319
- change: spend.change,
2320
- feeNote: spend.feeNote,
2321
- ephX: spend.ephX,
2322
- ephY: spend.ephY,
2323
- feeCt: spend.feeCt,
2324
- commit: witness.commit,
2325
- sealed,
2326
- memo,
2327
- encChange,
2328
- encFee,
2329
- },
2330
- };
2331
- }
2332
- /** `seal_policy::seal_approve_offer` for offer `seq`: the borrower's SEAL pass over `seal_offer` bound to the viewer. */
2333
- offerApprove(loan, loanKey, round, seq, pair) {
2334
- const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
2335
- const { member, credential } = readState(this.statePath, this.stateKey);
2336
- const room = keyId(loanKey);
2337
- const prover = this.prover();
2338
- return async (viewer) => {
2339
- const bind = `0x${Buffer.from(sealOfferBind(blake2b256, room, round, seq, viewer)).toString("hex")}`;
2340
- const pass = membership({
2341
- secrets: member,
2342
- credential: credential,
2343
- domain: DOMAIN_SENDER,
2344
- room,
2345
- bind,
2346
- });
2347
- const proved = await prover.prove("membership", pass.input);
2348
- return {
2349
- target: `${this.config.packages.loan}::seal_policy::seal_approve_offer`,
2350
- typeArguments: pair.map((c) => this.config.coins[c].type),
2351
- args: [
2352
- {
2353
- pure: "vector<u8>",
2354
- value: `0x${Buffer.from(offerKeyId(loanKey, round, seq)).toString("hex")}`,
2355
- },
2356
- { object: loan },
2357
- { pure: "u64", value: seq.toString() },
2358
- { object: passKey.id },
2359
- { pure: "u256", value: pass.publics[0].toString() },
2360
- { pure: "u64", value: credential.expiryMs.toString() },
2361
- { pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
2362
- { object: "0x6" },
2363
- ],
2364
- };
2365
- };
2366
- }
2367
- /**
2368
- * Offer `seq` of the current round, once closed, whose sealed plaintext does not open its commit (`offer::slash`):
2369
- * the borrower asks Seal for the offer key's derived keys under the same policy as its read, and the chain decrypts
2370
- * with them. An honest offer aborts 42_013, after the keys are public, so it is refused here before they are asked
2371
- * for. No penalty: the lock is reclaimed once the round resolves.
2372
- */
2373
- async slashOffer(loanId, seq) {
2374
- const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2375
- const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
2376
- const derive = this.io.sealDerivedKeys ?? notSetUp("missing config: no Seal key deriver");
2377
- const loan = address(loanId, "loan id");
2378
- const row = await read(loan);
2379
- if (!row)
2380
- unknownObject("no loan with this id");
2381
- const json = row.json;
2382
- const loanKey = BigInt(json.loan_key);
2383
- this.indexOfLoanKey(this.seed(), loanKey);
2384
- const round = BigInt(json.round);
2385
- const pair = this.pairOf(json.market_id);
2386
- const offers = row.round?.offers;
2387
- const offer = offers?.[Number(seq)];
2388
- if (!offer?.active)
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");
2392
- const approve = this.offerApprove(loan, loanKey, round, seq, pair);
2393
- const sealed = Uint8Array.from(Buffer.from(offer.sealed, "base64"));
2394
- const plain = await decrypt({ sealed, approve }).catch(() => undefined);
2395
- if (plain && offerOpens(plain, lockField(loanKey, round), BigInt(offer.commit), BigInt(offer.lock)))
2396
- throw new EsseyError("INVALID_ARGUMENT", "refused: the offer opens its commit and lock (offer::slash aborts 42_013)");
2397
- const derived = await derive({ id: offerKeyId(loanKey, round, seq), approve });
2398
- return this.freeLoan(slashLoan, { pool: pair[1], loan, round, seq, keys: this.pinnedKeys(derived) });
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");
2305
+ return { ...landed, offer, lock: { coin: L, noteIndex, amount: q.principal, unlockS } };
2306
+ }
2307
+ /** An offer or a bid: `spend` with the lock as out0, through the transfer path a payment takes (freeze §6.2). */
2308
+ lockTransfer(coin, amount, l) {
2309
+ const ownPub = noteEncKey(this.seed()).encPub;
2310
+ const hex = (b) => `0x${Buffer.from(b).toString("hex")}`;
2311
+ const encs = (encChange) => lockEncs({ ...l, changeEnc: hexBytes(encChange), ownPub }).map(hex);
2312
+ return this.spend(coin, { lock: { pk: l.pk, blinding: l.blinding, encs } }, (owned, rates, relayerFee) => ({
2313
+ value: amount,
2314
+ inputs: pickInputs(owned, withdrawCost(amount, rates, relayerFee)),
2315
+ }));
2427
2316
  }
2428
2317
  /**
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.
2318
+ * The borrower's offer scan (PRV-28 B+C, freeze §6.1): every lock of the loan pool sealed to this round's offer key
2319
+ * that rebuilds to its slot-0 leaf under the round's field at the principal, binds its enc point (ruling R5), unlocks
2320
+ * after the settle deadline (Erik's condition 4) and is unspent, with the tree a settle proves it in.
2431
2321
  */
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");
2322
+ async receivedOffers(q, keyIndex) {
2323
+ const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
2324
+ const events = await pools(q.pair[1]);
2325
+ const offers = await scanLocks({
2326
+ commitments: events.commitments,
2327
+ nullifiers: events.nullifiers.map((n) => BigInt(n)),
2328
+ recvSecret: offerRecvKey(this.seed(), keyIndex).secret,
2329
+ field: lockField(q.loanKey, q.round),
2330
+ open: offerOpen(q.principal),
2331
+ deadlineMs: q.settleByMs,
2332
+ });
2333
+ if (offers.length === 0)
2334
+ throw new EsseyError("INVALID_ARGUMENT", "refused: no usable offer reached this round; nothing was sent");
2335
+ const offer = offers[randomInt(offers.length)];
2336
+ const enc = (await unpackEncPoint(offer.aux));
2337
+ return { offer: { ...offer, encX: enc.x, encY: enc.y }, tree: poolTree(orderedLeaves(events)) };
2451
2338
  }
2452
2339
  /** Threshold many derived keys, each with its server's slot in `config.seal.servers` (`seal_servers::public_keys` order). */
2453
2340
  pinnedKeys(derived) {
@@ -2466,12 +2353,12 @@ export class Essey {
2466
2353
  */
2467
2354
  async ctFault(loanId, via) {
2468
2355
  const derive = this.io.sealDerivedKeys ?? notSetUp("missing config: no Seal key deriver");
2469
- const { loan, json, drained } = await this.activeLoan(loanId);
2356
+ const { loan, json } = await this.activeLoan(loanId);
2470
2357
  const retained = json.coll?.borrower_ct;
2471
2358
  if (!retained)
2472
2359
  throw new EsseyError("INVALID_ARGUMENT", "the loan holds no borrower ciphertext");
2473
2360
  const id = keeperKeyId(BigInt(json.loan_key), BigInt(retained.version));
2474
- const approval = await this.keeperApproval(json, loan, id, via, drained);
2361
+ const approval = await this.keeperApproval(json, loan, id, via);
2475
2362
  if (await this.retainedOpens(json, loan, approval))
2476
2363
  throw new EsseyError("INVALID_ARGUMENT", "refused: the ciphertext opens its lock and terms (prove_ct_fault aborts 43_212)");
2477
2364
  const derived = await derive({ id, ...approval });
@@ -2500,7 +2387,7 @@ export class Essey {
2500
2387
  decrypt: (r) => decrypt({ sealed: r.sealed, ...approval }),
2501
2388
  });
2502
2389
  rollTo(openingOf(payload), collNoteAt, nonce);
2503
- return termsCommit(payload.terms ?? NO_TERMS, payload.borrowerPk) === BigInt(json.terms_commit);
2390
+ return viewCommit(payload.terms ?? NO_VIEW, payload.borrowerPk) === BigInt(json.terms_commit);
2504
2391
  }
2505
2392
  catch {
2506
2393
  return false;
@@ -2512,26 +2399,16 @@ export class Essey {
2512
2399
  const row = await read(loan);
2513
2400
  if (!row)
2514
2401
  unknownObject("no loan with this id");
2515
- if (this.retired(row))
2516
- this.refuseRetired(row);
2402
+ this.refuseRetired(row);
2517
2403
  const json = row.json;
2518
2404
  if (Number(json.state) !== 2 && Number(json.state) !== 8)
2519
2405
  throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
2520
- const drained = this.drainedLoan(row);
2521
- return drained ? { loan, json, drained } : { loan, json };
2406
+ return { loan, json };
2522
2407
  }
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) {
2408
+ /** Either policy entry for key id `id`; the badge one carries the signer its Seal session must be made by. */
2409
+ async keeperApproval(json, loan, id, via = "pass") {
2528
2410
  const market = address(json.market_id, "market");
2529
2411
  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
- }
2535
2412
  if (via === "pass")
2536
2413
  return { approve: await this.keeperApprove(loan, market, id, pair) };
2537
2414
  const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
@@ -2633,14 +2510,8 @@ export class Essey {
2633
2510
  });
2634
2511
  }
2635
2512
  /** `keeper::seal_approve_keeper_proof`: a KEEPER pass for the deployment's keeper registry, bound to the viewer. */
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;
2513
+ async keeperApprove(loan, market, id, pair) {
2514
+ const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
2644
2515
  const { member, credential } = readState(this.statePath, this.stateKey);
2645
2516
  if (!member || credential?.role !== "keeper")
2646
2517
  notSetUp("no keeper credential");
@@ -2659,7 +2530,7 @@ export class Essey {
2659
2530
  });
2660
2531
  const proved = await prover.prove("membership", pass.input);
2661
2532
  return {
2662
- target: `${pkg}::keeper::seal_approve_keeper_proof${standin ? "_standin" : ""}`,
2533
+ target: `${this.config.packages.loan}::keeper::seal_approve_keeper_proof${standin ? "_standin" : ""}`,
2663
2534
  typeArguments: pair.map((c) => this.config.coins[c].type),
2664
2535
  args: [
2665
2536
  { pure: "vector<u8>", value: `0x${Buffer.from(id).toString("hex")}` },
@@ -2702,39 +2573,62 @@ export class Essey {
2702
2573
  }
2703
2574
  return notSetUp("no Pyth market in the deployment");
2704
2575
  }
2705
- /** The borrower's `loan_settle` on round 0: the round's pick wins, keeper ciphertext v1 carries its terms. */
2576
+ /** The market's price inputs a settle proves its LTV line at (PRV-03 B): `refi::settle_refi`'s rows. */
2577
+ async settlePrice(json, pair) {
2578
+ const readReading = this.io.readReading ?? notSetUp("missing config: no reading reader");
2579
+ const market = address(json.market_id, "market");
2580
+ const r = await readReading(market);
2581
+ const pClaim = r.spot < r.ema ? r.spot : r.ema;
2582
+ const rates = await this.rates(market);
2583
+ const ltvBps = BigInt(json.ltv_bps) < rates.current.ltvBps ? BigInt(json.ltv_bps) : rates.current.ltvBps;
2584
+ const price = {
2585
+ pClaim,
2586
+ expo: r.expo,
2587
+ cDec: BigInt(this.config.coins[pair[0]].decimals),
2588
+ lDec: BigInt(this.config.coins[pair[1]].decimals),
2589
+ ltvBps,
2590
+ };
2591
+ return { market, reading: r, price };
2592
+ }
2593
+ /** The borrower's `loan_settle` on round 0: one offer from its scan, keeper ciphertext v1 carries its terms. */
2706
2594
  async planSettle(id, collAmt) {
2707
2595
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2708
2596
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2709
- const q = await this.readRequest(id);
2597
+ const q = await this.ownRequest(id);
2710
2598
  // settle.move:131-135 refuses a settle until now_s * 1000 reaches close_ms.
2711
2599
  if (BigInt(Math.floor((this.io.now ?? Date.now)() / 1000)) * 1000n < q.closeMs)
2712
2600
  throw new EsseyError("INVALID_ARGUMENT", "refused: the offer window is still open");
2601
+ const update = this.io.priceUpdate ?? notSetUp("missing config: no price update source");
2713
2602
  const seed = this.seed();
2714
- const first = (await read(q.loan)).json;
2715
- this.ownOpening(seed, first, q.borrowerPk, collAmt);
2716
- const slots = await this.pickedSlots(q);
2717
2603
  const json = (await read(q.loan)).json;
2718
2604
  const { opening, index: keyIndex } = this.ownOpening(seed, json, q.borrowerPk, collAmt);
2719
- const { member, credential } = readState(this.statePath, this.stateKey);
2720
2605
  const L = q.pair[1];
2721
- const prover = this.prover();
2722
2606
  const fee = await this.loanFee(L, json.fee_commit);
2607
+ const { offer, tree } = await this.receivedOffers(q, keyIndex);
2608
+ const { market, reading, price } = await this.settlePrice(json, q.pair);
2609
+ const { member, credential } = readState(this.statePath, this.stateKey);
2610
+ const prover = this.prover();
2723
2611
  await this.keys();
2724
2612
  const noteIndex = this.reserve("notes");
2725
2613
  const mine = deriveNoteKey(seed, noteIndex);
2614
+ const pads = padPair(seed, () => this.reserve("notes"));
2615
+ const dummySeed = drawDummySeed();
2726
2616
  const nowS = settleNowS((this.io.now ?? Date.now)(), q.closeMs);
2727
2617
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2728
2618
  const plan = (extHash) => loanSettle({
2729
- slots,
2730
2619
  request: { ...q, collAmt: opening.amount, collBlind: opening.blinding },
2731
2620
  loanKey: q.loanKey,
2621
+ offer: { ...offer, lenderPk: offer.ownerPk, b: offerBlind(offer.ns, offer.encX, offer.encY) },
2622
+ lock: { root: tree.root, index: offer.index, path: tree.path(Number(offer.index)) },
2732
2623
  borrowerNote: { pk: notePk(mine.sk), blinding: mine.blinding },
2624
+ pads: [pads[0], pads[1]],
2625
+ dummySeed,
2733
2626
  e: drawEph(),
2734
2627
  nowS,
2735
2628
  extHash,
2736
2629
  fee,
2737
2630
  eph: drawEph(),
2631
+ price,
2738
2632
  });
2739
2633
  const draft = await plan(0n);
2740
2634
  const keeperCt = await seal({
@@ -2750,8 +2644,12 @@ export class Essey {
2750
2644
  }),
2751
2645
  });
2752
2646
  const encPrincipal = bytesOf(sealOpening({ value: draft.principalValue, blinding: mine.blinding, index: noteIndex }, noteEncKey(seed).encPub));
2753
- const encFee = bytesOf(fillerEnc());
2754
- const encs = [encPrincipal, encFee];
2647
+ const encs = [
2648
+ encPrincipal,
2649
+ bytesOf(fillerEnc()),
2650
+ bytesOf(fillerEnc()),
2651
+ bytesOf(fillerEnc()),
2652
+ ];
2755
2653
  const ext = loanExt(LOAN_SETTLE_KIND, q.loan, q.poolL, 0n, NO_ADDRESS, encs, blake2b256(keeperCt));
2756
2654
  const w = await plan(ext);
2757
2655
  if (w.termsCommit !== draft.termsCommit)
@@ -2763,22 +2661,32 @@ export class Essey {
2763
2661
  borrowerPk: q.borrowerPk,
2764
2662
  terms: w.terms,
2765
2663
  });
2766
- const args = settleArgs({
2767
- loan: q.loan,
2768
- poolL: q.poolL,
2769
- proof: proofBytes(settleProof.proof),
2664
+ const moved = {
2665
+ root: tree.root,
2666
+ nLock: w.nLock,
2667
+ nDummy: w.nDummy,
2770
2668
  termsCommit: w.termsCommit,
2771
2669
  principalNote: w.principalNote,
2772
2670
  feeNote: w.feeNote,
2773
- winNull: w.winNull,
2671
+ pad0: w.pads[0],
2672
+ pad1: w.pads[1],
2774
2673
  d: w.d,
2775
2674
  ephX: w.ephX,
2776
2675
  ephY: w.ephY,
2777
2676
  feeCt: w.feeCt,
2677
+ pClaim: price.pClaim,
2778
2678
  keeperCt,
2779
2679
  encs,
2780
2680
  nowS,
2781
2681
  memo,
2682
+ };
2683
+ const args = settleArgs({
2684
+ ...moved,
2685
+ loan: q.loan,
2686
+ poolL: q.poolL,
2687
+ market,
2688
+ reading: readingBytes(reading),
2689
+ proof: proofBytes(settleProof.proof),
2782
2690
  });
2783
2691
  const n0 = actionHash(blake2b256, q.loanKey, BigInt(json.nonce), "settle", args);
2784
2692
  const room = keyId(q.loanKey);
@@ -2796,8 +2704,10 @@ export class Essey {
2796
2704
  borrowerPk: q.borrowerPk,
2797
2705
  collAmt: opening.amount,
2798
2706
  body: {
2707
+ ...moved,
2799
2708
  pool: L,
2800
2709
  loan: q.loan,
2710
+ market,
2801
2711
  settle: { proof: settleProof.proof, publicSignals: w.publics.map(String) },
2802
2712
  pass: {
2803
2713
  proved: { proof: passProved.proof, publicSignals: pass.publics.map(String) },
@@ -2805,19 +2715,7 @@ export class Essey {
2805
2715
  expiryMs: credential.expiryMs,
2806
2716
  n0,
2807
2717
  },
2808
- termsCommit: w.termsCommit,
2809
- principalNote: w.principalNote,
2810
- feeNote: w.feeNote,
2811
- winNull: w.winNull,
2812
- d: w.d,
2813
- ephX: w.ephX,
2814
- ephY: w.ephY,
2815
- feeCt: w.feeCt,
2816
- keeperCt,
2817
- encPrincipal,
2818
- encFee,
2819
- nowS,
2820
- memo,
2718
+ priceUpdate: await update(market),
2821
2719
  },
2822
2720
  };
2823
2721
  }
@@ -2831,6 +2729,7 @@ export class Essey {
2831
2729
  const row = await read(loan);
2832
2730
  if (!row)
2833
2731
  unknownObject("no loan with this id");
2732
+ this.refuseRetiredLoanProof(row);
2834
2733
  const json = row.json;
2835
2734
  const pair = this.pairOf(json.market_id);
2836
2735
  const L = pair[1];
@@ -2845,7 +2744,7 @@ export class Essey {
2845
2744
  const fee = await this.loanFee(L, json.fee_commit);
2846
2745
  const { events, owned, seed } = await this.owned(L);
2847
2746
  const tree = poolTree(orderedLeaves(events));
2848
- const inputs = pickInputs(owned, terms.owed + relayerFee + feeOf({ base: terms.owed, bps: fee.bps, min: fee.min, max: fee.max }).fee);
2747
+ const inputs = pickInputs(owned, terms.owed + relayerFee + flatFeeOf({ base: terms.owed, ...fee, on: true }).fee);
2849
2748
  const ins = inputs.map((n) => ({
2850
2749
  amount: n.value,
2851
2750
  sk: n.sk,
@@ -2856,7 +2755,7 @@ export class Essey {
2856
2755
  await this.keys();
2857
2756
  const changeIndex = this.reserve("notes");
2858
2757
  const change = deriveNoteKey(seed, changeIndex);
2859
- const pad = { pk: notePk(drawSecret()), blinding: drawSecret() };
2758
+ const pad = padNote(seed, this.reserve("notes"));
2860
2759
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2861
2760
  const spent = [ins[0], ins[1] ?? dummyInput()];
2862
2761
  const base = {
@@ -2901,39 +2800,70 @@ export class Essey {
2901
2800
  /**
2902
2801
  * The repaid note is `Poseidon(owed, lenderPk, H(DOM_LBLIND, S.x))` with `S = encSk · repay_eph`
2903
2802
  * (`loan_repay.circom`), and a refi payoff the same over a `payoff_eph` pair (`loan_refi.circom`); either ciphertext
2904
- * is filler, so the scan never sees it; `owned` finds it through the state file's `held` list.
2803
+ * is filler, so the scan never sees it; `owned` finds it through the state file's `held` list. Erik's PRV-28
2804
+ * condition 3: the seed alone suffices. The slot-3 record gives the principal and the lock's field, the field names
2805
+ * the loan and round, and `owed` is found among the posted terms a request can carry (rate 0..10000 bps, a term
2806
+ * on `TERM_STEPS`); an OfferRecord's rate and term only skip that search.
2905
2807
  */
2906
- async collect(loanId, offer, sweep) {
2907
- const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2808
+ async collect(lock, offer, sweep) {
2908
2809
  const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
2909
- const loan = address(loanId, "loan id");
2910
- const row = await read(loan);
2911
- if (!row)
2912
- unknownObject("no loan with this id");
2913
- const json = row.json;
2810
+ const seed = this.seed();
2811
+ const events = await pools(lock.coin);
2812
+ const rec = scanRecoveries(events.commitments, noteEncKey(seed).encKey).find((r) => r.index === BigInt(lock.noteIndex));
2813
+ if (!rec)
2814
+ unknownObject("no lock of this record is in the pool");
2815
+ const json = await this.loanOfLock(rec.field);
2914
2816
  const flat = (v) => (v ?? []).flat(2).map((x) => BigInt(x));
2915
- // Only `loan::set_repaid` writes repay_eph (loan.move:483-486), and RELEASE then moves the loan to CLOSED.
2817
+ // Only `loan::set_repaid` writes repay_eph, and a refi settle pushes a payoff_eph pair (lane L loan.move).
2916
2818
  const ephs = [flat(json.repay_eph), flat(json.payoff_eph)].flatMap((xs) => Array.from({ length: Math.floor(xs.length / 2) }, (_, i) => [xs[2 * i], xs[2 * i + 1]]));
2917
- const L = this.pairOf(String(json.market_id))[1];
2918
- const seed = this.seed();
2919
- const own = deriveNoteKey(seed, offer.noteIndex);
2920
- const owed = interest(offer.principal, offer.rateBps, offer.termMs).owed;
2921
- const events = await pools(L);
2922
- let blinding = 0n;
2923
- let commitment = 0n;
2924
- let leaf;
2819
+ const own = deriveNoteKey(seed, lock.noteIndex);
2820
+ const pk = notePk(own.sk);
2821
+ const leaves = new Map(events.commitments.map((c) => [BigInt(c.commitment), c]));
2822
+ const owedTried = offer
2823
+ ? [interest(rec.amount, offer.rateBps, offer.termMs).owed]
2824
+ : this.postedOwed(rec.amount);
2925
2825
  for (const [ex, ey] of ephs) {
2926
2826
  const k = await ecdhBlind(ex, ey, poseidonHash([own.sk, own.blinding, 6n]) >> 2n);
2927
- blinding = poseidonHash([DOM_LBLIND, k.sx]);
2928
- commitment = noteCommitment(owed, notePk(own.sk), blinding);
2929
- leaf = events.commitments.find((c) => BigInt(c.commitment) === commitment);
2930
- if (leaf)
2931
- break;
2827
+ const blinding = poseidonHash([DOM_LBLIND, k.sx]);
2828
+ for (const owed of owedTried) {
2829
+ const leaf = leaves.get(noteCommitment(owed, pk, blinding));
2830
+ if (!leaf)
2831
+ continue;
2832
+ const note = { value: owed, sk: own.sk, blinding, index: Number(leaf.index) };
2833
+ return this.take(lock.coin, events, { ...note, key: lock.noteIndex }, sweep);
2834
+ }
2835
+ }
2836
+ return unknownObject("no repaid or refi payoff note of this lock is in the pool: it lost, or the loan is not repaid yet");
2837
+ }
2838
+ /** Every `owed` a request for `principal` can post: rate 0..10000 bps by `TERM_STEPS` terms, lowest rate first. */
2839
+ *postedOwed(principal) {
2840
+ const step = BigInt(this.config.closeStepMs ?? HOUR_MS);
2841
+ const seen = new Set();
2842
+ for (let rate = 0n; rate <= 10000n; rate++)
2843
+ for (const steps of TERM_STEPS) {
2844
+ const owed = interest(principal, rate, BigInt(steps) * step).owed;
2845
+ if (!seen.has(owed))
2846
+ yield (seen.add(owed), owed);
2847
+ }
2848
+ }
2849
+ /** The listed loan one of whose rounds has lock field `field` (`loan::lock_field`), as `readLoan` serves it. */
2850
+ async loanOfLock(field) {
2851
+ const readLoans = this.io.readLoans ?? notSetUp("missing config: no loan reader");
2852
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2853
+ let cursor = null;
2854
+ for (let pages = 1;; pages++) {
2855
+ const page = await readLoans(cursor);
2856
+ for (const row of page.loans) {
2857
+ const j = row.json;
2858
+ const key = BigInt(j.loan_key);
2859
+ for (let r = 0n; r <= BigInt(j.round ?? 0); r++)
2860
+ if (lockField(key, r) === field)
2861
+ return ((await read(address(row.id, "loan id")))?.json ?? j);
2862
+ }
2863
+ cursor = afterPage(page.next, pages);
2864
+ if (cursor === null)
2865
+ return unknownObject("no listed loan has a round this lock was offered to");
2932
2866
  }
2933
- if (!leaf)
2934
- unknownObject("no repaid or refi payoff note of this offer is in the pool: another offer won, or the record is not this loan's");
2935
- const note = { value: owed, sk: own.sk, blinding, index: Number(leaf.index) };
2936
- return this.take(L, events, { ...note, key: offer.noteIndex }, sweep);
2937
2867
  }
2938
2868
  /** Refuses a spent note. `sweep` moves it to the receive address now; otherwise it is held for the next spend. */
2939
2869
  async take(coin, events, note, sweep) {
@@ -3010,7 +2940,7 @@ export class Essey {
3010
2940
  }
3011
2941
  /**
3012
2942
  * A seizure leaves the lock's nonce one past the one it folded and `coll_note` as it was. `out` 0 pays
3013
- * `seize - pf - kf` to the lender, 1 pays `avail - seize` to the borrower, each at `outputBlind(blind, out, nonce)`.
2943
+ * `seize - kf` to the lender (seizures pay no protocol fee), 1 pays `avail - seize` to the borrower, each at `outputBlind(blind, out, nonce)`.
3014
2944
  * The split is recomputed from the `p_spot` the seizing call claimed (`io.readSeizure`).
3015
2945
  */
3016
2946
  async collectFromSeizure(loanId, out, open, sweep) {
@@ -3047,7 +2977,6 @@ export class Essey {
3047
2977
  pSpot: fault ? 1n : pSpot,
3048
2978
  expo: (await readPrice(String(json.market_id))).expo,
3049
2979
  risk: loanRisk(rates, decimals, { liquidate: MODE.LIQUIDATE, default: MODE.DEFAULT, fault: MODE.FAULT }[mode]),
3050
- fee: await this.loanFee(C, json.coll_fee_commit),
3051
2980
  fault,
3052
2981
  });
3053
2982
  const value = out === 0 ? split.toLender : split.surplus;
@@ -3086,6 +3015,7 @@ export class Essey {
3086
3015
  const row = await read(loan);
3087
3016
  if (!row)
3088
3017
  unknownObject("no loan with this id");
3018
+ this.refuseRetiredLoanProof(row);
3089
3019
  const json = row.json;
3090
3020
  if (Number(json.state) !== 3)
3091
3021
  throw new EsseyError("INVALID_ARGUMENT", "the loan is not repaid");
@@ -3113,6 +3043,8 @@ export class Essey {
3113
3043
  const encs = [
3114
3044
  bytesOf(sealOpening({ value: collAmt, blinding: outputBlind(opening.blinding, 0, nonce), index }, noteEncKey(seed).encPub)),
3115
3045
  bytesOf(fillerEnc()),
3046
+ bytesOf(fillerEnc()),
3047
+ bytesOf(fillerEnc()),
3116
3048
  ];
3117
3049
  const h = await health({
3118
3050
  mode: MODE.RELEASE,
@@ -3123,6 +3055,8 @@ export class Essey {
3123
3055
  extHash: releaseExt({ loan, poolC, market }, encs),
3124
3056
  fee,
3125
3057
  eph: drawEph(),
3058
+ pads: padPair(seed, () => this.reserve("notes")),
3059
+ dummySeeds: [drawDummySeed(), drawDummySeed()],
3126
3060
  terms,
3127
3061
  });
3128
3062
  const proved = await this.prover().prove("health", h.input);
@@ -3152,6 +3086,7 @@ export class Essey {
3152
3086
  const row = await read(loan);
3153
3087
  if (!row)
3154
3088
  unknownObject("no loan with this id");
3089
+ this.refuseRetiredLoanProof(row);
3155
3090
  const json = row.json;
3156
3091
  const loanKey = BigInt(json.loan_key);
3157
3092
  this.indexOfLoanKey(this.seed(), loanKey);
@@ -3199,8 +3134,9 @@ export class Essey {
3199
3134
  };
3200
3135
  }
3201
3136
  /**
3202
- * `refi::open_refi`: the request of round r+1 over the lock as it stands, sealed under the loan's request key. The salt
3203
- * derives from the lock's note index and the round, so the seed alone reopens it.
3137
+ * `refi::open_refi`: the request of round r+1 over the lock as it stands, sealed under the loan's request key, and
3138
+ * its request memo for round r+1 under this seed's memo key. The salt derives from the lock's note index and the
3139
+ * round, so the seed alone reopens it.
3204
3140
  */
3205
3141
  async openRefi(p) {
3206
3142
  assertLoanGrid(p, this.config.closeStepMs ?? HOUR_MS);
@@ -3228,6 +3164,8 @@ export class Essey {
3228
3164
  salt: poseidonHash([own.sk, own.blinding, 2n, round]),
3229
3165
  };
3230
3166
  const reqCommit = requestCommit(request, p.borrowerPk, collNote(opening));
3167
+ const posted = { principal: request.principal, maxRateBps: request.maxRateBps, termMs: request.termMs };
3168
+ const memo = sealMemo(memoKey(seed), { kind: MEMO_KIND.request, key: opening.loanKey, round }, requestMemoBody({ keyIndex: index, collAmt: opening.amount, borrowerPk: p.borrowerPk, ...posted }));
3231
3169
  const send = async () => {
3232
3170
  const closeMs = await this.loanClose(p.offerWindowMs);
3233
3171
  const reqSealed = await seal({
@@ -3238,62 +3176,54 @@ export class Essey {
3238
3176
  closeMs,
3239
3177
  market,
3240
3178
  coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
3179
+ offerEncPub: offerRecvKey(seed, index).pub,
3241
3180
  }),
3242
3181
  });
3243
- const args = openRefiArgs({ loan, poolL, reqCommit, reqSealed, closeMs });
3182
+ const args = openRefiArgs({ loan, poolL, reqCommit, reqSealed, memo, closeMs });
3244
3183
  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 };
3184
+ const body = { pool: L, loan, pass, reqCommit, reqSealed, memo, closeMs };
3185
+ return { ...(await this.freeLoan(refinanceLoan, body)), round, closeMs, request: posted };
3247
3186
  };
3248
3187
  return send().catch((err) => (lateClose(err) ? send() : Promise.reject(err)));
3249
3188
  }
3250
3189
  /**
3251
- * `refi::settle_refi`: the round's offers opened as `planSettle` opens them, the request read back through Seal, the
3190
+ * `refi::settle_refi`: the round's offers found as `planSettle` finds them, the borrower's own refi request, the
3252
3191
  * payoff to the old lender's enc key, and a pass bound to the exact reading the market's oracle builds.
3253
3192
  */
3254
3193
  async settleRefiOwn(p) {
3255
3194
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
3256
3195
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
3257
- const readReading = this.io.readReading ?? notSetUp("missing config: no reading reader");
3258
3196
  const update = this.io.priceUpdate ?? notSetUp("missing config: no price update source");
3259
- const q = await this.readRequest(p.loan);
3197
+ const q = await this.ownRequest(p.loan, p.request);
3260
3198
  if (BigInt((this.io.now ?? Date.now)()) < q.closeMs)
3261
3199
  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))
3264
- throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
3265
- const slots = await this.pickedSlots(q);
3266
3200
  const json = (await read(q.loan)).json;
3267
- const [C, L] = q.pair;
3268
- const market = address(json.market_id, "market");
3201
+ if (termsCommit(p.terms, p.borrowerPk) !== BigInt(json.terms_commit))
3202
+ throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
3203
+ const L = q.pair[1];
3269
3204
  const seed = this.seed();
3270
3205
  const { opening, index: keyIndex } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
3271
- const r = await readReading(market);
3272
- const pClaim = r.spot < r.ema ? r.spot : r.ema;
3273
- const rates = await this.rates(market);
3274
- const ltvBps = BigInt(json.ltv_bps) < rates.current.ltvBps ? BigInt(json.ltv_bps) : rates.current.ltvBps;
3275
3206
  const fee = await this.loanFee(L, json.fee_commit);
3207
+ const { offer, tree } = await this.receivedOffers(q, keyIndex);
3208
+ const { market, reading: r, price } = await this.settlePrice(json, q.pair);
3276
3209
  await this.keys();
3277
3210
  const noteIndex = this.reserve("notes");
3278
3211
  const mine = deriveNoteKey(seed, noteIndex);
3279
- const padKey = deriveNoteKey(seed, this.reserve("notes"));
3212
+ const pad = padNote(seed, this.reserve("notes"));
3213
+ const dummySeed = drawDummySeed();
3280
3214
  const nowS = settleNowS((this.io.now ?? Date.now)(), q.closeMs);
3281
3215
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
3282
3216
  const plan = (extHash) => loanRefi({
3283
- slots,
3284
3217
  round: q.round,
3285
3218
  request: { ...q, collAmt: opening.amount, collBlind: opening.blinding },
3286
3219
  old: p.terms,
3287
- price: {
3288
- pClaim,
3289
- expo: r.expo,
3290
- cDec: BigInt(this.config.coins[C].decimals),
3291
- lDec: BigInt(this.config.coins[L].decimals),
3292
- ltvBps,
3293
- },
3220
+ price,
3294
3221
  loanKey: q.loanKey,
3222
+ offer: { ...offer, lenderPk: offer.ownerPk, b: offerBlind(offer.ns, offer.encX, offer.encY) },
3223
+ lock: { root: tree.root, index: offer.index, path: tree.path(Number(offer.index)) },
3295
3224
  borrowerNote: { pk: notePk(mine.sk), blinding: mine.blinding },
3296
- pad: { pk: notePk(padKey.sk), blinding: padKey.blinding },
3225
+ pad,
3226
+ dummySeed,
3297
3227
  e: drawEph(),
3298
3228
  eP: drawEph(),
3299
3229
  nowS,
@@ -3318,9 +3248,10 @@ export class Essey {
3318
3248
  const encs = [
3319
3249
  bytesOf(sealOpening({ value: draft.borrowerValue, blinding: mine.blinding, index: noteIndex }, noteEncKey(seed).encPub)),
3320
3250
  bytesOf(fillerEnc()),
3251
+ bytesOf(fillerEnc()),
3252
+ bytesOf(fillerEnc()),
3321
3253
  ];
3322
- const encsP = [bytesOf(fillerEnc()), bytesOf(fillerEnc())];
3323
- const ext = loanExt(LOAN_REFI_KIND, q.loan, q.poolL, q.round, NO_ADDRESS, [...encs, ...encsP], blake2b256(keeperCt));
3254
+ const ext = loanExt(LOAN_REFI_KIND, q.loan, q.poolL, q.round, NO_ADDRESS, encs, blake2b256(keeperCt));
3324
3255
  const w = await plan(ext);
3325
3256
  if (w.termsCommit !== draft.termsCommit)
3326
3257
  throw new EsseyError("INVALID_ARGUMENT", "refused: the terms moved between drafts");
@@ -3331,16 +3262,13 @@ export class Essey {
3331
3262
  borrowerPk: p.borrowerPk,
3332
3263
  terms: w.terms,
3333
3264
  });
3334
- const args = settleRefiArgs({
3335
- loan: q.loan,
3336
- poolL: q.poolL,
3337
- market,
3338
- reading: readingBytes(r),
3339
- proof: proofBytes(refiProof.proof),
3265
+ const moved = {
3266
+ root: tree.root,
3267
+ nLock: w.nLock,
3268
+ nDummy: w.nDummy,
3340
3269
  termsCommit: w.termsCommit,
3341
3270
  borrowerNote: w.borrowerNote,
3342
3271
  feeNote: w.feeNote,
3343
- winNull: w.winNull,
3344
3272
  d: w.d,
3345
3273
  ephX: w.ephX,
3346
3274
  ephY: w.ephY,
@@ -3348,37 +3276,28 @@ export class Essey {
3348
3276
  payoffNote: w.payoffNote,
3349
3277
  pad: w.pad,
3350
3278
  ephP: w.ephP,
3351
- pClaim,
3279
+ pClaim: price.pClaim,
3352
3280
  keeperCt,
3353
3281
  encs,
3354
- encsP,
3355
3282
  nowS,
3356
3283
  memo,
3284
+ };
3285
+ const args = settleRefiArgs({
3286
+ ...moved,
3287
+ loan: q.loan,
3288
+ poolL: q.poolL,
3289
+ market,
3290
+ reading: readingBytes(r),
3291
+ proof: proofBytes(refiProof.proof),
3357
3292
  });
3358
3293
  const pass = await this.borrowerPass(json, "settle_refi", args);
3359
3294
  const landed = await this.freeLoan(settleRefiLoan, {
3295
+ ...moved,
3360
3296
  pool: L,
3361
3297
  loan: q.loan,
3362
3298
  market,
3363
3299
  pass,
3364
3300
  refi: { proof: refiProof.proof, publicSignals: w.publics.map(String) },
3365
- termsCommit: w.termsCommit,
3366
- borrowerNote: w.borrowerNote,
3367
- feeNote: w.feeNote,
3368
- winNull: w.winNull,
3369
- d: w.d,
3370
- ephX: w.ephX,
3371
- ephY: w.ephY,
3372
- feeCt: w.feeCt,
3373
- payoffNote: w.payoffNote,
3374
- pad: w.pad,
3375
- ephP: w.ephP,
3376
- pClaim,
3377
- keeperCt,
3378
- encs,
3379
- encsP,
3380
- nowS,
3381
- memo,
3382
3301
  priceUpdate: await update(market),
3383
3302
  });
3384
3303
  return { ...landed, rateBps: w.terms.rateBps, terms: w.terms };
@@ -3389,6 +3308,7 @@ export class Essey {
3389
3308
  const row = await read(loan);
3390
3309
  if (!row)
3391
3310
  unknownObject("no loan with this id");
3311
+ this.refuseRetiredLoanProof(row);
3392
3312
  const json = row.json;
3393
3313
  this.indexOfLoanKey(this.seed(), BigInt(json.loan_key));
3394
3314
  const poolL = address(json.pool_l, "pool_l");
@@ -3402,6 +3322,7 @@ export class Essey {
3402
3322
  const row = await read(loan);
3403
3323
  if (!row)
3404
3324
  unknownObject("no loan with this id");
3325
+ this.refuseRetiredLoanProof(row);
3405
3326
  const json = row.json;
3406
3327
  const loanKey = BigInt(json.loan_key);
3407
3328
  const C = this.pairOf(json.market_id)[0];
@@ -3414,6 +3335,8 @@ export class Essey {
3414
3335
  await this.keys();
3415
3336
  const outIndex = this.reserve("notes");
3416
3337
  const out = deriveNoteKey(seed, outIndex);
3338
+ const pads = padPair(seed, () => this.reserve("notes"));
3339
+ const dummySeed = drawDummySeed();
3417
3340
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
3418
3341
  const plan = (encs) => reclaimColl({
3419
3342
  loanKey,
@@ -3421,15 +3344,19 @@ export class Essey {
3421
3344
  borrowerSk: own.sk,
3422
3345
  collBlind: own.blinding,
3423
3346
  out: { pk: notePk(out.sk), blinding: out.blinding },
3347
+ pads: [pads[0], pads[1]],
3348
+ dummySeed,
3424
3349
  encs,
3425
3350
  fee,
3426
3351
  eph,
3427
3352
  });
3428
3353
  const eph = drawEph();
3429
- const draft = await plan([new Uint8Array(128), new Uint8Array(128)]);
3354
+ const draft = await plan([]);
3430
3355
  const encs = [
3431
3356
  bytesOf(sealOpening({ value: draft.outAmt, blinding: out.blinding, index: outIndex }, noteEncKey(seed).encPub)),
3432
3357
  bytesOf(fillerEnc()),
3358
+ bytesOf(fillerEnc()),
3359
+ bytesOf(fillerEnc()),
3433
3360
  ];
3434
3361
  const w = await plan(encs);
3435
3362
  const proved = await this.prover().prove("reclaim_coll", w.input);
@@ -3438,13 +3365,15 @@ export class Essey {
3438
3365
  loan,
3439
3366
  proved: { proof: proved.proof, publicSignals: w.publics.map(String) },
3440
3367
  nullifier: w.n,
3368
+ nDummy: w.nDummy,
3441
3369
  outNote: w.outNote,
3442
3370
  feeNote: w.feeNote,
3371
+ pad0: w.pad0,
3372
+ pad1: w.pad1,
3443
3373
  ephX: w.ephX,
3444
3374
  ephY: w.ephY,
3445
3375
  feeCt: w.feeCt,
3446
- encOut: encs[0],
3447
- encFee: encs[1],
3376
+ encs,
3448
3377
  });
3449
3378
  }
3450
3379
  /**
@@ -3497,7 +3426,7 @@ export class Essey {
3497
3426
  const readLoans = this.io.readLoans ?? notSetUp("missing config: no loan reader");
3498
3427
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
3499
3428
  const key = memoKey(this.seed());
3500
- const out = { loans: [], offers: [] };
3429
+ const out = { loans: [], locks: [] };
3501
3430
  const bytes = (v) => typeof v === "string" ? Uint8Array.from(Buffer.from(v, "base64")) : new Uint8Array();
3502
3431
  let cursor = null;
3503
3432
  let pages = 0;
@@ -3517,87 +3446,108 @@ export class Essey {
3517
3446
  if (r === 0n)
3518
3447
  record = openRequestMemo(key, loanKey, bytes(round.req_memo)) ?? record;
3519
3448
  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
3449
  }
3526
3450
  if (record)
3527
3451
  out.loans.push({ loan, record });
3528
3452
  }
3529
3453
  cursor = afterPage(page.next, pages);
3530
3454
  if (cursor === null)
3531
- return out;
3455
+ break;
3532
3456
  }
3457
+ out.locks = await this.ownLocks();
3458
+ return out;
3533
3459
  }
3534
- /** `reclaim::reclaim`: the lender's Lock4 among the round's resolved locks, refunded to a fresh own note. */
3535
- async reclaimOffer(loanId, offer, roundArg) {
3536
- const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
3537
- const loan = address(loanId, "loan id");
3538
- const row = await read(loan);
3539
- if (!row)
3540
- unknownObject("no loan with this id");
3541
- const json = row.json;
3542
- const L = this.pairOf(json.market_id)[1];
3543
- const loanKey = BigInt(json.loan_key);
3460
+ /** Every offer and bid lock this seed made, from the slot-3 recovery records of each pool (freeze §6.4). */
3461
+ async ownLocks() {
3462
+ const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
3463
+ const encKey = noteEncKey(this.seed()).encKey;
3464
+ const out = [];
3465
+ for (const coin of COINS) {
3466
+ if (!this.config.objects.pools[coin])
3467
+ continue;
3468
+ const events = await pools(coin);
3469
+ for (const r of scanRecoveries(events.commitments, encKey))
3470
+ out.push({ coin, noteIndex: Number(r.index), amount: r.amount, unlockS: r.unlockS });
3471
+ }
3472
+ return out;
3473
+ }
3474
+ /**
3475
+ * PRV-28 C, freeze D21: the one reclaim for offer and bid locks, naming the pool and its fee config only. The lock
3476
+ * comes back from the seed: note index `noteIndex`'s slot-3 recovery record gives its amount, field and `unlock_s`
3477
+ * (Erik's condition 3). Before `unlock_s` the circuit charges the bond F (condition 4).
3478
+ */
3479
+ async reclaimOwnLock(coin, noteIndex) {
3480
+ const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
3544
3481
  const seed = this.seed();
3545
- const own = deriveNoteKey(seed, offer.noteIndex);
3546
- const ns = poseidonHash([own.sk, own.blinding, 3n]);
3547
- const b = poseidonHash([own.sk, own.blinding, 4n]);
3548
- const { round, locks, slot } = await lockRound({
3549
- current: BigInt(json.round),
3550
- currentRound: row.round,
3551
- round: roundArg,
3552
- readRound: async (r) => (await read(loan, r))?.round,
3553
- lockAt: (r) => lock4(lockField(loanKey, r), notePk(own.sk), ns, offer.principal, b),
3554
- });
3555
- const field = lockField(loanKey, round);
3482
+ const events = await pools(coin);
3483
+ const rec = scanRecoveries(events.commitments, noteEncKey(seed).encKey).find((r) => r.index === BigInt(noteIndex));
3484
+ if (!rec)
3485
+ unknownObject("no lock of this record is in the pool");
3486
+ const own = deriveNoteKey(seed, noteIndex);
3487
+ const keys = await offerKeys(own.sk, own.blinding);
3488
+ const leaf = events.commitments.find((c) => c.index === rec.lockIndex)?.commitment;
3489
+ const lockOf = (b) => lock5({ ...rec, ownerPk: keys.ownerPk, ns: keys.ns, b });
3490
+ const b = [keys.b, bidBlind(keys.ns)].find((x) => lockOf(x).lock === leaf);
3491
+ if (b === undefined)
3492
+ throw new EsseyError("CT_MISMATCH", "refused: the recovery record does not rebuild its lock");
3493
+ const { nullifier } = lockOf(b);
3494
+ if (events.nullifiers.some((n) => BigInt(n) === nullifier))
3495
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the lock is spent: a settle took it, or it was reclaimed");
3556
3496
  const relayer = this.relayerAddress();
3557
- const relayerFee = this.coinFee(L);
3558
- const fee = await this.feeParams(L);
3497
+ const relayerFee = this.coinFee(coin);
3498
+ const fee = await this.feeParams(coin);
3499
+ const tree = poolTree(orderedLeaves(events));
3559
3500
  await this.keys();
3560
3501
  const outIndex = this.reserve("notes");
3561
3502
  const out = deriveNoteKey(seed, outIndex);
3562
- const eph = drawEph();
3563
- const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
3564
- const plan = (encs) => reclaimLock({
3565
- locks,
3566
- slot,
3567
- field,
3568
- amount: offer.principal,
3503
+ const pads = padPair(seed, () => this.reserve("notes"));
3504
+ const nowS = defaultNowS((this.io.now ?? Date.now)());
3505
+ const base = {
3506
+ field: rec.field,
3507
+ amount: rec.amount,
3569
3508
  ownerSk: own.sk,
3570
- ns,
3509
+ ns: keys.ns,
3571
3510
  b,
3511
+ unlockS: rec.unlockS,
3512
+ root: tree.root,
3513
+ lockIndex: rec.lockIndex,
3514
+ lockPath: tree.path(Number(rec.lockIndex)),
3515
+ nowS,
3572
3516
  out: { pk: notePk(out.sk), blinding: out.blinding },
3517
+ pads,
3518
+ dummySeed: drawDummySeed(),
3573
3519
  relayer,
3574
3520
  relayerFee,
3575
- encs,
3576
3521
  fee,
3577
- eph,
3578
- });
3579
- const draft = await plan([new Uint8Array(128), new Uint8Array(128)]);
3522
+ eph: drawEph(),
3523
+ };
3524
+ const draft = await reclaimLock({ ...base, encs: [] });
3580
3525
  const encs = [
3581
- bytesOf(sealOpening({ value: draft.outAmt, blinding: out.blinding, index: outIndex }, noteEncKey(seed).encPub)),
3582
- bytesOf(fillerEnc()),
3583
- ];
3584
- const w = await plan(encs);
3526
+ sealOpening({ value: draft.outAmt, blinding: out.blinding, index: outIndex }, noteEncKey(seed).encPub),
3527
+ fillerEnc(),
3528
+ fillerEnc(),
3529
+ fillerEnc(),
3530
+ ].map(hexBytes);
3531
+ const w = await reclaimLock({ ...base, encs });
3585
3532
  const proved = await this.prover().prove("reclaim", w.input);
3586
- return this.paidLoan(reclaimLoan, {
3587
- pool: L,
3588
- loan,
3533
+ const landed = await this.paidLoan(reclaimLoan, {
3534
+ pool: coin,
3589
3535
  proved: { proof: proved.proof, publicSignals: w.publics.map(String) },
3590
- round,
3591
- nullifier: w.n,
3536
+ root: tree.root,
3537
+ nLock: w.nLock,
3538
+ nDummy: w.nDummy,
3592
3539
  refund: w.outNote,
3593
- feeCommit: w.feeCommit,
3540
+ feeNote: w.feeNote,
3541
+ pad0: pads[0].leaf,
3542
+ pad1: pads[1].leaf,
3594
3543
  ephX: w.ephX,
3595
3544
  ephY: w.ephY,
3596
3545
  feeCt: w.feeCt,
3597
- feeNote: w.feeNote,
3598
- encRefund: encs[0],
3599
- encFee: encs[1],
3546
+ feeCommit: w.feeCommit,
3547
+ nowS,
3548
+ encs,
3600
3549
  });
3550
+ return { ...landed, value: draft.outAmt };
3601
3551
  }
3602
3552
  /**
3603
3553
  * The lock as it stands: the open blinding at nonce 1, rolled one re-lock per heartbeat (`rollTo` refuses an opening
@@ -3623,6 +3573,7 @@ export class Essey {
3623
3573
  const row = await read(loan);
3624
3574
  if (!row)
3625
3575
  unknownObject("no loan with this id");
3576
+ this.refuseRetiredLoanProof(row);
3626
3577
  const json = row.json;
3627
3578
  if (Number(json.state) !== 2)
3628
3579
  throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
@@ -3634,8 +3585,7 @@ export class Essey {
3634
3585
  const expiryMs = await this.heartbeatExpiry(json, market, p.terms.maturityS, p.expiryMs);
3635
3586
  const { opening } = this.ownOpening(this.seed(), json, p.borrowerPk, p.collAmt);
3636
3587
  const reading = await readPrice(market);
3637
- const retired = this.retired(row);
3638
- const floor = retired ? legacyHeartbeatFloor(reading) : heartbeatFloor(reading);
3588
+ const floor = heartbeatFloor(reading);
3639
3589
  const fee = await this.loanFee(C, json.coll_fee_commit);
3640
3590
  const rates = {
3641
3591
  ltvBps: BigInt(json.ltv_bps),
@@ -3649,7 +3599,8 @@ export class Essey {
3649
3599
  lDec: BigInt(this.config.coins[L].decimals),
3650
3600
  };
3651
3601
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
3652
- const encs = [bytesOf(fillerEnc()), bytesOf(fillerEnc())];
3602
+ const encs = [fillerEnc(), fillerEnc(), fillerEnc(), fillerEnc()].map(bytesOf);
3603
+ const seed = this.seed();
3653
3604
  const h = await health({
3654
3605
  mode: MODE.HEARTBEAT,
3655
3606
  opening,
@@ -3659,6 +3610,8 @@ export class Essey {
3659
3610
  extHash: heartbeatExt({ loan, poolC, market }, encs),
3660
3611
  fee,
3661
3612
  eph: drawEph(),
3613
+ pads: padPair(seed, () => this.reserve("notes")),
3614
+ dummySeeds: [drawDummySeed(), drawDummySeed()],
3662
3615
  terms: p.terms,
3663
3616
  });
3664
3617
  const proved = await this.prover().prove("health", h.input);
@@ -3672,17 +3625,21 @@ export class Essey {
3672
3625
  encs,
3673
3626
  expiryMs,
3674
3627
  priceUpdate: await update(market),
3675
- retired,
3676
3628
  }));
3677
3629
  return { ...landed, expiryMs };
3678
3630
  }
3679
3631
  /**
3680
3632
  * PRV-15: until a loan's first heartbeat every keeper may read its terms (`keeper.move:204`), so this follows the
3681
3633
  * settle at once and unpaced. A heartbeat may follow a settle at once: `hb_at_ms` is 0 (`liquidation.move:199`).
3634
+ * A short term whose settle-stored expiry (`collateral.move:244`) already reaches maturity plus grace needs none:
3635
+ * no heartbeat may cover past that (`health.circom:301`), and keepers read only once it lapses (`keeper.move:212`).
3682
3636
  */
3683
3637
  async firstCover(p) {
3684
3638
  try {
3685
- await this.untilSettled(p.loan, termsCommit(p.terms, p.borrowerPk));
3639
+ const json = await this.untilSettled(p.loan, termsCommit(p.terms, p.borrowerPk));
3640
+ const stored = BigInt(json.coll?.hb_expiry_ms ?? 0);
3641
+ if (stored >= (p.terms.maturityS + GRACE_S) * 1000n)
3642
+ return { ok: true, stored: true, expiryMs: stored };
3686
3643
  const { digest, ticket, expiryMs } = await this.heartbeatOwn(p);
3687
3644
  return { ok: true, digest, ticket, expiryMs };
3688
3645
  }
@@ -3700,7 +3657,7 @@ export class Essey {
3700
3657
  await this.sleep(SETTLE_READ_MS);
3701
3658
  const json = (await read(loan))?.json;
3702
3659
  if (Number(json?.state) === 2 && BigInt(json?.terms_commit ?? -1) === commit)
3703
- return;
3660
+ return json;
3704
3661
  }
3705
3662
  throw new EsseyError("STATE_REFUSED", "the loan read does not show the settle yet");
3706
3663
  }
@@ -3745,6 +3702,7 @@ export class Essey {
3745
3702
  const row = await read(loan);
3746
3703
  if (!row)
3747
3704
  unknownObject("no loan with this id");
3705
+ this.refuseRetiredLoanProof(row);
3748
3706
  const json = row.json;
3749
3707
  if (Number(json.state) !== 2)
3750
3708
  throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
@@ -3768,6 +3726,7 @@ export class Essey {
3768
3726
  const addKey = deriveNoteKey(seed, this.reserve("notes"));
3769
3727
  const changeIndex = this.reserve("notes");
3770
3728
  const change = deriveNoteKey(seed, changeIndex);
3729
+ const lockPads = padPair(seed, () => this.reserve("notes"));
3771
3730
  const lock = await collLock({
3772
3731
  root: tree.root,
3773
3732
  ins: [ins[0], ins[1] ?? dummyInput()],
@@ -3778,10 +3737,10 @@ export class Essey {
3778
3737
  extHash: collLockExt(MODE_TOPUP, ids.loan, ids.poolC, ids.market),
3779
3738
  fee,
3780
3739
  eph: drawEph(),
3740
+ pads: [lockPads[0], lockPads[1]],
3781
3741
  });
3782
3742
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
3783
3743
  const encChange = bytesOf(sealOpening({ value: lock.changeAmount, blinding: change.blinding, index: changeIndex }, noteEncKey(seed).encPub));
3784
- const encFee = bytesOf(fillerEnc());
3785
3744
  const version = json.coll.keeper_ct == null ? 0n : BigInt(json.coll.keeper_ct_version) + 1n;
3786
3745
  const keeperCt = await seal({
3787
3746
  id: keeperKeyId(opening.loanKey, version),
@@ -3794,9 +3753,8 @@ export class Essey {
3794
3753
  nonceAtCt: opening.nonce + 1n,
3795
3754
  terms: p.terms,
3796
3755
  }),
3797
- ...this.sealOrigin(row),
3798
3756
  });
3799
- const encs = [bytesOf(fillerEnc()), bytesOf(fillerEnc())];
3757
+ const encs = [encChange, bytesOf(fillerEnc()), bytesOf(fillerEnc()), bytesOf(fillerEnc())];
3800
3758
  const decimals = {
3801
3759
  cDec: BigInt(this.config.coins[C].decimals),
3802
3760
  lDec: BigInt(this.config.coins[L].decimals),
@@ -3808,15 +3766,18 @@ export class Essey {
3808
3766
  keeperLiqBps: BigInt(json.keeper_liq_bps),
3809
3767
  keeperDefaultBps: BigInt(json.keeper_default_bps),
3810
3768
  };
3769
+ // Health TOPUP's out1/out2 and the CollLock fee note are hashed, not inserted (Z1-LEAF-MAP.md, top-up row).
3811
3770
  const h = await health({
3812
3771
  mode: MODE.TOPUP,
3813
3772
  opening,
3814
3773
  risk: loanRisk(rates, decimals, MODE.TOPUP),
3815
3774
  price: { spot: 0n, ema: 0n, expo: 0n },
3816
3775
  timeS: 0n,
3817
- extHash: (p.asBorrower ? topupByBorrowerExt : topupExt)(ids, keeperCt, encChange, encFee, encs),
3776
+ extHash: (p.asBorrower ? topupByBorrowerExt : topupExt)(ids, keeperCt, encs),
3818
3777
  fee,
3819
3778
  eph: drawEph(),
3779
+ pads: [randomPad(), randomPad()],
3780
+ dummySeeds: [drawDummySeed(), drawDummySeed()],
3820
3781
  terms: p.terms,
3821
3782
  add: { amount: p.add, blinding: addKey.blinding, ephL: drawEph() },
3822
3783
  });
@@ -3834,7 +3795,6 @@ export class Essey {
3834
3795
  wait: true,
3835
3796
  lock: lock.spend,
3836
3797
  lockProved: { proof: lockProof.proof, publicSignals: lock.publics.map(String) },
3837
- lockEncs: [encChange, encFee],
3838
3798
  keeperCt,
3839
3799
  encs,
3840
3800
  };
@@ -3844,9 +3804,7 @@ export class Essey {
3844
3804
  const args = topupArgs({
3845
3805
  ...ids,
3846
3806
  lockProof: proofBytes(lockProof.proof),
3847
- fields: [s.root, s.n0, s.n1, s.note, s.change, s.feeNote, s.ephX, s.ephY, s.feeCt],
3848
- encChange,
3849
- encFee,
3807
+ fields: [s.root, s.n0, s.n1, s.note, s.change, s.feeNote, s.pad0, s.pad1, s.ephX, s.ephY, s.feeCt],
3850
3808
  keeperCt,
3851
3809
  proof: proofBytes(healthProof.proof),
3852
3810
  outs: h.statement.outs,
@@ -3862,7 +3820,7 @@ export class Essey {
3862
3820
  */
3863
3821
  borrowerSeize(p, mode) {
3864
3822
  return this.seize(p.loan, mode, async (json, seed) => ({
3865
- terms: p.terms,
3823
+ terms: keeperView(p.terms),
3866
3824
  borrowerPk: p.borrowerPk,
3867
3825
  opening: this.ownOpening(seed, json, p.borrowerPk, p.collAmt).opening,
3868
3826
  }));
@@ -3893,7 +3851,7 @@ export class Essey {
3893
3851
  };
3894
3852
  const start = { loanKey, borrowerPk, ...(await this.lenderLock(json, own)), nonce: 1n };
3895
3853
  return {
3896
- terms,
3854
+ terms: keeperView(terms),
3897
3855
  borrowerPk,
3898
3856
  opening: rollTo(start, BigInt(json.coll.coll_note), BigInt(json.coll.nonce)),
3899
3857
  };
@@ -3901,22 +3859,22 @@ export class Essey {
3901
3859
  }
3902
3860
  /** The keeper reads the current keeper ciphertext under its pass or badge, rolls the opening to the lock's nonce and seizes. */
3903
3861
  keeperLiquidate(loanId, via) {
3904
- return this.seize(loanId, MODE.LIQUIDATE, (json, _seed, loan, drained) => this.keeperOpening(json, loan, via, drained));
3862
+ return this.seize(loanId, MODE.LIQUIDATE, (json, _seed, loan) => this.keeperOpening(json, loan, via));
3905
3863
  }
3906
3864
  /** Any read that does not open the lock and the terms commit throws CT_MISMATCH. */
3907
- async keeperOpening(json, loan, via, drained) {
3865
+ async keeperOpening(json, loan, via) {
3908
3866
  const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
3909
3867
  const readCt = this.io.readKeeperCt ?? notSetUp("missing config: no keeper ciphertext reader");
3910
3868
  const loanKey = BigInt(json.loan_key);
3911
3869
  const version = BigInt(json.coll.keeper_ct_version);
3912
- const approval = await this.keeperApproval(json, loan, keeperKeyId(loanKey, version), via, drained);
3870
+ const { approve, signer } = await this.keeperApproval(json, loan, keeperKeyId(loanKey, version), via);
3913
3871
  const sealed = { loan, loanKey, keeperCt: await readCt(loan), keeperCtVersion: version };
3914
3872
  const payload = await fetchKeeperPlaintext(sealed, {
3915
- decrypt: (r) => decrypt({ sealed: r.sealed, ...approval }).catch(keeperRefusal),
3873
+ decrypt: (r) => decrypt({ sealed: r.sealed, approve, signer }).catch(keeperRefusal),
3916
3874
  });
3917
3875
  if (!payload.terms)
3918
3876
  throw new EsseyError("CT_MISMATCH", "refused: the keeper plaintext carries no terms");
3919
- if (termsCommit(payload.terms, payload.borrowerPk) !== BigInt(json.terms_commit))
3877
+ if (viewCommit(payload.terms, payload.borrowerPk) !== BigInt(json.terms_commit))
3920
3878
  throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
3921
3879
  const opening = rollTo(openingOf(payload), BigInt(json.coll.coll_note), BigInt(json.coll.nonce));
3922
3880
  return { terms: payload.terms, borrowerPk: payload.borrowerPk, opening };
@@ -3928,10 +3886,10 @@ export class Essey {
3928
3886
  */
3929
3887
  async judge(loanId, via) {
3930
3888
  const readPrice = this.io.readPrice ?? notSetUp("missing config: no price reader");
3931
- const { loan, json, drained } = await this.activeLoan(loanId);
3889
+ const { loan, json } = await this.activeLoan(loanId);
3932
3890
  let opened;
3933
3891
  try {
3934
- opened = await this.keeperOpening(json, loan, via, drained);
3892
+ opened = await this.keeperOpening(json, loan, via);
3935
3893
  }
3936
3894
  catch (err) {
3937
3895
  if (!isEsseyError(err, "CT_MISMATCH"))
@@ -3959,12 +3917,13 @@ export class Essey {
3959
3917
  const row = await read(loan);
3960
3918
  if (!row)
3961
3919
  unknownObject("no loan with this id");
3920
+ this.refuseRetiredLoanProof(row);
3962
3921
  const json = row.json;
3963
3922
  if (Number(json.state) !== 2 && Number(json.state) !== 8)
3964
3923
  throw new EsseyError("INVALID_ARGUMENT", "the loan is not seizable");
3965
3924
  const seed = this.seed();
3966
- const { terms, borrowerPk, opening } = await open(json, seed, loan, this.drainedLoan(row));
3967
- if (termsCommit(terms, borrowerPk) !== BigInt(json.terms_commit))
3925
+ const { terms, borrowerPk, opening } = await open(json, seed, loan);
3926
+ if (viewCommit(terms, borrowerPk) !== BigInt(json.terms_commit))
3968
3927
  throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
3969
3928
  const [C, L] = this.pairOf(json.market_id);
3970
3929
  const poolC = address(json.pool_c, "pool_c");
@@ -3996,7 +3955,10 @@ export class Essey {
3996
3955
  timeS: nowS,
3997
3956
  fee,
3998
3957
  eph: drawEph(),
3999
- terms,
3958
+ pads: [randomPad(), randomPad()],
3959
+ dummySeeds: [drawDummySeed(), drawDummySeed()],
3960
+ terms: viewTerms(terms),
3961
+ hRest: terms.hRest,
4000
3962
  keeper: { pk: notePk(keeper.sk), blinding: keeper.blinding },
4001
3963
  };
4002
3964
  const draft = await health({ ...common, extHash: 0n });
@@ -4065,8 +4027,10 @@ export class Essey {
4065
4027
  opening,
4066
4028
  });
4067
4029
  }
4068
- /** The seller keys and bounds salt of the sale opened at note index `index`, so the seed alone reopens them. */
4069
- /** D-SPEC §6.2:599. The seller pass over `sale_room::open_args`, at action nonce 0; the relayer or the callback pays. */
4030
+ /**
4031
+ * D-SPEC §6.2:599. The seller pass over `sale_room::open_args`, at action nonce 0; the relayer or the callback pays.
4032
+ * The seller keys, the posted salt and the bid key derive from one reserved note index, so the seed reopens them.
4033
+ */
4070
4034
  async openSale(p) {
4071
4035
  const open = assertSaleOpen(p);
4072
4036
  await this.saleWindow(open);
@@ -4079,23 +4043,26 @@ export class Essey {
4079
4043
  : (this.io.submitSaleOpen ?? notSetUp("missing config: sale open has no submitter"));
4080
4044
  const typeName = asInvalid(() => typeNameOf(open.itemType));
4081
4045
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
4046
+ const floor = minHiddenBase(await this.feeParams(open.coin));
4047
+ if (open.price < floor)
4048
+ throw new EsseyError("INVALID_ARGUMENT", `refused: the price is under ${floor}, 10 x the flat fee, so no finish could prove; nothing was sent`);
4082
4049
  const { secrets, credential } = this.member();
4083
4050
  const prover = this.prover();
4084
4051
  const seed = await this.keys();
4085
4052
  const noteIndex = this.reserve("notes");
4086
4053
  const s = saleSecrets(deriveNoteKey(seed, noteIndex));
4087
4054
  const commits = openCommits(s, open.price);
4088
- const bounds = { lo: open.price, hi: open.price, salt: s.boundsSalt };
4089
4055
  const saleKey = drawSecret();
4056
+ const bidEncPub = offerRecvKey(seed, noteIndex).pub;
4090
4057
  const listing = await seal({
4091
4058
  id: listingKeyId(saleKey),
4092
- data: listingPlaintext({ price: open.price, salt: s.postedSalt }),
4059
+ data: listingPlaintext({ price: open.price, salt: s.postedSalt, bidEncPub }),
4093
4060
  pkg: "sale",
4094
4061
  });
4095
4062
  const memo = sealSaleMemo(memoKey(seed), saleKey, { noteIndex, price: open.price });
4096
4063
  const t = await this.saleWindow(open);
4097
4064
  const { closeMs, finishByMs } = t;
4098
- const shape = { pool, item: { id: item.id, typeName }, closeMs, finishByMs, maxBids: open.maxBids };
4065
+ const shape = { pool, item: { id: item.id, typeName }, closeMs, finishByMs };
4099
4066
  const n0 = actionHash(blake2b256, saleKey, 0n, "open", openArgs({ ...shape, ...commits, listing, memo, saleKey }));
4100
4067
  const pass = membership({
4101
4068
  secrets,
@@ -4115,7 +4082,6 @@ export class Essey {
4115
4082
  memo,
4116
4083
  closeMs,
4117
4084
  finishByMs,
4118
- maxBids: open.maxBids,
4119
4085
  pass: {
4120
4086
  tag: pass.publics[0],
4121
4087
  expiryMs: credential.expiryMs,
@@ -4136,7 +4102,7 @@ export class Essey {
4136
4102
  id,
4137
4103
  digest: landed.digest,
4138
4104
  ticket: landed.ticket,
4139
- sale: { room: id, noteIndex, seller, bounds },
4105
+ sale: { room: id, noteIndex, seller },
4140
4106
  };
4141
4107
  }
4142
4108
  /** PRV-27 (b), `sale_room::check_grid` (44_041): the close and finish a sale opening about now must carry. */
@@ -4242,12 +4208,11 @@ export class Essey {
4242
4208
  const row = await read(key);
4243
4209
  if (!row)
4244
4210
  unknownObject("no room with this id");
4245
- const bounds = this.io.roomBounds ? await this.io.roomBounds(key) : null;
4246
- return viewRoomObject(this.config, { id: key, json: row.json }, bounds);
4211
+ return viewRoomObject(this.config, { id: key, json: row.json });
4247
4212
  }
4248
4213
  /**
4249
4214
  * 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.
4215
+ * (DECISION-R1-MIGRATION A, `sales/package-gate.ts`).
4251
4216
  */
4252
4217
  async saleRoom(id, kind) {
4253
4218
  requireSale(this.config);
@@ -4256,22 +4221,13 @@ export class Essey {
4256
4221
  const row = await read(room);
4257
4222
  if (!row)
4258
4223
  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);
4224
+ const { legacy } = row.type ? this.saleGate(kind, row.type) : { legacy: false };
4264
4225
  const json = row.json;
4265
- const bids = (json.bids ?? []);
4266
- const pick = optionU256(json.pick, "the room's pick");
4267
4226
  return {
4268
4227
  legacy,
4269
- drained: !!drained,
4270
- policyPkg,
4271
- ...(drained ? { origin: drained.origin } : {}),
4272
- pick: pick === null ? null : Number(pick),
4273
4228
  postedCommit: BigInt(json.posted_commit ?? 0),
4274
4229
  listing: optionBytes(json.listing),
4230
+ memo: optionBytes(json.memo),
4275
4231
  id: room,
4276
4232
  coin: coinByPool(this.config, String(json.pool_id)),
4277
4233
  saleKey: BigInt(json.sale_key),
@@ -4279,29 +4235,11 @@ export class Essey {
4279
4235
  nonce: BigInt(json.nonce),
4280
4236
  closeMs: BigInt(json.close_ms),
4281
4237
  finishByMs: BigInt(json.finish_by_ms),
4282
- maxBids: Number(json.max_bids),
4283
- residual: BigInt(json.residual ?? 0),
4284
- boundsCommit: BigInt(json.bounds_commit),
4285
4238
  sellerCommit: BigInt(json.seller_commit),
4286
- bids: bids.map((b) => ({
4287
- ...b,
4288
- commit: BigInt(b.commit),
4289
- lock: BigInt(b.lock),
4290
- active: b.active === true,
4291
- })),
4292
4239
  };
4293
4240
  }
4294
4241
  bidSecrets(seed, record) {
4295
- const own = deriveNoteKey(seed, record.noteIndex);
4296
- const tagged = (t) => poseidonHash([own.sk, own.blinding, t]);
4297
- return {
4298
- v: record.v,
4299
- amount: record.amount,
4300
- ownerSk: own.sk,
4301
- ns: tagged(3n),
4302
- b: tagged(4n),
4303
- s: tagged(5n),
4304
- };
4242
+ return bidSecrets(deriveNoteKey(seed, record.noteIndex));
4305
4243
  }
4306
4244
  nowMs() {
4307
4245
  return BigInt((this.io.now ?? Date.now)());
@@ -4311,12 +4249,14 @@ export class Essey {
4311
4249
  throw new EsseyError("INVALID_ARGUMENT", `${what} has closed or closes within 2 minutes, too soon to prove and land; nothing was sent`);
4312
4250
  }
4313
4251
  /**
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.
4252
+ * `sale_room::seal_approve_listing` (freeze D24): a SEAL pass under a fresh non-zero nonce, bound to the viewer, so
4253
+ * two reads show two tags, and a funds proof of an own sale-coin note of at least `10 * F` of the accepted hidden
4254
+ * fee opening, bound to that pass's Seal bind and nonce (PRV-22 a).
4316
4255
  */
4317
4256
  async readRoomListing(room) {
4318
4257
  const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
4319
4258
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
4259
+ const cfg = this.feeConfigId(room.coin, "hidden") ?? notSetUp("missing config: no fee config for the sale coin");
4320
4260
  const { member, credential } = readState(this.statePath, this.stateKey);
4321
4261
  if (!member || !credential)
4322
4262
  notSetUp("no credential: call credential.obtain first");
@@ -4324,32 +4264,41 @@ export class Essey {
4324
4264
  unknownObject("the room holds no sealed listing");
4325
4265
  const scope = keyId(room.saleKey);
4326
4266
  const prover = this.prover();
4267
+ const fee = await this.feeParams(room.coin);
4268
+ const funds = await this.fundsWitness(room.coin, fee);
4327
4269
  return decrypt({
4328
4270
  sealed: room.listing,
4329
4271
  pkg: "sale",
4330
4272
  approve: async (viewer) => {
4331
4273
  const nonce = drawSecret();
4332
- const bind = `0x${Buffer.from(sealListingBind(scope, viewer)).toString("hex")}`;
4274
+ const sealBind = sealListingBind(scope, viewer);
4333
4275
  const pass = membership({
4334
4276
  secrets: member,
4335
4277
  credential: credential,
4336
4278
  domain: DOMAIN_SENDER,
4337
4279
  room: scope,
4338
- bind,
4280
+ bind: `0x${Buffer.from(sealBind).toString("hex")}`,
4339
4281
  nonce,
4340
4282
  });
4341
4283
  const proved = await prover.prove("membership", pass.input);
4284
+ const fundsProof = await funds.prove(sealBind, nonce);
4285
+ const hex = (b) => `0x${Buffer.from(b).toString("hex")}`;
4342
4286
  return {
4343
4287
  target: `${this.config.packages.sale}::sale_room::seal_approve_listing`,
4344
4288
  typeArguments: [this.config.coins[room.coin].type],
4345
4289
  args: [
4346
- { pure: "vector<u8>", value: `0x${Buffer.from(listingKeyId(room.saleKey)).toString("hex")}` },
4290
+ { pure: "vector<u8>", value: hex(listingKeyId(room.saleKey)) },
4347
4291
  { object: room.id },
4292
+ { object: poolId(this.config, room.coin) },
4293
+ { object: cfg },
4348
4294
  { object: passKey.id },
4349
4295
  { pure: "u256", value: pass.publics[0].toString() },
4350
- { pure: "u256", value: nonce.toString() },
4351
4296
  { pure: "u64", value: credential.expiryMs.toString() },
4352
- { pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
4297
+ { pure: "vector<u8>", value: hex(proofBytes(proved.proof)) },
4298
+ { pure: "u256", value: nonce.toString() },
4299
+ { pure: "u256", value: funds.root.toString() },
4300
+ { pure: "u256", value: feeCommit(fee).toString() },
4301
+ { pure: "vector<u8>", value: hex(fundsProof) },
4353
4302
  { object: "0x6" },
4354
4303
  ],
4355
4304
  };
@@ -4363,9 +4312,6 @@ export class Essey {
4363
4312
  if (room.state !== SALE_STATE.open)
4364
4313
  throw new EsseyError("INVALID_ARGUMENT", "the room is not taking bids");
4365
4314
  this.assertBeforeClose(room.closeMs, "the room");
4366
- const seq = room.bids.length;
4367
- if (seq >= room.maxBids)
4368
- throw new EsseyError("INVALID_ARGUMENT", "the room is full");
4369
4315
  const plain = await this.readRoomListing(room);
4370
4316
  const listing = asInvalid(() => readListing(plain, room.postedCommit));
4371
4317
  if (!listing)
@@ -4376,120 +4322,24 @@ export class Essey {
4376
4322
  const amount = asked ?? v;
4377
4323
  if (amount < v)
4378
4324
  throw new EsseyError("INVALID_ARGUMENT", "the deposit must cover the posted price");
4379
- const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
4380
- const { member, credential } = readState(this.statePath, this.stateKey);
4381
- if (!member || !credential)
4382
- notSetUp("no credential: call credential.obtain first");
4383
- const relayer = this.relayerAddress();
4384
- const relayerFee = this.coinFee(room.coin);
4385
- const prover = this.prover();
4386
- const fee = await this.feeParams(room.coin);
4387
- const { events, owned, seed } = await this.owned(room.coin);
4388
- const inputs = pickInputs(owned, amount + relayerFee);
4389
- const tree = poolTree(orderedLeaves(events));
4390
- const ins = inputs.map((n) => ({
4391
- amount: n.value,
4392
- sk: n.sk,
4393
- blinding: n.blinding,
4394
- pathIndex: BigInt(n.index),
4395
- pathElements: tree.path(n.index),
4396
- }));
4397
- const spent = [ins[0], ins[1] ?? dummyInput()];
4398
- const n0 = noteNullifier(noteCommitment(spent[0].amount, notePk(spent[0].sk), spent[0].blinding), spent[0].sk, spent[0].pathIndex);
4325
+ const seed = this.seed();
4399
4326
  await this.keys();
4400
- const record = { room: room.id, noteIndex: this.reserve("notes"), v, amount };
4401
- const changeIndex = this.reserve("notes");
4402
- const change = deriveNoteKey(seed, changeIndex);
4403
- const secrets = { ...this.bidSecrets(seed, record), s: listing.salt };
4404
- const memo = sealBidMemo(memoKey(seed), room.saleKey, record);
4405
- const sealed = await seal({
4406
- id: bidKeyId(room.saleKey, BigInt(seq)),
4407
- data: bidPlaintext(secrets),
4408
- aad: bidAad(n0),
4409
- pkg: "sale",
4410
- });
4411
- const changeValue = spent[0].amount + spent[1].amount - amount - relayerFee;
4412
- const encChange = sealOpening({ value: changeValue, blinding: change.blinding, index: changeIndex }, noteEncKey(seed).encPub);
4413
- const encs = [hexBytes(encChange), hexBytes(fillerEnc())];
4414
- const w = await lockBid({
4415
- root: tree.root,
4416
- ins: spent,
4417
- room: { id: room.id, saleKey: room.saleKey, seq, postedCommit: room.postedCommit },
4418
- bid: secrets,
4419
- change: { pk: notePk(change.sk), blinding: change.blinding },
4420
- relayer,
4421
- relayerFee,
4422
- sealed,
4423
- memo,
4424
- encs,
4425
- fee,
4426
- eph: drawEph(),
4427
- });
4428
- const pass = membership({
4429
- secrets: member,
4430
- credential: credential,
4431
- domain: DOMAIN_SPEND,
4432
- room: keyId(room.saleKey),
4433
- bind: keyId(n0),
4434
- });
4435
- const proved = async (circuit, input, publics) => ({
4436
- proof: (await prover.prove(circuit, input)).proof,
4437
- publicSignals: publics.map(String),
4438
- });
4439
- const landed = await this.paidLoan(bidBody, {
4440
- pool: room.coin,
4441
- room: room.id,
4442
- pass: {
4443
- proved: await proved("membership", pass.input, pass.publics),
4444
- tag: pass.publics[0],
4445
- expiryMs: credential.expiryMs,
4446
- },
4447
- proved: await proved("lock_bid", w.input, w.publics),
4448
- statement: w.statement,
4449
- sealed,
4450
- memo,
4451
- encs,
4327
+ const noteIndex = this.reserve("notes");
4328
+ const lock = asInvalid(() => bidLock({
4329
+ saleKey: room.saleKey,
4330
+ own: deriveNoteKey(seed, noteIndex),
4331
+ noteIndex,
4332
+ amount,
4333
+ finishByMs: room.finishByMs,
4334
+ }));
4335
+ const landed = await this.lockTransfer(room.coin, amount, {
4336
+ ...lock,
4337
+ counterpartyPub: listing.bidEncPub,
4452
4338
  });
4453
- return { ...landed, bid: record };
4454
- }
4455
- /** `sale_room::seal_approve_bid`: the seller's SEAL pass over `seal_bid` of bid `seq`, bound to the viewer, nonce 0. */
4456
- bidApprove(room, seq) {
4457
- const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
4458
- const { member, credential } = readState(this.statePath, this.stateKey);
4459
- if (!member || !credential)
4460
- notSetUp("no credential: call credential.obtain first");
4461
- const scope = keyId(room.saleKey);
4462
- const prover = this.prover();
4463
- return async (viewer) => {
4464
- const bind = `0x${Buffer.from(sealBidBind(scope, BigInt(seq), viewer)).toString("hex")}`;
4465
- const pass = membership({
4466
- secrets: member,
4467
- credential: credential,
4468
- domain: DOMAIN_SENDER,
4469
- room: scope,
4470
- bind,
4471
- });
4472
- const proved = await prover.prove("membership", pass.input);
4473
- return {
4474
- target: `${room.policyPkg}::sale_room::seal_approve_bid`,
4475
- typeArguments: [this.config.coins[room.coin].type],
4476
- args: [
4477
- {
4478
- pure: "vector<u8>",
4479
- value: `0x${Buffer.from(bidKeyId(room.saleKey, BigInt(seq))).toString("hex")}`,
4480
- },
4481
- { object: room.id },
4482
- { pure: "u64", value: seq.toString() },
4483
- { object: passKey.id },
4484
- { pure: "u256", value: pass.publics[0].toString() },
4485
- { pure: "u64", value: credential.expiryMs.toString() },
4486
- { pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
4487
- { object: "0x6" },
4488
- ],
4489
- };
4490
- };
4339
+ const own = { coin: room.coin, noteIndex, amount, unlockS: lock.recovery.unlockS };
4340
+ return { ...landed, bid: { room: room.id, noteIndex, v, amount }, lock: own };
4491
4341
  }
4492
- /** `seal_approve_bid` releases keys from close until `finish_by_ms`, for an active bid (`sale_room.move:337-341`). */
4342
+ /** Finish runs from close until `finish_by_ms` (`sale_room::check_finish`). */
4493
4343
  async closedRoom(roomId, kind) {
4494
4344
  const room = await this.saleRoom(roomId, kind);
4495
4345
  const now = this.nowMs();
@@ -4497,55 +4347,53 @@ export class Essey {
4497
4347
  throw new EsseyError("INVALID_ARGUMENT", "the room is not between close and its finish deadline");
4498
4348
  return room;
4499
4349
  }
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");
4506
- const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
4507
- const derive = this.io.sealDerivedKeys ?? notSetUp("missing config: no Seal key deriver");
4508
- const bid = room.bids[seq];
4509
- if (typeof bid.sealed !== "string")
4510
- notSetUp("the room reader gave no sealed bid");
4511
- const approve = this.bidApprove(room, seq);
4512
- const sealed = Uint8Array.from(Buffer.from(bid.sealed, "base64"));
4513
- const plain = await decrypt({ sealed, approve, pkg: "sale" }).catch(() => undefined);
4514
- if (openBid(plain, room.saleKey, bid.commit, bid.lock))
4515
- throw new EsseyError("INVALID_ARGUMENT", "refused: the bid opens its commit and lock (slash aborts 44_019)");
4516
- const derived = await derive({ id: bidKeyId(room.saleKey, BigInt(seq)), approve, pkg: "sale" });
4517
- return this.freeLoan(slashBody, {
4518
- pool: room.coin,
4519
- room: room.id,
4520
- seq: BigInt(seq),
4521
- keys: this.pinnedKeys(derived),
4522
- });
4523
- }
4350
+ /**
4351
+ * The seller's scan (PRV-28 B+C): every lock of the sale pool sealed to this listing's bid key that rebuilds to its
4352
+ * slot-0 leaf under `sale_key`, covers the price, unlocks after `finish_by_ms` and is unspent; one is settled on.
4353
+ * The price comes back from the seller's memo and must open `posted_commit` (checked in `sales/auctioneer.ts`).
4354
+ */
4524
4355
  async finishSale(p) {
4525
- const room = await this.pickedRoom(p.room);
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);
4528
- const plains = [];
4529
- for (const [i, b] of room.bids.entries()) {
4530
- if (opened(i) && typeof b.sealed !== "string")
4531
- notSetUp("the room reader gave no sealed bid");
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 })));
4535
- }
4356
+ const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
4357
+ const room = await this.closedRoom(p.room, "finish");
4536
4358
  const seed = this.seed();
4537
4359
  const sellerIndex = this.indexOfSellerKey(seed, p.seller.sellerSk);
4360
+ const memo = room.memo && openSaleMemo(memoKey(seed), room.saleKey, room.memo);
4361
+ if (!memo || memo.noteIndex !== sellerIndex)
4362
+ throw new EsseyError("CT_MISMATCH", "refused: the room's memo is not this seller's record");
4363
+ const events = await pools(room.coin);
4364
+ const bids = await scanLocks({
4365
+ commitments: events.commitments,
4366
+ nullifiers: events.nullifiers.map((n) => BigInt(n)),
4367
+ recvSecret: offerRecvKey(seed, sellerIndex).secret,
4368
+ field: room.saleKey,
4369
+ open: bidOpen(memo.price),
4370
+ deadlineMs: room.finishByMs,
4371
+ });
4372
+ if (bids.length === 0)
4373
+ throw new EsseyError("INVALID_ARGUMENT", "refused: no usable bid reached this room; it ends through expire once the finish window passes");
4374
+ const bid = bids[randomInt(bids.length)];
4375
+ const tree = poolTree(orderedLeaves(events));
4538
4376
  const fee = await this.feeParams(room.coin);
4539
- const eph = drawEph();
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 });
4542
- const draft = await planFor([new Uint8Array(128), new Uint8Array(128)]);
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
- }
4377
+ await this.keys();
4378
+ const base = {
4379
+ room,
4380
+ price: memo.price,
4381
+ postSalt: saleSecrets(deriveNoteKey(seed, sellerIndex)).postedSalt,
4382
+ seller: p.seller,
4383
+ bid: { ...bid, b: bidBlind(bid.ns), amount: unpackAmount(bid.aux) },
4384
+ lock: { root: tree.root, index: bid.index, path: tree.path(Number(bid.index)) },
4385
+ pad: padNote(seed, this.reserve("notes")),
4386
+ dummySeed: drawDummySeed(),
4387
+ fee,
4388
+ eph: drawEph(),
4389
+ };
4390
+ const filler = () => hexBytes(fillerEnc());
4391
+ const planFor = (encs) => settlePlan({ ...base, encs }).catch((err) => {
4392
+ throw new EsseyError("INVALID_ARGUMENT", err instanceof Error ? err.message.slice(0, 200) : "unknown");
4393
+ });
4394
+ const draft = await planFor([filler(), filler(), filler(), filler()]);
4547
4395
  const encSeller = sealOpening({ ...draft.sellerNote, index: sellerIndex }, noteEncKey(seed).encPub);
4548
- const encs = [hexBytes(encSeller), hexBytes(fillerEnc())];
4396
+ const encs = [hexBytes(encSeller), filler(), filler(), filler()];
4549
4397
  const w = await planFor(encs);
4550
4398
  const proof = (await this.prover().prove("sale_settle", w.input)).proof;
4551
4399
  return this.freeLoan(finishBody, {
@@ -4557,26 +4405,6 @@ export class Essey {
4557
4405
  encs,
4558
4406
  });
4559
4407
  }
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
- }
4580
4408
  indexOfSellerKey(seed, sellerSk) {
4581
4409
  const n = readState(this.statePath, this.stateKey).notes ?? 0;
4582
4410
  for (let i = n - 1; i >= 0; i--)
@@ -4592,48 +4420,36 @@ export class Essey {
4592
4420
  }
4593
4421
  async cancelSale(roomId, vault) {
4594
4422
  const room = await this.saleRoom(roomId, "cancel");
4595
- if (room.state !== SALE_STATE.open || room.bids.length > 0)
4596
- throw new EsseyError("INVALID_ARGUMENT", "only an open room with no bid cancels");
4423
+ if (room.legacy)
4424
+ refuseRetiredProof("room");
4425
+ if (room.state !== SALE_STATE.open)
4426
+ throw new EsseyError("INVALID_ARGUMENT", "only an open room cancels");
4597
4427
  // `sale_room::action_hash` is `loan::action_hash`'s encoding over `sale_key` (`sale_room.move:528-529`).
4598
4428
  const pass = await this.borrowerPass({ loan_key: room.saleKey, nonce: room.nonce }, "cancel", new Uint8Array());
4599
4429
  return this.freeLoan(cancelBody, { pool: room.coin, room: room.id, vault, pass });
4600
4430
  }
4601
- async reclaimBid(roomId, record, what) {
4602
- const room = await this.saleRoom(roomId, "reclaim");
4603
- if (room.state !== SALE_STATE.settled && room.state !== SALE_STATE.expired)
4604
- throw new EsseyError("INVALID_ARGUMENT", "the room has not ended");
4431
+ /**
4432
+ * Freeze §3.5: a won bid's change is `Note(amount - v, ownerPk_w, Poseidon2(DOM_RBLIND, ns_w))`, a note under the
4433
+ * bid's own key that no ciphertext names. It is found by its commitment and held (or swept) as an own note.
4434
+ */
4435
+ async collectBidChange(record, sweep) {
4436
+ const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
4437
+ const room = await this.saleRoom(record.room, "claim");
4438
+ if (room.state !== SALE_STATE.settled)
4439
+ throw new EsseyError("INVALID_ARGUMENT", "the room has not settled");
4440
+ const value = record.amount - record.v;
4441
+ if (value <= 0n)
4442
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the bid covered the price exactly");
4605
4443
  const seed = this.seed();
4606
- const relayer = this.relayerAddress();
4607
- const relayerFee = this.coinFee(room.coin);
4608
- const fee = await this.feeParams(room.coin);
4609
- await this.keys();
4610
- const outIndex = this.reserve("notes");
4611
- const out = deriveNoteKey(seed, outIndex);
4612
- const eph = drawEph();
4613
- const planFor = (encs) => saleReclaim({
4614
- room: { saleKey: room.saleKey, locks: room.bids.map((b) => b.lock), residual: room.residual },
4615
- bid: this.bidSecrets(seed, record),
4616
- what,
4617
- out: { pk: notePk(out.sk), blinding: out.blinding },
4618
- relayer,
4619
- relayerFee,
4620
- encs,
4621
- fee,
4622
- eph,
4623
- });
4624
- const draft = await planFor([new Uint8Array(128), new Uint8Array(128)]);
4625
- const encOut = sealOpening({ value: draft.outAmt, blinding: out.blinding, index: outIndex }, noteEncKey(seed).encPub);
4626
- const encs = [hexBytes(encOut), hexBytes(fillerEnc())];
4627
- const w = await planFor(encs);
4628
- const proof = (await this.prover().prove("reclaim", w.input)).proof;
4629
- const landed = await this.paidLoan(reclaimBody, {
4630
- pool: room.coin,
4631
- room: room.id,
4632
- proved: { proof, publicSignals: w.publics.map(String) },
4633
- statement: w.statement,
4634
- encs,
4635
- });
4636
- return { ...landed, value: w.outAmt };
4444
+ const own = deriveNoteKey(seed, record.noteIndex);
4445
+ const blinding = poseidonHash([DOM_RBLIND, bidSecrets(own).ns]);
4446
+ const events = await pools(room.coin);
4447
+ const commitment = noteCommitment(value, notePk(own.sk), blinding);
4448
+ const leaf = events.commitments.find((c) => c.commitment === commitment);
4449
+ if (!leaf)
4450
+ unknownObject("no change note of this bid is in the pool: another bid won, or it is not indexed yet");
4451
+ const note = { value, sk: own.sk, blinding, index: Number(leaf.index) };
4452
+ return this.take(room.coin, events, { ...note, key: record.noteIndex }, sweep);
4637
4453
  }
4638
4454
  async claimItem(p) {
4639
4455
  if (!p.bid === !p.seller)
@@ -4648,6 +4464,8 @@ export class Essey {
4648
4464
  if (claim === null)
4649
4465
  throw new EsseyError("INVALID_ARGUMENT", "the vault holds no claim yet");
4650
4466
  const room = await this.saleRoom(String(json.room_id), "claim");
4467
+ if (room.legacy)
4468
+ refuseRetiredProof("room");
4651
4469
  let holder;
4652
4470
  if (p.bid) {
4653
4471
  const own = this.bidSecrets(this.seed(), p.bid);