@esseyonsui/sui-sdk-v3 0.1.9 → 0.2.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 (50) hide show
  1. package/dist/config.d.ts +2 -0
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/config.js +8 -1
  4. package/dist/errors.d.ts +1 -1
  5. package/dist/errors.d.ts.map +1 -1
  6. package/dist/errors.js +1 -0
  7. package/dist/essey.d.ts +177 -55
  8. package/dist/essey.d.ts.map +1 -1
  9. package/dist/essey.js +549 -233
  10. package/dist/index.d.ts +2 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -0
  13. package/dist/network.d.ts +8 -0
  14. package/dist/network.d.ts.map +1 -1
  15. package/dist/network.js +23 -0
  16. package/dist/v3/collateral/math.d.ts +6 -0
  17. package/dist/v3/collateral/math.d.ts.map +1 -1
  18. package/dist/v3/collateral/math.js +12 -0
  19. package/dist/v3/credential/membership.d.ts +2 -0
  20. package/dist/v3/credential/membership.d.ts.map +1 -1
  21. package/dist/v3/credential/membership.js +4 -0
  22. package/dist/v3/fees.d.ts +6 -0
  23. package/dist/v3/fees.d.ts.map +1 -1
  24. package/dist/v3/loans/offer-plan.d.ts +1 -1
  25. package/dist/v3/loans/offer-plan.d.ts.map +1 -1
  26. package/dist/v3/loans/offer-plan.js +5 -4
  27. package/dist/v3/loans/open-plan.d.ts +7 -3
  28. package/dist/v3/loans/open-plan.d.ts.map +1 -1
  29. package/dist/v3/loans/open-plan.js +11 -3
  30. package/dist/v3/notes/derive.d.ts +7 -0
  31. package/dist/v3/notes/derive.d.ts.map +1 -1
  32. package/dist/v3/notes/derive.js +10 -0
  33. package/dist/v3/notes/opening.d.ts +22 -1
  34. package/dist/v3/notes/opening.d.ts.map +1 -1
  35. package/dist/v3/notes/opening.js +55 -22
  36. package/dist/v3/notes/scan.d.ts +20 -3
  37. package/dist/v3/notes/scan.d.ts.map +1 -1
  38. package/dist/v3/notes/scan.js +59 -16
  39. package/dist/v3/notes/withdraw.d.ts +2 -0
  40. package/dist/v3/notes/withdraw.d.ts.map +1 -1
  41. package/dist/v3/notes/withdraw.js +9 -0
  42. package/dist/v3/pace.d.ts +1 -1
  43. package/dist/v3/pace.js +1 -1
  44. package/dist/v3/stage1.d.ts +5 -2
  45. package/dist/v3/stage1.d.ts.map +1 -1
  46. package/dist/v3/stage1.js +17 -6
  47. package/dist/v3/time-grid.d.ts +22 -2
  48. package/dist/v3/time-grid.d.ts.map +1 -1
  49. package/dist/v3/time-grid.js +44 -8
  50. package/package.json +1 -1
package/dist/essey.js CHANGED
@@ -1,23 +1,25 @@
1
- import { randomBytes } from "node:crypto";
1
+ import { randomBytes, randomInt } from "node:crypto";
2
2
  import { closeSync, existsSync, fstatSync, lstatSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
3
3
  import { dirname } from "node:path";
4
4
  import { fromBase64, normalizeSuiAddress } from "@mysten/sui/utils";
5
5
  import { poseidonHash } from "@mysten/sui/zklogin";
6
+ import { xchacha20poly1305 } from "@noble/ciphers/chacha.js";
7
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
6
8
  import { blake2b } from "@noble/hashes/blake2.js";
7
9
  import { COINS, loadConfig } from "./config.js";
8
10
  import { EsseyError, isEsseyError } from "./errors.js";
9
11
  import { keeperSection, } from "./keeper.js";
10
- import { address, assertTestnet, decimal, getJson, postJson, serviceUrl } from "./network.js";
12
+ import { address, assertTestnet, decimal, fixedHeaders, getJson, postJson, serviceUrl, } from "./network.js";
11
13
  import { credentialSigned, parseCredential, renewOpensAt, requestCredential, solveChallenge, } from "./v3/credential/issue.js";
12
- import { DOMAIN_KEEPER, DOMAIN_SENDER, DOMAIN_SPEND, FEE_PARAMS_ROOM, memberCommitment, } from "./v3/credential/membership.js";
14
+ import { DOMAIN_KEEPER, DOMAIN_SENDER, DOMAIN_SPEND, FEE_PARAMS_ROOM, feeNonceLane, memberCommitment, } from "./v3/credential/membership.js";
13
15
  import { passProof, transfer as transferBody, withdraw as withdrawBody, } from "./v3/bodies.js";
14
16
  import { cancel as cancelLoan, slash as slashLoan, ctFault as ctFaultLoan, cancelRefi as cancelRefiLoan, claimDefault as claimDefaultLoan, offer as offerLoan, open as openLoan, reclaim as reclaimLoan, reclaimColl as reclaimCollLoan, refinance as refinanceLoan, settleRefi as settleRefiLoan, repay as repayLoan, settle as settleLoan, } from "./v3/loans/bodies.js";
15
17
  import { DOM_LBLIND, DOM_TSALT, R } from "./v3/domains.js";
16
18
  import { MODE_OPEN, MODE_TOPUP, NO_ADDRESS, collLockExt } from "./v3/ext.js";
17
19
  import { defaultExt, faultExt, heartbeatExt, liquidateExt, openExt, releaseExt, topupByBorrowerExt, topupExt, } from "./v3/collateral/ext.js";
18
20
  import { claimDefault as claimDefaultBody, faultLiquidate as faultLiquidateBody, heartbeat as heartbeatBody, liquidate as liquidateBody, release as releaseBody, topup as topupBody, topupBorrower as topupBorrowerBody, } from "./v3/collateral/bodies.js";
19
- import { GRACE_S, heartbeatFloor } from "./v3/collateral/math.js";
20
- import { heartbeatHour, settleNowS } from "./v3/time-grid.js";
21
+ import { GRACE_S, coverExpiry, heartbeatFloor } from "./v3/collateral/math.js";
22
+ import { assertLoanGrid, assertRequestClose, assertRequestTerm, assertSaleGrid, defaultNowS, settleNowS, } from "./v3/time-grid.js";
21
23
  /**
22
24
  * The Seal servers dry-run `keeper::check_loan` and answer "does not have access" when it aborts: a heartbeat still
23
25
  * covers the loan at this price, the loan is not active, or the pass or badge does not match.
@@ -32,8 +34,9 @@ function keeperRefusal(err) {
32
34
  const HB_GAP_MS = 3000000n;
33
35
  const HB_GAP_STANDIN_MS = 120000n;
34
36
  const H_MAX_MS = 86400000n;
35
- const FIND_LOAN_TRIES = 15;
36
- const FIND_LOAN_PAUSE_MS = 1_500;
37
+ const FIND_LISTED_TRIES = 15;
38
+ const FIND_LISTED_PAUSE_MS = 1_500;
39
+ const STALE_REQUEST_MS = 86_400_000;
37
40
  import { MODE, NO_TERMS, health, lenderAmount, loanRisk, seizeIsLast, seizeSplit, } from "./v3/collateral/health.js";
38
41
  import { collLockPk, collNote, outputBlind, requestCommit, termsCommit, } from "./v3/collateral/openings.js";
39
42
  import { fetchKeeperPlaintext, keeperKeyId, openingOf, rollTo } from "./v3/collateral/seal.js";
@@ -52,7 +55,7 @@ import { proveFaucet } from "./v3/faucet.js";
52
55
  import { ecdhBlind, feeCommit, feeOf, treasuryPoint, verifyFeeOpening, } from "./v3/fees.js";
53
56
  import { JS4_LEVELS, deposit as depositInput, js4, membership, } from "./v3/inputs.js";
54
57
  import { marketRates } from "./v3/market.js";
55
- import { afterPage, assertLoanOpen, assertRoomMatches, assertSaleOpen, coinByPool, listPositions, openPosition, poolId, requireSale, summarizeLoan, summarizeRoom, viewLoanObject, viewPosition, viewRoomObject, } from "./v3/stage1.js";
58
+ import { afterPage, assertLoanOpen, assertRoomMatches, assertSaleOpen, coinByPool, openPosition, poolId, requireSale, summarizeLoan, summarizeRoom, viewLoanObject, viewPosition, viewRoomObject, } from "./v3/stage1.js";
56
59
  import { plan as settlePlan } from "./v3/sales/auctioneer.js";
57
60
  import { lockBid } from "./v3/sales/bid.js";
58
61
  import { bidBody, cancelBody, claimBody, expireBody, finishBody, reclaimBody, slashBody, } from "./v3/sales/bodies.js";
@@ -64,17 +67,19 @@ import { bidAad, bidKeyId, bidPlaintext, openBid, sealBidBind } from "./v3/sales
64
67
  import { assertFinishWindow, openArgs, openCommits, typeNameOf } from "./v3/sales/seller.js";
65
68
  import { splitDenominations } from "./v3/notes/denominations.js";
66
69
  import { DEPOSIT_ROOM, carriesKind, depositKind, executeSponsored, sponsor, } from "./v3/notes/deposit.js";
67
- import { SEED_BYTES, deriveNoteKey, depositSigner, noteEncKey } from "./v3/notes/derive.js";
70
+ import { SEED_BYTES, deriveNoteKey, depositSigner, itemHolder, noteEncKey, receiveKey, } from "./v3/notes/derive.js";
68
71
  import { faucetGrant } from "./v3/notes/faucet.js";
69
72
  import { noteCommitment, noteNullifier, notePk } from "./v3/notes/keys.js";
70
- import { fillerEnc, sealOpening } from "./v3/notes/opening.js";
71
- import { orderedLeaves, ownNotes, ownOpenings, usedIndices, } from "./v3/notes/scan.js";
73
+ import { fillerEnc, sealOpening, sealOpening2 } from "./v3/notes/opening.js";
74
+ import { heldStatus, orderedLeaves, ownNotes, ownOpenings, usedIndices, } from "./v3/notes/scan.js";
72
75
  import { poolTree } from "./v3/notes/tree.js";
73
- import { exitKept, exitPieces, exitValue, piecePayees, pickInputs, refuseLinkedAmount, refuseUncovered, transferValue, withdrawCost, withdrawPieces, } from "./v3/notes/withdraw.js";
76
+ import { exitKept, exitPieces, exitValue, paidTag, piecePayees, pickInputs, refuseLinkedAmount, refuseUncovered, transferValue, withdrawCost, withdrawPieces, } from "./v3/notes/withdraw.js";
74
77
  import { paceDelay } from "./v3/pace.js";
75
78
  import { proofBytes } from "./v3/proof-bytes.js";
76
79
  import { RelayClient, failure, } from "./v3/relay/client.js";
77
80
  import { provePossession } from "./v3/relay/possession.js";
81
+ const SETTLE_READS = 15;
82
+ const SETTLE_READ_MS = 2_000;
78
83
  /** A ticket lives 15 min (`services/relayer-v3/src/tickets.ts:7`); a minute past it the relayer answers "expired". */
79
84
  const FOLLOW_CAP_MS = 16 * 60_000;
80
85
  /** Times a seize output's collect waits again while nothing has landed after the seizure. */
@@ -82,7 +87,6 @@ const SEIZE_REWAITS = 3;
82
87
  /** The relayer's 202 after its wait cap can carry an etaMs near 0 (LOAD-02), which would spend every poll in seconds. */
83
88
  const FOLLOW_MIN_GAP_MS = 2_000;
84
89
  const SPENT_POLLS = 60;
85
- const MAX_USED_SENDERS = 64;
86
90
  const EPH_SHIFT = 3n;
87
91
  const NO_RELAYER = "no relayer url: the deployment record names none yet; nothing was sent";
88
92
  const NO_RELAYER_ADDRESS = "no relayer address: the deployment record names none yet; nothing was sent";
@@ -107,6 +111,14 @@ function unknownObject(what) {
107
111
  function wrongCoinObject() {
108
112
  throw new EsseyError("INVALID_ARGUMENT", "wrong coin: the envelope pool is not the loan coin");
109
113
  }
114
+ function readRequestPlain(plain) {
115
+ try {
116
+ return decodeRequest(plain);
117
+ }
118
+ catch (err) {
119
+ throw new EsseyError("CT_MISMATCH", `refused: ${err instanceof Error ? err.message.slice(0, 200) : "unknown"}`);
120
+ }
121
+ }
110
122
  const isIndex = (n) => Number.isSafeInteger(n) && n >= 0;
111
123
  const isSigned = (c, s) => c.commitment === s.commitment && c.enc === s.enc;
112
124
  const landedIn = (events, r) => events.commitments.some((c) => r.signed.some((s) => isSigned(c, s)));
@@ -132,6 +144,18 @@ function parseStranded(raw) {
132
144
  const signed = r.signed.map(parseSigned);
133
145
  return { coin: r.coin, signer: r.signer, note: r.note, value, signed };
134
146
  }
147
+ function parseHeld(raw) {
148
+ const r = (raw ?? {});
149
+ const field = (v) => (typeof v === "string" && /^(0|[1-9][0-9]*)$/.test(v) ? BigInt(v) : R);
150
+ const [value, blinding] = [field(r.value), field(r.blinding)];
151
+ if (!COINS.includes(r.coin) ||
152
+ !isIndex(r.key) ||
153
+ !isIndex(r.index) ||
154
+ value >= 1n << 64n ||
155
+ blinding >= R)
156
+ throw new Error("held");
157
+ return { coin: r.coin, key: r.key, value, blinding, index: r.index };
158
+ }
135
159
  function parseSigned(raw) {
136
160
  const { commitment, enc } = (raw ?? {});
137
161
  if (typeof commitment !== "string" || typeof enc !== "string" || !/^0x[0-9a-f]+$/.test(enc))
@@ -161,13 +185,32 @@ function stateText(path) {
161
185
  Atomics.wait(pause, 0, 0, 1);
162
186
  }
163
187
  }
164
- function readState(path) {
188
+ const SEALED_AAD = new TextEncoder().encode("essey-v3 state v2");
189
+ const SEAL_NONCE = 24;
190
+ /** PRV-36a: the whole state as `{"v":2,"sealed":<base64 nonce ‖ XChaCha20-Poly1305>}` under the caller's state key. */
191
+ function sealState(key, text) {
192
+ const nonce = randomBytes(SEAL_NONCE);
193
+ const box = xchacha20poly1305(key, nonce, SEALED_AAD).encrypt(new TextEncoder().encode(text));
194
+ return JSON.stringify({ v: 2, sealed: Buffer.concat([nonce, box]).toString("base64") });
195
+ }
196
+ /** A v1 file is plain (read with or without a key, resealed by `connect`); a v2 file opens only under its key. */
197
+ function stateJson(text, key) {
198
+ const raw = JSON.parse(text);
199
+ if (raw.v !== 2)
200
+ return raw;
201
+ if (!key)
202
+ throw new EsseyError("STATE_REFUSED", "refused: the state file is sealed; connect with its stateKey");
203
+ const bytes = Buffer.from(String(raw.sealed), "base64");
204
+ const box = xchacha20poly1305(key, bytes.subarray(0, SEAL_NONCE), SEALED_AAD);
205
+ return JSON.parse(new TextDecoder().decode(box.decrypt(bytes.subarray(SEAL_NONCE))));
206
+ }
207
+ function readState(path, key) {
165
208
  if (!existsSync(path))
166
209
  return { v: 1 };
167
210
  if ((statSync(path).mode & 0o077) !== 0)
168
211
  throw new EsseyError("STATE_REFUSED", "refused: the state file must be mode 600");
169
212
  try {
170
- const raw = JSON.parse(stateText(path));
213
+ const raw = stateJson(stateText(path), key);
171
214
  if (raw.v !== 1)
172
215
  throw new Error("version");
173
216
  const m = raw.member;
@@ -177,11 +220,17 @@ function readState(path) {
177
220
  const credential = raw.credential === undefined ? undefined : parseCredential(raw.credential);
178
221
  if (raw.seed !== undefined && !(typeof raw.seed === "string" && /^[0-9a-f]{64}$/.test(raw.seed)))
179
222
  throw new Error("seed");
180
- const counters = [raw.notes, raw.signers];
223
+ const counters = [raw.notes, raw.signers, raw.holders];
181
224
  if (counters.some((n) => n !== undefined && !isIndex(n)))
182
225
  throw new Error("counter");
183
226
  if (raw.stranded !== undefined && !Array.isArray(raw.stranded))
184
227
  throw new Error("stranded");
228
+ if (raw.held !== undefined && !Array.isArray(raw.held))
229
+ throw new Error("held");
230
+ const paid = raw.paid;
231
+ if (paid !== undefined &&
232
+ !(Array.isArray(paid) && paid.every((t) => typeof t === "string" && /^[0-9a-f]{64}$/.test(t))))
233
+ throw new Error("paid");
185
234
  return {
186
235
  v: 1,
187
236
  member,
@@ -190,11 +239,16 @@ function readState(path) {
190
239
  seed: raw.seed,
191
240
  notes: raw.notes,
192
241
  signers: raw.signers,
242
+ holders: raw.holders,
193
243
  stranded: raw.stranded?.map(parseStranded),
194
244
  badge: raw.badge === undefined ? undefined : parseBadge(raw.badge),
245
+ held: raw.held?.map(parseHeld),
246
+ paid: paid,
195
247
  };
196
248
  }
197
- catch {
249
+ catch (error) {
250
+ if (isEsseyError(error, "STATE_REFUSED"))
251
+ throw error;
198
252
  throw new EsseyError("STATE_REFUSED", "refused: the state file is not readable as SDK state");
199
253
  }
200
254
  }
@@ -202,12 +256,12 @@ function readState(path) {
202
256
  * Written beside the target and renamed over it, so a failure leaves the old file whole. "wx" refuses
203
257
  * an existing name instead of following a planted link with the member secrets.
204
258
  */
205
- function writeState(path, state, held) {
259
+ function writeState(path, state, held, key) {
206
260
  const tmp = `${path}.${randomBytes(16).toString("hex")}.tmp`;
207
261
  const fd = openSync(tmp, "wx", 0o600);
208
262
  try {
209
263
  try {
210
- writeFileSync(fd, toJson(state));
264
+ writeFileSync(fd, key ? sealState(key, toJson(state)) : toJson(state));
211
265
  }
212
266
  finally {
213
267
  closeSync(fd);
@@ -549,16 +603,41 @@ function partial(error, landed, pieces, stranded) {
549
603
  * `address()` pads a short value and takes zero, and `pool::withdraw` pays what it is given
550
604
  * (`move/v3/pool/sources/pool.move:312`).
551
605
  */
552
- const RECEIVE_PREFIX = "v3note:";
553
- /** `v3note:<pk decimal>:<33-byte compressed enc key hex>:<index>`, as `notes.receiveAddress` writes it. */
606
+ const RECEIVE_PREFIX = "v3note2:";
607
+ const NOT_RECEIVE = "to is not a v3note receive address; nothing was sent";
608
+ const POINT = "((?:02|03)[0-9a-f]{64})";
609
+ function point(hex) {
610
+ try {
611
+ secp256k1.Point.fromHex(hex).assertValidity();
612
+ }
613
+ catch {
614
+ throw new EsseyError("INVALID_ARGUMENT", NOT_RECEIVE);
615
+ }
616
+ return Uint8Array.from(Buffer.from(hex, "hex"));
617
+ }
618
+ /**
619
+ * `v3note2:<pk 64 hex>:<C>:<D>` as `notes.receiveAddress` writes it (SCOPE-PRV34 §2.2), or an older
620
+ * `v3note:<pk decimal>:<enc key>:<index>`. A compressed point cannot encode the identity, so the format refuses it.
621
+ */
554
622
  function receiveTarget(to) {
555
- const m = typeof to === "string" ? /^v3note:([0-9]{1,78}):((?:02|03)[0-9a-f]{64}):([0-9]{1,15})$/.exec(to) : null;
556
- if (!m)
557
- throw new EsseyError("INVALID_ARGUMENT", "to is not a v3note receive address; nothing was sent");
558
- const pk = BigInt(m[1]);
623
+ const v1 = typeof to === "string" ? new RegExp(`^v3note:([0-9]{1,78}):${POINT}:([0-9]{1,15})$`).exec(to) : null;
624
+ const v2 = typeof to === "string" ? new RegExp(`^v3note2:([0-9a-f]{64}):${POINT}:${POINT}$`).exec(to) : null;
625
+ if (!v1 && !v2)
626
+ throw new EsseyError("INVALID_ARGUMENT", NOT_RECEIVE);
627
+ const pk = BigInt(v1 ? v1[1] : `0x${v2[1]}`);
559
628
  if (pk >= R)
560
- throw new EsseyError("INVALID_ARGUMENT", "to is not a v3note receive address; nothing was sent");
561
- return { pk, encPub: Uint8Array.from(Buffer.from(m[2], "hex")), index: Number(m[3]) };
629
+ throw new EsseyError("INVALID_ARGUMENT", NOT_RECEIVE);
630
+ if (v1)
631
+ return { pk, encPub: point(v1[2]), index: Number(v1[3]) };
632
+ if (v2[2] === v2[3])
633
+ throw new EsseyError("INVALID_ARGUMENT", NOT_RECEIVE);
634
+ return { pk, C: point(v2[2]), D: point(v2[3]) };
635
+ }
636
+ const paidBefore = () => new EsseyError("INVALID_ARGUMENT", "refused: this state already paid that one-use address; nothing was sent");
637
+ function sealPaid(to, value, blinding) {
638
+ return "index" in to
639
+ ? sealOpening({ value, blinding, index: to.index }, to.encPub)
640
+ : sealOpening2({ value, blinding }, to);
562
641
  }
563
642
  function payee(to) {
564
643
  if (typeof to !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(to))
@@ -569,6 +648,7 @@ function payee(to) {
569
648
  return recipient;
570
649
  }
571
650
  const listOf = (to) => (Array.isArray(to) ? to : [to]);
651
+ const piecesTo = (pieces, to) => pieces.map((amount, i) => ({ amount, to: to[i] }));
572
652
  function onePayee(to) {
573
653
  const list = listOf(to);
574
654
  if (list.length !== 1)
@@ -576,7 +656,7 @@ function onePayee(to) {
576
656
  return list[0];
577
657
  }
578
658
  /** Pieces already paid are public and final; the error lists them so none is paid twice. */
579
- function payoutStopped(error, paid, pieces) {
659
+ function payoutStopped(error, paid, rest) {
580
660
  if (paid.length === 0)
581
661
  return error;
582
662
  const at = paid.length + 1;
@@ -586,11 +666,11 @@ function payoutStopped(error, paid, pieces) {
586
666
  : error instanceof Error
587
667
  ? error.message
588
668
  : "it threw";
589
- const stopped = new EsseyError(inner?.code ?? "RELAY_FAILED", `withdraw stopped at piece ${at} of ${pieces.length}: ${why}. Pieces paid before it: ${paid.length}, listed in detail.landed; do not pay them again`, {
669
+ const stopped = new EsseyError(inner?.code ?? "RELAY_FAILED", `withdraw stopped at piece ${at} of ${paid.length + rest.length}: ${why}. Pieces paid before it: ${paid.length}, listed in detail.landed; do not pay them again`, {
590
670
  ...inner?.detail,
591
671
  landed: paid.map((p) => ({ digest: p.digest, value: p.amount.toString(), to: p.to })),
592
- stopped: pieces[paid.length].toString(),
593
- untried: pieces.slice(at).map(String),
672
+ stopped: rest[0].toString(),
673
+ untried: rest.slice(1).map(String),
594
674
  });
595
675
  stopped.cause = error;
596
676
  return stopped;
@@ -622,6 +702,7 @@ export class Essey {
622
702
  relayerBase;
623
703
  seedOption;
624
704
  pacing;
705
+ stateKey;
625
706
  credential;
626
707
  fees;
627
708
  relayer;
@@ -631,9 +712,11 @@ export class Essey {
631
712
  /** D-SPEC §6.2:598-600. Sealed sale rooms. */
632
713
  sales;
633
714
  keeper;
634
- /** Each pass over the fee room carries the same tag, so one fetch per coin per commit is all v3api sees. */
715
+ /** Each pass over the fee room carries the same tag, so one fetch per coin, lane and commit is all v3api sees. */
635
716
  feeOpenings = new Map();
636
- constructor(config, statePath, apiOrigin, fetch, io, relay, relayerBase, seedOption, pacing) {
717
+ /** Loan snapshot openings by `coin:commit`, apart from `feeOpenings`, which follows the config as it stands. */
718
+ snapshotOpenings = new Map();
719
+ constructor(config, statePath, apiOrigin, fetch, io, relay, relayerBase, seedOption, pacing, stateKey) {
637
720
  this.config = config;
638
721
  this.statePath = statePath;
639
722
  this.apiOrigin = apiOrigin;
@@ -643,17 +726,18 @@ export class Essey {
643
726
  this.relayerBase = relayerBase;
644
727
  this.seedOption = seedOption;
645
728
  this.pacing = pacing;
729
+ this.stateKey = stateKey;
646
730
  const closeOf = (loan) => () => this.roundDeadline(loan, "close_ms");
647
731
  const settleByOf = (loan) => () => this.roundDeadline(loan, "settle_by_ms");
648
732
  const coverOf = (loan) => () => this.coverDeadline(loan);
649
733
  this.credential = {
650
734
  obtain: (o) => this.obtain(o?.invite, o?.role ?? "member"),
651
- status: () => this.info(readState(this.statePath).credential),
735
+ status: () => this.info(readState(this.statePath, this.stateKey).credential),
652
736
  list: () => this.listCredentials(),
653
737
  view: () => this.viewCredential(),
654
738
  renew: () => this.renew(),
655
739
  };
656
- this.fees = { params: (coin) => this.feeParams(coin) };
740
+ this.fees = { params: (coin, lane) => this.feeParams(coin, lane) };
657
741
  this.relayer = {
658
742
  info: async () => this.relayClient().info(),
659
743
  status: async (ticket) => this.relayClient().status(ticket),
@@ -665,6 +749,8 @@ export class Essey {
665
749
  offer: (p) => this.paidLoan(offerLoan, p),
666
750
  request: (id) => this.readRequest(id),
667
751
  lend: async (p) => {
752
+ await this.refuseStaleRequest(p.loan);
753
+ await this.refuseOffGridClose(p.loan);
668
754
  const send = async () => {
669
755
  await this.pause("offer", p.loan, closeOf(p.loan));
670
756
  const { body, record, seq } = await this.planOffer(p.loan, BigInt(p.rateBps));
@@ -683,12 +769,14 @@ export class Essey {
683
769
  return (await send()).sent;
684
770
  }
685
771
  },
686
- collect: (p) => this.paced("collect", p.loan, null, () => this.collect(p.loan, p.offer)),
687
- collectSeized: (p) => this.paced("collect_seized", p.loan, null, () => this.collectSeized(p.loan, p.offer)),
688
- collectSurplus: (p) => this.paced("collect_surplus", p.loan, null, () => this.collectSurplus(p)),
689
- accept: (id) => this.paced("settle", id, settleByOf(id), async () => {
690
- const { body, rateBps, terms, borrowerPk, collAmt } = await this.planSettle(id);
691
- return { ...(await this.freeLoan(settleLoan, body)), rateBps, terms, borrowerPk, collAmt };
772
+ collect: (p) => this.collecting("collect", p, (sweep) => this.collect(p.loan, p.offer, sweep)),
773
+ collectSeized: (p) => this.collecting("collect_seized", p, (sweep) => this.collectSeized(p.loan, p.offer, sweep)),
774
+ collectSurplus: (p) => this.collecting("collect_surplus", p, (sweep) => this.collectSurplus(p, sweep)),
775
+ accept: (p) => this.paced("settle", p.loan, settleByOf(p.loan), async () => {
776
+ const { body, rateBps, terms, borrowerPk, collAmt } = await this.planSettle(p.loan, p.collAmt);
777
+ const landed = await this.freeLoan(settleLoan, body);
778
+ const cover = await this.firstCover({ loan: p.loan, terms, borrowerPk, collAmt });
779
+ return { ...landed, rateBps, terms, borrowerPk, collAmt, cover };
692
780
  }),
693
781
  release: (p) => this.paced("release", p.loan, null, () => this.releaseCollateral(p.loan, p.terms, p.borrowerPk, p.collAmt)),
694
782
  cancelOwn: (id) => this.cancelOwn(id),
@@ -696,7 +784,10 @@ export class Essey {
696
784
  fault: (p) => this.paced("fault", p.loan, null, () => this.ctFault(p.loan, p.via)),
697
785
  openRefi: (p) => this.openRefi(p),
698
786
  cancelRefi: (id) => this.cancelRefiOwn(id),
699
- settleRefi: (p) => this.paced("settle", p.loan, settleByOf(p.loan), () => this.settleRefiOwn(p)),
787
+ settleRefi: (p) => this.paced("settle", p.loan, settleByOf(p.loan), async () => {
788
+ const settled = await this.settleRefiOwn(p);
789
+ return { ...settled, cover: await this.firstCover({ ...p, terms: settled.terms }) };
790
+ }),
700
791
  reclaimOffer: (p) => this.paced("reclaim_offer", p.loan, null, () => this.reclaimOffer(p.loan, p.offer, p.round)),
701
792
  heartbeat: (p) => this.paced("heartbeat", p.loan, coverOf(p.loan), () => this.heartbeatOwn(p)),
702
793
  topup: (p) => this.paced("topup", p.loan, coverOf(p.loan), () => this.topupOwn(p)),
@@ -723,13 +814,23 @@ export class Essey {
723
814
  open: (coin, index) => this.openNote(coin, index),
724
815
  list: (coin) => this.listNotes(coin),
725
816
  view: (coin, index) => this.viewNote(coin, index),
726
- withdraw: async (coin, amount, to, o = {}) => {
817
+ withdrawFirst: async (coin, amount, to, o = {}) => {
727
818
  const plan = this.withdrawPlan(coin, amount, to, o);
728
- return this.paced("withdraw", `${coin}:${amount}:${to}`, null, () => this.withdraw(coin, plan, o));
819
+ this.refusePaid(to, o);
820
+ return this.paced("withdraw", `${coin}:${amount}:${to}`, null, () => this.withdrawStart(coin, plan, o));
729
821
  },
822
+ withdraw: async (coin, amount, to, o) => this.drain(await this.notes.withdrawFirst(coin, amount, to, o)),
823
+ payNext: (pending) => this.payNext(pending),
730
824
  receiveAddress: () => this.receiveAddress(),
731
825
  transfer: (coin, amount, to) => this.paced("transfer", `${coin}:${amount}:${to}`, null, () => this.transfer(coin, amount, to)),
732
- exit: (coin, to, o) => this.paced("exit", `${coin}:${to}`, null, () => this.exit(coin, to, o)),
826
+ exitFirst: async (coin, to, o = {}) => {
827
+ this.refusePaid(to, o);
828
+ return this.paced("exit", `${coin}:${to}`, null, () => this.exitStart(coin, to, o));
829
+ },
830
+ exit: async (coin, to, o) => {
831
+ const first = await this.notes.exitFirst(coin, to, o);
832
+ return { payouts: await this.drain(first), kept: first.kept };
833
+ },
733
834
  recoverStranded: () => this.recoverStranded(),
734
835
  };
735
836
  this.sales = {
@@ -742,8 +843,9 @@ export class Essey {
742
843
  expire: (p) => this.expireSale(p.room, p.vault),
743
844
  reclaim: (p) => this.paced("sale_reclaim", p.room, null, () => this.reclaimBid(p.room, p.bid, p.what ?? "lock")),
744
845
  claim: (p) => this.claimItem(p),
846
+ itemAddress: () => this.itemAddress(),
745
847
  cancel: (p) => this.cancelSale(p.room, p.vault),
746
- badgeGrant: (to) => this.badgeGrant(to),
848
+ badgeGrant: (to) => this.badgeGrant(to ?? this.itemAddress()),
747
849
  };
748
850
  this.keeper = {
749
851
  ...keeperSection(io.keeper, io.now ?? Date.now),
@@ -754,15 +856,21 @@ export class Essey {
754
856
  }
755
857
  static async connect(o, io = {}) {
756
858
  assertTestnet(o.network);
757
- const fetch = io.fetch ?? ((url, init) => globalThis.fetch(url, init));
859
+ const fetch = fixedHeaders(io.fetch ?? ((url, init) => globalThis.fetch(url, init)));
758
860
  if (o.seed !== undefined && !(o.seed instanceof Uint8Array && o.seed.length === SEED_BYTES))
759
861
  throw new EsseyError("INVALID_ARGUMENT", "seed must be 32 bytes");
760
- readState(o.statePath);
862
+ if (o.stateKey !== undefined && !(o.stateKey instanceof Uint8Array && o.stateKey.length === 32))
863
+ throw new EsseyError("INVALID_ARGUMENT", "stateKey must be 32 bytes");
864
+ const stateKey = o.stateKey && Uint8Array.from(o.stateKey);
865
+ readState(o.statePath, stateKey);
761
866
  const { config, apiOrigin } = await loadConfig(o.config, fetch);
762
867
  const url = relayerUrl(o.relayer ?? "clear", config);
763
868
  const relay = url === null ? null : new RelayClient({ url, fetch });
764
869
  const relayerBase = url === null ? null : serviceUrl(url, "relayer url").origin;
765
- return new Essey(config, o.statePath, apiOrigin, fetch, io, relay, relayerBase, o.seed && Uint8Array.from(o.seed), pacingOf(o.delays));
870
+ const essey = new Essey(config, o.statePath, apiOrigin, fetch, io, relay, relayerBase, o.seed && Uint8Array.from(o.seed), pacingOf(o.delays), stateKey);
871
+ if (stateKey && existsSync(o.statePath) && JSON.parse(stateText(o.statePath)).v === 1)
872
+ essey.update(() => { });
873
+ return essey;
766
874
  }
767
875
  paced(action, subject, deadline, run) {
768
876
  return this.pause(action, subject, deadline).then(run);
@@ -774,12 +882,25 @@ export class Essey {
774
882
  const at = deadline ? await deadline() : null;
775
883
  const nowMs = (this.io.now ?? Date.now)();
776
884
  const delayMs = paceDelay(action, nowMs, at, Number(CLOSE_MARGIN_MS));
777
- const wait = this.io.pace ?? ((p) => this.sleep(p.delayMs));
778
- await wait({ action, subject, delayMs, notBeforeMs: nowMs + delayMs });
885
+ await this.waitOut({ action, subject, delayMs, notBeforeMs: nowMs + delayMs });
886
+ }
887
+ waitOut(p) {
888
+ return (this.io.pace ?? ((q) => this.sleep(q.delayMs)))(p);
889
+ }
890
+ /** PRV-11: when the next piece of a split payout may go, a long-class draw after this one. */
891
+ pieceAt() {
892
+ const nowMs = (this.io.now ?? Date.now)();
893
+ if (!this.pacing)
894
+ return nowMs;
895
+ return nowMs + paceDelay("withdraw_piece", nowMs, null, Number(CLOSE_MARGIN_MS));
779
896
  }
780
897
  sleep(ms) {
781
898
  return (this.io.sleep ?? ((t) => new Promise((resolve) => setTimeout(resolve, t))))(ms);
782
899
  }
900
+ /** PRV-08: only a sweep sends a transaction, so only a sweep waits; a held note waits for the spend that takes it. */
901
+ collecting(action, p, run) {
902
+ return p.sweep === true ? this.paced(action, p.loan, null, () => run(true)) : run(false);
903
+ }
783
904
  /** The current round's `close_ms` (offers, `loan.move:339`) or `settle_by_ms` (settles, `settle.move:132`). */
784
905
  async roundDeadline(loanId, field) {
785
906
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
@@ -787,6 +908,26 @@ export class Essey {
787
908
  const at = row?.round?.[field];
788
909
  return at === undefined ? null : { atMs: Number(at) };
789
910
  }
911
+ /**
912
+ * PRV-03 stopgap (Erik, Nov 30): a request hides its collateral, and round-0 settle does not re-check the LTV
913
+ * (`loan_settle.circom` has no OverLine), so an offer on bidding that opened over 24 h ago is refused up front.
914
+ */
915
+ async refuseStaleRequest(loanId) {
916
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
917
+ const row = await read(address(loanId, "loan id"));
918
+ const round = Number(row?.json?.round ?? -1);
919
+ const opened = Number(row?.round?.opened_ms ?? NaN);
920
+ if (round !== 0 || !(opened + STALE_REQUEST_MS < (this.io.now ?? Date.now)()))
921
+ return;
922
+ throw new EsseyError("REQUEST_STALE", "refused: this loan's bidding opened over 24 h ago, so its open-time loan-to-value is too old to rely on; nothing was sent");
923
+ }
924
+ async refuseOffGridClose(loanId) {
925
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
926
+ const row = await read(address(loanId, "loan id"));
927
+ const close = row?.round?.close_ms;
928
+ if (close !== undefined)
929
+ assertRequestClose(BigInt(String(close)), this.config.closeStepMs ?? HOUR_MS);
930
+ }
790
931
  /** The stored heartbeat expiry, past which a keeper may liquidate (`keeper.move:204`); none before a first heartbeat. */
791
932
  async coverDeadline(loanId) {
792
933
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
@@ -829,10 +970,10 @@ export class Essey {
829
970
  */
830
971
  update(change) {
831
972
  return withLock(this.statePath, (file, held) => {
832
- const state = readState(file);
973
+ const state = readState(file, this.stateKey);
833
974
  this.ownSeed(state);
834
975
  const result = change(state);
835
- writeState(file, state, held);
976
+ writeState(file, state, held, this.stateKey);
836
977
  return result;
837
978
  });
838
979
  }
@@ -847,7 +988,7 @@ export class Essey {
847
988
  return this.issue(api, member, slot, role);
848
989
  }
849
990
  async renew() {
850
- const { member, slot, credential } = readState(this.statePath);
991
+ const { member, slot, credential } = readState(this.statePath, this.stateKey);
851
992
  if (!slot || !credential)
852
993
  notSetUp("no credential to renew: call credential.obtain first");
853
994
  const info = await this.issue(this.api(), member, slot, credential.role);
@@ -864,18 +1005,42 @@ export class Essey {
864
1005
  return this.info(credential);
865
1006
  }
866
1007
  /** The opening for one coin, returned only after it matches the commit read from chain (D §5.4). */
867
- async feeParams(coin) {
1008
+ async feeParams(coin, asked = "hidden") {
868
1009
  if (!COINS.includes(coin))
869
1010
  throw new EsseyError("INVALID_ARGUMENT", "coin is not tusdsui, usdc or sui");
1011
+ const lane = this.feeLane(coin, asked);
1012
+ const readFeeCommit = this.io.readFeeCommit ?? notSetUp("no chain reader: the FeeConfig objects are not published yet");
1013
+ const key = `${coin}:${lane}`;
1014
+ const held = this.feeOpenings.get(key);
1015
+ if (held && feeCommit(held) === (await readFeeCommit(coin, lane)))
1016
+ return held;
1017
+ const body = await this.feePass("/v3/fee-params", { coin, ...(lane === "edge" ? { lane } : {}) });
1018
+ const params = verifyFeeOpening(body, await readFeeCommit(coin, lane));
1019
+ this.feeOpenings.set(key, params);
1020
+ return params;
1021
+ }
1022
+ /**
1023
+ * PRV-02: a loan step folds the loan's own snapshot (`loan.move:141-143`), not the config as it stands, so its
1024
+ * opening is fetched by that commit (v3api's archive) and must hash to it.
1025
+ */
1026
+ async loanFee(coin, snapshot) {
1027
+ const commit = BigInt(String(snapshot));
1028
+ const key = `${coin}:${commit}`;
1029
+ const held = this.snapshotOpenings.get(key);
1030
+ if (held)
1031
+ return held;
1032
+ const body = await this.feePass("/v3/fee-params/opening", { coin, commit: commit.toString() });
1033
+ const params = verifyFeeOpening(body, commit);
1034
+ this.snapshotOpenings.set(key, params);
1035
+ return params;
1036
+ }
1037
+ /** One fee-params pass (`FEE_PARAMS_ROOM`, bound to a fresh challenge) carrying `fields`; the reply body. */
1038
+ async feePass(path, fields) {
870
1039
  const api = this.api();
871
- const { member, credential } = readState(this.statePath);
1040
+ const { member, credential } = readState(this.statePath, this.stateKey);
872
1041
  if (!member || !credential)
873
1042
  notSetUp("no credential: call credential.obtain first");
874
1043
  const prover = this.io.prover ?? this.missingProver("membership");
875
- const readFeeCommit = this.io.readFeeCommit ?? notSetUp("no chain reader: the FeeConfig objects are not published yet");
876
- const held = this.feeOpenings.get(coin);
877
- if (held && feeCommit(held) === (await readFeeCommit(coin)))
878
- return held;
879
1044
  const challenge = await getJson(this.fetch, `${api}/v3/fee-params/challenge`);
880
1045
  const nonce = challenge.body.nonce;
881
1046
  if (challenge.status !== 200 || typeof nonce !== "string")
@@ -887,18 +1052,27 @@ export class Essey {
887
1052
  domain: credential.role === "keeper" ? DOMAIN_KEEPER : DOMAIN_SENDER,
888
1053
  room: FEE_PARAMS_ROOM,
889
1054
  bind: nonce,
1055
+ nonce: feeNonceLane(nonce),
890
1056
  });
891
- const reply = await postJson(this.fetch, `${api}/v3/fee-params`, {
892
- coin,
1057
+ const reply = await postJson(this.fetch, `${api}${path}`, {
1058
+ ...fields,
893
1059
  nonce,
894
1060
  publicInputs: publics.map(String),
895
1061
  proof: passProof(await prover.prove("membership", input)),
896
1062
  });
897
- if (reply.status !== 200 || reply.body.ok !== true || reply.body.coin !== coin)
1063
+ if (reply.status !== 200 || reply.body.ok !== true || reply.body.coin !== fields.coin)
898
1064
  throw refusedBy("v3api", reply);
899
- const params = verifyFeeOpening(reply.body, await readFeeCommit(coin));
900
- this.feeOpenings.set(coin, params);
901
- return params;
1065
+ return reply.body;
1066
+ }
1067
+ /** The edge lane only once the record names the coin's edge config; before that the pool takes its pinned one. */
1068
+ feeLane(coin, asked) {
1069
+ return asked === "edge" && this.config.objects.edgeFeeConfigs?.[coin] ? "edge" : "hidden";
1070
+ }
1071
+ feeConfigId(coin, lane) {
1072
+ const ids = this.feeLane(coin, lane) === "edge"
1073
+ ? this.config.objects.edgeFeeConfigs
1074
+ : this.config.objects.feeConfigs;
1075
+ return ids?.[coin];
902
1076
  }
903
1077
  async rates(market) {
904
1078
  const id = address(market, "market");
@@ -911,14 +1085,14 @@ export class Essey {
911
1085
  */
912
1086
  seed() {
913
1087
  if (this.seedOption) {
914
- this.ownSeed(readState(this.statePath));
1088
+ this.ownSeed(readState(this.statePath, this.stateKey));
915
1089
  return this.seedOption;
916
1090
  }
917
- const stored = readState(this.statePath).seed ??
1091
+ const stored = readState(this.statePath, this.stateKey).seed ??
918
1092
  this.update((s) => {
919
1093
  if (s.seed !== undefined)
920
1094
  return s.seed;
921
- if (s.notes || s.signers || s.stranded?.length)
1095
+ if (s.notes || s.signers || s.holders || s.stranded?.length)
922
1096
  throw new EsseyError("STATE_REFUSED", NO_SEED);
923
1097
  return (s.seed = randomBytes(SEED_BYTES).toString("hex"));
924
1098
  });
@@ -934,27 +1108,24 @@ export class Essey {
934
1108
  const { encKey } = noteEncKey(seed);
935
1109
  let next = 0;
936
1110
  for (const coin of COINS)
937
- for (const used of usedIndices(await read(coin), seed, encKey))
1111
+ for (const used of usedIndices(await read(coin), seed, encKey, this.noteNext()))
938
1112
  next = Math.max(next, used + 1);
939
- if (next > (readState(this.statePath).notes ?? 0))
1113
+ if (next > (readState(this.statePath, this.stateKey).notes ?? 0))
940
1114
  this.update((s) => {
941
1115
  s.notes = Math.max(next, s.notes ?? 0);
942
1116
  });
943
1117
  return seed;
944
1118
  }
945
- addressUsed() {
946
- if (this.io.readAddressUsed || !this.seedOption)
947
- return this.io.readAddressUsed;
948
- return notSetUp("no readAddressUsed: a seed option may have used a deposit sender");
949
- }
950
- /** A deposit sender the chain has never seen, so no two deposits share one. */
951
- async freshSigner(seed, used) {
952
- for (let i = 0; i < MAX_USED_SENDERS; i++) {
953
- const signer = this.reserve("signers");
954
- if (!used || !(await used(depositSigner(seed, signer).toSuiAddress())))
955
- return signer;
956
- }
957
- throw new EsseyError("STATE_REFUSED", "refused: every deposit sender tried is already used; nothing was sent");
1119
+ /**
1120
+ * PRV-07 b (decided Nov 30): a sender index no lookup has to vouch for. A fresh state starts at a random u48, so a
1121
+ * restored seed lands far from the indexes it used before; the next index is on disk before this one is used.
1122
+ */
1123
+ freshSigner() {
1124
+ return this.update((state) => {
1125
+ const index = state.signers ?? (this.io.signerStart ?? (() => randomInt(2 ** 20, 2 ** 48 - 1)))();
1126
+ state.signers = index + 1;
1127
+ return index;
1128
+ });
958
1129
  }
959
1130
  /** Write-ahead: a deposit is on disk as stranded before its value moves, and leaves once it has landed. */
960
1131
  strand(s, on) {
@@ -987,7 +1158,7 @@ export class Essey {
987
1158
  });
988
1159
  }
989
1160
  member() {
990
- const { member, credential } = readState(this.statePath);
1161
+ const { member, credential } = readState(this.statePath, this.stateKey);
991
1162
  if (!member || !credential)
992
1163
  notSetUp("no credential: call credential.obtain first");
993
1164
  return { secrets: member, credential: credential };
@@ -1016,7 +1187,7 @@ export class Essey {
1016
1187
  const { secrets, credential } = this.member();
1017
1188
  const prover = this.prover();
1018
1189
  const seed = await this.keys();
1019
- const fee = await this.feeParams(coinOf(coin));
1190
+ const fee = await this.feeParams(coinOf(coin), "edge");
1020
1191
  const value = faucetGrant(coin);
1021
1192
  const index = this.reserve("notes");
1022
1193
  const keys = deriveNoteKey(seed, index);
@@ -1074,7 +1245,6 @@ export class Essey {
1074
1245
  const pieces = (denominations ?? list !== undefined) ? splitDenominations(amount, list ?? []) : [amount];
1075
1246
  const relayer = this.sponsorRelayer();
1076
1247
  const fund = this.io.fundDeposit ?? notSetUp("no fundDeposit: the SDK never holds the paying wallet");
1077
- const used = this.addressUsed();
1078
1248
  const seed = await this.keys();
1079
1249
  const read = this.io.readPool;
1080
1250
  const ctx = await this.depositContext(coin);
@@ -1082,7 +1252,7 @@ export class Essey {
1082
1252
  for (const value of pieces) {
1083
1253
  let signer;
1084
1254
  try {
1085
- signer = await this.freshSigner(seed, used);
1255
+ signer = this.freshSigner();
1086
1256
  const note = this.reserve("notes");
1087
1257
  const piece = { coin, signer, note, value, signed: [] };
1088
1258
  const { digest, ticket } = (await this.depositPiece(ctx, seed, piece, relayer, read, fund));
@@ -1097,13 +1267,13 @@ export class Essey {
1097
1267
  async depositContext(coin) {
1098
1268
  const pkg = this.config.packages.pool;
1099
1269
  const poolId = this.config.objects.pools[coin];
1100
- const feeConfigId = this.config.objects.feeConfigs?.[coin];
1270
+ const feeConfigId = this.feeConfigId(coin, "edge");
1101
1271
  if (!pkg || !poolId || !feeConfigId)
1102
1272
  notSetUp("the pool is not published yet");
1103
1273
  const readShared = this.io.readSharedVersion ?? notSetUp("no chain reader for shared object versions");
1104
1274
  const { secrets, credential } = this.member();
1105
1275
  const prover = this.prover();
1106
- const fee = await this.feeParams(coin);
1276
+ const fee = await this.feeParams(coin, "edge");
1107
1277
  return {
1108
1278
  pkg: pkg,
1109
1279
  coinType: this.config.coins[coin].type,
@@ -1205,7 +1375,7 @@ export class Essey {
1205
1375
  const seed = this.seed();
1206
1376
  const outcomes = [];
1207
1377
  let unsent = false;
1208
- for (const piece of readState(this.statePath).stranded ?? []) {
1378
+ for (const piece of readState(this.statePath, this.stateKey).stranded ?? []) {
1209
1379
  try {
1210
1380
  const outcome = await this.recoverOne(piece, seed, read, relayer);
1211
1381
  if (outcome)
@@ -1259,7 +1429,7 @@ export class Essey {
1259
1429
  return { ...record, outcome: sent.inPool ? "landed" : "unconfirmed", digest: sent.digest };
1260
1430
  }
1261
1431
  record(signer) {
1262
- return readState(this.statePath).stranded?.find((r) => r.signer === signer);
1432
+ return readState(this.statePath, this.stateKey).stranded?.find((r) => r.signer === signer);
1263
1433
  }
1264
1434
  /** A state file that cannot be read may hold the record, so it counts as held. */
1265
1435
  strandedAt(signer) {
@@ -1297,7 +1467,27 @@ export class Essey {
1297
1467
  const read = this.io.readPool ?? notSetUp("no pool reader: the pool events are read by the caller");
1298
1468
  const seed = this.seed();
1299
1469
  const events = await read(coin);
1300
- return { events, owned: ownNotes(events, seed, noteEncKey(seed).encKey), seed };
1470
+ return { events, owned: this.ownedIn(coin, events, seed), seed };
1471
+ }
1472
+ /** The scan's notes, then each held note of `coin` whose leaf is in `events` unspent. */
1473
+ ownedIn(coin, events, seed) {
1474
+ const scanned = ownNotes(events, seed, noteEncKey(seed).encKey, this.noteNext());
1475
+ const held = (readState(this.statePath, this.stateKey).held ?? []).flatMap((h) => {
1476
+ if (h.coin !== coin || scanned.some((n) => n.index === h.index))
1477
+ return [];
1478
+ const { status, sk } = heldStatus(events, seed, h);
1479
+ return status === "live" ? [{ value: h.value, sk, blinding: h.blinding, index: h.index }] : [];
1480
+ });
1481
+ return [...scanned, ...held];
1482
+ }
1483
+ /** Records a found note for the next spend; held notes of `coin` the read pool shows spent are dropped. */
1484
+ hold(coin, events, note) {
1485
+ const seed = this.seed();
1486
+ this.update((state) => {
1487
+ const kept = (state.held ?? []).filter((h) => h.coin !== coin || (h.index !== note.index && heldStatus(events, seed, h).status !== "spent"));
1488
+ state.held = [...kept, note];
1489
+ });
1490
+ return { held: true, value: note.value };
1301
1491
  }
1302
1492
  async scan(coin) {
1303
1493
  const summary = {};
@@ -1318,13 +1508,13 @@ export class Essey {
1318
1508
  const pieces = withdrawPieces(amount, list);
1319
1509
  return { amount, pieces, sendTo: piecePayees(pieces.length, payees) };
1320
1510
  }
1321
- async withdraw(coin, plan, o) {
1511
+ async withdrawStart(coin, plan, o) {
1322
1512
  if ("exact" in plan)
1323
- return [await this.withdrawExact(coin, plan.amount, plan.exact, o)];
1513
+ return { paid: await this.withdrawExact(coin, plan.amount, plan.exact, o), pending: null };
1324
1514
  const { fee, relayerFee, owned } = await this.payoutPlan(coin);
1325
1515
  refuseUncovered(owned, plan.pieces, fee, relayerFee);
1326
1516
  refuseLinkedAmount(plan.amount, faucetGrant(coin), owned, fee, relayerFee);
1327
- return this.payPieces(coin, plan.pieces, plan.sendTo, fee);
1517
+ return this.payPiece(coin, piecesTo(plan.pieces, plan.sendTo), fee);
1328
1518
  }
1329
1519
  async withdrawExact(coin, amount, to, o) {
1330
1520
  const landed = await this.spend(coin, { to }, (owned, rates, relayerFee) => {
@@ -1333,7 +1523,27 @@ export class Essey {
1333
1523
  refuseLinkedAmount(amount, faucetGrant(coin), owned, rates, relayerFee);
1334
1524
  return { value: amount, inputs };
1335
1525
  });
1336
- return { ...landed, amount, to: payee(to) };
1526
+ return this.paidTo(landed, amount, to);
1527
+ }
1528
+ /** PRV-11: a reused payee joins two payouts on chain. With no tag on disk this reads no seed and writes nothing. */
1529
+ refusePaid(to, o) {
1530
+ if (o.allowReuse === true)
1531
+ return;
1532
+ const paid = readState(this.statePath, this.stateKey).paid;
1533
+ if (!paid)
1534
+ return;
1535
+ const seed = this.seed();
1536
+ if (listOf(to).some((t) => paid.includes(paidTag(seed, payee(t)))))
1537
+ throw new EsseyError("INVALID_ARGUMENT", "refused: to lists an address this seed already paid in an earlier withdraw, which links the two on chain; use a fresh address. nothing was sent");
1538
+ }
1539
+ paidTo(landed, amount, to) {
1540
+ const address = payee(to);
1541
+ const tag = paidTag(this.seed(), address);
1542
+ this.update((s) => {
1543
+ if (!s.paid?.includes(tag))
1544
+ s.paid = [...(s.paid ?? []), tag];
1545
+ });
1546
+ return { ...landed, amount, to: address };
1337
1547
  }
1338
1548
  /** The same reads and set-up checks `spend` makes, once for every piece of a split payout. */
1339
1549
  async payoutPlan(coin) {
@@ -1341,27 +1551,52 @@ export class Essey {
1341
1551
  this.relayerAddress();
1342
1552
  this.prover();
1343
1553
  const relayerFee = this.coinFee(coin);
1344
- const fee = await this.feeParams(coin);
1554
+ const fee = await this.feeParams(coin, "edge");
1345
1555
  const { owned } = await this.owned(coin);
1346
1556
  return { fee, relayerFee, owned };
1347
1557
  }
1348
- /** The one loop over a payout's pieces, where a wait between them belongs. Each reads the pool after the last is seen spent. */
1349
- async payPieces(coin, pieces, to, fee) {
1350
- const paid = [];
1558
+ /** Pays `pieces[0]`; the rest come back as `pending`, due a long-class time from now. */
1559
+ async payPiece(coin, pieces, fee) {
1560
+ const [{ amount, to }, ...rest] = pieces;
1351
1561
  let spent = [];
1352
- for (const [i, amount] of pieces.entries()) {
1562
+ const landed = await this.spend(coin, { to }, (owned, rates, relayerFee) => {
1563
+ spent = pickInputs(owned, withdrawCost(amount, rates, relayerFee));
1564
+ return { value: amount, inputs: spent };
1565
+ }, [], fee);
1566
+ const paid = this.paidTo(landed, amount, to);
1567
+ if (rest.length === 0)
1568
+ return { paid, pending: null };
1569
+ return {
1570
+ paid,
1571
+ pending: { coin, pieces: rest, notBeforeMs: this.pieceAt(), spent: spent.map((n) => n.index) },
1572
+ };
1573
+ }
1574
+ async payNext(p) {
1575
+ if (p.pieces.length === 0)
1576
+ throw new EsseyError("INVALID_ARGUMENT", "refused: no piece is pending");
1577
+ await this.awaitSpent(coinOf(p.coin), p.spent);
1578
+ return this.payPiece(p.coin, p.pieces);
1579
+ }
1580
+ /** The in-process schedule: each pending piece waits out its `notBeforeMs` through `io.pace`, then goes. */
1581
+ async drain(first) {
1582
+ const paid = [first.paid];
1583
+ for (let p = first.pending; p !== null;) {
1584
+ const due = p;
1353
1585
  try {
1354
- if (i > 0)
1355
- await this.pause("withdraw_piece", `${coin}:${to[i]}`, null);
1356
- await this.awaitSpent(coin, spent);
1357
- const landed = await this.spend(coin, { to: to[i] }, (owned, rates, relayerFee) => {
1358
- spent = pickInputs(owned, withdrawCost(amount, rates, relayerFee));
1359
- return { value: amount, inputs: spent };
1360
- }, [], fee);
1361
- paid.push({ ...landed, amount, to: to[i] });
1586
+ const nowMs = (this.io.now ?? Date.now)();
1587
+ if (this.pacing)
1588
+ await this.waitOut({
1589
+ action: "withdraw_piece",
1590
+ subject: `${due.coin}:${due.pieces[0].to}`,
1591
+ delayMs: Math.max(0, due.notBeforeMs - nowMs),
1592
+ notBeforeMs: due.notBeforeMs,
1593
+ });
1594
+ const next = await this.payNext(due);
1595
+ paid.push(next.paid);
1596
+ p = next.pending;
1362
1597
  }
1363
1598
  catch (error) {
1364
- throw payoutStopped(error, paid, pieces);
1599
+ throw payoutStopped(error, paid, due.pieces.map((x) => x.amount));
1365
1600
  }
1366
1601
  }
1367
1602
  return paid;
@@ -1372,7 +1607,7 @@ export class Essey {
1372
1607
  const sleep = this.io.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1373
1608
  for (let i = 0; i < SPENT_POLLS; i++) {
1374
1609
  const { owned } = await this.owned(coin);
1375
- if (!owned.some((n) => spent.some((s) => s.index === n.index)))
1610
+ if (!owned.some((n) => spent.includes(n.index)))
1376
1611
  return;
1377
1612
  await sleep(FOLLOW_MIN_GAP_MS);
1378
1613
  }
@@ -1383,19 +1618,40 @@ export class Essey {
1383
1618
  receiveAddress() {
1384
1619
  const seed = this.seed();
1385
1620
  const index = this.reserve("notes");
1386
- const pk = notePk(deriveNoteKey(seed, index).sk);
1387
- return `${RECEIVE_PREFIX}${pk}:${Buffer.from(noteEncKey(seed).encPub).toString("hex")}:${index}`;
1621
+ const pk = notePk(deriveNoteKey(seed, index).sk).toString(16).padStart(64, "0");
1622
+ const { C, D } = receiveKey(seed, index);
1623
+ return `${RECEIVE_PREFIX}${pk}:${Buffer.from(C).toString("hex")}:${Buffer.from(D).toString("hex")}`;
1624
+ }
1625
+ noteNext() {
1626
+ return readState(this.statePath, this.stateKey).notes ?? 0;
1627
+ }
1628
+ itemAddress() {
1629
+ return itemHolder(this.seed(), this.reserve("holders")).toSuiAddress();
1630
+ }
1631
+ holderOf(owner) {
1632
+ const count = readState(this.statePath, this.stateKey).holders ?? 0;
1633
+ if (owner === null || count === 0)
1634
+ return null;
1635
+ const seed = this.seed();
1636
+ const at = normalizeSuiAddress(owner);
1637
+ for (let i = 0; i < count; i++)
1638
+ if (itemHolder(seed, i).toSuiAddress() === at)
1639
+ return i;
1640
+ return null;
1388
1641
  }
1389
1642
  async transfer(coin, amount, to) {
1390
1643
  if (amount <= 0n)
1391
1644
  throw new EsseyError("INVALID_ARGUMENT", "amount must be above 0");
1392
1645
  const payTo = receiveTarget(to);
1393
- return this.spend(coin, { payTo }, (owned, rates, relayerFee) => ({
1646
+ const mark = paidTag(this.seed(), to);
1647
+ if (readState(this.statePath, this.stateKey).paid?.includes(mark))
1648
+ throw paidBefore();
1649
+ return this.spend(coin, { payTo, mark }, (owned, rates, relayerFee) => ({
1394
1650
  value: amount,
1395
1651
  inputs: pickInputs(owned, withdrawCost(amount, rates, relayerFee)),
1396
1652
  }));
1397
1653
  }
1398
- async exit(coin, to, o = {}) {
1654
+ async exitStart(coin, to, o) {
1399
1655
  const list = this.config.denominations[coinOf(coin)];
1400
1656
  if (list === undefined || o.force === true)
1401
1657
  return this.exitExact(coin, onePayee(to), o);
@@ -1409,8 +1665,8 @@ export class Essey {
1409
1665
  refuseUncovered(owned, pieces, fee, relayerFee);
1410
1666
  const value = pieces.reduce((sum, piece) => sum + piece, 0n);
1411
1667
  refuseLinkedAmount(value, faucetGrant(coin), owned, fee, relayerFee);
1412
- const payouts = await this.payPieces(coin, pieces, sendTo, fee);
1413
- return { payouts, kept: exitKept(total, pieces, fee, relayerFee) };
1668
+ const first = await this.payPiece(coin, piecesTo(pieces, sendTo), fee);
1669
+ return { ...first, kept: exitKept(total, pieces, fee, relayerFee) };
1414
1670
  }
1415
1671
  async exitExact(coin, to, o) {
1416
1672
  let value = 0n;
@@ -1427,7 +1683,7 @@ export class Essey {
1427
1683
  kept = total - withdrawCost(value, rates, relayerFee);
1428
1684
  return { value, inputs: owned };
1429
1685
  });
1430
- return { payouts: [{ ...landed, amount: value, to: payee(to) }], kept };
1686
+ return { paid: this.paidTo(landed, value, to), pending: null, kept };
1431
1687
  }
1432
1688
  /** js4 with the withdraw field (`src/v3/inputs.ts:39`); the change note's index is on disk before the body leaves. */
1433
1689
  async spend(coin, dest, choose, extra = [], known) {
@@ -1436,7 +1692,7 @@ export class Essey {
1436
1692
  const relay = this.relayClient();
1437
1693
  const relayer = this.relayerAddress();
1438
1694
  const prover = this.prover();
1439
- const fee = known ?? (await this.feeParams(coin));
1695
+ const fee = known ?? (await this.feeParams(coin, "edge"));
1440
1696
  const { events, owned, seed } = await this.owned(coin);
1441
1697
  const { value, inputs } = choose([...owned, ...extra], fee, relayerFee);
1442
1698
  const tree = poolTree(orderedLeaves(events));
@@ -1468,9 +1724,7 @@ export class Essey {
1468
1724
  const changeValue = BigInt(js.input.outAmount1);
1469
1725
  const encChange = sealOpening({ value: changeValue, blinding: change.blinding, index }, noteEncKey(seed).encPub);
1470
1726
  const proved = await prover.prove("js4", js.input);
1471
- const encPaid = "payTo" in dest
1472
- ? sealOpening({ value, blinding: paidBlinding, index: dest.payTo.index }, dest.payTo.encPub)
1473
- : fillerEnc();
1727
+ const encPaid = "payTo" in dest ? sealPaid(dest.payTo, value, paidBlinding) : fillerEnc();
1474
1728
  const body = ("payTo" in dest ? transferBody : withdrawBody)({
1475
1729
  pool: coin,
1476
1730
  proved: { proof: proved.proof, publicSignals: js.publics.map(String) },
@@ -1479,9 +1733,19 @@ export class Essey {
1479
1733
  relayerFee,
1480
1734
  wait: true,
1481
1735
  });
1736
+ if ("payTo" in dest && dest.mark)
1737
+ this.markPaid(dest.mark);
1482
1738
  const sent = await relay.submit(body);
1483
1739
  return "digest" in sent ? sent : this.follow(relay, sent, "withdraw");
1484
1740
  }
1741
+ /** PRV-34 write-ahead: an address is marked paid before the body leaves, so a second payment to it never does. */
1742
+ markPaid(mark) {
1743
+ this.update((s) => {
1744
+ if (s.paid?.includes(mark))
1745
+ throw paidBefore();
1746
+ s.paid = [...(s.paid ?? []), mark];
1747
+ });
1748
+ }
1485
1749
  /** A 202 carries no digest (`src/v3/relay/client.ts:100`): the ticket is followed until it lands. */
1486
1750
  async follow(relay, queued, what) {
1487
1751
  const gap = Math.max(queued.etaMs, FOLLOW_MIN_GAP_MS);
@@ -1526,7 +1790,7 @@ export class Essey {
1526
1790
  return (await this.checkedCredential()) ?? unknownObject("no credential is stored");
1527
1791
  }
1528
1792
  async checkedCredential() {
1529
- const { member, credential } = readState(this.statePath);
1793
+ const { member, credential } = readState(this.statePath, this.stateKey);
1530
1794
  if (!credential)
1531
1795
  return null;
1532
1796
  if (!member)
@@ -1552,7 +1816,7 @@ export class Essey {
1552
1816
  const out = [];
1553
1817
  for (const c of coins) {
1554
1818
  const { events, seed } = await this.poolOf(c);
1555
- out.push(...listPositions(c, events, seed));
1819
+ out.push(...this.ownedIn(c, events, seed).map((n) => ({ coin: c, index: n.index, value: n.value })));
1556
1820
  }
1557
1821
  return out;
1558
1822
  }
@@ -1564,6 +1828,7 @@ export class Essey {
1564
1828
  /** D-SPEC §6.2:588. The envelope is `v3.loans.open`; the id is whatever the digest created. */
1565
1829
  async openRequest(p) {
1566
1830
  assertLoanOpen(p);
1831
+ assertLoanGrid(p, this.config.closeStepMs ?? HOUR_MS);
1567
1832
  poolId(this.config, p.loanCoin);
1568
1833
  poolId(this.config, p.collateralCoin);
1569
1834
  if (this.config.relayer.url === null)
@@ -1575,30 +1840,37 @@ export class Essey {
1575
1840
  if (proved.pool !== p.loanCoin)
1576
1841
  wrongCoinObject();
1577
1842
  const landed = await this.paidLoan(openLoan, { ...proved, wait: true });
1578
- return { ...landed, id: await this.loanByKey(proved.loanKey) };
1843
+ const read = this.io.readLoans;
1844
+ const row = await this.listedByKey("loan", "loan_key", proved.loanKey, async (c) => {
1845
+ const page = await read(c);
1846
+ return { rows: page.loans, next: page.next };
1847
+ });
1848
+ return { ...landed, id: row.id };
1579
1849
  }
1580
- /** PRV-07: the new loan is found among all loans by the key the borrower chose, not by its own digest. */
1581
- async loanByKey(loanKey) {
1582
- const read = this.io.readLoans ?? notSetUp("missing config: no loan reader");
1583
- for (let attempt = 0; attempt < FIND_LOAN_TRIES; attempt++) {
1850
+ /**
1851
+ * PRV-07: what an open created is found among every listed object of its kind by the key its opener chose
1852
+ * (`field`), never by the opener's own digest.
1853
+ */
1854
+ async listedByKey(what, field, key, read) {
1855
+ for (let attempt = 0; attempt < FIND_LISTED_TRIES; attempt++) {
1584
1856
  if (attempt > 0)
1585
- await this.sleep(FIND_LOAN_PAUSE_MS);
1857
+ await this.sleep(FIND_LISTED_PAUSE_MS);
1586
1858
  let cursor = null;
1587
1859
  let pages = 0;
1588
1860
  for (;;) {
1589
1861
  const page = await read(cursor);
1590
1862
  pages += 1;
1591
- const row = page.loans.find((l) => l.json?.loan_key?.toString() === `${loanKey}`);
1863
+ const row = page.rows.find((l) => l.json?.[field]?.toString() === `${key}`);
1592
1864
  if (row && !/^0x[0-9a-fA-F]{64}$/.test(row.id))
1593
- unknownObject("the listed loan id is not an object id");
1865
+ unknownObject(`the listed ${what} id is not an object id`);
1594
1866
  if (row)
1595
- return address(row.id, "loan id");
1867
+ return { id: address(row.id, `${what} id`), json: row.json };
1596
1868
  cursor = afterPage(page.next, pages);
1597
1869
  if (cursor === null)
1598
1870
  break;
1599
1871
  }
1600
1872
  }
1601
- return unknownObject("the open landed, but no listed loan carries its key yet");
1873
+ return unknownObject(`the open landed, but no listed ${what} carries its key yet`);
1602
1874
  }
1603
1875
  /**
1604
1876
  * The borrower's `loan_open`: a CollLock spend of up to two own notes into the lock, the Health OPEN rows, the
@@ -1612,7 +1884,7 @@ export class Essey {
1612
1884
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
1613
1885
  const readPrice = this.io.readPrice ?? notSetUp("missing config: no price reader");
1614
1886
  const update = this.io.priceUpdate ?? notSetUp("missing config: no price update source");
1615
- const { member, credential } = readState(this.statePath);
1887
+ const { member, credential } = readState(this.statePath, this.stateKey);
1616
1888
  if (!member || !credential)
1617
1889
  notSetUp("no credential: call credential.obtain first");
1618
1890
  const relayer = this.relayerAddress();
@@ -1651,8 +1923,6 @@ export class Essey {
1651
1923
  data: requestPlaintext({
1652
1924
  ...request,
1653
1925
  borrowerPk,
1654
- collAmt: p.collateral,
1655
- collBlind: own.blinding,
1656
1926
  closeMs,
1657
1927
  market,
1658
1928
  coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
@@ -1752,7 +2022,7 @@ export class Essey {
1752
2022
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
1753
2023
  const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
1754
2024
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
1755
- const { member, credential } = readState(this.statePath);
2025
+ const { member, credential } = readState(this.statePath, this.stateKey);
1756
2026
  if (!member || !credential)
1757
2027
  notSetUp("no credential: call credential.obtain first");
1758
2028
  const loan = address(id, "loan id");
@@ -1803,11 +2073,8 @@ export class Essey {
1803
2073
  };
1804
2074
  },
1805
2075
  });
1806
- const q = decodeRequest(plain);
1807
- const note = collNote({ loanKey, borrowerPk: q.borrowerPk, amount: q.collAmt, blinding: q.collBlind });
1808
- const locked = refi ? json.coll.coll_note : json.collateral_commit;
1809
- if (note !== BigInt(locked))
1810
- throw new EsseyError("CT_MISMATCH", "refused: the request opens another lock");
2076
+ const q = readRequestPlain(plain);
2077
+ const note = BigInt(refi ? json.coll.coll_note : json.collateral_commit);
1811
2078
  const request = { principal: q.principal, maxRateBps: q.maxRateBps, termMs: q.termMs, salt: q.salt };
1812
2079
  if (requestCommit(request, q.borrowerPk, note) !== BigInt(round.req_commit))
1813
2080
  throw new EsseyError("CT_MISMATCH", "refused: the request does not open the loan's commit");
@@ -1820,8 +2087,6 @@ export class Essey {
1820
2087
  poolL: address(json.pool_l, "pool_l"),
1821
2088
  ...request,
1822
2089
  borrowerPk: q.borrowerPk,
1823
- collAmt: q.collAmt,
1824
- collBlind: q.collBlind,
1825
2090
  collNote: note,
1826
2091
  closeMs: q.closeMs,
1827
2092
  };
@@ -1840,17 +2105,19 @@ export class Essey {
1840
2105
  /** The lender's `loan_offer`: the principal locked to the round from up to two own notes, its sealed terms pinned. */
1841
2106
  async planOffer(loanId, rateBps) {
1842
2107
  const q = await this.readRequest(loanId, true);
2108
+ assertRequestTerm(q.termMs, this.config.closeStepMs ?? HOUR_MS);
1843
2109
  const L = q.pair[1];
1844
2110
  if (poolId(this.config, L) !== q.poolL)
1845
2111
  wrongCoinObject();
1846
2112
  if (rateBps > q.maxRateBps)
1847
2113
  throw new EsseyError("INVALID_ARGUMENT", "the rate is above the request's maximum");
1848
2114
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
1849
- const { member, credential } = readState(this.statePath);
2115
+ const { member, credential } = readState(this.statePath, this.stateKey);
1850
2116
  const relayer = this.relayerAddress();
1851
2117
  const relayerFee = this.coinFee(L);
1852
2118
  const prover = this.prover();
1853
- const fee = await this.feeParams(L);
2119
+ const row = await (this.io.readLoan ?? notSetUp("missing config: no loan reader"))(q.loan);
2120
+ const fee = await this.loanFee(L, row.json.fee_commit);
1854
2121
  const { events, owned, seed } = await this.owned(L);
1855
2122
  const inputs = pickInputs(owned, q.principal + relayerFee);
1856
2123
  const tree = poolTree(orderedLeaves(events));
@@ -1955,7 +2222,7 @@ export class Essey {
1955
2222
  /** `seal_policy::seal_approve_offer` for offer `seq`: the borrower's SEAL pass over `seal_offer` bound to the viewer. */
1956
2223
  offerApprove(loan, loanKey, round, seq, pair) {
1957
2224
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
1958
- const { member, credential } = readState(this.statePath);
2225
+ const { member, credential } = readState(this.statePath, this.stateKey);
1959
2226
  const room = keyId(loanKey);
1960
2227
  const prover = this.prover();
1961
2228
  return async (viewer) => {
@@ -2093,7 +2360,7 @@ export class Essey {
2093
2360
  if (via === "pass")
2094
2361
  return { approve: await this.keeperApprove(loan, market, id, pair) };
2095
2362
  const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
2096
- const held = readState(this.statePath).badge;
2363
+ const held = readState(this.statePath, this.stateKey).badge;
2097
2364
  if (!held || BigInt((this.io.now ?? Date.now)()) >= held.expiresMs)
2098
2365
  notSetUp("no live keeper badge: call keeper.mintBadge");
2099
2366
  const signer = depositSigner(this.seed(), held.signer);
@@ -2117,7 +2384,7 @@ export class Essey {
2117
2384
  return { approve, signer };
2118
2385
  }
2119
2386
  heldBadge() {
2120
- const held = readState(this.statePath).badge;
2387
+ const held = readState(this.statePath, this.stateKey).badge;
2121
2388
  if (!held)
2122
2389
  return null;
2123
2390
  const holder = depositSigner(this.seed(), held.signer).toSuiAddress();
@@ -2130,14 +2397,14 @@ export class Essey {
2130
2397
  async mintBadge() {
2131
2398
  const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
2132
2399
  const pkg = this.config.packages.loan ?? notSetUp("the loan package is not published yet");
2133
- const readBadge = this.io.readBadge ?? notSetUp("missing config: no badge reader");
2400
+ const readBadges = this.io.readBadges ?? notSetUp("missing config: no badge reader");
2134
2401
  const relayer = this.sponsorRelayer();
2135
2402
  const { secrets, credential } = this.member();
2136
2403
  if (credential.role !== "keeper")
2137
2404
  notSetUp("no keeper credential");
2138
2405
  const prover = this.prover();
2139
2406
  const seed = this.seed();
2140
- const index = await this.freshSigner(seed, this.io.readAddressUsed);
2407
+ const index = this.freshSigner();
2141
2408
  const signer = depositSigner(seed, index);
2142
2409
  const holder = signer.toSuiAddress();
2143
2410
  const room = keeper.registry.id;
@@ -2161,9 +2428,10 @@ export class Essey {
2161
2428
  proof: `0x${Buffer.from(proof).toString("hex")}`,
2162
2429
  };
2163
2430
  const digest = await this.sponsoredSend(signer, txKindB64, wire, relayer);
2164
- const row = await readBadge(digest);
2165
- if (!row)
2166
- throw new EsseyError("SERVICE_REFUSED", `the mint ${digest} created no badge`);
2431
+ const row = await this.listedByKey("badge", "tag", pass.publics[0], async (c) => {
2432
+ const page = await readBadges(c);
2433
+ return { rows: page.badges, next: page.next };
2434
+ });
2167
2435
  const { id, expiresMs } = badgeOf(row, { holder, registry: room });
2168
2436
  this.update((s) => {
2169
2437
  s.badge = { signer: index, id, expiresMs };
@@ -2191,7 +2459,7 @@ export class Essey {
2191
2459
  /** `keeper::seal_approve_keeper_proof`: a KEEPER pass for the deployment's keeper registry, bound to the viewer. */
2192
2460
  async keeperApprove(loan, market, id, pair) {
2193
2461
  const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
2194
- const { member, credential } = readState(this.statePath);
2462
+ const { member, credential } = readState(this.statePath, this.stateKey);
2195
2463
  if (!member || credential?.role !== "keeper")
2196
2464
  notSetUp("no keeper credential");
2197
2465
  const { price, standin } = await this.keeperFeed(market);
@@ -2255,7 +2523,7 @@ export class Essey {
2255
2523
  return decodeOffer(plain);
2256
2524
  }
2257
2525
  /** The borrower's `loan_settle` on round 0: the lowest eligible offer wins, keeper ciphertext v1 carries its terms. */
2258
- async planSettle(id) {
2526
+ async planSettle(id, collAmt) {
2259
2527
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2260
2528
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2261
2529
  const q = await this.readRequest(id);
@@ -2264,6 +2532,8 @@ export class Essey {
2264
2532
  throw new EsseyError("INVALID_ARGUMENT", "refused: the offer window is still open");
2265
2533
  const row = await read(q.loan);
2266
2534
  const json = row.json;
2535
+ const seed = this.seed();
2536
+ const { opening } = this.ownOpening(seed, json, q.borrowerPk, collAmt);
2267
2537
  const round = row.round;
2268
2538
  const slots = [];
2269
2539
  for (const [i, o] of round.offers.entries()) {
@@ -2273,11 +2543,10 @@ export class Essey {
2273
2543
  : undefined;
2274
2544
  slots.push({ commit: BigInt(o.commit), lock: BigInt(o.lock), active: o.active, open });
2275
2545
  }
2276
- const { member, credential } = readState(this.statePath);
2546
+ const { member, credential } = readState(this.statePath, this.stateKey);
2277
2547
  const L = q.pair[1];
2278
2548
  const prover = this.prover();
2279
- const fee = await this.feeParams(L);
2280
- const seed = this.seed();
2549
+ const fee = await this.loanFee(L, json.fee_commit);
2281
2550
  await this.keys();
2282
2551
  const noteIndex = this.reserve("notes");
2283
2552
  const mine = deriveNoteKey(seed, noteIndex);
@@ -2285,7 +2554,7 @@ export class Essey {
2285
2554
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2286
2555
  const plan = (extHash) => loanSettle({
2287
2556
  slots,
2288
- request: q,
2557
+ request: { ...q, collAmt: opening.amount, collBlind: opening.blinding },
2289
2558
  loanKey: q.loanKey,
2290
2559
  borrowerNote: { pk: notePk(mine.sk), blinding: mine.blinding },
2291
2560
  e: drawEph(),
@@ -2301,8 +2570,8 @@ export class Essey {
2301
2570
  version: KEEPER_LAYOUT_VERSION,
2302
2571
  loanKey: q.loanKey,
2303
2572
  borrowerPk: q.borrowerPk,
2304
- collAmt: q.collAmt,
2305
- collBlind: q.collBlind,
2573
+ collAmt: opening.amount,
2574
+ collBlind: opening.blinding,
2306
2575
  nonceAtCt: 1n,
2307
2576
  terms: draft.terms,
2308
2577
  }),
@@ -2345,7 +2614,7 @@ export class Essey {
2345
2614
  rateBps: w.terms.rateBps,
2346
2615
  terms: w.terms,
2347
2616
  borrowerPk: q.borrowerPk,
2348
- collAmt: q.collAmt,
2617
+ collAmt: opening.amount,
2349
2618
  body: {
2350
2619
  pool: L,
2351
2620
  loan: q.loan,
@@ -2389,7 +2658,7 @@ export class Essey {
2389
2658
  const relayer = this.relayerAddress();
2390
2659
  const relayerFee = this.coinFee(L);
2391
2660
  const prover = this.prover();
2392
- const fee = await this.feeParams(L);
2661
+ const fee = await this.loanFee(L, json.fee_commit);
2393
2662
  const { events, owned, seed } = await this.owned(L);
2394
2663
  const tree = poolTree(orderedLeaves(events));
2395
2664
  const inputs = pickInputs(owned, terms.owed + relayerFee + feeOf({ base: terms.owed, bps: fee.bps, min: fee.min, max: fee.max }).fee);
@@ -2448,9 +2717,9 @@ export class Essey {
2448
2717
  /**
2449
2718
  * The repaid note is `Poseidon(owed, lenderPk, H(DOM_LBLIND, S.x))` with `S = encSk · repay_eph`
2450
2719
  * (`loan_repay.circom`), and a refi payoff the same over a `payoff_eph` pair (`loan_refi.circom`); either ciphertext
2451
- * is filler, so the scan never sees it. It is spent into an own note.
2720
+ * is filler, so the scan never sees it; `owned` finds it through the state file's `held` list.
2452
2721
  */
2453
- async collect(loanId, offer) {
2722
+ async collect(loanId, offer, sweep) {
2454
2723
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2455
2724
  const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
2456
2725
  const loan = address(loanId, "loan id");
@@ -2479,14 +2748,22 @@ export class Essey {
2479
2748
  }
2480
2749
  if (!leaf)
2481
2750
  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");
2482
- return this.claimLeaf(L, events, { value: owed, sk: own.sk, blinding, index: Number(leaf.index) });
2751
+ const note = { value: owed, sk: own.sk, blinding, index: Number(leaf.index) };
2752
+ return this.take(L, events, { ...note, key: offer.noteIndex }, sweep);
2483
2753
  }
2484
- /** Spends a note no ciphertext names, found by its commitment, to the receive address. */
2485
- async claimLeaf(coin, events, note) {
2754
+ /** Refuses a spent note. `sweep` moves it to the receive address now; otherwise it is held for the next spend. */
2755
+ async take(coin, events, note, sweep) {
2486
2756
  const commitment = noteCommitment(note.value, notePk(note.sk), note.blinding);
2487
2757
  const n = noteNullifier(commitment, note.sk, BigInt(note.index));
2488
2758
  if (events.nullifiers.some((x) => BigInt(x) === n))
2489
2759
  throw new EsseyError("INVALID_ARGUMENT", "already collected");
2760
+ const { key, value, blinding, index } = note;
2761
+ if (!sweep)
2762
+ return this.hold(coin, events, { coin, key, value, blinding, index });
2763
+ return { ...(await this.claimLeaf(coin, note)), held: false };
2764
+ }
2765
+ /** Spends a note no ciphertext names, found by its commitment, to the receive address. */
2766
+ async claimLeaf(coin, note) {
2490
2767
  const payTo = receiveTarget(this.receiveAddress());
2491
2768
  let value = 0n;
2492
2769
  const landed = await this.spend(coin, { payTo }, (_owned, _rates, relayerFee) => {
@@ -2510,8 +2787,8 @@ export class Essey {
2510
2787
  };
2511
2788
  }
2512
2789
  /** B §5.5 out0 of a seizure, the lender's, from its lock opening; each heartbeat and TOPUP rolled the blinding one step. */
2513
- collectSeized(loanId, offer) {
2514
- return this.collectFromSeizure(loanId, 0, async (json, seizeNonce) => {
2790
+ collectSeized(loanId, offer, sweep) {
2791
+ const open = async (json, seizeNonce) => {
2515
2792
  const own = deriveNoteKey(this.seed(), offer.noteIndex);
2516
2793
  const lock = await this.lenderLock(json, own);
2517
2794
  let blinding = lock.blinding;
@@ -2520,18 +2797,21 @@ export class Essey {
2520
2797
  return {
2521
2798
  owed: interest(offer.principal, offer.rateBps, offer.termMs).owed,
2522
2799
  collAmt: lock.amount,
2800
+ key: offer.noteIndex,
2523
2801
  sk: own.sk,
2524
2802
  blinding,
2525
2803
  };
2526
- });
2804
+ };
2805
+ return this.collectFromSeizure(loanId, 0, open, sweep);
2527
2806
  }
2528
2807
  /** B §5.5 out1 of a seizure, the borrower's surplus `avail - seize`, from its own opening rolled to the seizing nonce. */
2529
- collectSurplus(p) {
2530
- return this.collectFromSeizure(p.loan, 1, async (json, seizeNonce) => {
2808
+ collectSurplus(p, sweep) {
2809
+ const open = async (json, seizeNonce) => {
2531
2810
  if (termsCommit(p.terms, p.borrowerPk) !== BigInt(json.terms_commit))
2532
2811
  throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
2533
2812
  const seed = this.seed();
2534
- const own = deriveNoteKey(seed, this.indexOfPk(seed, p.borrowerPk));
2813
+ const key = this.indexOfPk(seed, p.borrowerPk);
2814
+ const own = deriveNoteKey(seed, key);
2535
2815
  const start = {
2536
2816
  loanKey: BigInt(json.loan_key),
2537
2817
  borrowerPk: p.borrowerPk,
@@ -2540,15 +2820,16 @@ export class Essey {
2540
2820
  nonce: 1n,
2541
2821
  };
2542
2822
  const opening = rollTo(start, BigInt(json.coll.coll_note), seizeNonce);
2543
- return { owed: p.terms.owed, collAmt: p.collAmt, sk: own.sk, blinding: opening.blinding };
2544
- });
2823
+ return { owed: p.terms.owed, collAmt: p.collAmt, key, sk: own.sk, blinding: opening.blinding };
2824
+ };
2825
+ return this.collectFromSeizure(p.loan, 1, open, sweep);
2545
2826
  }
2546
2827
  /**
2547
2828
  * A seizure leaves the lock's nonce one past the one it folded and `coll_note` as it was. `out` 0 pays
2548
2829
  * `seize - pf - kf` to the lender, 1 pays `avail - seize` to the borrower, each at `outputBlind(blind, out, nonce)`.
2549
2830
  * The split is recomputed from the `p_spot` the seizing call claimed (`io.readSeizure`).
2550
2831
  */
2551
- async collectFromSeizure(loanId, out, open) {
2832
+ async collectFromSeizure(loanId, out, open, sweep) {
2552
2833
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2553
2834
  const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
2554
2835
  const seizure = this.io.readSeizure ?? notSetUp("missing config: no seizure reader");
@@ -2582,7 +2863,7 @@ export class Essey {
2582
2863
  pSpot: fault ? 1n : pSpot,
2583
2864
  expo: (await readPrice(String(json.market_id))).expo,
2584
2865
  risk: loanRisk(rates, decimals, { liquidate: MODE.LIQUIDATE, default: MODE.DEFAULT, fault: MODE.FAULT }[mode]),
2585
- fee: await this.feeParams(C),
2866
+ fee: await this.loanFee(C, json.coll_fee_commit),
2586
2867
  fault,
2587
2868
  });
2588
2869
  const value = out === 0 ? split.toLender : split.surplus;
@@ -2594,15 +2875,18 @@ export class Essey {
2594
2875
  const leaf = events.commitments.find((c) => BigInt(c.commitment) === commitment);
2595
2876
  if (!leaf)
2596
2877
  unknownObject("no seized note of this side is in the pool: another offer won, or the loan was topped up");
2597
- for (let i = 0; i < SEIZE_REWAITS && this.pacing && seizeIsLast(BigInt(events.commitments.length), leaf.index, out); i++) {
2878
+ for (let i = 0; sweep &&
2879
+ i < SEIZE_REWAITS &&
2880
+ this.pacing &&
2881
+ seizeIsLast(BigInt(events.commitments.length), leaf.index, out); i++) {
2598
2882
  await this.pause(out === 0 ? "collect_seized" : "collect_surplus", loan, null);
2599
2883
  events = await pools(C);
2600
2884
  }
2601
- return this.claimLeaf(C, events, { ...note, index: Number(leaf.index) });
2885
+ return this.take(C, events, { ...note, key: opened.key, index: Number(leaf.index) }, sweep);
2602
2886
  }
2603
2887
  /** The seed index whose key is `pk`: the borrower key of a loan this seed opened. */
2604
2888
  indexOfPk(seed, pk) {
2605
- const n = readState(this.statePath).notes ?? 0;
2889
+ const n = readState(this.statePath, this.stateKey).notes ?? 0;
2606
2890
  for (let i = n - 1; i >= 0; i--)
2607
2891
  if (notePk(deriveNoteKey(seed, i).sk) === pk)
2608
2892
  return i;
@@ -2629,7 +2913,7 @@ export class Essey {
2629
2913
  const seed = this.seed();
2630
2914
  const { opening, index } = this.ownOpening(seed, json, borrowerPk, collAmt);
2631
2915
  const nonce = opening.nonce;
2632
- const fee = await this.feeParams(C);
2916
+ const fee = await this.loanFee(C, json.coll_fee_commit);
2633
2917
  const rates = {
2634
2918
  ltvBps: BigInt(json.ltv_bps),
2635
2919
  liqBps: BigInt(json.liq_bps),
@@ -2670,7 +2954,7 @@ export class Essey {
2670
2954
  }
2671
2955
  /** The seed index a loan this seed opened derives from: its loan key is `Poseidon(sk, blinding, 1)` of that index. */
2672
2956
  indexOfLoanKey(seed, loanKey) {
2673
- const n = readState(this.statePath).notes ?? 0;
2957
+ const n = readState(this.statePath, this.stateKey).notes ?? 0;
2674
2958
  for (let i = n - 1; i >= 0; i--) {
2675
2959
  const k = deriveNoteKey(seed, i);
2676
2960
  if (poseidonHash([k.sk, k.blinding, 1n]) === loanKey)
@@ -2687,7 +2971,7 @@ export class Essey {
2687
2971
  const json = row.json;
2688
2972
  const loanKey = BigInt(json.loan_key);
2689
2973
  this.indexOfLoanKey(this.seed(), loanKey);
2690
- const { member, credential } = readState(this.statePath);
2974
+ const { member, credential } = readState(this.statePath, this.stateKey);
2691
2975
  const n0 = actionHash(blake2b256, loanKey, BigInt(json.nonce), "cancel", new Uint8Array());
2692
2976
  const pass = membership({
2693
2977
  secrets: member,
@@ -2711,7 +2995,7 @@ export class Essey {
2711
2995
  /** The borrower's pass over `kind` and its args, at the loan's next action nonce. */
2712
2996
  async borrowerPass(json, kind, args) {
2713
2997
  const loanKey = BigInt(json.loan_key);
2714
- const { member, credential } = readState(this.statePath);
2998
+ const { member, credential } = readState(this.statePath, this.stateKey);
2715
2999
  if (!member || !credential)
2716
3000
  notSetUp("no credential: call credential.obtain first");
2717
3001
  const n0 = actionHash(blake2b256, loanKey, BigInt(json.nonce), kind, args);
@@ -2735,6 +3019,7 @@ export class Essey {
2735
3019
  * derives from the lock's note index and the round, so the seed alone reopens it.
2736
3020
  */
2737
3021
  async openRefi(p) {
3022
+ assertLoanGrid(p, this.config.closeStepMs ?? HOUR_MS);
2738
3023
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2739
3024
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2740
3025
  const loan = address(p.loan, "loan id");
@@ -2764,8 +3049,6 @@ export class Essey {
2764
3049
  data: requestPlaintext({
2765
3050
  ...request,
2766
3051
  borrowerPk: p.borrowerPk,
2767
- collAmt: opening.amount,
2768
- collBlind: opening.blinding,
2769
3052
  closeMs,
2770
3053
  market,
2771
3054
  coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
@@ -2806,7 +3089,7 @@ export class Essey {
2806
3089
  const pClaim = r.spot < r.ema ? r.spot : r.ema;
2807
3090
  const rates = await this.rates(market);
2808
3091
  const ltvBps = BigInt(json.ltv_bps) < rates.current.ltvBps ? BigInt(json.ltv_bps) : rates.current.ltvBps;
2809
- const fee = await this.feeParams(L);
3092
+ const fee = await this.loanFee(L, json.fee_commit);
2810
3093
  await this.keys();
2811
3094
  const noteIndex = this.reserve("notes");
2812
3095
  const mine = deriveNoteKey(seed, noteIndex);
@@ -2816,7 +3099,7 @@ export class Essey {
2816
3099
  const plan = (extHash) => loanRefi({
2817
3100
  slots,
2818
3101
  round: q.round,
2819
- request: q,
3102
+ request: { ...q, collAmt: opening.amount, collBlind: opening.blinding },
2820
3103
  old: p.terms,
2821
3104
  price: {
2822
3105
  pClaim,
@@ -2936,7 +3219,7 @@ export class Essey {
2936
3219
  const opening = { loanKey, borrowerPk: notePk(own.sk), amount: collAmt, blinding: own.blinding };
2937
3220
  if (collNote(opening) !== BigInt(json.coll.coll_note))
2938
3221
  throw new EsseyError("CT_MISMATCH", "refused: the amount does not open the locked note");
2939
- const fee = await this.feeParams(C);
3222
+ const fee = await this.loanFee(C, json.coll_fee_commit);
2940
3223
  await this.keys();
2941
3224
  const outIndex = this.reserve("notes");
2942
3225
  const out = deriveNoteKey(seed, outIndex);
@@ -2991,7 +3274,7 @@ export class Essey {
2991
3274
  const loanKey = BigInt(json.loan_key);
2992
3275
  const [C, L] = this.pairOf(json.market_id);
2993
3276
  const seed = await this.keys();
2994
- const mine = ownOpenings(await readPool(C), seed, noteEncKey(seed).encKey);
3277
+ const mine = ownOpenings(await readPool(C), seed, noteEncKey(seed).encKey, this.noteNext());
2995
3278
  const keyAt = (i) => deriveNoteKey(seed, i);
2996
3279
  const change = mine.find((o) => {
2997
3280
  if (o.keyIndex === 0)
@@ -3115,12 +3398,12 @@ export class Essey {
3115
3398
  const [C, L] = this.pairOf(json.market_id);
3116
3399
  const poolC = address(json.pool_c, "pool_c");
3117
3400
  const market = address(json.market_id, "market");
3118
- const expiryMs = await this.heartbeatExpiry(json, market, p.expiryMs);
3401
+ const expiryMs = await this.heartbeatExpiry(json, market, p.terms.maturityS, p.expiryMs);
3119
3402
  const { opening } = this.ownOpening(this.seed(), json, p.borrowerPk, p.collAmt);
3120
3403
  const k = p.k ?? 1;
3121
3404
  const reading = await readPrice(market);
3122
3405
  const floor = heartbeatFloor(reading, k);
3123
- const fee = await this.feeParams(C);
3406
+ const fee = await this.loanFee(C, json.coll_fee_commit);
3124
3407
  const rates = {
3125
3408
  ltvBps: BigInt(json.ltv_bps),
3126
3409
  liqBps: BigInt(json.liq_bps),
@@ -3146,7 +3429,7 @@ export class Essey {
3146
3429
  terms: p.terms,
3147
3430
  });
3148
3431
  const proved = await this.prover().prove("health", h.input);
3149
- return this.relayed(heartbeatBody({
3432
+ const landed = await this.relayed(heartbeatBody({
3150
3433
  pool: C,
3151
3434
  loan,
3152
3435
  market,
@@ -3158,14 +3441,43 @@ export class Essey {
3158
3441
  expiryMs,
3159
3442
  priceUpdate: await update(market),
3160
3443
  }));
3444
+ return { ...landed, expiryMs };
3445
+ }
3446
+ /**
3447
+ * PRV-15: until a loan's first heartbeat every keeper may read its terms (`keeper.move:204`), so this follows the
3448
+ * settle at once and unpaced. A heartbeat may follow a settle at once: `hb_at_ms` is 0 (`liquidation.move:199`).
3449
+ */
3450
+ async firstCover(p) {
3451
+ try {
3452
+ await this.untilSettled(p.loan, termsCommit(p.terms, p.borrowerPk));
3453
+ const { digest, ticket, expiryMs } = await this.heartbeatOwn(p);
3454
+ return { ok: true, digest, ticket, expiryMs };
3455
+ }
3456
+ catch (err) {
3457
+ const code = isEsseyError(err) ? err.code : "UNEXPECTED";
3458
+ return { ok: false, code, error: err instanceof Error ? err.message.slice(0, 200) : "unknown" };
3459
+ }
3460
+ }
3461
+ /** The loan reader is an indexer that may trail the landed settle. */
3462
+ async untilSettled(loanId, commit) {
3463
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
3464
+ const loan = address(loanId, "loan id");
3465
+ for (let i = 0; i < SETTLE_READS; i++) {
3466
+ if (i > 0)
3467
+ await this.sleep(SETTLE_READ_MS);
3468
+ const json = (await read(loan))?.json;
3469
+ if (Number(json?.state) === 2 && BigInt(json?.terms_commit ?? -1) === commit)
3470
+ return;
3471
+ }
3472
+ throw new EsseyError("STATE_REFUSED", "the loan read does not show the settle yet");
3161
3473
  }
3162
3474
  /**
3163
3475
  * `liquidation::heartbeat`'s clock rules, checked before proving: one heartbeat per gap (43_015), an expiry at
3164
3476
  * least one gap and at most `H_MAX_MS` ahead (43_005) and not before the stored one (43_019). The gap is
3165
- * `liquidation::hb_gap_ms`: 2 minutes on a stand-in market, 50 on any other. No expiry given takes an hour, or the
3166
- * stored expiry when that is later.
3477
+ * `liquidation::hb_gap_ms`: 2 minutes on a stand-in market, 50 on any other. No expiry given takes `coverExpiry`,
3478
+ * or the stored expiry when that is later.
3167
3479
  */
3168
- async heartbeatExpiry(json, market, asked) {
3480
+ async heartbeatExpiry(json, market, maturityS, asked) {
3169
3481
  const read = this.io.readMarket ?? notSetUp("missing config: no market reader");
3170
3482
  const standin = /::standin_oracle::StandinOracle$/.test((await read(market)).oracle ?? "");
3171
3483
  const gap = standin ? HB_GAP_STANDIN_MS : HB_GAP_MS;
@@ -3176,8 +3488,10 @@ export class Essey {
3176
3488
  const wait = (last + gap - now + 999n) / 1000n;
3177
3489
  throw new EsseyError("INVALID_ARGUMENT", `the last heartbeat is under one gap old; retry in ${wait} s`);
3178
3490
  }
3179
- const hour = heartbeatHour(now);
3180
- const expiry = asked ?? (stored > hour ? stored : hour);
3491
+ const fresh = coverExpiry(now, maturityS);
3492
+ if (asked === undefined && fresh < now + gap)
3493
+ throw new EsseyError("INVALID_ARGUMENT", "the loan is under one gap from maturity plus grace");
3494
+ const expiry = asked ?? (stored > fresh ? stored : fresh);
3181
3495
  if (expiry < now + gap || expiry > now + H_MAX_MS)
3182
3496
  throw new EsseyError("INVALID_ARGUMENT", "the expiry must be at least one gap and at most 24 h ahead");
3183
3497
  if (expiry < stored)
@@ -3203,7 +3517,7 @@ export class Essey {
3203
3517
  throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
3204
3518
  const [C, L] = this.pairOf(json.market_id);
3205
3519
  const ids = { loan, poolC: address(json.pool_c, "pool_c"), market: address(json.market_id, "market") };
3206
- const fee = await this.feeParams(C);
3520
+ const fee = await this.loanFee(C, json.coll_fee_commit);
3207
3521
  const { events, owned, seed } = await this.owned(C);
3208
3522
  const { opening } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
3209
3523
  const inputs = pickInputs(owned, p.add);
@@ -3421,8 +3735,8 @@ export class Essey {
3421
3735
  const market = address(json.market_id, "market");
3422
3736
  const reading = await readPrice(market);
3423
3737
  const asDefault = mode === MODE.DEFAULT;
3424
- const nowS = asDefault ? BigInt(Math.floor((this.io.now ?? Date.now)() / 1000)) : 0n;
3425
- const fee = await this.feeParams(C);
3738
+ const nowS = asDefault ? defaultNowS((this.io.now ?? Date.now)()) : 0n;
3739
+ const fee = await this.loanFee(C, json.coll_fee_commit);
3426
3740
  await this.keys();
3427
3741
  const keeperIndex = this.reserve("notes");
3428
3742
  const keeper = deriveNoteKey(seed, keeperIndex);
@@ -3524,17 +3838,19 @@ export class Essey {
3524
3838
  /** D-SPEC §6.2:599. The seller pass over `sale_room::open_args`, at action nonce 0; the relayer or the callback pays. */
3525
3839
  async openSale(p) {
3526
3840
  const asked = assertSaleOpen(p);
3841
+ assertSaleGrid(asked, this.config.closeStepMs ?? HOUR_MS);
3842
+ const nowMs = (this.io.now ?? Date.now)();
3527
3843
  const open = {
3528
3844
  ...asked,
3529
- closeMs: stepClose(asked.closeMs, (this.io.now ?? Date.now)(), SALE_MAX_WINDOW_MS, this.config.closeStepMs),
3845
+ closeMs: stepClose(nowMs + asked.bidWindowMs, nowMs, SALE_MAX_WINDOW_MS, this.config.closeStepMs),
3530
3846
  };
3531
3847
  requireSale(this.config);
3532
3848
  const pool = poolId(this.config, open.coin);
3849
+ const item = { id: address(open.itemId, "itemId"), type: open.itemType };
3850
+ const readRooms = this.io.readRooms ?? notSetUp("missing config: no room reader");
3533
3851
  const submit = (open.sponsored ?? this.sponsoring() !== null)
3534
- ? this.saleSponsor(pool)
3852
+ ? await this.saleSponsor(pool, item.id)
3535
3853
  : (this.io.submitSaleOpen ?? notSetUp("missing config: sale open has no submitter"));
3536
- const read = this.io.readRoom ?? notSetUp("missing config: no room reader");
3537
- const item = { id: address(open.itemId, "itemId"), type: open.itemType };
3538
3854
  const closeMs = BigInt(open.closeMs);
3539
3855
  const finishByMs = closeMs + BigInt(open.finishWindowMs);
3540
3856
  const typeName = asInvalid(() => {
@@ -3577,15 +3893,11 @@ export class Essey {
3577
3893
  });
3578
3894
  if (typeof landed.digest !== "string" || landed.digest.length === 0 || typeof landed.ticket !== "string")
3579
3895
  unknownObject("the sale open returned no digest");
3580
- if (typeof landed.id !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(landed.id))
3581
- unknownObject("the sale open returned no room");
3582
- const id = address(landed.id, "room id");
3583
- const row = await read(id);
3584
- if (!row)
3585
- unknownObject("the digest created no room");
3586
- assertRoomMatches(this.config, open, { id, json: row.json });
3587
- if (String(row.json.sale_key) !== saleKey.toString())
3588
- unknownObject("the room is not this open");
3896
+ const { id, json } = await this.listedByKey("room", "sale_key", saleKey, async (c) => {
3897
+ const page = await readRooms(c);
3898
+ return { rows: page.rooms, next: page.next };
3899
+ });
3900
+ assertRoomMatches(this.config, open, { id, json });
3589
3901
  return {
3590
3902
  id,
3591
3903
  digest: landed.digest,
@@ -3594,19 +3906,21 @@ export class Essey {
3594
3906
  };
3595
3907
  }
3596
3908
  /**
3597
- * The sponsored open (E-34): a fresh seed-derived sender receives the item, then signs `from_proof` and `open`
3598
- * while the relayer pays gas. Every reader is checked here, before any proof, reserve or delivery. An open that
3599
- * stops after the delivery leaves the item at that sender, which only its seed can move.
3909
+ * The sponsored open (E-34): a fresh seed-derived sender signs `from_proof` and `open` while the relayer pays gas.
3910
+ * PRV-35: an item at one of this seed's `itemAddress()` holders opens from that holder with no hand-over; any other
3911
+ * item is first delivered to a fresh deposit signer. Every reader is checked here, before any proof, reserve or
3912
+ * delivery. An open that stops after the delivery leaves the item at that sender, which only its seed can move.
3600
3913
  */
3601
- saleSponsor(pool) {
3914
+ async saleSponsor(pool, itemId) {
3602
3915
  const relayer = this.sponsorRelayer();
3603
- const deliver = this.io.deliverSaleItem ?? notSetUp("no deliverSaleItem: the SDK never holds the item's wallet");
3604
3916
  const readRef = this.io.readObjectRef ?? notSetUp("no object reader for the item's version");
3605
- const readOpened = this.io.readSaleOpened ?? notSetUp("no reader for the room an open created");
3606
3917
  const readShared = this.io.readSharedVersion ?? notSetUp("no chain reader for shared object versions");
3607
3918
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
3608
3919
  const keyRegistry = this.config.objects.keyRegistry ?? notSetUp("missing config: no KeyRegistry");
3609
- const used = this.addressUsed();
3920
+ const held = this.holderOf((await readRef(itemId)).owner);
3921
+ const deliver = held !== null
3922
+ ? null
3923
+ : (this.io.deliverSaleItem ?? notSetUp("no deliverSaleItem: the SDK never holds the item's wallet"));
3610
3924
  const packages = { pool: this.config.packages.pool, sale: this.config.packages.sale };
3611
3925
  const shared = (r) => ({
3612
3926
  objectId: r.id,
@@ -3614,9 +3928,10 @@ export class Essey {
3614
3928
  });
3615
3929
  return async (tx) => {
3616
3930
  const seed = this.seed();
3617
- const signer = depositSigner(seed, await this.freshSigner(seed, used));
3931
+ const signer = held !== null ? itemHolder(seed, held) : depositSigner(seed, this.freshSigner());
3618
3932
  const sender = signer.toSuiAddress();
3619
- await deliver({ item: tx.item, sender });
3933
+ if (deliver)
3934
+ await deliver({ item: tx.item, sender });
3620
3935
  const ref = await readRef(tx.item.id);
3621
3936
  if (ref.owner === null || normalizeSuiAddress(ref.owner) !== sender)
3622
3937
  throw new EsseyError("SERVICE_REFUSED", "refused: the item is not at the sale sender; nothing was signed");
@@ -3650,7 +3965,7 @@ export class Essey {
3650
3965
  txBytesB64: sponsored.txBytesB64,
3651
3966
  userSig: signature,
3652
3967
  });
3653
- return { id: (await readOpened(digest)).room, digest, ticket: "" };
3968
+ return { digest, ticket: "" };
3654
3969
  };
3655
3970
  }
3656
3971
  /** D-SPEC §6.2:600. */
@@ -3741,7 +4056,7 @@ export class Essey {
3741
4056
  if (seq >= room.maxBids)
3742
4057
  throw new EsseyError("INVALID_ARGUMENT", "the room is full");
3743
4058
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
3744
- const { member, credential } = readState(this.statePath);
4059
+ const { member, credential } = readState(this.statePath, this.stateKey);
3745
4060
  if (!member || !credential)
3746
4061
  notSetUp("no credential: call credential.obtain first");
3747
4062
  const relayer = this.relayerAddress();
@@ -3816,7 +4131,7 @@ export class Essey {
3816
4131
  /** `sale_room::seal_approve_bid`: the seller's SEAL pass over `seal_bid` of bid `seq`, bound to the viewer, nonce 0. */
3817
4132
  bidApprove(room, seq) {
3818
4133
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
3819
- const { member, credential } = readState(this.statePath);
4134
+ const { member, credential } = readState(this.statePath, this.stateKey);
3820
4135
  if (!member || !credential)
3821
4136
  notSetUp("no credential: call credential.obtain first");
3822
4137
  const scope = keyId(room.saleKey);
@@ -3912,7 +4227,7 @@ export class Essey {
3912
4227
  });
3913
4228
  }
3914
4229
  indexOfSellerKey(seed, sellerSk) {
3915
- const n = readState(this.statePath).notes ?? 0;
4230
+ const n = readState(this.statePath, this.stateKey).notes ?? 0;
3916
4231
  for (let i = n - 1; i >= 0; i--)
3917
4232
  if (deriveNoteKey(seed, i).sk === sellerSk)
3918
4233
  return i;
@@ -3992,17 +4307,18 @@ export class Essey {
3992
4307
  const w = itemClaim({
3993
4308
  vault: { roomField: BigInt(json.room_field), claim },
3994
4309
  holder,
3995
- recipient: p.recipient,
4310
+ recipient: p.recipient ?? this.itemAddress(),
3996
4311
  relayer: this.relayerAddress(),
3997
4312
  });
3998
4313
  const proof = (await this.prover().prove("item_claim", w.input)).proof;
3999
- return this.freeLoan(claimBody, {
4314
+ const landed = await this.freeLoan(claimBody, {
4000
4315
  pool: room.coin,
4001
4316
  vault,
4002
4317
  recipient: w.statement.recipient,
4003
4318
  nullifier: w.statement.nullifier,
4004
4319
  proved: { proof, publicSignals: w.publics.map(String) },
4005
4320
  });
4321
+ return { ...landed, to: w.statement.recipient };
4006
4322
  }
4007
4323
  async prepareOpen(body) {
4008
4324
  if (body.kind !== "loan_open")