@esseyonsui/sui-sdk-v3 0.1.9 → 0.2.1

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 +182 -55
  8. package/dist/essey.d.ts.map +1 -1
  9. package/dist/essey.js +567 -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,60 @@ 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 = await this.servedOrStaged(coin, body, await readFeeCommit(coin, lane));
1019
+ this.feeOpenings.set(key, params);
1020
+ return params;
1021
+ }
1022
+ /**
1023
+ * PRV-02 O5: across a `fee_config::update` the book's current row trails the chain, and the opening the chain now
1024
+ * holds is a staged `next` row, filed by commit (`services/v3api/src/fee-archive.ts:60-82`).
1025
+ */
1026
+ async servedOrStaged(coin, served, onChain) {
1027
+ try {
1028
+ return verifyFeeOpening(served, onChain);
1029
+ }
1030
+ catch (mismatch) {
1031
+ try {
1032
+ return await this.loanFee(coin, onChain);
1033
+ }
1034
+ catch (error) {
1035
+ const unknown = isEsseyError(error, "SERVICE_REFUSED") && error.detail?.error === "FEE_OPENING_UNKNOWN";
1036
+ throw unknown ? mismatch : error;
1037
+ }
1038
+ }
1039
+ }
1040
+ /**
1041
+ * PRV-02: a loan step folds the loan's own snapshot (`loan.move:141-143`), not the config as it stands, so its
1042
+ * opening is fetched by that commit (v3api's archive) and must hash to it.
1043
+ */
1044
+ async loanFee(coin, snapshot) {
1045
+ const commit = BigInt(String(snapshot));
1046
+ const key = `${coin}:${commit}`;
1047
+ const held = this.snapshotOpenings.get(key);
1048
+ if (held)
1049
+ return held;
1050
+ const body = await this.feePass("/v3/fee-params/opening", { coin, commit: commit.toString() });
1051
+ const params = verifyFeeOpening(body, commit);
1052
+ this.snapshotOpenings.set(key, params);
1053
+ return params;
1054
+ }
1055
+ /** One fee-params pass (`FEE_PARAMS_ROOM`, bound to a fresh challenge) carrying `fields`; the reply body. */
1056
+ async feePass(path, fields) {
870
1057
  const api = this.api();
871
- const { member, credential } = readState(this.statePath);
1058
+ const { member, credential } = readState(this.statePath, this.stateKey);
872
1059
  if (!member || !credential)
873
1060
  notSetUp("no credential: call credential.obtain first");
874
1061
  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
1062
  const challenge = await getJson(this.fetch, `${api}/v3/fee-params/challenge`);
880
1063
  const nonce = challenge.body.nonce;
881
1064
  if (challenge.status !== 200 || typeof nonce !== "string")
@@ -887,18 +1070,27 @@ export class Essey {
887
1070
  domain: credential.role === "keeper" ? DOMAIN_KEEPER : DOMAIN_SENDER,
888
1071
  room: FEE_PARAMS_ROOM,
889
1072
  bind: nonce,
1073
+ nonce: feeNonceLane(nonce),
890
1074
  });
891
- const reply = await postJson(this.fetch, `${api}/v3/fee-params`, {
892
- coin,
1075
+ const reply = await postJson(this.fetch, `${api}${path}`, {
1076
+ ...fields,
893
1077
  nonce,
894
1078
  publicInputs: publics.map(String),
895
1079
  proof: passProof(await prover.prove("membership", input)),
896
1080
  });
897
- if (reply.status !== 200 || reply.body.ok !== true || reply.body.coin !== coin)
1081
+ if (reply.status !== 200 || reply.body.ok !== true || reply.body.coin !== fields.coin)
898
1082
  throw refusedBy("v3api", reply);
899
- const params = verifyFeeOpening(reply.body, await readFeeCommit(coin));
900
- this.feeOpenings.set(coin, params);
901
- return params;
1083
+ return reply.body;
1084
+ }
1085
+ /** The edge lane only once the record names the coin's edge config; before that the pool takes its pinned one. */
1086
+ feeLane(coin, asked) {
1087
+ return asked === "edge" && this.config.objects.edgeFeeConfigs?.[coin] ? "edge" : "hidden";
1088
+ }
1089
+ feeConfigId(coin, lane) {
1090
+ const ids = this.feeLane(coin, lane) === "edge"
1091
+ ? this.config.objects.edgeFeeConfigs
1092
+ : this.config.objects.feeConfigs;
1093
+ return ids?.[coin];
902
1094
  }
903
1095
  async rates(market) {
904
1096
  const id = address(market, "market");
@@ -911,14 +1103,14 @@ export class Essey {
911
1103
  */
912
1104
  seed() {
913
1105
  if (this.seedOption) {
914
- this.ownSeed(readState(this.statePath));
1106
+ this.ownSeed(readState(this.statePath, this.stateKey));
915
1107
  return this.seedOption;
916
1108
  }
917
- const stored = readState(this.statePath).seed ??
1109
+ const stored = readState(this.statePath, this.stateKey).seed ??
918
1110
  this.update((s) => {
919
1111
  if (s.seed !== undefined)
920
1112
  return s.seed;
921
- if (s.notes || s.signers || s.stranded?.length)
1113
+ if (s.notes || s.signers || s.holders || s.stranded?.length)
922
1114
  throw new EsseyError("STATE_REFUSED", NO_SEED);
923
1115
  return (s.seed = randomBytes(SEED_BYTES).toString("hex"));
924
1116
  });
@@ -934,27 +1126,24 @@ export class Essey {
934
1126
  const { encKey } = noteEncKey(seed);
935
1127
  let next = 0;
936
1128
  for (const coin of COINS)
937
- for (const used of usedIndices(await read(coin), seed, encKey))
1129
+ for (const used of usedIndices(await read(coin), seed, encKey, this.noteNext()))
938
1130
  next = Math.max(next, used + 1);
939
- if (next > (readState(this.statePath).notes ?? 0))
1131
+ if (next > (readState(this.statePath, this.stateKey).notes ?? 0))
940
1132
  this.update((s) => {
941
1133
  s.notes = Math.max(next, s.notes ?? 0);
942
1134
  });
943
1135
  return seed;
944
1136
  }
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");
1137
+ /**
1138
+ * 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
1139
+ * restored seed lands far from the indexes it used before; the next index is on disk before this one is used.
1140
+ */
1141
+ freshSigner() {
1142
+ return this.update((state) => {
1143
+ const index = state.signers ?? (this.io.signerStart ?? (() => randomInt(2 ** 20, 2 ** 48 - 1)))();
1144
+ state.signers = index + 1;
1145
+ return index;
1146
+ });
958
1147
  }
959
1148
  /** Write-ahead: a deposit is on disk as stranded before its value moves, and leaves once it has landed. */
960
1149
  strand(s, on) {
@@ -987,7 +1176,7 @@ export class Essey {
987
1176
  });
988
1177
  }
989
1178
  member() {
990
- const { member, credential } = readState(this.statePath);
1179
+ const { member, credential } = readState(this.statePath, this.stateKey);
991
1180
  if (!member || !credential)
992
1181
  notSetUp("no credential: call credential.obtain first");
993
1182
  return { secrets: member, credential: credential };
@@ -1016,7 +1205,7 @@ export class Essey {
1016
1205
  const { secrets, credential } = this.member();
1017
1206
  const prover = this.prover();
1018
1207
  const seed = await this.keys();
1019
- const fee = await this.feeParams(coinOf(coin));
1208
+ const fee = await this.feeParams(coinOf(coin), "edge");
1020
1209
  const value = faucetGrant(coin);
1021
1210
  const index = this.reserve("notes");
1022
1211
  const keys = deriveNoteKey(seed, index);
@@ -1074,7 +1263,6 @@ export class Essey {
1074
1263
  const pieces = (denominations ?? list !== undefined) ? splitDenominations(amount, list ?? []) : [amount];
1075
1264
  const relayer = this.sponsorRelayer();
1076
1265
  const fund = this.io.fundDeposit ?? notSetUp("no fundDeposit: the SDK never holds the paying wallet");
1077
- const used = this.addressUsed();
1078
1266
  const seed = await this.keys();
1079
1267
  const read = this.io.readPool;
1080
1268
  const ctx = await this.depositContext(coin);
@@ -1082,7 +1270,7 @@ export class Essey {
1082
1270
  for (const value of pieces) {
1083
1271
  let signer;
1084
1272
  try {
1085
- signer = await this.freshSigner(seed, used);
1273
+ signer = this.freshSigner();
1086
1274
  const note = this.reserve("notes");
1087
1275
  const piece = { coin, signer, note, value, signed: [] };
1088
1276
  const { digest, ticket } = (await this.depositPiece(ctx, seed, piece, relayer, read, fund));
@@ -1097,13 +1285,13 @@ export class Essey {
1097
1285
  async depositContext(coin) {
1098
1286
  const pkg = this.config.packages.pool;
1099
1287
  const poolId = this.config.objects.pools[coin];
1100
- const feeConfigId = this.config.objects.feeConfigs?.[coin];
1288
+ const feeConfigId = this.feeConfigId(coin, "edge");
1101
1289
  if (!pkg || !poolId || !feeConfigId)
1102
1290
  notSetUp("the pool is not published yet");
1103
1291
  const readShared = this.io.readSharedVersion ?? notSetUp("no chain reader for shared object versions");
1104
1292
  const { secrets, credential } = this.member();
1105
1293
  const prover = this.prover();
1106
- const fee = await this.feeParams(coin);
1294
+ const fee = await this.feeParams(coin, "edge");
1107
1295
  return {
1108
1296
  pkg: pkg,
1109
1297
  coinType: this.config.coins[coin].type,
@@ -1205,7 +1393,7 @@ export class Essey {
1205
1393
  const seed = this.seed();
1206
1394
  const outcomes = [];
1207
1395
  let unsent = false;
1208
- for (const piece of readState(this.statePath).stranded ?? []) {
1396
+ for (const piece of readState(this.statePath, this.stateKey).stranded ?? []) {
1209
1397
  try {
1210
1398
  const outcome = await this.recoverOne(piece, seed, read, relayer);
1211
1399
  if (outcome)
@@ -1259,7 +1447,7 @@ export class Essey {
1259
1447
  return { ...record, outcome: sent.inPool ? "landed" : "unconfirmed", digest: sent.digest };
1260
1448
  }
1261
1449
  record(signer) {
1262
- return readState(this.statePath).stranded?.find((r) => r.signer === signer);
1450
+ return readState(this.statePath, this.stateKey).stranded?.find((r) => r.signer === signer);
1263
1451
  }
1264
1452
  /** A state file that cannot be read may hold the record, so it counts as held. */
1265
1453
  strandedAt(signer) {
@@ -1297,7 +1485,27 @@ export class Essey {
1297
1485
  const read = this.io.readPool ?? notSetUp("no pool reader: the pool events are read by the caller");
1298
1486
  const seed = this.seed();
1299
1487
  const events = await read(coin);
1300
- return { events, owned: ownNotes(events, seed, noteEncKey(seed).encKey), seed };
1488
+ return { events, owned: this.ownedIn(coin, events, seed), seed };
1489
+ }
1490
+ /** The scan's notes, then each held note of `coin` whose leaf is in `events` unspent. */
1491
+ ownedIn(coin, events, seed) {
1492
+ const scanned = ownNotes(events, seed, noteEncKey(seed).encKey, this.noteNext());
1493
+ const held = (readState(this.statePath, this.stateKey).held ?? []).flatMap((h) => {
1494
+ if (h.coin !== coin || scanned.some((n) => n.index === h.index))
1495
+ return [];
1496
+ const { status, sk } = heldStatus(events, seed, h);
1497
+ return status === "live" ? [{ value: h.value, sk, blinding: h.blinding, index: h.index }] : [];
1498
+ });
1499
+ return [...scanned, ...held];
1500
+ }
1501
+ /** Records a found note for the next spend; held notes of `coin` the read pool shows spent are dropped. */
1502
+ hold(coin, events, note) {
1503
+ const seed = this.seed();
1504
+ this.update((state) => {
1505
+ const kept = (state.held ?? []).filter((h) => h.coin !== coin || (h.index !== note.index && heldStatus(events, seed, h).status !== "spent"));
1506
+ state.held = [...kept, note];
1507
+ });
1508
+ return { held: true, value: note.value };
1301
1509
  }
1302
1510
  async scan(coin) {
1303
1511
  const summary = {};
@@ -1318,13 +1526,13 @@ export class Essey {
1318
1526
  const pieces = withdrawPieces(amount, list);
1319
1527
  return { amount, pieces, sendTo: piecePayees(pieces.length, payees) };
1320
1528
  }
1321
- async withdraw(coin, plan, o) {
1529
+ async withdrawStart(coin, plan, o) {
1322
1530
  if ("exact" in plan)
1323
- return [await this.withdrawExact(coin, plan.amount, plan.exact, o)];
1531
+ return { paid: await this.withdrawExact(coin, plan.amount, plan.exact, o), pending: null };
1324
1532
  const { fee, relayerFee, owned } = await this.payoutPlan(coin);
1325
1533
  refuseUncovered(owned, plan.pieces, fee, relayerFee);
1326
1534
  refuseLinkedAmount(plan.amount, faucetGrant(coin), owned, fee, relayerFee);
1327
- return this.payPieces(coin, plan.pieces, plan.sendTo, fee);
1535
+ return this.payPiece(coin, piecesTo(plan.pieces, plan.sendTo), fee);
1328
1536
  }
1329
1537
  async withdrawExact(coin, amount, to, o) {
1330
1538
  const landed = await this.spend(coin, { to }, (owned, rates, relayerFee) => {
@@ -1333,7 +1541,27 @@ export class Essey {
1333
1541
  refuseLinkedAmount(amount, faucetGrant(coin), owned, rates, relayerFee);
1334
1542
  return { value: amount, inputs };
1335
1543
  });
1336
- return { ...landed, amount, to: payee(to) };
1544
+ return this.paidTo(landed, amount, to);
1545
+ }
1546
+ /** PRV-11: a reused payee joins two payouts on chain. With no tag on disk this reads no seed and writes nothing. */
1547
+ refusePaid(to, o) {
1548
+ if (o.allowReuse === true)
1549
+ return;
1550
+ const paid = readState(this.statePath, this.stateKey).paid;
1551
+ if (!paid)
1552
+ return;
1553
+ const seed = this.seed();
1554
+ if (listOf(to).some((t) => paid.includes(paidTag(seed, payee(t)))))
1555
+ 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");
1556
+ }
1557
+ paidTo(landed, amount, to) {
1558
+ const address = payee(to);
1559
+ const tag = paidTag(this.seed(), address);
1560
+ this.update((s) => {
1561
+ if (!s.paid?.includes(tag))
1562
+ s.paid = [...(s.paid ?? []), tag];
1563
+ });
1564
+ return { ...landed, amount, to: address };
1337
1565
  }
1338
1566
  /** The same reads and set-up checks `spend` makes, once for every piece of a split payout. */
1339
1567
  async payoutPlan(coin) {
@@ -1341,27 +1569,52 @@ export class Essey {
1341
1569
  this.relayerAddress();
1342
1570
  this.prover();
1343
1571
  const relayerFee = this.coinFee(coin);
1344
- const fee = await this.feeParams(coin);
1572
+ const fee = await this.feeParams(coin, "edge");
1345
1573
  const { owned } = await this.owned(coin);
1346
1574
  return { fee, relayerFee, owned };
1347
1575
  }
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 = [];
1576
+ /** Pays `pieces[0]`; the rest come back as `pending`, due a long-class time from now. */
1577
+ async payPiece(coin, pieces, fee) {
1578
+ const [{ amount, to }, ...rest] = pieces;
1351
1579
  let spent = [];
1352
- for (const [i, amount] of pieces.entries()) {
1580
+ const landed = await this.spend(coin, { to }, (owned, rates, relayerFee) => {
1581
+ spent = pickInputs(owned, withdrawCost(amount, rates, relayerFee));
1582
+ return { value: amount, inputs: spent };
1583
+ }, [], fee);
1584
+ const paid = this.paidTo(landed, amount, to);
1585
+ if (rest.length === 0)
1586
+ return { paid, pending: null };
1587
+ return {
1588
+ paid,
1589
+ pending: { coin, pieces: rest, notBeforeMs: this.pieceAt(), spent: spent.map((n) => n.index) },
1590
+ };
1591
+ }
1592
+ async payNext(p) {
1593
+ if (p.pieces.length === 0)
1594
+ throw new EsseyError("INVALID_ARGUMENT", "refused: no piece is pending");
1595
+ await this.awaitSpent(coinOf(p.coin), p.spent);
1596
+ return this.payPiece(p.coin, p.pieces);
1597
+ }
1598
+ /** The in-process schedule: each pending piece waits out its `notBeforeMs` through `io.pace`, then goes. */
1599
+ async drain(first) {
1600
+ const paid = [first.paid];
1601
+ for (let p = first.pending; p !== null;) {
1602
+ const due = p;
1353
1603
  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] });
1604
+ const nowMs = (this.io.now ?? Date.now)();
1605
+ if (this.pacing)
1606
+ await this.waitOut({
1607
+ action: "withdraw_piece",
1608
+ subject: `${due.coin}:${due.pieces[0].to}`,
1609
+ delayMs: Math.max(0, due.notBeforeMs - nowMs),
1610
+ notBeforeMs: due.notBeforeMs,
1611
+ });
1612
+ const next = await this.payNext(due);
1613
+ paid.push(next.paid);
1614
+ p = next.pending;
1362
1615
  }
1363
1616
  catch (error) {
1364
- throw payoutStopped(error, paid, pieces);
1617
+ throw payoutStopped(error, paid, due.pieces.map((x) => x.amount));
1365
1618
  }
1366
1619
  }
1367
1620
  return paid;
@@ -1372,7 +1625,7 @@ export class Essey {
1372
1625
  const sleep = this.io.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1373
1626
  for (let i = 0; i < SPENT_POLLS; i++) {
1374
1627
  const { owned } = await this.owned(coin);
1375
- if (!owned.some((n) => spent.some((s) => s.index === n.index)))
1628
+ if (!owned.some((n) => spent.includes(n.index)))
1376
1629
  return;
1377
1630
  await sleep(FOLLOW_MIN_GAP_MS);
1378
1631
  }
@@ -1383,19 +1636,40 @@ export class Essey {
1383
1636
  receiveAddress() {
1384
1637
  const seed = this.seed();
1385
1638
  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}`;
1639
+ const pk = notePk(deriveNoteKey(seed, index).sk).toString(16).padStart(64, "0");
1640
+ const { C, D } = receiveKey(seed, index);
1641
+ return `${RECEIVE_PREFIX}${pk}:${Buffer.from(C).toString("hex")}:${Buffer.from(D).toString("hex")}`;
1642
+ }
1643
+ noteNext() {
1644
+ return readState(this.statePath, this.stateKey).notes ?? 0;
1645
+ }
1646
+ itemAddress() {
1647
+ return itemHolder(this.seed(), this.reserve("holders")).toSuiAddress();
1648
+ }
1649
+ holderOf(owner) {
1650
+ const count = readState(this.statePath, this.stateKey).holders ?? 0;
1651
+ if (owner === null || count === 0)
1652
+ return null;
1653
+ const seed = this.seed();
1654
+ const at = normalizeSuiAddress(owner);
1655
+ for (let i = 0; i < count; i++)
1656
+ if (itemHolder(seed, i).toSuiAddress() === at)
1657
+ return i;
1658
+ return null;
1388
1659
  }
1389
1660
  async transfer(coin, amount, to) {
1390
1661
  if (amount <= 0n)
1391
1662
  throw new EsseyError("INVALID_ARGUMENT", "amount must be above 0");
1392
1663
  const payTo = receiveTarget(to);
1393
- return this.spend(coin, { payTo }, (owned, rates, relayerFee) => ({
1664
+ const mark = paidTag(this.seed(), to);
1665
+ if (readState(this.statePath, this.stateKey).paid?.includes(mark))
1666
+ throw paidBefore();
1667
+ return this.spend(coin, { payTo, mark }, (owned, rates, relayerFee) => ({
1394
1668
  value: amount,
1395
1669
  inputs: pickInputs(owned, withdrawCost(amount, rates, relayerFee)),
1396
1670
  }));
1397
1671
  }
1398
- async exit(coin, to, o = {}) {
1672
+ async exitStart(coin, to, o) {
1399
1673
  const list = this.config.denominations[coinOf(coin)];
1400
1674
  if (list === undefined || o.force === true)
1401
1675
  return this.exitExact(coin, onePayee(to), o);
@@ -1409,8 +1683,8 @@ export class Essey {
1409
1683
  refuseUncovered(owned, pieces, fee, relayerFee);
1410
1684
  const value = pieces.reduce((sum, piece) => sum + piece, 0n);
1411
1685
  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) };
1686
+ const first = await this.payPiece(coin, piecesTo(pieces, sendTo), fee);
1687
+ return { ...first, kept: exitKept(total, pieces, fee, relayerFee) };
1414
1688
  }
1415
1689
  async exitExact(coin, to, o) {
1416
1690
  let value = 0n;
@@ -1427,7 +1701,7 @@ export class Essey {
1427
1701
  kept = total - withdrawCost(value, rates, relayerFee);
1428
1702
  return { value, inputs: owned };
1429
1703
  });
1430
- return { payouts: [{ ...landed, amount: value, to: payee(to) }], kept };
1704
+ return { paid: this.paidTo(landed, value, to), pending: null, kept };
1431
1705
  }
1432
1706
  /** js4 with the withdraw field (`src/v3/inputs.ts:39`); the change note's index is on disk before the body leaves. */
1433
1707
  async spend(coin, dest, choose, extra = [], known) {
@@ -1436,7 +1710,7 @@ export class Essey {
1436
1710
  const relay = this.relayClient();
1437
1711
  const relayer = this.relayerAddress();
1438
1712
  const prover = this.prover();
1439
- const fee = known ?? (await this.feeParams(coin));
1713
+ const fee = known ?? (await this.feeParams(coin, "edge"));
1440
1714
  const { events, owned, seed } = await this.owned(coin);
1441
1715
  const { value, inputs } = choose([...owned, ...extra], fee, relayerFee);
1442
1716
  const tree = poolTree(orderedLeaves(events));
@@ -1468,9 +1742,7 @@ export class Essey {
1468
1742
  const changeValue = BigInt(js.input.outAmount1);
1469
1743
  const encChange = sealOpening({ value: changeValue, blinding: change.blinding, index }, noteEncKey(seed).encPub);
1470
1744
  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();
1745
+ const encPaid = "payTo" in dest ? sealPaid(dest.payTo, value, paidBlinding) : fillerEnc();
1474
1746
  const body = ("payTo" in dest ? transferBody : withdrawBody)({
1475
1747
  pool: coin,
1476
1748
  proved: { proof: proved.proof, publicSignals: js.publics.map(String) },
@@ -1479,9 +1751,19 @@ export class Essey {
1479
1751
  relayerFee,
1480
1752
  wait: true,
1481
1753
  });
1754
+ if ("payTo" in dest && dest.mark)
1755
+ this.markPaid(dest.mark);
1482
1756
  const sent = await relay.submit(body);
1483
1757
  return "digest" in sent ? sent : this.follow(relay, sent, "withdraw");
1484
1758
  }
1759
+ /** PRV-34 write-ahead: an address is marked paid before the body leaves, so a second payment to it never does. */
1760
+ markPaid(mark) {
1761
+ this.update((s) => {
1762
+ if (s.paid?.includes(mark))
1763
+ throw paidBefore();
1764
+ s.paid = [...(s.paid ?? []), mark];
1765
+ });
1766
+ }
1485
1767
  /** A 202 carries no digest (`src/v3/relay/client.ts:100`): the ticket is followed until it lands. */
1486
1768
  async follow(relay, queued, what) {
1487
1769
  const gap = Math.max(queued.etaMs, FOLLOW_MIN_GAP_MS);
@@ -1526,7 +1808,7 @@ export class Essey {
1526
1808
  return (await this.checkedCredential()) ?? unknownObject("no credential is stored");
1527
1809
  }
1528
1810
  async checkedCredential() {
1529
- const { member, credential } = readState(this.statePath);
1811
+ const { member, credential } = readState(this.statePath, this.stateKey);
1530
1812
  if (!credential)
1531
1813
  return null;
1532
1814
  if (!member)
@@ -1552,7 +1834,7 @@ export class Essey {
1552
1834
  const out = [];
1553
1835
  for (const c of coins) {
1554
1836
  const { events, seed } = await this.poolOf(c);
1555
- out.push(...listPositions(c, events, seed));
1837
+ out.push(...this.ownedIn(c, events, seed).map((n) => ({ coin: c, index: n.index, value: n.value })));
1556
1838
  }
1557
1839
  return out;
1558
1840
  }
@@ -1564,6 +1846,7 @@ export class Essey {
1564
1846
  /** D-SPEC §6.2:588. The envelope is `v3.loans.open`; the id is whatever the digest created. */
1565
1847
  async openRequest(p) {
1566
1848
  assertLoanOpen(p);
1849
+ assertLoanGrid(p, this.config.closeStepMs ?? HOUR_MS);
1567
1850
  poolId(this.config, p.loanCoin);
1568
1851
  poolId(this.config, p.collateralCoin);
1569
1852
  if (this.config.relayer.url === null)
@@ -1575,30 +1858,37 @@ export class Essey {
1575
1858
  if (proved.pool !== p.loanCoin)
1576
1859
  wrongCoinObject();
1577
1860
  const landed = await this.paidLoan(openLoan, { ...proved, wait: true });
1578
- return { ...landed, id: await this.loanByKey(proved.loanKey) };
1861
+ const read = this.io.readLoans;
1862
+ const row = await this.listedByKey("loan", "loan_key", proved.loanKey, async (c) => {
1863
+ const page = await read(c);
1864
+ return { rows: page.loans, next: page.next };
1865
+ });
1866
+ return { ...landed, id: row.id };
1579
1867
  }
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++) {
1868
+ /**
1869
+ * PRV-07: what an open created is found among every listed object of its kind by the key its opener chose
1870
+ * (`field`), never by the opener's own digest.
1871
+ */
1872
+ async listedByKey(what, field, key, read) {
1873
+ for (let attempt = 0; attempt < FIND_LISTED_TRIES; attempt++) {
1584
1874
  if (attempt > 0)
1585
- await this.sleep(FIND_LOAN_PAUSE_MS);
1875
+ await this.sleep(FIND_LISTED_PAUSE_MS);
1586
1876
  let cursor = null;
1587
1877
  let pages = 0;
1588
1878
  for (;;) {
1589
1879
  const page = await read(cursor);
1590
1880
  pages += 1;
1591
- const row = page.loans.find((l) => l.json?.loan_key?.toString() === `${loanKey}`);
1881
+ const row = page.rows.find((l) => l.json?.[field]?.toString() === `${key}`);
1592
1882
  if (row && !/^0x[0-9a-fA-F]{64}$/.test(row.id))
1593
- unknownObject("the listed loan id is not an object id");
1883
+ unknownObject(`the listed ${what} id is not an object id`);
1594
1884
  if (row)
1595
- return address(row.id, "loan id");
1885
+ return { id: address(row.id, `${what} id`), json: row.json };
1596
1886
  cursor = afterPage(page.next, pages);
1597
1887
  if (cursor === null)
1598
1888
  break;
1599
1889
  }
1600
1890
  }
1601
- return unknownObject("the open landed, but no listed loan carries its key yet");
1891
+ return unknownObject(`the open landed, but no listed ${what} carries its key yet`);
1602
1892
  }
1603
1893
  /**
1604
1894
  * The borrower's `loan_open`: a CollLock spend of up to two own notes into the lock, the Health OPEN rows, the
@@ -1612,7 +1902,7 @@ export class Essey {
1612
1902
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
1613
1903
  const readPrice = this.io.readPrice ?? notSetUp("missing config: no price reader");
1614
1904
  const update = this.io.priceUpdate ?? notSetUp("missing config: no price update source");
1615
- const { member, credential } = readState(this.statePath);
1905
+ const { member, credential } = readState(this.statePath, this.stateKey);
1616
1906
  if (!member || !credential)
1617
1907
  notSetUp("no credential: call credential.obtain first");
1618
1908
  const relayer = this.relayerAddress();
@@ -1651,8 +1941,6 @@ export class Essey {
1651
1941
  data: requestPlaintext({
1652
1942
  ...request,
1653
1943
  borrowerPk,
1654
- collAmt: p.collateral,
1655
- collBlind: own.blinding,
1656
1944
  closeMs,
1657
1945
  market,
1658
1946
  coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
@@ -1752,7 +2040,7 @@ export class Essey {
1752
2040
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
1753
2041
  const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
1754
2042
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
1755
- const { member, credential } = readState(this.statePath);
2043
+ const { member, credential } = readState(this.statePath, this.stateKey);
1756
2044
  if (!member || !credential)
1757
2045
  notSetUp("no credential: call credential.obtain first");
1758
2046
  const loan = address(id, "loan id");
@@ -1803,11 +2091,8 @@ export class Essey {
1803
2091
  };
1804
2092
  },
1805
2093
  });
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");
2094
+ const q = readRequestPlain(plain);
2095
+ const note = BigInt(refi ? json.coll.coll_note : json.collateral_commit);
1811
2096
  const request = { principal: q.principal, maxRateBps: q.maxRateBps, termMs: q.termMs, salt: q.salt };
1812
2097
  if (requestCommit(request, q.borrowerPk, note) !== BigInt(round.req_commit))
1813
2098
  throw new EsseyError("CT_MISMATCH", "refused: the request does not open the loan's commit");
@@ -1820,8 +2105,6 @@ export class Essey {
1820
2105
  poolL: address(json.pool_l, "pool_l"),
1821
2106
  ...request,
1822
2107
  borrowerPk: q.borrowerPk,
1823
- collAmt: q.collAmt,
1824
- collBlind: q.collBlind,
1825
2108
  collNote: note,
1826
2109
  closeMs: q.closeMs,
1827
2110
  };
@@ -1840,17 +2123,19 @@ export class Essey {
1840
2123
  /** The lender's `loan_offer`: the principal locked to the round from up to two own notes, its sealed terms pinned. */
1841
2124
  async planOffer(loanId, rateBps) {
1842
2125
  const q = await this.readRequest(loanId, true);
2126
+ assertRequestTerm(q.termMs, this.config.closeStepMs ?? HOUR_MS);
1843
2127
  const L = q.pair[1];
1844
2128
  if (poolId(this.config, L) !== q.poolL)
1845
2129
  wrongCoinObject();
1846
2130
  if (rateBps > q.maxRateBps)
1847
2131
  throw new EsseyError("INVALID_ARGUMENT", "the rate is above the request's maximum");
1848
2132
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
1849
- const { member, credential } = readState(this.statePath);
2133
+ const { member, credential } = readState(this.statePath, this.stateKey);
1850
2134
  const relayer = this.relayerAddress();
1851
2135
  const relayerFee = this.coinFee(L);
1852
2136
  const prover = this.prover();
1853
- const fee = await this.feeParams(L);
2137
+ const row = await (this.io.readLoan ?? notSetUp("missing config: no loan reader"))(q.loan);
2138
+ const fee = await this.loanFee(L, row.json.fee_commit);
1854
2139
  const { events, owned, seed } = await this.owned(L);
1855
2140
  const inputs = pickInputs(owned, q.principal + relayerFee);
1856
2141
  const tree = poolTree(orderedLeaves(events));
@@ -1955,7 +2240,7 @@ export class Essey {
1955
2240
  /** `seal_policy::seal_approve_offer` for offer `seq`: the borrower's SEAL pass over `seal_offer` bound to the viewer. */
1956
2241
  offerApprove(loan, loanKey, round, seq, pair) {
1957
2242
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
1958
- const { member, credential } = readState(this.statePath);
2243
+ const { member, credential } = readState(this.statePath, this.stateKey);
1959
2244
  const room = keyId(loanKey);
1960
2245
  const prover = this.prover();
1961
2246
  return async (viewer) => {
@@ -2093,7 +2378,7 @@ export class Essey {
2093
2378
  if (via === "pass")
2094
2379
  return { approve: await this.keeperApprove(loan, market, id, pair) };
2095
2380
  const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
2096
- const held = readState(this.statePath).badge;
2381
+ const held = readState(this.statePath, this.stateKey).badge;
2097
2382
  if (!held || BigInt((this.io.now ?? Date.now)()) >= held.expiresMs)
2098
2383
  notSetUp("no live keeper badge: call keeper.mintBadge");
2099
2384
  const signer = depositSigner(this.seed(), held.signer);
@@ -2117,7 +2402,7 @@ export class Essey {
2117
2402
  return { approve, signer };
2118
2403
  }
2119
2404
  heldBadge() {
2120
- const held = readState(this.statePath).badge;
2405
+ const held = readState(this.statePath, this.stateKey).badge;
2121
2406
  if (!held)
2122
2407
  return null;
2123
2408
  const holder = depositSigner(this.seed(), held.signer).toSuiAddress();
@@ -2130,14 +2415,14 @@ export class Essey {
2130
2415
  async mintBadge() {
2131
2416
  const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
2132
2417
  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");
2418
+ const readBadges = this.io.readBadges ?? notSetUp("missing config: no badge reader");
2134
2419
  const relayer = this.sponsorRelayer();
2135
2420
  const { secrets, credential } = this.member();
2136
2421
  if (credential.role !== "keeper")
2137
2422
  notSetUp("no keeper credential");
2138
2423
  const prover = this.prover();
2139
2424
  const seed = this.seed();
2140
- const index = await this.freshSigner(seed, this.io.readAddressUsed);
2425
+ const index = this.freshSigner();
2141
2426
  const signer = depositSigner(seed, index);
2142
2427
  const holder = signer.toSuiAddress();
2143
2428
  const room = keeper.registry.id;
@@ -2161,9 +2446,10 @@ export class Essey {
2161
2446
  proof: `0x${Buffer.from(proof).toString("hex")}`,
2162
2447
  };
2163
2448
  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`);
2449
+ const row = await this.listedByKey("badge", "tag", pass.publics[0], async (c) => {
2450
+ const page = await readBadges(c);
2451
+ return { rows: page.badges, next: page.next };
2452
+ });
2167
2453
  const { id, expiresMs } = badgeOf(row, { holder, registry: room });
2168
2454
  this.update((s) => {
2169
2455
  s.badge = { signer: index, id, expiresMs };
@@ -2191,7 +2477,7 @@ export class Essey {
2191
2477
  /** `keeper::seal_approve_keeper_proof`: a KEEPER pass for the deployment's keeper registry, bound to the viewer. */
2192
2478
  async keeperApprove(loan, market, id, pair) {
2193
2479
  const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
2194
- const { member, credential } = readState(this.statePath);
2480
+ const { member, credential } = readState(this.statePath, this.stateKey);
2195
2481
  if (!member || credential?.role !== "keeper")
2196
2482
  notSetUp("no keeper credential");
2197
2483
  const { price, standin } = await this.keeperFeed(market);
@@ -2255,7 +2541,7 @@ export class Essey {
2255
2541
  return decodeOffer(plain);
2256
2542
  }
2257
2543
  /** The borrower's `loan_settle` on round 0: the lowest eligible offer wins, keeper ciphertext v1 carries its terms. */
2258
- async planSettle(id) {
2544
+ async planSettle(id, collAmt) {
2259
2545
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2260
2546
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2261
2547
  const q = await this.readRequest(id);
@@ -2264,6 +2550,8 @@ export class Essey {
2264
2550
  throw new EsseyError("INVALID_ARGUMENT", "refused: the offer window is still open");
2265
2551
  const row = await read(q.loan);
2266
2552
  const json = row.json;
2553
+ const seed = this.seed();
2554
+ const { opening } = this.ownOpening(seed, json, q.borrowerPk, collAmt);
2267
2555
  const round = row.round;
2268
2556
  const slots = [];
2269
2557
  for (const [i, o] of round.offers.entries()) {
@@ -2273,11 +2561,10 @@ export class Essey {
2273
2561
  : undefined;
2274
2562
  slots.push({ commit: BigInt(o.commit), lock: BigInt(o.lock), active: o.active, open });
2275
2563
  }
2276
- const { member, credential } = readState(this.statePath);
2564
+ const { member, credential } = readState(this.statePath, this.stateKey);
2277
2565
  const L = q.pair[1];
2278
2566
  const prover = this.prover();
2279
- const fee = await this.feeParams(L);
2280
- const seed = this.seed();
2567
+ const fee = await this.loanFee(L, json.fee_commit);
2281
2568
  await this.keys();
2282
2569
  const noteIndex = this.reserve("notes");
2283
2570
  const mine = deriveNoteKey(seed, noteIndex);
@@ -2285,7 +2572,7 @@ export class Essey {
2285
2572
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2286
2573
  const plan = (extHash) => loanSettle({
2287
2574
  slots,
2288
- request: q,
2575
+ request: { ...q, collAmt: opening.amount, collBlind: opening.blinding },
2289
2576
  loanKey: q.loanKey,
2290
2577
  borrowerNote: { pk: notePk(mine.sk), blinding: mine.blinding },
2291
2578
  e: drawEph(),
@@ -2301,8 +2588,8 @@ export class Essey {
2301
2588
  version: KEEPER_LAYOUT_VERSION,
2302
2589
  loanKey: q.loanKey,
2303
2590
  borrowerPk: q.borrowerPk,
2304
- collAmt: q.collAmt,
2305
- collBlind: q.collBlind,
2591
+ collAmt: opening.amount,
2592
+ collBlind: opening.blinding,
2306
2593
  nonceAtCt: 1n,
2307
2594
  terms: draft.terms,
2308
2595
  }),
@@ -2345,7 +2632,7 @@ export class Essey {
2345
2632
  rateBps: w.terms.rateBps,
2346
2633
  terms: w.terms,
2347
2634
  borrowerPk: q.borrowerPk,
2348
- collAmt: q.collAmt,
2635
+ collAmt: opening.amount,
2349
2636
  body: {
2350
2637
  pool: L,
2351
2638
  loan: q.loan,
@@ -2389,7 +2676,7 @@ export class Essey {
2389
2676
  const relayer = this.relayerAddress();
2390
2677
  const relayerFee = this.coinFee(L);
2391
2678
  const prover = this.prover();
2392
- const fee = await this.feeParams(L);
2679
+ const fee = await this.loanFee(L, json.fee_commit);
2393
2680
  const { events, owned, seed } = await this.owned(L);
2394
2681
  const tree = poolTree(orderedLeaves(events));
2395
2682
  const inputs = pickInputs(owned, terms.owed + relayerFee + feeOf({ base: terms.owed, bps: fee.bps, min: fee.min, max: fee.max }).fee);
@@ -2448,9 +2735,9 @@ export class Essey {
2448
2735
  /**
2449
2736
  * The repaid note is `Poseidon(owed, lenderPk, H(DOM_LBLIND, S.x))` with `S = encSk · repay_eph`
2450
2737
  * (`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.
2738
+ * is filler, so the scan never sees it; `owned` finds it through the state file's `held` list.
2452
2739
  */
2453
- async collect(loanId, offer) {
2740
+ async collect(loanId, offer, sweep) {
2454
2741
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2455
2742
  const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
2456
2743
  const loan = address(loanId, "loan id");
@@ -2479,14 +2766,22 @@ export class Essey {
2479
2766
  }
2480
2767
  if (!leaf)
2481
2768
  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) });
2769
+ const note = { value: owed, sk: own.sk, blinding, index: Number(leaf.index) };
2770
+ return this.take(L, events, { ...note, key: offer.noteIndex }, sweep);
2483
2771
  }
2484
- /** Spends a note no ciphertext names, found by its commitment, to the receive address. */
2485
- async claimLeaf(coin, events, note) {
2772
+ /** Refuses a spent note. `sweep` moves it to the receive address now; otherwise it is held for the next spend. */
2773
+ async take(coin, events, note, sweep) {
2486
2774
  const commitment = noteCommitment(note.value, notePk(note.sk), note.blinding);
2487
2775
  const n = noteNullifier(commitment, note.sk, BigInt(note.index));
2488
2776
  if (events.nullifiers.some((x) => BigInt(x) === n))
2489
2777
  throw new EsseyError("INVALID_ARGUMENT", "already collected");
2778
+ const { key, value, blinding, index } = note;
2779
+ if (!sweep)
2780
+ return this.hold(coin, events, { coin, key, value, blinding, index });
2781
+ return { ...(await this.claimLeaf(coin, note)), held: false };
2782
+ }
2783
+ /** Spends a note no ciphertext names, found by its commitment, to the receive address. */
2784
+ async claimLeaf(coin, note) {
2490
2785
  const payTo = receiveTarget(this.receiveAddress());
2491
2786
  let value = 0n;
2492
2787
  const landed = await this.spend(coin, { payTo }, (_owned, _rates, relayerFee) => {
@@ -2510,8 +2805,8 @@ export class Essey {
2510
2805
  };
2511
2806
  }
2512
2807
  /** 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) => {
2808
+ collectSeized(loanId, offer, sweep) {
2809
+ const open = async (json, seizeNonce) => {
2515
2810
  const own = deriveNoteKey(this.seed(), offer.noteIndex);
2516
2811
  const lock = await this.lenderLock(json, own);
2517
2812
  let blinding = lock.blinding;
@@ -2520,18 +2815,21 @@ export class Essey {
2520
2815
  return {
2521
2816
  owed: interest(offer.principal, offer.rateBps, offer.termMs).owed,
2522
2817
  collAmt: lock.amount,
2818
+ key: offer.noteIndex,
2523
2819
  sk: own.sk,
2524
2820
  blinding,
2525
2821
  };
2526
- });
2822
+ };
2823
+ return this.collectFromSeizure(loanId, 0, open, sweep);
2527
2824
  }
2528
2825
  /** 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) => {
2826
+ collectSurplus(p, sweep) {
2827
+ const open = async (json, seizeNonce) => {
2531
2828
  if (termsCommit(p.terms, p.borrowerPk) !== BigInt(json.terms_commit))
2532
2829
  throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
2533
2830
  const seed = this.seed();
2534
- const own = deriveNoteKey(seed, this.indexOfPk(seed, p.borrowerPk));
2831
+ const key = this.indexOfPk(seed, p.borrowerPk);
2832
+ const own = deriveNoteKey(seed, key);
2535
2833
  const start = {
2536
2834
  loanKey: BigInt(json.loan_key),
2537
2835
  borrowerPk: p.borrowerPk,
@@ -2540,15 +2838,16 @@ export class Essey {
2540
2838
  nonce: 1n,
2541
2839
  };
2542
2840
  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
- });
2841
+ return { owed: p.terms.owed, collAmt: p.collAmt, key, sk: own.sk, blinding: opening.blinding };
2842
+ };
2843
+ return this.collectFromSeizure(p.loan, 1, open, sweep);
2545
2844
  }
2546
2845
  /**
2547
2846
  * A seizure leaves the lock's nonce one past the one it folded and `coll_note` as it was. `out` 0 pays
2548
2847
  * `seize - pf - kf` to the lender, 1 pays `avail - seize` to the borrower, each at `outputBlind(blind, out, nonce)`.
2549
2848
  * The split is recomputed from the `p_spot` the seizing call claimed (`io.readSeizure`).
2550
2849
  */
2551
- async collectFromSeizure(loanId, out, open) {
2850
+ async collectFromSeizure(loanId, out, open, sweep) {
2552
2851
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2553
2852
  const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
2554
2853
  const seizure = this.io.readSeizure ?? notSetUp("missing config: no seizure reader");
@@ -2582,7 +2881,7 @@ export class Essey {
2582
2881
  pSpot: fault ? 1n : pSpot,
2583
2882
  expo: (await readPrice(String(json.market_id))).expo,
2584
2883
  risk: loanRisk(rates, decimals, { liquidate: MODE.LIQUIDATE, default: MODE.DEFAULT, fault: MODE.FAULT }[mode]),
2585
- fee: await this.feeParams(C),
2884
+ fee: await this.loanFee(C, json.coll_fee_commit),
2586
2885
  fault,
2587
2886
  });
2588
2887
  const value = out === 0 ? split.toLender : split.surplus;
@@ -2594,15 +2893,18 @@ export class Essey {
2594
2893
  const leaf = events.commitments.find((c) => BigInt(c.commitment) === commitment);
2595
2894
  if (!leaf)
2596
2895
  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++) {
2896
+ for (let i = 0; sweep &&
2897
+ i < SEIZE_REWAITS &&
2898
+ this.pacing &&
2899
+ seizeIsLast(BigInt(events.commitments.length), leaf.index, out); i++) {
2598
2900
  await this.pause(out === 0 ? "collect_seized" : "collect_surplus", loan, null);
2599
2901
  events = await pools(C);
2600
2902
  }
2601
- return this.claimLeaf(C, events, { ...note, index: Number(leaf.index) });
2903
+ return this.take(C, events, { ...note, key: opened.key, index: Number(leaf.index) }, sweep);
2602
2904
  }
2603
2905
  /** The seed index whose key is `pk`: the borrower key of a loan this seed opened. */
2604
2906
  indexOfPk(seed, pk) {
2605
- const n = readState(this.statePath).notes ?? 0;
2907
+ const n = readState(this.statePath, this.stateKey).notes ?? 0;
2606
2908
  for (let i = n - 1; i >= 0; i--)
2607
2909
  if (notePk(deriveNoteKey(seed, i).sk) === pk)
2608
2910
  return i;
@@ -2629,7 +2931,7 @@ export class Essey {
2629
2931
  const seed = this.seed();
2630
2932
  const { opening, index } = this.ownOpening(seed, json, borrowerPk, collAmt);
2631
2933
  const nonce = opening.nonce;
2632
- const fee = await this.feeParams(C);
2934
+ const fee = await this.loanFee(C, json.coll_fee_commit);
2633
2935
  const rates = {
2634
2936
  ltvBps: BigInt(json.ltv_bps),
2635
2937
  liqBps: BigInt(json.liq_bps),
@@ -2670,7 +2972,7 @@ export class Essey {
2670
2972
  }
2671
2973
  /** The seed index a loan this seed opened derives from: its loan key is `Poseidon(sk, blinding, 1)` of that index. */
2672
2974
  indexOfLoanKey(seed, loanKey) {
2673
- const n = readState(this.statePath).notes ?? 0;
2975
+ const n = readState(this.statePath, this.stateKey).notes ?? 0;
2674
2976
  for (let i = n - 1; i >= 0; i--) {
2675
2977
  const k = deriveNoteKey(seed, i);
2676
2978
  if (poseidonHash([k.sk, k.blinding, 1n]) === loanKey)
@@ -2687,7 +2989,7 @@ export class Essey {
2687
2989
  const json = row.json;
2688
2990
  const loanKey = BigInt(json.loan_key);
2689
2991
  this.indexOfLoanKey(this.seed(), loanKey);
2690
- const { member, credential } = readState(this.statePath);
2992
+ const { member, credential } = readState(this.statePath, this.stateKey);
2691
2993
  const n0 = actionHash(blake2b256, loanKey, BigInt(json.nonce), "cancel", new Uint8Array());
2692
2994
  const pass = membership({
2693
2995
  secrets: member,
@@ -2711,7 +3013,7 @@ export class Essey {
2711
3013
  /** The borrower's pass over `kind` and its args, at the loan's next action nonce. */
2712
3014
  async borrowerPass(json, kind, args) {
2713
3015
  const loanKey = BigInt(json.loan_key);
2714
- const { member, credential } = readState(this.statePath);
3016
+ const { member, credential } = readState(this.statePath, this.stateKey);
2715
3017
  if (!member || !credential)
2716
3018
  notSetUp("no credential: call credential.obtain first");
2717
3019
  const n0 = actionHash(blake2b256, loanKey, BigInt(json.nonce), kind, args);
@@ -2735,6 +3037,7 @@ export class Essey {
2735
3037
  * derives from the lock's note index and the round, so the seed alone reopens it.
2736
3038
  */
2737
3039
  async openRefi(p) {
3040
+ assertLoanGrid(p, this.config.closeStepMs ?? HOUR_MS);
2738
3041
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2739
3042
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2740
3043
  const loan = address(p.loan, "loan id");
@@ -2764,8 +3067,6 @@ export class Essey {
2764
3067
  data: requestPlaintext({
2765
3068
  ...request,
2766
3069
  borrowerPk: p.borrowerPk,
2767
- collAmt: opening.amount,
2768
- collBlind: opening.blinding,
2769
3070
  closeMs,
2770
3071
  market,
2771
3072
  coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
@@ -2806,7 +3107,7 @@ export class Essey {
2806
3107
  const pClaim = r.spot < r.ema ? r.spot : r.ema;
2807
3108
  const rates = await this.rates(market);
2808
3109
  const ltvBps = BigInt(json.ltv_bps) < rates.current.ltvBps ? BigInt(json.ltv_bps) : rates.current.ltvBps;
2809
- const fee = await this.feeParams(L);
3110
+ const fee = await this.loanFee(L, json.fee_commit);
2810
3111
  await this.keys();
2811
3112
  const noteIndex = this.reserve("notes");
2812
3113
  const mine = deriveNoteKey(seed, noteIndex);
@@ -2816,7 +3117,7 @@ export class Essey {
2816
3117
  const plan = (extHash) => loanRefi({
2817
3118
  slots,
2818
3119
  round: q.round,
2819
- request: q,
3120
+ request: { ...q, collAmt: opening.amount, collBlind: opening.blinding },
2820
3121
  old: p.terms,
2821
3122
  price: {
2822
3123
  pClaim,
@@ -2936,7 +3237,7 @@ export class Essey {
2936
3237
  const opening = { loanKey, borrowerPk: notePk(own.sk), amount: collAmt, blinding: own.blinding };
2937
3238
  if (collNote(opening) !== BigInt(json.coll.coll_note))
2938
3239
  throw new EsseyError("CT_MISMATCH", "refused: the amount does not open the locked note");
2939
- const fee = await this.feeParams(C);
3240
+ const fee = await this.loanFee(C, json.coll_fee_commit);
2940
3241
  await this.keys();
2941
3242
  const outIndex = this.reserve("notes");
2942
3243
  const out = deriveNoteKey(seed, outIndex);
@@ -2991,7 +3292,7 @@ export class Essey {
2991
3292
  const loanKey = BigInt(json.loan_key);
2992
3293
  const [C, L] = this.pairOf(json.market_id);
2993
3294
  const seed = await this.keys();
2994
- const mine = ownOpenings(await readPool(C), seed, noteEncKey(seed).encKey);
3295
+ const mine = ownOpenings(await readPool(C), seed, noteEncKey(seed).encKey, this.noteNext());
2995
3296
  const keyAt = (i) => deriveNoteKey(seed, i);
2996
3297
  const change = mine.find((o) => {
2997
3298
  if (o.keyIndex === 0)
@@ -3115,12 +3416,12 @@ export class Essey {
3115
3416
  const [C, L] = this.pairOf(json.market_id);
3116
3417
  const poolC = address(json.pool_c, "pool_c");
3117
3418
  const market = address(json.market_id, "market");
3118
- const expiryMs = await this.heartbeatExpiry(json, market, p.expiryMs);
3419
+ const expiryMs = await this.heartbeatExpiry(json, market, p.terms.maturityS, p.expiryMs);
3119
3420
  const { opening } = this.ownOpening(this.seed(), json, p.borrowerPk, p.collAmt);
3120
3421
  const k = p.k ?? 1;
3121
3422
  const reading = await readPrice(market);
3122
3423
  const floor = heartbeatFloor(reading, k);
3123
- const fee = await this.feeParams(C);
3424
+ const fee = await this.loanFee(C, json.coll_fee_commit);
3124
3425
  const rates = {
3125
3426
  ltvBps: BigInt(json.ltv_bps),
3126
3427
  liqBps: BigInt(json.liq_bps),
@@ -3146,7 +3447,7 @@ export class Essey {
3146
3447
  terms: p.terms,
3147
3448
  });
3148
3449
  const proved = await this.prover().prove("health", h.input);
3149
- return this.relayed(heartbeatBody({
3450
+ const landed = await this.relayed(heartbeatBody({
3150
3451
  pool: C,
3151
3452
  loan,
3152
3453
  market,
@@ -3158,14 +3459,43 @@ export class Essey {
3158
3459
  expiryMs,
3159
3460
  priceUpdate: await update(market),
3160
3461
  }));
3462
+ return { ...landed, expiryMs };
3463
+ }
3464
+ /**
3465
+ * PRV-15: until a loan's first heartbeat every keeper may read its terms (`keeper.move:204`), so this follows the
3466
+ * settle at once and unpaced. A heartbeat may follow a settle at once: `hb_at_ms` is 0 (`liquidation.move:199`).
3467
+ */
3468
+ async firstCover(p) {
3469
+ try {
3470
+ await this.untilSettled(p.loan, termsCommit(p.terms, p.borrowerPk));
3471
+ const { digest, ticket, expiryMs } = await this.heartbeatOwn(p);
3472
+ return { ok: true, digest, ticket, expiryMs };
3473
+ }
3474
+ catch (err) {
3475
+ const code = isEsseyError(err) ? err.code : "UNEXPECTED";
3476
+ return { ok: false, code, error: err instanceof Error ? err.message.slice(0, 200) : "unknown" };
3477
+ }
3478
+ }
3479
+ /** The loan reader is an indexer that may trail the landed settle. */
3480
+ async untilSettled(loanId, commit) {
3481
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
3482
+ const loan = address(loanId, "loan id");
3483
+ for (let i = 0; i < SETTLE_READS; i++) {
3484
+ if (i > 0)
3485
+ await this.sleep(SETTLE_READ_MS);
3486
+ const json = (await read(loan))?.json;
3487
+ if (Number(json?.state) === 2 && BigInt(json?.terms_commit ?? -1) === commit)
3488
+ return;
3489
+ }
3490
+ throw new EsseyError("STATE_REFUSED", "the loan read does not show the settle yet");
3161
3491
  }
3162
3492
  /**
3163
3493
  * `liquidation::heartbeat`'s clock rules, checked before proving: one heartbeat per gap (43_015), an expiry at
3164
3494
  * 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.
3495
+ * `liquidation::hb_gap_ms`: 2 minutes on a stand-in market, 50 on any other. No expiry given takes `coverExpiry`,
3496
+ * or the stored expiry when that is later.
3167
3497
  */
3168
- async heartbeatExpiry(json, market, asked) {
3498
+ async heartbeatExpiry(json, market, maturityS, asked) {
3169
3499
  const read = this.io.readMarket ?? notSetUp("missing config: no market reader");
3170
3500
  const standin = /::standin_oracle::StandinOracle$/.test((await read(market)).oracle ?? "");
3171
3501
  const gap = standin ? HB_GAP_STANDIN_MS : HB_GAP_MS;
@@ -3176,8 +3506,10 @@ export class Essey {
3176
3506
  const wait = (last + gap - now + 999n) / 1000n;
3177
3507
  throw new EsseyError("INVALID_ARGUMENT", `the last heartbeat is under one gap old; retry in ${wait} s`);
3178
3508
  }
3179
- const hour = heartbeatHour(now);
3180
- const expiry = asked ?? (stored > hour ? stored : hour);
3509
+ const fresh = coverExpiry(now, maturityS);
3510
+ if (asked === undefined && fresh < now + gap)
3511
+ throw new EsseyError("INVALID_ARGUMENT", "the loan is under one gap from maturity plus grace");
3512
+ const expiry = asked ?? (stored > fresh ? stored : fresh);
3181
3513
  if (expiry < now + gap || expiry > now + H_MAX_MS)
3182
3514
  throw new EsseyError("INVALID_ARGUMENT", "the expiry must be at least one gap and at most 24 h ahead");
3183
3515
  if (expiry < stored)
@@ -3203,7 +3535,7 @@ export class Essey {
3203
3535
  throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
3204
3536
  const [C, L] = this.pairOf(json.market_id);
3205
3537
  const ids = { loan, poolC: address(json.pool_c, "pool_c"), market: address(json.market_id, "market") };
3206
- const fee = await this.feeParams(C);
3538
+ const fee = await this.loanFee(C, json.coll_fee_commit);
3207
3539
  const { events, owned, seed } = await this.owned(C);
3208
3540
  const { opening } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
3209
3541
  const inputs = pickInputs(owned, p.add);
@@ -3421,8 +3753,8 @@ export class Essey {
3421
3753
  const market = address(json.market_id, "market");
3422
3754
  const reading = await readPrice(market);
3423
3755
  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);
3756
+ const nowS = asDefault ? defaultNowS((this.io.now ?? Date.now)()) : 0n;
3757
+ const fee = await this.loanFee(C, json.coll_fee_commit);
3426
3758
  await this.keys();
3427
3759
  const keeperIndex = this.reserve("notes");
3428
3760
  const keeper = deriveNoteKey(seed, keeperIndex);
@@ -3524,17 +3856,19 @@ export class Essey {
3524
3856
  /** D-SPEC §6.2:599. The seller pass over `sale_room::open_args`, at action nonce 0; the relayer or the callback pays. */
3525
3857
  async openSale(p) {
3526
3858
  const asked = assertSaleOpen(p);
3859
+ assertSaleGrid(asked, this.config.closeStepMs ?? HOUR_MS);
3860
+ const nowMs = (this.io.now ?? Date.now)();
3527
3861
  const open = {
3528
3862
  ...asked,
3529
- closeMs: stepClose(asked.closeMs, (this.io.now ?? Date.now)(), SALE_MAX_WINDOW_MS, this.config.closeStepMs),
3863
+ closeMs: stepClose(nowMs + asked.bidWindowMs, nowMs, SALE_MAX_WINDOW_MS, this.config.closeStepMs),
3530
3864
  };
3531
3865
  requireSale(this.config);
3532
3866
  const pool = poolId(this.config, open.coin);
3867
+ const item = { id: address(open.itemId, "itemId"), type: open.itemType };
3868
+ const readRooms = this.io.readRooms ?? notSetUp("missing config: no room reader");
3533
3869
  const submit = (open.sponsored ?? this.sponsoring() !== null)
3534
- ? this.saleSponsor(pool)
3870
+ ? await this.saleSponsor(pool, item.id)
3535
3871
  : (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
3872
  const closeMs = BigInt(open.closeMs);
3539
3873
  const finishByMs = closeMs + BigInt(open.finishWindowMs);
3540
3874
  const typeName = asInvalid(() => {
@@ -3577,15 +3911,11 @@ export class Essey {
3577
3911
  });
3578
3912
  if (typeof landed.digest !== "string" || landed.digest.length === 0 || typeof landed.ticket !== "string")
3579
3913
  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");
3914
+ const { id, json } = await this.listedByKey("room", "sale_key", saleKey, async (c) => {
3915
+ const page = await readRooms(c);
3916
+ return { rows: page.rooms, next: page.next };
3917
+ });
3918
+ assertRoomMatches(this.config, open, { id, json });
3589
3919
  return {
3590
3920
  id,
3591
3921
  digest: landed.digest,
@@ -3594,19 +3924,21 @@ export class Essey {
3594
3924
  };
3595
3925
  }
3596
3926
  /**
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.
3927
+ * The sponsored open (E-34): a fresh seed-derived sender signs `from_proof` and `open` while the relayer pays gas.
3928
+ * PRV-35: an item at one of this seed's `itemAddress()` holders opens from that holder with no hand-over; any other
3929
+ * item is first delivered to a fresh deposit signer. Every reader is checked here, before any proof, reserve or
3930
+ * delivery. An open that stops after the delivery leaves the item at that sender, which only its seed can move.
3600
3931
  */
3601
- saleSponsor(pool) {
3932
+ async saleSponsor(pool, itemId) {
3602
3933
  const relayer = this.sponsorRelayer();
3603
- const deliver = this.io.deliverSaleItem ?? notSetUp("no deliverSaleItem: the SDK never holds the item's wallet");
3604
3934
  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
3935
  const readShared = this.io.readSharedVersion ?? notSetUp("no chain reader for shared object versions");
3607
3936
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
3608
3937
  const keyRegistry = this.config.objects.keyRegistry ?? notSetUp("missing config: no KeyRegistry");
3609
- const used = this.addressUsed();
3938
+ const held = this.holderOf((await readRef(itemId)).owner);
3939
+ const deliver = held !== null
3940
+ ? null
3941
+ : (this.io.deliverSaleItem ?? notSetUp("no deliverSaleItem: the SDK never holds the item's wallet"));
3610
3942
  const packages = { pool: this.config.packages.pool, sale: this.config.packages.sale };
3611
3943
  const shared = (r) => ({
3612
3944
  objectId: r.id,
@@ -3614,9 +3946,10 @@ export class Essey {
3614
3946
  });
3615
3947
  return async (tx) => {
3616
3948
  const seed = this.seed();
3617
- const signer = depositSigner(seed, await this.freshSigner(seed, used));
3949
+ const signer = held !== null ? itemHolder(seed, held) : depositSigner(seed, this.freshSigner());
3618
3950
  const sender = signer.toSuiAddress();
3619
- await deliver({ item: tx.item, sender });
3951
+ if (deliver)
3952
+ await deliver({ item: tx.item, sender });
3620
3953
  const ref = await readRef(tx.item.id);
3621
3954
  if (ref.owner === null || normalizeSuiAddress(ref.owner) !== sender)
3622
3955
  throw new EsseyError("SERVICE_REFUSED", "refused: the item is not at the sale sender; nothing was signed");
@@ -3650,7 +3983,7 @@ export class Essey {
3650
3983
  txBytesB64: sponsored.txBytesB64,
3651
3984
  userSig: signature,
3652
3985
  });
3653
- return { id: (await readOpened(digest)).room, digest, ticket: "" };
3986
+ return { digest, ticket: "" };
3654
3987
  };
3655
3988
  }
3656
3989
  /** D-SPEC §6.2:600. */
@@ -3741,7 +4074,7 @@ export class Essey {
3741
4074
  if (seq >= room.maxBids)
3742
4075
  throw new EsseyError("INVALID_ARGUMENT", "the room is full");
3743
4076
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
3744
- const { member, credential } = readState(this.statePath);
4077
+ const { member, credential } = readState(this.statePath, this.stateKey);
3745
4078
  if (!member || !credential)
3746
4079
  notSetUp("no credential: call credential.obtain first");
3747
4080
  const relayer = this.relayerAddress();
@@ -3816,7 +4149,7 @@ export class Essey {
3816
4149
  /** `sale_room::seal_approve_bid`: the seller's SEAL pass over `seal_bid` of bid `seq`, bound to the viewer, nonce 0. */
3817
4150
  bidApprove(room, seq) {
3818
4151
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
3819
- const { member, credential } = readState(this.statePath);
4152
+ const { member, credential } = readState(this.statePath, this.stateKey);
3820
4153
  if (!member || !credential)
3821
4154
  notSetUp("no credential: call credential.obtain first");
3822
4155
  const scope = keyId(room.saleKey);
@@ -3912,7 +4245,7 @@ export class Essey {
3912
4245
  });
3913
4246
  }
3914
4247
  indexOfSellerKey(seed, sellerSk) {
3915
- const n = readState(this.statePath).notes ?? 0;
4248
+ const n = readState(this.statePath, this.stateKey).notes ?? 0;
3916
4249
  for (let i = n - 1; i >= 0; i--)
3917
4250
  if (deriveNoteKey(seed, i).sk === sellerSk)
3918
4251
  return i;
@@ -3992,17 +4325,18 @@ export class Essey {
3992
4325
  const w = itemClaim({
3993
4326
  vault: { roomField: BigInt(json.room_field), claim },
3994
4327
  holder,
3995
- recipient: p.recipient,
4328
+ recipient: p.recipient ?? this.itemAddress(),
3996
4329
  relayer: this.relayerAddress(),
3997
4330
  });
3998
4331
  const proof = (await this.prover().prove("item_claim", w.input)).proof;
3999
- return this.freeLoan(claimBody, {
4332
+ const landed = await this.freeLoan(claimBody, {
4000
4333
  pool: room.coin,
4001
4334
  vault,
4002
4335
  recipient: w.statement.recipient,
4003
4336
  nullifier: w.statement.nullifier,
4004
4337
  proved: { proof, publicSignals: w.publics.map(String) },
4005
4338
  });
4339
+ return { ...landed, to: w.statement.recipient };
4006
4340
  }
4007
4341
  async prepareOpen(body) {
4008
4342
  if (body.kind !== "loan_open")