@esseyonsui/sui-sdk-v3 0.1.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) 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 +180 -54
  8. package/dist/essey.d.ts.map +1 -1
  9. package/dist/essey.js +580 -227
  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/health.d.ts +2 -0
  17. package/dist/v3/collateral/health.d.ts.map +1 -1
  18. package/dist/v3/collateral/health.js +6 -0
  19. package/dist/v3/collateral/math.d.ts +6 -0
  20. package/dist/v3/collateral/math.d.ts.map +1 -1
  21. package/dist/v3/collateral/math.js +12 -0
  22. package/dist/v3/credential/membership.d.ts +2 -0
  23. package/dist/v3/credential/membership.d.ts.map +1 -1
  24. package/dist/v3/credential/membership.js +4 -0
  25. package/dist/v3/fees.d.ts +6 -0
  26. package/dist/v3/fees.d.ts.map +1 -1
  27. package/dist/v3/loans/offer-plan.d.ts +1 -1
  28. package/dist/v3/loans/offer-plan.d.ts.map +1 -1
  29. package/dist/v3/loans/offer-plan.js +5 -4
  30. package/dist/v3/loans/open-plan.d.ts +7 -3
  31. package/dist/v3/loans/open-plan.d.ts.map +1 -1
  32. package/dist/v3/loans/open-plan.js +11 -3
  33. package/dist/v3/notes/derive.d.ts +7 -0
  34. package/dist/v3/notes/derive.d.ts.map +1 -1
  35. package/dist/v3/notes/derive.js +10 -0
  36. package/dist/v3/notes/opening.d.ts +26 -2
  37. package/dist/v3/notes/opening.d.ts.map +1 -1
  38. package/dist/v3/notes/opening.js +61 -24
  39. package/dist/v3/notes/scan.d.ts +20 -3
  40. package/dist/v3/notes/scan.d.ts.map +1 -1
  41. package/dist/v3/notes/scan.js +59 -16
  42. package/dist/v3/notes/withdraw.d.ts +2 -0
  43. package/dist/v3/notes/withdraw.d.ts.map +1 -1
  44. package/dist/v3/notes/withdraw.js +9 -0
  45. package/dist/v3/pace.d.ts +1 -1
  46. package/dist/v3/pace.js +1 -1
  47. package/dist/v3/stage1.d.ts +5 -2
  48. package/dist/v3/stage1.d.ts.map +1 -1
  49. package/dist/v3/stage1.js +17 -6
  50. package/dist/v3/time-grid.d.ts +25 -0
  51. package/dist/v3/time-grid.d.ts.map +1 -0
  52. package/dist/v3/time-grid.js +51 -0
  53. package/package.json +1 -1
package/dist/essey.js CHANGED
@@ -1,22 +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";
21
+ import { GRACE_S, coverExpiry, heartbeatFloor } from "./v3/collateral/math.js";
22
+ import { assertLoanGrid, assertRequestClose, assertRequestTerm, assertSaleGrid, defaultNowS, settleNowS, } from "./v3/time-grid.js";
20
23
  /**
21
24
  * The Seal servers dry-run `keeper::check_loan` and answer "does not have access" when it aborts: a heartbeat still
22
25
  * covers the loan at this price, the loan is not active, or the pass or badge does not match.
@@ -31,7 +34,10 @@ function keeperRefusal(err) {
31
34
  const HB_GAP_MS = 3000000n;
32
35
  const HB_GAP_STANDIN_MS = 120000n;
33
36
  const H_MAX_MS = 86400000n;
34
- import { MODE, NO_TERMS, health, lenderAmount, loanRisk, seizeSplit } from "./v3/collateral/health.js";
37
+ const FIND_LISTED_TRIES = 15;
38
+ const FIND_LISTED_PAUSE_MS = 1_500;
39
+ const STALE_REQUEST_MS = 86_400_000;
40
+ import { MODE, NO_TERMS, health, lenderAmount, loanRisk, seizeIsLast, seizeSplit, } from "./v3/collateral/health.js";
35
41
  import { collLockPk, collNote, outputBlind, requestCommit, termsCommit, } from "./v3/collateral/openings.js";
36
42
  import { fetchKeeperPlaintext, keeperKeyId, openingOf, rollTo } from "./v3/collateral/seal.js";
37
43
  import { localHealth } from "./v3/collateral/local-health.js";
@@ -46,10 +52,10 @@ import { LOAN_REFI_KIND, loanRefi } from "./v3/loans/refi-plan.js";
46
52
  import { LOAN_OFFER_KIND, decodeRequest, lock4, lockField, loanExt, loanOffer, offerKeyId, offerPlaintext, offerRoom, sealListingBind, } from "./v3/loans/offer-plan.js";
47
53
  import { badgeRecipient, proveBadge } from "./v3/badge.js";
48
54
  import { proveFaucet } from "./v3/faucet.js";
49
- import { ecdhBlind, feeOf, treasuryPoint, verifyFeeOpening, } from "./v3/fees.js";
55
+ import { ecdhBlind, feeCommit, feeOf, treasuryPoint, verifyFeeOpening, } from "./v3/fees.js";
50
56
  import { JS4_LEVELS, deposit as depositInput, js4, membership, } from "./v3/inputs.js";
51
57
  import { marketRates } from "./v3/market.js";
52
- 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";
53
59
  import { plan as settlePlan } from "./v3/sales/auctioneer.js";
54
60
  import { lockBid } from "./v3/sales/bid.js";
55
61
  import { bidBody, cancelBody, claimBody, expireBody, finishBody, reclaimBody, slashBody, } from "./v3/sales/bodies.js";
@@ -61,17 +67,19 @@ import { bidAad, bidKeyId, bidPlaintext, openBid, sealBidBind } from "./v3/sales
61
67
  import { assertFinishWindow, openArgs, openCommits, typeNameOf } from "./v3/sales/seller.js";
62
68
  import { splitDenominations } from "./v3/notes/denominations.js";
63
69
  import { DEPOSIT_ROOM, carriesKind, depositKind, executeSponsored, sponsor, } from "./v3/notes/deposit.js";
64
- 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";
65
71
  import { faucetGrant } from "./v3/notes/faucet.js";
66
72
  import { noteCommitment, noteNullifier, notePk } from "./v3/notes/keys.js";
67
- import { fillerEnc, sealOpening } from "./v3/notes/opening.js";
68
- 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";
69
75
  import { poolTree } from "./v3/notes/tree.js";
70
- 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";
71
77
  import { paceDelay } from "./v3/pace.js";
72
78
  import { proofBytes } from "./v3/proof-bytes.js";
73
79
  import { RelayClient, failure, } from "./v3/relay/client.js";
74
80
  import { provePossession } from "./v3/relay/possession.js";
81
+ const SETTLE_READS = 15;
82
+ const SETTLE_READ_MS = 2_000;
75
83
  /** A ticket lives 15 min (`services/relayer-v3/src/tickets.ts:7`); a minute past it the relayer answers "expired". */
76
84
  const FOLLOW_CAP_MS = 16 * 60_000;
77
85
  /** Times a seize output's collect waits again while nothing has landed after the seizure. */
@@ -79,7 +87,6 @@ const SEIZE_REWAITS = 3;
79
87
  /** The relayer's 202 after its wait cap can carry an etaMs near 0 (LOAD-02), which would spend every poll in seconds. */
80
88
  const FOLLOW_MIN_GAP_MS = 2_000;
81
89
  const SPENT_POLLS = 60;
82
- const MAX_USED_SENDERS = 64;
83
90
  const EPH_SHIFT = 3n;
84
91
  const NO_RELAYER = "no relayer url: the deployment record names none yet; nothing was sent";
85
92
  const NO_RELAYER_ADDRESS = "no relayer address: the deployment record names none yet; nothing was sent";
@@ -104,6 +111,14 @@ function unknownObject(what) {
104
111
  function wrongCoinObject() {
105
112
  throw new EsseyError("INVALID_ARGUMENT", "wrong coin: the envelope pool is not the loan coin");
106
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
+ }
107
122
  const isIndex = (n) => Number.isSafeInteger(n) && n >= 0;
108
123
  const isSigned = (c, s) => c.commitment === s.commitment && c.enc === s.enc;
109
124
  const landedIn = (events, r) => events.commitments.some((c) => r.signed.some((s) => isSigned(c, s)));
@@ -129,6 +144,18 @@ function parseStranded(raw) {
129
144
  const signed = r.signed.map(parseSigned);
130
145
  return { coin: r.coin, signer: r.signer, note: r.note, value, signed };
131
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
+ }
132
159
  function parseSigned(raw) {
133
160
  const { commitment, enc } = (raw ?? {});
134
161
  if (typeof commitment !== "string" || typeof enc !== "string" || !/^0x[0-9a-f]+$/.test(enc))
@@ -158,13 +185,32 @@ function stateText(path) {
158
185
  Atomics.wait(pause, 0, 0, 1);
159
186
  }
160
187
  }
161
- 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) {
162
208
  if (!existsSync(path))
163
209
  return { v: 1 };
164
210
  if ((statSync(path).mode & 0o077) !== 0)
165
211
  throw new EsseyError("STATE_REFUSED", "refused: the state file must be mode 600");
166
212
  try {
167
- const raw = JSON.parse(stateText(path));
213
+ const raw = stateJson(stateText(path), key);
168
214
  if (raw.v !== 1)
169
215
  throw new Error("version");
170
216
  const m = raw.member;
@@ -174,11 +220,17 @@ function readState(path) {
174
220
  const credential = raw.credential === undefined ? undefined : parseCredential(raw.credential);
175
221
  if (raw.seed !== undefined && !(typeof raw.seed === "string" && /^[0-9a-f]{64}$/.test(raw.seed)))
176
222
  throw new Error("seed");
177
- const counters = [raw.notes, raw.signers];
223
+ const counters = [raw.notes, raw.signers, raw.holders];
178
224
  if (counters.some((n) => n !== undefined && !isIndex(n)))
179
225
  throw new Error("counter");
180
226
  if (raw.stranded !== undefined && !Array.isArray(raw.stranded))
181
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");
182
234
  return {
183
235
  v: 1,
184
236
  member,
@@ -187,11 +239,16 @@ function readState(path) {
187
239
  seed: raw.seed,
188
240
  notes: raw.notes,
189
241
  signers: raw.signers,
242
+ holders: raw.holders,
190
243
  stranded: raw.stranded?.map(parseStranded),
191
244
  badge: raw.badge === undefined ? undefined : parseBadge(raw.badge),
245
+ held: raw.held?.map(parseHeld),
246
+ paid: paid,
192
247
  };
193
248
  }
194
- catch {
249
+ catch (error) {
250
+ if (isEsseyError(error, "STATE_REFUSED"))
251
+ throw error;
195
252
  throw new EsseyError("STATE_REFUSED", "refused: the state file is not readable as SDK state");
196
253
  }
197
254
  }
@@ -199,12 +256,12 @@ function readState(path) {
199
256
  * Written beside the target and renamed over it, so a failure leaves the old file whole. "wx" refuses
200
257
  * an existing name instead of following a planted link with the member secrets.
201
258
  */
202
- function writeState(path, state, held) {
259
+ function writeState(path, state, held, key) {
203
260
  const tmp = `${path}.${randomBytes(16).toString("hex")}.tmp`;
204
261
  const fd = openSync(tmp, "wx", 0o600);
205
262
  try {
206
263
  try {
207
- writeFileSync(fd, toJson(state));
264
+ writeFileSync(fd, key ? sealState(key, toJson(state)) : toJson(state));
208
265
  }
209
266
  finally {
210
267
  closeSync(fd);
@@ -506,8 +563,6 @@ function relayerUrl(choice, config) {
506
563
  throw new EsseyError("ONION_UNAVAILABLE", "refused: this build has no Tor transport; nothing was sent");
507
564
  return choice === "clear" ? config.relayer.url : choice;
508
565
  }
509
- /** A seize inserts its notes in pairs (`liquidation.move:445-446`, `pool.move:677-685`): its last leaf is `index | 1`. */
510
- const lastLanded = (events, index) => BigInt(events.commitments.length) === (index | 1n) + 1n;
511
566
  function pacingOf(delays) {
512
567
  if (delays === undefined || delays === "default")
513
568
  return true;
@@ -548,16 +603,41 @@ function partial(error, landed, pieces, stranded) {
548
603
  * `address()` pads a short value and takes zero, and `pool::withdraw` pays what it is given
549
604
  * (`move/v3/pool/sources/pool.move:312`).
550
605
  */
551
- const RECEIVE_PREFIX = "v3note:";
552
- /** `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
+ */
553
622
  function receiveTarget(to) {
554
- const m = typeof to === "string" ? /^v3note:([0-9]{1,78}):((?:02|03)[0-9a-f]{64}):([0-9]{1,15})$/.exec(to) : null;
555
- if (!m)
556
- throw new EsseyError("INVALID_ARGUMENT", "to is not a v3note receive address; nothing was sent");
557
- 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]}`);
558
628
  if (pk >= R)
559
- throw new EsseyError("INVALID_ARGUMENT", "to is not a v3note receive address; nothing was sent");
560
- 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);
561
641
  }
562
642
  function payee(to) {
563
643
  if (typeof to !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(to))
@@ -568,6 +648,7 @@ function payee(to) {
568
648
  return recipient;
569
649
  }
570
650
  const listOf = (to) => (Array.isArray(to) ? to : [to]);
651
+ const piecesTo = (pieces, to) => pieces.map((amount, i) => ({ amount, to: to[i] }));
571
652
  function onePayee(to) {
572
653
  const list = listOf(to);
573
654
  if (list.length !== 1)
@@ -575,7 +656,7 @@ function onePayee(to) {
575
656
  return list[0];
576
657
  }
577
658
  /** Pieces already paid are public and final; the error lists them so none is paid twice. */
578
- function payoutStopped(error, paid, pieces) {
659
+ function payoutStopped(error, paid, rest) {
579
660
  if (paid.length === 0)
580
661
  return error;
581
662
  const at = paid.length + 1;
@@ -585,11 +666,11 @@ function payoutStopped(error, paid, pieces) {
585
666
  : error instanceof Error
586
667
  ? error.message
587
668
  : "it threw";
588
- 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`, {
589
670
  ...inner?.detail,
590
671
  landed: paid.map((p) => ({ digest: p.digest, value: p.amount.toString(), to: p.to })),
591
- stopped: pieces[paid.length].toString(),
592
- untried: pieces.slice(at).map(String),
672
+ stopped: rest[0].toString(),
673
+ untried: rest.slice(1).map(String),
593
674
  });
594
675
  stopped.cause = error;
595
676
  return stopped;
@@ -621,6 +702,7 @@ export class Essey {
621
702
  relayerBase;
622
703
  seedOption;
623
704
  pacing;
705
+ stateKey;
624
706
  credential;
625
707
  fees;
626
708
  relayer;
@@ -630,7 +712,11 @@ export class Essey {
630
712
  /** D-SPEC §6.2:598-600. Sealed sale rooms. */
631
713
  sales;
632
714
  keeper;
633
- constructor(config, statePath, apiOrigin, fetch, io, relay, relayerBase, seedOption, pacing) {
715
+ /** Each pass over the fee room carries the same tag, so one fetch per coin, lane and commit is all v3api sees. */
716
+ feeOpenings = new Map();
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) {
634
720
  this.config = config;
635
721
  this.statePath = statePath;
636
722
  this.apiOrigin = apiOrigin;
@@ -640,17 +726,18 @@ export class Essey {
640
726
  this.relayerBase = relayerBase;
641
727
  this.seedOption = seedOption;
642
728
  this.pacing = pacing;
729
+ this.stateKey = stateKey;
643
730
  const closeOf = (loan) => () => this.roundDeadline(loan, "close_ms");
644
731
  const settleByOf = (loan) => () => this.roundDeadline(loan, "settle_by_ms");
645
732
  const coverOf = (loan) => () => this.coverDeadline(loan);
646
733
  this.credential = {
647
734
  obtain: (o) => this.obtain(o?.invite, o?.role ?? "member"),
648
- status: () => this.info(readState(this.statePath).credential),
735
+ status: () => this.info(readState(this.statePath, this.stateKey).credential),
649
736
  list: () => this.listCredentials(),
650
737
  view: () => this.viewCredential(),
651
738
  renew: () => this.renew(),
652
739
  };
653
- this.fees = { params: (coin) => this.feeParams(coin) };
740
+ this.fees = { params: (coin, lane) => this.feeParams(coin, lane) };
654
741
  this.relayer = {
655
742
  info: async () => this.relayClient().info(),
656
743
  status: async (ticket) => this.relayClient().status(ticket),
@@ -662,6 +749,8 @@ export class Essey {
662
749
  offer: (p) => this.paidLoan(offerLoan, p),
663
750
  request: (id) => this.readRequest(id),
664
751
  lend: async (p) => {
752
+ await this.refuseStaleRequest(p.loan);
753
+ await this.refuseOffGridClose(p.loan);
665
754
  const send = async () => {
666
755
  await this.pause("offer", p.loan, closeOf(p.loan));
667
756
  const { body, record, seq } = await this.planOffer(p.loan, BigInt(p.rateBps));
@@ -680,12 +769,14 @@ export class Essey {
680
769
  return (await send()).sent;
681
770
  }
682
771
  },
683
- collect: (p) => this.paced("collect", p.loan, null, () => this.collect(p.loan, p.offer)),
684
- collectSeized: (p) => this.paced("collect_seized", p.loan, null, () => this.collectSeized(p.loan, p.offer)),
685
- collectSurplus: (p) => this.paced("collect_surplus", p.loan, null, () => this.collectSurplus(p)),
686
- accept: (id) => this.paced("settle", id, settleByOf(id), async () => {
687
- const { body, rateBps, terms, borrowerPk, collAmt } = await this.planSettle(id);
688
- 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 };
689
780
  }),
690
781
  release: (p) => this.paced("release", p.loan, null, () => this.releaseCollateral(p.loan, p.terms, p.borrowerPk, p.collAmt)),
691
782
  cancelOwn: (id) => this.cancelOwn(id),
@@ -693,7 +784,10 @@ export class Essey {
693
784
  fault: (p) => this.paced("fault", p.loan, null, () => this.ctFault(p.loan, p.via)),
694
785
  openRefi: (p) => this.openRefi(p),
695
786
  cancelRefi: (id) => this.cancelRefiOwn(id),
696
- 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
+ }),
697
791
  reclaimOffer: (p) => this.paced("reclaim_offer", p.loan, null, () => this.reclaimOffer(p.loan, p.offer, p.round)),
698
792
  heartbeat: (p) => this.paced("heartbeat", p.loan, coverOf(p.loan), () => this.heartbeatOwn(p)),
699
793
  topup: (p) => this.paced("topup", p.loan, coverOf(p.loan), () => this.topupOwn(p)),
@@ -720,10 +814,23 @@ export class Essey {
720
814
  open: (coin, index) => this.openNote(coin, index),
721
815
  list: (coin) => this.listNotes(coin),
722
816
  view: (coin, index) => this.viewNote(coin, index),
723
- withdraw: (coin, amount, to, o) => this.paced("withdraw", `${coin}:${amount}:${to}`, null, () => this.withdraw(coin, amount, to, o)),
817
+ withdrawFirst: async (coin, amount, to, o = {}) => {
818
+ const plan = this.withdrawPlan(coin, amount, to, o);
819
+ this.refusePaid(to, o);
820
+ return this.paced("withdraw", `${coin}:${amount}:${to}`, null, () => this.withdrawStart(coin, plan, o));
821
+ },
822
+ withdraw: async (coin, amount, to, o) => this.drain(await this.notes.withdrawFirst(coin, amount, to, o)),
823
+ payNext: (pending) => this.payNext(pending),
724
824
  receiveAddress: () => this.receiveAddress(),
725
825
  transfer: (coin, amount, to) => this.paced("transfer", `${coin}:${amount}:${to}`, null, () => this.transfer(coin, amount, to)),
726
- 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
+ },
727
834
  recoverStranded: () => this.recoverStranded(),
728
835
  };
729
836
  this.sales = {
@@ -736,8 +843,9 @@ export class Essey {
736
843
  expire: (p) => this.expireSale(p.room, p.vault),
737
844
  reclaim: (p) => this.paced("sale_reclaim", p.room, null, () => this.reclaimBid(p.room, p.bid, p.what ?? "lock")),
738
845
  claim: (p) => this.claimItem(p),
846
+ itemAddress: () => this.itemAddress(),
739
847
  cancel: (p) => this.cancelSale(p.room, p.vault),
740
- badgeGrant: (to) => this.badgeGrant(to),
848
+ badgeGrant: (to) => this.badgeGrant(to ?? this.itemAddress()),
741
849
  };
742
850
  this.keeper = {
743
851
  ...keeperSection(io.keeper, io.now ?? Date.now),
@@ -748,15 +856,21 @@ export class Essey {
748
856
  }
749
857
  static async connect(o, io = {}) {
750
858
  assertTestnet(o.network);
751
- const fetch = io.fetch ?? ((url, init) => globalThis.fetch(url, init));
859
+ const fetch = fixedHeaders(io.fetch ?? ((url, init) => globalThis.fetch(url, init)));
752
860
  if (o.seed !== undefined && !(o.seed instanceof Uint8Array && o.seed.length === SEED_BYTES))
753
861
  throw new EsseyError("INVALID_ARGUMENT", "seed must be 32 bytes");
754
- 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);
755
866
  const { config, apiOrigin } = await loadConfig(o.config, fetch);
756
867
  const url = relayerUrl(o.relayer ?? "clear", config);
757
868
  const relay = url === null ? null : new RelayClient({ url, fetch });
758
869
  const relayerBase = url === null ? null : serviceUrl(url, "relayer url").origin;
759
- 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;
760
874
  }
761
875
  paced(action, subject, deadline, run) {
762
876
  return this.pause(action, subject, deadline).then(run);
@@ -768,12 +882,25 @@ export class Essey {
768
882
  const at = deadline ? await deadline() : null;
769
883
  const nowMs = (this.io.now ?? Date.now)();
770
884
  const delayMs = paceDelay(action, nowMs, at, Number(CLOSE_MARGIN_MS));
771
- const wait = this.io.pace ?? ((p) => this.sleep(p.delayMs));
772
- 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));
773
896
  }
774
897
  sleep(ms) {
775
898
  return (this.io.sleep ?? ((t) => new Promise((resolve) => setTimeout(resolve, t))))(ms);
776
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
+ }
777
904
  /** The current round's `close_ms` (offers, `loan.move:339`) or `settle_by_ms` (settles, `settle.move:132`). */
778
905
  async roundDeadline(loanId, field) {
779
906
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
@@ -781,6 +908,26 @@ export class Essey {
781
908
  const at = row?.round?.[field];
782
909
  return at === undefined ? null : { atMs: Number(at) };
783
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
+ }
784
931
  /** The stored heartbeat expiry, past which a keeper may liquidate (`keeper.move:204`); none before a first heartbeat. */
785
932
  async coverDeadline(loanId) {
786
933
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
@@ -823,10 +970,10 @@ export class Essey {
823
970
  */
824
971
  update(change) {
825
972
  return withLock(this.statePath, (file, held) => {
826
- const state = readState(file);
973
+ const state = readState(file, this.stateKey);
827
974
  this.ownSeed(state);
828
975
  const result = change(state);
829
- writeState(file, state, held);
976
+ writeState(file, state, held, this.stateKey);
830
977
  return result;
831
978
  });
832
979
  }
@@ -841,7 +988,7 @@ export class Essey {
841
988
  return this.issue(api, member, slot, role);
842
989
  }
843
990
  async renew() {
844
- const { member, slot, credential } = readState(this.statePath);
991
+ const { member, slot, credential } = readState(this.statePath, this.stateKey);
845
992
  if (!slot || !credential)
846
993
  notSetUp("no credential to renew: call credential.obtain first");
847
994
  const info = await this.issue(this.api(), member, slot, credential.role);
@@ -858,15 +1005,42 @@ export class Essey {
858
1005
  return this.info(credential);
859
1006
  }
860
1007
  /** The opening for one coin, returned only after it matches the commit read from chain (D §5.4). */
861
- async feeParams(coin) {
1008
+ async feeParams(coin, asked = "hidden") {
862
1009
  if (!COINS.includes(coin))
863
1010
  throw new EsseyError("INVALID_ARGUMENT", "coin is not tusdsui, usdc or sui");
1011
+ const lane = this.feeLane(coin, asked);
1012
+ const readFeeCommit = this.io.readFeeCommit ?? notSetUp("no chain reader: the FeeConfig objects are not published yet");
1013
+ const key = `${coin}:${lane}`;
1014
+ const held = this.feeOpenings.get(key);
1015
+ if (held && feeCommit(held) === (await readFeeCommit(coin, lane)))
1016
+ return held;
1017
+ const body = await this.feePass("/v3/fee-params", { coin, ...(lane === "edge" ? { lane } : {}) });
1018
+ const params = verifyFeeOpening(body, await readFeeCommit(coin, lane));
1019
+ this.feeOpenings.set(key, params);
1020
+ return params;
1021
+ }
1022
+ /**
1023
+ * PRV-02: a loan step folds the loan's own snapshot (`loan.move:141-143`), not the config as it stands, so its
1024
+ * opening is fetched by that commit (v3api's archive) and must hash to it.
1025
+ */
1026
+ async loanFee(coin, snapshot) {
1027
+ const commit = BigInt(String(snapshot));
1028
+ const key = `${coin}:${commit}`;
1029
+ const held = this.snapshotOpenings.get(key);
1030
+ if (held)
1031
+ return held;
1032
+ const body = await this.feePass("/v3/fee-params/opening", { coin, commit: commit.toString() });
1033
+ const params = verifyFeeOpening(body, commit);
1034
+ this.snapshotOpenings.set(key, params);
1035
+ return params;
1036
+ }
1037
+ /** One fee-params pass (`FEE_PARAMS_ROOM`, bound to a fresh challenge) carrying `fields`; the reply body. */
1038
+ async feePass(path, fields) {
864
1039
  const api = this.api();
865
- const { member, credential } = readState(this.statePath);
1040
+ const { member, credential } = readState(this.statePath, this.stateKey);
866
1041
  if (!member || !credential)
867
1042
  notSetUp("no credential: call credential.obtain first");
868
1043
  const prover = this.io.prover ?? this.missingProver("membership");
869
- const readFeeCommit = this.io.readFeeCommit ?? notSetUp("no chain reader: the FeeConfig objects are not published yet");
870
1044
  const challenge = await getJson(this.fetch, `${api}/v3/fee-params/challenge`);
871
1045
  const nonce = challenge.body.nonce;
872
1046
  if (challenge.status !== 200 || typeof nonce !== "string")
@@ -878,16 +1052,27 @@ export class Essey {
878
1052
  domain: credential.role === "keeper" ? DOMAIN_KEEPER : DOMAIN_SENDER,
879
1053
  room: FEE_PARAMS_ROOM,
880
1054
  bind: nonce,
1055
+ nonce: feeNonceLane(nonce),
881
1056
  });
882
- const reply = await postJson(this.fetch, `${api}/v3/fee-params`, {
883
- coin,
1057
+ const reply = await postJson(this.fetch, `${api}${path}`, {
1058
+ ...fields,
884
1059
  nonce,
885
1060
  publicInputs: publics.map(String),
886
1061
  proof: passProof(await prover.prove("membership", input)),
887
1062
  });
888
- if (reply.status !== 200 || reply.body.ok !== true || reply.body.coin !== coin)
1063
+ if (reply.status !== 200 || reply.body.ok !== true || reply.body.coin !== fields.coin)
889
1064
  throw refusedBy("v3api", reply);
890
- return verifyFeeOpening(reply.body, await readFeeCommit(coin));
1065
+ return reply.body;
1066
+ }
1067
+ /** The edge lane only once the record names the coin's edge config; before that the pool takes its pinned one. */
1068
+ feeLane(coin, asked) {
1069
+ return asked === "edge" && this.config.objects.edgeFeeConfigs?.[coin] ? "edge" : "hidden";
1070
+ }
1071
+ feeConfigId(coin, lane) {
1072
+ const ids = this.feeLane(coin, lane) === "edge"
1073
+ ? this.config.objects.edgeFeeConfigs
1074
+ : this.config.objects.feeConfigs;
1075
+ return ids?.[coin];
891
1076
  }
892
1077
  async rates(market) {
893
1078
  const id = address(market, "market");
@@ -900,14 +1085,14 @@ export class Essey {
900
1085
  */
901
1086
  seed() {
902
1087
  if (this.seedOption) {
903
- this.ownSeed(readState(this.statePath));
1088
+ this.ownSeed(readState(this.statePath, this.stateKey));
904
1089
  return this.seedOption;
905
1090
  }
906
- const stored = readState(this.statePath).seed ??
1091
+ const stored = readState(this.statePath, this.stateKey).seed ??
907
1092
  this.update((s) => {
908
1093
  if (s.seed !== undefined)
909
1094
  return s.seed;
910
- if (s.notes || s.signers || s.stranded?.length)
1095
+ if (s.notes || s.signers || s.holders || s.stranded?.length)
911
1096
  throw new EsseyError("STATE_REFUSED", NO_SEED);
912
1097
  return (s.seed = randomBytes(SEED_BYTES).toString("hex"));
913
1098
  });
@@ -923,27 +1108,24 @@ export class Essey {
923
1108
  const { encKey } = noteEncKey(seed);
924
1109
  let next = 0;
925
1110
  for (const coin of COINS)
926
- for (const used of usedIndices(await read(coin), seed, encKey))
1111
+ for (const used of usedIndices(await read(coin), seed, encKey, this.noteNext()))
927
1112
  next = Math.max(next, used + 1);
928
- if (next > (readState(this.statePath).notes ?? 0))
1113
+ if (next > (readState(this.statePath, this.stateKey).notes ?? 0))
929
1114
  this.update((s) => {
930
1115
  s.notes = Math.max(next, s.notes ?? 0);
931
1116
  });
932
1117
  return seed;
933
1118
  }
934
- addressUsed() {
935
- if (this.io.readAddressUsed || !this.seedOption)
936
- return this.io.readAddressUsed;
937
- return notSetUp("no readAddressUsed: a seed option may have used a deposit sender");
938
- }
939
- /** A deposit sender the chain has never seen, so no two deposits share one. */
940
- async freshSigner(seed, used) {
941
- for (let i = 0; i < MAX_USED_SENDERS; i++) {
942
- const signer = this.reserve("signers");
943
- if (!used || !(await used(depositSigner(seed, signer).toSuiAddress())))
944
- return signer;
945
- }
946
- throw new EsseyError("STATE_REFUSED", "refused: every deposit sender tried is already used; nothing was sent");
1119
+ /**
1120
+ * PRV-07 b (decided Nov 30): a sender index no lookup has to vouch for. A fresh state starts at a random u48, so a
1121
+ * restored seed lands far from the indexes it used before; the next index is on disk before this one is used.
1122
+ */
1123
+ freshSigner() {
1124
+ return this.update((state) => {
1125
+ const index = state.signers ?? (this.io.signerStart ?? (() => randomInt(2 ** 20, 2 ** 48 - 1)))();
1126
+ state.signers = index + 1;
1127
+ return index;
1128
+ });
947
1129
  }
948
1130
  /** Write-ahead: a deposit is on disk as stranded before its value moves, and leaves once it has landed. */
949
1131
  strand(s, on) {
@@ -976,7 +1158,7 @@ export class Essey {
976
1158
  });
977
1159
  }
978
1160
  member() {
979
- const { member, credential } = readState(this.statePath);
1161
+ const { member, credential } = readState(this.statePath, this.stateKey);
980
1162
  if (!member || !credential)
981
1163
  notSetUp("no credential: call credential.obtain first");
982
1164
  return { secrets: member, credential: credential };
@@ -1005,7 +1187,7 @@ export class Essey {
1005
1187
  const { secrets, credential } = this.member();
1006
1188
  const prover = this.prover();
1007
1189
  const seed = await this.keys();
1008
- const fee = await this.feeParams(coinOf(coin));
1190
+ const fee = await this.feeParams(coinOf(coin), "edge");
1009
1191
  const value = faucetGrant(coin);
1010
1192
  const index = this.reserve("notes");
1011
1193
  const keys = deriveNoteKey(seed, index);
@@ -1063,7 +1245,6 @@ export class Essey {
1063
1245
  const pieces = (denominations ?? list !== undefined) ? splitDenominations(amount, list ?? []) : [amount];
1064
1246
  const relayer = this.sponsorRelayer();
1065
1247
  const fund = this.io.fundDeposit ?? notSetUp("no fundDeposit: the SDK never holds the paying wallet");
1066
- const used = this.addressUsed();
1067
1248
  const seed = await this.keys();
1068
1249
  const read = this.io.readPool;
1069
1250
  const ctx = await this.depositContext(coin);
@@ -1071,7 +1252,7 @@ export class Essey {
1071
1252
  for (const value of pieces) {
1072
1253
  let signer;
1073
1254
  try {
1074
- signer = await this.freshSigner(seed, used);
1255
+ signer = this.freshSigner();
1075
1256
  const note = this.reserve("notes");
1076
1257
  const piece = { coin, signer, note, value, signed: [] };
1077
1258
  const { digest, ticket } = (await this.depositPiece(ctx, seed, piece, relayer, read, fund));
@@ -1086,13 +1267,13 @@ export class Essey {
1086
1267
  async depositContext(coin) {
1087
1268
  const pkg = this.config.packages.pool;
1088
1269
  const poolId = this.config.objects.pools[coin];
1089
- const feeConfigId = this.config.objects.feeConfigs?.[coin];
1270
+ const feeConfigId = this.feeConfigId(coin, "edge");
1090
1271
  if (!pkg || !poolId || !feeConfigId)
1091
1272
  notSetUp("the pool is not published yet");
1092
1273
  const readShared = this.io.readSharedVersion ?? notSetUp("no chain reader for shared object versions");
1093
1274
  const { secrets, credential } = this.member();
1094
1275
  const prover = this.prover();
1095
- const fee = await this.feeParams(coin);
1276
+ const fee = await this.feeParams(coin, "edge");
1096
1277
  return {
1097
1278
  pkg: pkg,
1098
1279
  coinType: this.config.coins[coin].type,
@@ -1194,7 +1375,7 @@ export class Essey {
1194
1375
  const seed = this.seed();
1195
1376
  const outcomes = [];
1196
1377
  let unsent = false;
1197
- for (const piece of readState(this.statePath).stranded ?? []) {
1378
+ for (const piece of readState(this.statePath, this.stateKey).stranded ?? []) {
1198
1379
  try {
1199
1380
  const outcome = await this.recoverOne(piece, seed, read, relayer);
1200
1381
  if (outcome)
@@ -1248,7 +1429,7 @@ export class Essey {
1248
1429
  return { ...record, outcome: sent.inPool ? "landed" : "unconfirmed", digest: sent.digest };
1249
1430
  }
1250
1431
  record(signer) {
1251
- return readState(this.statePath).stranded?.find((r) => r.signer === signer);
1432
+ return readState(this.statePath, this.stateKey).stranded?.find((r) => r.signer === signer);
1252
1433
  }
1253
1434
  /** A state file that cannot be read may hold the record, so it counts as held. */
1254
1435
  strandedAt(signer) {
@@ -1286,7 +1467,27 @@ export class Essey {
1286
1467
  const read = this.io.readPool ?? notSetUp("no pool reader: the pool events are read by the caller");
1287
1468
  const seed = this.seed();
1288
1469
  const events = await read(coin);
1289
- return { events, owned: ownNotes(events, seed, noteEncKey(seed).encKey), seed };
1470
+ return { events, owned: this.ownedIn(coin, events, seed), seed };
1471
+ }
1472
+ /** The scan's notes, then each held note of `coin` whose leaf is in `events` unspent. */
1473
+ ownedIn(coin, events, seed) {
1474
+ const scanned = ownNotes(events, seed, noteEncKey(seed).encKey, this.noteNext());
1475
+ const held = (readState(this.statePath, this.stateKey).held ?? []).flatMap((h) => {
1476
+ if (h.coin !== coin || scanned.some((n) => n.index === h.index))
1477
+ return [];
1478
+ const { status, sk } = heldStatus(events, seed, h);
1479
+ return status === "live" ? [{ value: h.value, sk, blinding: h.blinding, index: h.index }] : [];
1480
+ });
1481
+ return [...scanned, ...held];
1482
+ }
1483
+ /** Records a found note for the next spend; held notes of `coin` the read pool shows spent are dropped. */
1484
+ hold(coin, events, note) {
1485
+ const seed = this.seed();
1486
+ this.update((state) => {
1487
+ const kept = (state.held ?? []).filter((h) => h.coin !== coin || (h.index !== note.index && heldStatus(events, seed, h).status !== "spent"));
1488
+ state.held = [...kept, note];
1489
+ });
1490
+ return { held: true, value: note.value };
1290
1491
  }
1291
1492
  async scan(coin) {
1292
1493
  const summary = {};
@@ -1296,19 +1497,24 @@ export class Essey {
1296
1497
  }
1297
1498
  return summary;
1298
1499
  }
1299
- async withdraw(coin, amount, to, o = {}) {
1500
+ /** Every refusal that needs no chain read, so a bad call is refused before its wait rather than after it. */
1501
+ withdrawPlan(coin, amount, to, o) {
1300
1502
  if (amount <= 0n)
1301
1503
  throw new EsseyError("INVALID_ARGUMENT", "amount must be above 0");
1302
1504
  const list = this.config.denominations[coinOf(coin)];
1303
1505
  if (list === undefined || o.force === true)
1304
- return [await this.withdrawExact(coin, amount, onePayee(to), o)];
1506
+ return { amount, exact: onePayee(to) };
1305
1507
  const payees = listOf(to).map(payee);
1306
1508
  const pieces = withdrawPieces(amount, list);
1307
- const sendTo = piecePayees(pieces.length, payees);
1509
+ return { amount, pieces, sendTo: piecePayees(pieces.length, payees) };
1510
+ }
1511
+ async withdrawStart(coin, plan, o) {
1512
+ if ("exact" in plan)
1513
+ return { paid: await this.withdrawExact(coin, plan.amount, plan.exact, o), pending: null };
1308
1514
  const { fee, relayerFee, owned } = await this.payoutPlan(coin);
1309
- refuseUncovered(owned, pieces, fee, relayerFee);
1310
- refuseLinkedAmount(amount, faucetGrant(coin), owned, fee, relayerFee);
1311
- return this.payPieces(coin, pieces, sendTo, fee);
1515
+ refuseUncovered(owned, plan.pieces, fee, relayerFee);
1516
+ refuseLinkedAmount(plan.amount, faucetGrant(coin), owned, fee, relayerFee);
1517
+ return this.payPiece(coin, piecesTo(plan.pieces, plan.sendTo), fee);
1312
1518
  }
1313
1519
  async withdrawExact(coin, amount, to, o) {
1314
1520
  const landed = await this.spend(coin, { to }, (owned, rates, relayerFee) => {
@@ -1317,7 +1523,27 @@ export class Essey {
1317
1523
  refuseLinkedAmount(amount, faucetGrant(coin), owned, rates, relayerFee);
1318
1524
  return { value: amount, inputs };
1319
1525
  });
1320
- return { ...landed, amount, to: payee(to) };
1526
+ return this.paidTo(landed, amount, to);
1527
+ }
1528
+ /** PRV-11: a reused payee joins two payouts on chain. With no tag on disk this reads no seed and writes nothing. */
1529
+ refusePaid(to, o) {
1530
+ if (o.allowReuse === true)
1531
+ return;
1532
+ const paid = readState(this.statePath, this.stateKey).paid;
1533
+ if (!paid)
1534
+ return;
1535
+ const seed = this.seed();
1536
+ if (listOf(to).some((t) => paid.includes(paidTag(seed, payee(t)))))
1537
+ throw new EsseyError("INVALID_ARGUMENT", "refused: to lists an address this seed already paid in an earlier withdraw, which links the two on chain; use a fresh address. nothing was sent");
1538
+ }
1539
+ paidTo(landed, amount, to) {
1540
+ const address = payee(to);
1541
+ const tag = paidTag(this.seed(), address);
1542
+ this.update((s) => {
1543
+ if (!s.paid?.includes(tag))
1544
+ s.paid = [...(s.paid ?? []), tag];
1545
+ });
1546
+ return { ...landed, amount, to: address };
1321
1547
  }
1322
1548
  /** The same reads and set-up checks `spend` makes, once for every piece of a split payout. */
1323
1549
  async payoutPlan(coin) {
@@ -1325,27 +1551,52 @@ export class Essey {
1325
1551
  this.relayerAddress();
1326
1552
  this.prover();
1327
1553
  const relayerFee = this.coinFee(coin);
1328
- const fee = await this.feeParams(coin);
1554
+ const fee = await this.feeParams(coin, "edge");
1329
1555
  const { owned } = await this.owned(coin);
1330
1556
  return { fee, relayerFee, owned };
1331
1557
  }
1332
- /** The one loop over a payout's pieces, where a wait between them belongs. Each reads the pool after the last is seen spent. */
1333
- async payPieces(coin, pieces, to, fee) {
1334
- const paid = [];
1558
+ /** Pays `pieces[0]`; the rest come back as `pending`, due a long-class time from now. */
1559
+ async payPiece(coin, pieces, fee) {
1560
+ const [{ amount, to }, ...rest] = pieces;
1335
1561
  let spent = [];
1336
- for (const [i, amount] of pieces.entries()) {
1562
+ const landed = await this.spend(coin, { to }, (owned, rates, relayerFee) => {
1563
+ spent = pickInputs(owned, withdrawCost(amount, rates, relayerFee));
1564
+ return { value: amount, inputs: spent };
1565
+ }, [], fee);
1566
+ const paid = this.paidTo(landed, amount, to);
1567
+ if (rest.length === 0)
1568
+ return { paid, pending: null };
1569
+ return {
1570
+ paid,
1571
+ pending: { coin, pieces: rest, notBeforeMs: this.pieceAt(), spent: spent.map((n) => n.index) },
1572
+ };
1573
+ }
1574
+ async payNext(p) {
1575
+ if (p.pieces.length === 0)
1576
+ throw new EsseyError("INVALID_ARGUMENT", "refused: no piece is pending");
1577
+ await this.awaitSpent(coinOf(p.coin), p.spent);
1578
+ return this.payPiece(p.coin, p.pieces);
1579
+ }
1580
+ /** The in-process schedule: each pending piece waits out its `notBeforeMs` through `io.pace`, then goes. */
1581
+ async drain(first) {
1582
+ const paid = [first.paid];
1583
+ for (let p = first.pending; p !== null;) {
1584
+ const due = p;
1337
1585
  try {
1338
- if (i > 0)
1339
- await this.pause("withdraw_piece", `${coin}:${to[i]}`, null);
1340
- await this.awaitSpent(coin, spent);
1341
- const landed = await this.spend(coin, { to: to[i] }, (owned, rates, relayerFee) => {
1342
- spent = pickInputs(owned, withdrawCost(amount, rates, relayerFee));
1343
- return { value: amount, inputs: spent };
1344
- }, [], fee);
1345
- paid.push({ ...landed, amount, to: to[i] });
1586
+ const nowMs = (this.io.now ?? Date.now)();
1587
+ if (this.pacing)
1588
+ await this.waitOut({
1589
+ action: "withdraw_piece",
1590
+ subject: `${due.coin}:${due.pieces[0].to}`,
1591
+ delayMs: Math.max(0, due.notBeforeMs - nowMs),
1592
+ notBeforeMs: due.notBeforeMs,
1593
+ });
1594
+ const next = await this.payNext(due);
1595
+ paid.push(next.paid);
1596
+ p = next.pending;
1346
1597
  }
1347
1598
  catch (error) {
1348
- throw payoutStopped(error, paid, pieces);
1599
+ throw payoutStopped(error, paid, due.pieces.map((x) => x.amount));
1349
1600
  }
1350
1601
  }
1351
1602
  return paid;
@@ -1356,7 +1607,7 @@ export class Essey {
1356
1607
  const sleep = this.io.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1357
1608
  for (let i = 0; i < SPENT_POLLS; i++) {
1358
1609
  const { owned } = await this.owned(coin);
1359
- if (!owned.some((n) => spent.some((s) => s.index === n.index)))
1610
+ if (!owned.some((n) => spent.includes(n.index)))
1360
1611
  return;
1361
1612
  await sleep(FOLLOW_MIN_GAP_MS);
1362
1613
  }
@@ -1367,19 +1618,40 @@ export class Essey {
1367
1618
  receiveAddress() {
1368
1619
  const seed = this.seed();
1369
1620
  const index = this.reserve("notes");
1370
- const pk = notePk(deriveNoteKey(seed, index).sk);
1371
- return `${RECEIVE_PREFIX}${pk}:${Buffer.from(noteEncKey(seed).encPub).toString("hex")}:${index}`;
1621
+ const pk = notePk(deriveNoteKey(seed, index).sk).toString(16).padStart(64, "0");
1622
+ const { C, D } = receiveKey(seed, index);
1623
+ return `${RECEIVE_PREFIX}${pk}:${Buffer.from(C).toString("hex")}:${Buffer.from(D).toString("hex")}`;
1624
+ }
1625
+ noteNext() {
1626
+ return readState(this.statePath, this.stateKey).notes ?? 0;
1627
+ }
1628
+ itemAddress() {
1629
+ return itemHolder(this.seed(), this.reserve("holders")).toSuiAddress();
1630
+ }
1631
+ holderOf(owner) {
1632
+ const count = readState(this.statePath, this.stateKey).holders ?? 0;
1633
+ if (owner === null || count === 0)
1634
+ return null;
1635
+ const seed = this.seed();
1636
+ const at = normalizeSuiAddress(owner);
1637
+ for (let i = 0; i < count; i++)
1638
+ if (itemHolder(seed, i).toSuiAddress() === at)
1639
+ return i;
1640
+ return null;
1372
1641
  }
1373
1642
  async transfer(coin, amount, to) {
1374
1643
  if (amount <= 0n)
1375
1644
  throw new EsseyError("INVALID_ARGUMENT", "amount must be above 0");
1376
1645
  const payTo = receiveTarget(to);
1377
- return this.spend(coin, { payTo }, (owned, rates, relayerFee) => ({
1646
+ const mark = paidTag(this.seed(), to);
1647
+ if (readState(this.statePath, this.stateKey).paid?.includes(mark))
1648
+ throw paidBefore();
1649
+ return this.spend(coin, { payTo, mark }, (owned, rates, relayerFee) => ({
1378
1650
  value: amount,
1379
1651
  inputs: pickInputs(owned, withdrawCost(amount, rates, relayerFee)),
1380
1652
  }));
1381
1653
  }
1382
- async exit(coin, to, o = {}) {
1654
+ async exitStart(coin, to, o) {
1383
1655
  const list = this.config.denominations[coinOf(coin)];
1384
1656
  if (list === undefined || o.force === true)
1385
1657
  return this.exitExact(coin, onePayee(to), o);
@@ -1393,8 +1665,8 @@ export class Essey {
1393
1665
  refuseUncovered(owned, pieces, fee, relayerFee);
1394
1666
  const value = pieces.reduce((sum, piece) => sum + piece, 0n);
1395
1667
  refuseLinkedAmount(value, faucetGrant(coin), owned, fee, relayerFee);
1396
- const payouts = await this.payPieces(coin, pieces, sendTo, fee);
1397
- return { payouts, kept: exitKept(total, pieces, fee, relayerFee) };
1668
+ const first = await this.payPiece(coin, piecesTo(pieces, sendTo), fee);
1669
+ return { ...first, kept: exitKept(total, pieces, fee, relayerFee) };
1398
1670
  }
1399
1671
  async exitExact(coin, to, o) {
1400
1672
  let value = 0n;
@@ -1411,7 +1683,7 @@ export class Essey {
1411
1683
  kept = total - withdrawCost(value, rates, relayerFee);
1412
1684
  return { value, inputs: owned };
1413
1685
  });
1414
- return { payouts: [{ ...landed, amount: value, to: payee(to) }], kept };
1686
+ return { paid: this.paidTo(landed, value, to), pending: null, kept };
1415
1687
  }
1416
1688
  /** js4 with the withdraw field (`src/v3/inputs.ts:39`); the change note's index is on disk before the body leaves. */
1417
1689
  async spend(coin, dest, choose, extra = [], known) {
@@ -1420,7 +1692,7 @@ export class Essey {
1420
1692
  const relay = this.relayClient();
1421
1693
  const relayer = this.relayerAddress();
1422
1694
  const prover = this.prover();
1423
- const fee = known ?? (await this.feeParams(coin));
1695
+ const fee = known ?? (await this.feeParams(coin, "edge"));
1424
1696
  const { events, owned, seed } = await this.owned(coin);
1425
1697
  const { value, inputs } = choose([...owned, ...extra], fee, relayerFee);
1426
1698
  const tree = poolTree(orderedLeaves(events));
@@ -1452,9 +1724,7 @@ export class Essey {
1452
1724
  const changeValue = BigInt(js.input.outAmount1);
1453
1725
  const encChange = sealOpening({ value: changeValue, blinding: change.blinding, index }, noteEncKey(seed).encPub);
1454
1726
  const proved = await prover.prove("js4", js.input);
1455
- const encPaid = "payTo" in dest
1456
- ? sealOpening({ value, blinding: paidBlinding, index: dest.payTo.index }, dest.payTo.encPub)
1457
- : fillerEnc();
1727
+ const encPaid = "payTo" in dest ? sealPaid(dest.payTo, value, paidBlinding) : fillerEnc();
1458
1728
  const body = ("payTo" in dest ? transferBody : withdrawBody)({
1459
1729
  pool: coin,
1460
1730
  proved: { proof: proved.proof, publicSignals: js.publics.map(String) },
@@ -1463,9 +1733,19 @@ export class Essey {
1463
1733
  relayerFee,
1464
1734
  wait: true,
1465
1735
  });
1736
+ if ("payTo" in dest && dest.mark)
1737
+ this.markPaid(dest.mark);
1466
1738
  const sent = await relay.submit(body);
1467
1739
  return "digest" in sent ? sent : this.follow(relay, sent, "withdraw");
1468
1740
  }
1741
+ /** PRV-34 write-ahead: an address is marked paid before the body leaves, so a second payment to it never does. */
1742
+ markPaid(mark) {
1743
+ this.update((s) => {
1744
+ if (s.paid?.includes(mark))
1745
+ throw paidBefore();
1746
+ s.paid = [...(s.paid ?? []), mark];
1747
+ });
1748
+ }
1469
1749
  /** A 202 carries no digest (`src/v3/relay/client.ts:100`): the ticket is followed until it lands. */
1470
1750
  async follow(relay, queued, what) {
1471
1751
  const gap = Math.max(queued.etaMs, FOLLOW_MIN_GAP_MS);
@@ -1510,7 +1790,7 @@ export class Essey {
1510
1790
  return (await this.checkedCredential()) ?? unknownObject("no credential is stored");
1511
1791
  }
1512
1792
  async checkedCredential() {
1513
- const { member, credential } = readState(this.statePath);
1793
+ const { member, credential } = readState(this.statePath, this.stateKey);
1514
1794
  if (!credential)
1515
1795
  return null;
1516
1796
  if (!member)
@@ -1536,7 +1816,7 @@ export class Essey {
1536
1816
  const out = [];
1537
1817
  for (const c of coins) {
1538
1818
  const { events, seed } = await this.poolOf(c);
1539
- out.push(...listPositions(c, events, seed));
1819
+ out.push(...this.ownedIn(c, events, seed).map((n) => ({ coin: c, index: n.index, value: n.value })));
1540
1820
  }
1541
1821
  return out;
1542
1822
  }
@@ -1548,20 +1828,49 @@ export class Essey {
1548
1828
  /** D-SPEC §6.2:588. The envelope is `v3.loans.open`; the id is whatever the digest created. */
1549
1829
  async openRequest(p) {
1550
1830
  assertLoanOpen(p);
1831
+ assertLoanGrid(p, this.config.closeStepMs ?? HOUR_MS);
1551
1832
  poolId(this.config, p.loanCoin);
1552
1833
  poolId(this.config, p.collateralCoin);
1553
1834
  if (this.config.relayer.url === null)
1554
1835
  notSetUp("missing config: the deployment record names no relayer");
1555
1836
  const plan = this.io.planLoanOpen ?? ((q) => this.planOpen(q));
1556
- const read = this.io.readCreated ?? notSetUp("missing config: no loan reader");
1837
+ if (!this.io.readLoans)
1838
+ notSetUp("missing config: no loan reader");
1557
1839
  const proved = await plan(p);
1558
1840
  if (proved.pool !== p.loanCoin)
1559
1841
  wrongCoinObject();
1560
1842
  const landed = await this.paidLoan(openLoan, { ...proved, wait: true });
1561
- const id = await read(landed.digest);
1562
- if (typeof id !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(id))
1563
- unknownObject("the digest created no loan");
1564
- return { ...landed, id: address(id, "loan id") };
1843
+ const read = this.io.readLoans;
1844
+ const row = await this.listedByKey("loan", "loan_key", proved.loanKey, async (c) => {
1845
+ const page = await read(c);
1846
+ return { rows: page.loans, next: page.next };
1847
+ });
1848
+ return { ...landed, id: row.id };
1849
+ }
1850
+ /**
1851
+ * PRV-07: what an open created is found among every listed object of its kind by the key its opener chose
1852
+ * (`field`), never by the opener's own digest.
1853
+ */
1854
+ async listedByKey(what, field, key, read) {
1855
+ for (let attempt = 0; attempt < FIND_LISTED_TRIES; attempt++) {
1856
+ if (attempt > 0)
1857
+ await this.sleep(FIND_LISTED_PAUSE_MS);
1858
+ let cursor = null;
1859
+ let pages = 0;
1860
+ for (;;) {
1861
+ const page = await read(cursor);
1862
+ pages += 1;
1863
+ const row = page.rows.find((l) => l.json?.[field]?.toString() === `${key}`);
1864
+ if (row && !/^0x[0-9a-fA-F]{64}$/.test(row.id))
1865
+ unknownObject(`the listed ${what} id is not an object id`);
1866
+ if (row)
1867
+ return { id: address(row.id, `${what} id`), json: row.json };
1868
+ cursor = afterPage(page.next, pages);
1869
+ if (cursor === null)
1870
+ break;
1871
+ }
1872
+ }
1873
+ return unknownObject(`the open landed, but no listed ${what} carries its key yet`);
1565
1874
  }
1566
1875
  /**
1567
1876
  * The borrower's `loan_open`: a CollLock spend of up to two own notes into the lock, the Health OPEN rows, the
@@ -1575,7 +1884,7 @@ export class Essey {
1575
1884
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
1576
1885
  const readPrice = this.io.readPrice ?? notSetUp("missing config: no price reader");
1577
1886
  const update = this.io.priceUpdate ?? notSetUp("missing config: no price update source");
1578
- const { member, credential } = readState(this.statePath);
1887
+ const { member, credential } = readState(this.statePath, this.stateKey);
1579
1888
  if (!member || !credential)
1580
1889
  notSetUp("no credential: call credential.obtain first");
1581
1890
  const relayer = this.relayerAddress();
@@ -1614,8 +1923,6 @@ export class Essey {
1614
1923
  data: requestPlaintext({
1615
1924
  ...request,
1616
1925
  borrowerPk,
1617
- collAmt: p.collateral,
1618
- collBlind: own.blinding,
1619
1926
  closeMs,
1620
1927
  market,
1621
1928
  coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
@@ -1715,7 +2022,7 @@ export class Essey {
1715
2022
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
1716
2023
  const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
1717
2024
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
1718
- const { member, credential } = readState(this.statePath);
2025
+ const { member, credential } = readState(this.statePath, this.stateKey);
1719
2026
  if (!member || !credential)
1720
2027
  notSetUp("no credential: call credential.obtain first");
1721
2028
  const loan = address(id, "loan id");
@@ -1766,11 +2073,8 @@ export class Essey {
1766
2073
  };
1767
2074
  },
1768
2075
  });
1769
- const q = decodeRequest(plain);
1770
- const note = collNote({ loanKey, borrowerPk: q.borrowerPk, amount: q.collAmt, blinding: q.collBlind });
1771
- const locked = refi ? json.coll.coll_note : json.collateral_commit;
1772
- if (note !== BigInt(locked))
1773
- throw new EsseyError("CT_MISMATCH", "refused: the request opens another lock");
2076
+ const q = readRequestPlain(plain);
2077
+ const note = BigInt(refi ? json.coll.coll_note : json.collateral_commit);
1774
2078
  const request = { principal: q.principal, maxRateBps: q.maxRateBps, termMs: q.termMs, salt: q.salt };
1775
2079
  if (requestCommit(request, q.borrowerPk, note) !== BigInt(round.req_commit))
1776
2080
  throw new EsseyError("CT_MISMATCH", "refused: the request does not open the loan's commit");
@@ -1783,8 +2087,6 @@ export class Essey {
1783
2087
  poolL: address(json.pool_l, "pool_l"),
1784
2088
  ...request,
1785
2089
  borrowerPk: q.borrowerPk,
1786
- collAmt: q.collAmt,
1787
- collBlind: q.collBlind,
1788
2090
  collNote: note,
1789
2091
  closeMs: q.closeMs,
1790
2092
  };
@@ -1803,17 +2105,19 @@ export class Essey {
1803
2105
  /** The lender's `loan_offer`: the principal locked to the round from up to two own notes, its sealed terms pinned. */
1804
2106
  async planOffer(loanId, rateBps) {
1805
2107
  const q = await this.readRequest(loanId, true);
2108
+ assertRequestTerm(q.termMs, this.config.closeStepMs ?? HOUR_MS);
1806
2109
  const L = q.pair[1];
1807
2110
  if (poolId(this.config, L) !== q.poolL)
1808
2111
  wrongCoinObject();
1809
2112
  if (rateBps > q.maxRateBps)
1810
2113
  throw new EsseyError("INVALID_ARGUMENT", "the rate is above the request's maximum");
1811
2114
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
1812
- const { member, credential } = readState(this.statePath);
2115
+ const { member, credential } = readState(this.statePath, this.stateKey);
1813
2116
  const relayer = this.relayerAddress();
1814
2117
  const relayerFee = this.coinFee(L);
1815
2118
  const prover = this.prover();
1816
- const fee = await this.feeParams(L);
2119
+ const row = await (this.io.readLoan ?? notSetUp("missing config: no loan reader"))(q.loan);
2120
+ const fee = await this.loanFee(L, row.json.fee_commit);
1817
2121
  const { events, owned, seed } = await this.owned(L);
1818
2122
  const inputs = pickInputs(owned, q.principal + relayerFee);
1819
2123
  const tree = poolTree(orderedLeaves(events));
@@ -1918,7 +2222,7 @@ export class Essey {
1918
2222
  /** `seal_policy::seal_approve_offer` for offer `seq`: the borrower's SEAL pass over `seal_offer` bound to the viewer. */
1919
2223
  offerApprove(loan, loanKey, round, seq, pair) {
1920
2224
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
1921
- const { member, credential } = readState(this.statePath);
2225
+ const { member, credential } = readState(this.statePath, this.stateKey);
1922
2226
  const room = keyId(loanKey);
1923
2227
  const prover = this.prover();
1924
2228
  return async (viewer) => {
@@ -2056,7 +2360,7 @@ export class Essey {
2056
2360
  if (via === "pass")
2057
2361
  return { approve: await this.keeperApprove(loan, market, id, pair) };
2058
2362
  const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
2059
- const held = readState(this.statePath).badge;
2363
+ const held = readState(this.statePath, this.stateKey).badge;
2060
2364
  if (!held || BigInt((this.io.now ?? Date.now)()) >= held.expiresMs)
2061
2365
  notSetUp("no live keeper badge: call keeper.mintBadge");
2062
2366
  const signer = depositSigner(this.seed(), held.signer);
@@ -2080,7 +2384,7 @@ export class Essey {
2080
2384
  return { approve, signer };
2081
2385
  }
2082
2386
  heldBadge() {
2083
- const held = readState(this.statePath).badge;
2387
+ const held = readState(this.statePath, this.stateKey).badge;
2084
2388
  if (!held)
2085
2389
  return null;
2086
2390
  const holder = depositSigner(this.seed(), held.signer).toSuiAddress();
@@ -2093,14 +2397,14 @@ export class Essey {
2093
2397
  async mintBadge() {
2094
2398
  const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
2095
2399
  const pkg = this.config.packages.loan ?? notSetUp("the loan package is not published yet");
2096
- const readBadge = this.io.readBadge ?? notSetUp("missing config: no badge reader");
2400
+ const readBadges = this.io.readBadges ?? notSetUp("missing config: no badge reader");
2097
2401
  const relayer = this.sponsorRelayer();
2098
2402
  const { secrets, credential } = this.member();
2099
2403
  if (credential.role !== "keeper")
2100
2404
  notSetUp("no keeper credential");
2101
2405
  const prover = this.prover();
2102
2406
  const seed = this.seed();
2103
- const index = await this.freshSigner(seed, this.io.readAddressUsed);
2407
+ const index = this.freshSigner();
2104
2408
  const signer = depositSigner(seed, index);
2105
2409
  const holder = signer.toSuiAddress();
2106
2410
  const room = keeper.registry.id;
@@ -2124,9 +2428,10 @@ export class Essey {
2124
2428
  proof: `0x${Buffer.from(proof).toString("hex")}`,
2125
2429
  };
2126
2430
  const digest = await this.sponsoredSend(signer, txKindB64, wire, relayer);
2127
- const row = await readBadge(digest);
2128
- if (!row)
2129
- throw new EsseyError("SERVICE_REFUSED", `the mint ${digest} created no badge`);
2431
+ const row = await this.listedByKey("badge", "tag", pass.publics[0], async (c) => {
2432
+ const page = await readBadges(c);
2433
+ return { rows: page.badges, next: page.next };
2434
+ });
2130
2435
  const { id, expiresMs } = badgeOf(row, { holder, registry: room });
2131
2436
  this.update((s) => {
2132
2437
  s.badge = { signer: index, id, expiresMs };
@@ -2154,7 +2459,7 @@ export class Essey {
2154
2459
  /** `keeper::seal_approve_keeper_proof`: a KEEPER pass for the deployment's keeper registry, bound to the viewer. */
2155
2460
  async keeperApprove(loan, market, id, pair) {
2156
2461
  const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
2157
- const { member, credential } = readState(this.statePath);
2462
+ const { member, credential } = readState(this.statePath, this.stateKey);
2158
2463
  if (!member || credential?.role !== "keeper")
2159
2464
  notSetUp("no keeper credential");
2160
2465
  const { price, standin } = await this.keeperFeed(market);
@@ -2218,7 +2523,7 @@ export class Essey {
2218
2523
  return decodeOffer(plain);
2219
2524
  }
2220
2525
  /** The borrower's `loan_settle` on round 0: the lowest eligible offer wins, keeper ciphertext v1 carries its terms. */
2221
- async planSettle(id) {
2526
+ async planSettle(id, collAmt) {
2222
2527
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2223
2528
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2224
2529
  const q = await this.readRequest(id);
@@ -2227,6 +2532,8 @@ export class Essey {
2227
2532
  throw new EsseyError("INVALID_ARGUMENT", "refused: the offer window is still open");
2228
2533
  const row = await read(q.loan);
2229
2534
  const json = row.json;
2535
+ const seed = this.seed();
2536
+ const { opening } = this.ownOpening(seed, json, q.borrowerPk, collAmt);
2230
2537
  const round = row.round;
2231
2538
  const slots = [];
2232
2539
  for (const [i, o] of round.offers.entries()) {
@@ -2236,19 +2543,18 @@ export class Essey {
2236
2543
  : undefined;
2237
2544
  slots.push({ commit: BigInt(o.commit), lock: BigInt(o.lock), active: o.active, open });
2238
2545
  }
2239
- const { member, credential } = readState(this.statePath);
2546
+ const { member, credential } = readState(this.statePath, this.stateKey);
2240
2547
  const L = q.pair[1];
2241
2548
  const prover = this.prover();
2242
- const fee = await this.feeParams(L);
2243
- const seed = this.seed();
2549
+ const fee = await this.loanFee(L, json.fee_commit);
2244
2550
  await this.keys();
2245
2551
  const noteIndex = this.reserve("notes");
2246
2552
  const mine = deriveNoteKey(seed, noteIndex);
2247
- const nowS = BigInt(Math.floor((this.io.now ?? Date.now)() / 1000));
2553
+ const nowS = settleNowS((this.io.now ?? Date.now)(), q.closeMs);
2248
2554
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2249
2555
  const plan = (extHash) => loanSettle({
2250
2556
  slots,
2251
- request: q,
2557
+ request: { ...q, collAmt: opening.amount, collBlind: opening.blinding },
2252
2558
  loanKey: q.loanKey,
2253
2559
  borrowerNote: { pk: notePk(mine.sk), blinding: mine.blinding },
2254
2560
  e: drawEph(),
@@ -2264,8 +2570,8 @@ export class Essey {
2264
2570
  version: KEEPER_LAYOUT_VERSION,
2265
2571
  loanKey: q.loanKey,
2266
2572
  borrowerPk: q.borrowerPk,
2267
- collAmt: q.collAmt,
2268
- collBlind: q.collBlind,
2573
+ collAmt: opening.amount,
2574
+ collBlind: opening.blinding,
2269
2575
  nonceAtCt: 1n,
2270
2576
  terms: draft.terms,
2271
2577
  }),
@@ -2308,7 +2614,7 @@ export class Essey {
2308
2614
  rateBps: w.terms.rateBps,
2309
2615
  terms: w.terms,
2310
2616
  borrowerPk: q.borrowerPk,
2311
- collAmt: q.collAmt,
2617
+ collAmt: opening.amount,
2312
2618
  body: {
2313
2619
  pool: L,
2314
2620
  loan: q.loan,
@@ -2352,7 +2658,7 @@ export class Essey {
2352
2658
  const relayer = this.relayerAddress();
2353
2659
  const relayerFee = this.coinFee(L);
2354
2660
  const prover = this.prover();
2355
- const fee = await this.feeParams(L);
2661
+ const fee = await this.loanFee(L, json.fee_commit);
2356
2662
  const { events, owned, seed } = await this.owned(L);
2357
2663
  const tree = poolTree(orderedLeaves(events));
2358
2664
  const inputs = pickInputs(owned, terms.owed + relayerFee + feeOf({ base: terms.owed, bps: fee.bps, min: fee.min, max: fee.max }).fee);
@@ -2411,9 +2717,9 @@ export class Essey {
2411
2717
  /**
2412
2718
  * The repaid note is `Poseidon(owed, lenderPk, H(DOM_LBLIND, S.x))` with `S = encSk · repay_eph`
2413
2719
  * (`loan_repay.circom`), and a refi payoff the same over a `payoff_eph` pair (`loan_refi.circom`); either ciphertext
2414
- * is filler, so the scan never sees it. It is spent into an own note.
2720
+ * is filler, so the scan never sees it; `owned` finds it through the state file's `held` list.
2415
2721
  */
2416
- async collect(loanId, offer) {
2722
+ async collect(loanId, offer, sweep) {
2417
2723
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2418
2724
  const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
2419
2725
  const loan = address(loanId, "loan id");
@@ -2442,14 +2748,22 @@ export class Essey {
2442
2748
  }
2443
2749
  if (!leaf)
2444
2750
  unknownObject("no repaid or refi payoff note of this offer is in the pool: another offer won, or the record is not this loan's");
2445
- return this.claimLeaf(L, events, { value: owed, sk: own.sk, blinding, index: Number(leaf.index) });
2751
+ const note = { value: owed, sk: own.sk, blinding, index: Number(leaf.index) };
2752
+ return this.take(L, events, { ...note, key: offer.noteIndex }, sweep);
2446
2753
  }
2447
- /** Spends a note no ciphertext names, found by its commitment, to the receive address. */
2448
- async claimLeaf(coin, events, note) {
2754
+ /** Refuses a spent note. `sweep` moves it to the receive address now; otherwise it is held for the next spend. */
2755
+ async take(coin, events, note, sweep) {
2449
2756
  const commitment = noteCommitment(note.value, notePk(note.sk), note.blinding);
2450
2757
  const n = noteNullifier(commitment, note.sk, BigInt(note.index));
2451
2758
  if (events.nullifiers.some((x) => BigInt(x) === n))
2452
2759
  throw new EsseyError("INVALID_ARGUMENT", "already collected");
2760
+ const { key, value, blinding, index } = note;
2761
+ if (!sweep)
2762
+ return this.hold(coin, events, { coin, key, value, blinding, index });
2763
+ return { ...(await this.claimLeaf(coin, note)), held: false };
2764
+ }
2765
+ /** Spends a note no ciphertext names, found by its commitment, to the receive address. */
2766
+ async claimLeaf(coin, note) {
2453
2767
  const payTo = receiveTarget(this.receiveAddress());
2454
2768
  let value = 0n;
2455
2769
  const landed = await this.spend(coin, { payTo }, (_owned, _rates, relayerFee) => {
@@ -2473,8 +2787,8 @@ export class Essey {
2473
2787
  };
2474
2788
  }
2475
2789
  /** B §5.5 out0 of a seizure, the lender's, from its lock opening; each heartbeat and TOPUP rolled the blinding one step. */
2476
- collectSeized(loanId, offer) {
2477
- return this.collectFromSeizure(loanId, 0, async (json, seizeNonce) => {
2790
+ collectSeized(loanId, offer, sweep) {
2791
+ const open = async (json, seizeNonce) => {
2478
2792
  const own = deriveNoteKey(this.seed(), offer.noteIndex);
2479
2793
  const lock = await this.lenderLock(json, own);
2480
2794
  let blinding = lock.blinding;
@@ -2483,18 +2797,21 @@ export class Essey {
2483
2797
  return {
2484
2798
  owed: interest(offer.principal, offer.rateBps, offer.termMs).owed,
2485
2799
  collAmt: lock.amount,
2800
+ key: offer.noteIndex,
2486
2801
  sk: own.sk,
2487
2802
  blinding,
2488
2803
  };
2489
- });
2804
+ };
2805
+ return this.collectFromSeizure(loanId, 0, open, sweep);
2490
2806
  }
2491
2807
  /** B §5.5 out1 of a seizure, the borrower's surplus `avail - seize`, from its own opening rolled to the seizing nonce. */
2492
- collectSurplus(p) {
2493
- return this.collectFromSeizure(p.loan, 1, async (json, seizeNonce) => {
2808
+ collectSurplus(p, sweep) {
2809
+ const open = async (json, seizeNonce) => {
2494
2810
  if (termsCommit(p.terms, p.borrowerPk) !== BigInt(json.terms_commit))
2495
2811
  throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
2496
2812
  const seed = this.seed();
2497
- const own = deriveNoteKey(seed, this.indexOfPk(seed, p.borrowerPk));
2813
+ const key = this.indexOfPk(seed, p.borrowerPk);
2814
+ const own = deriveNoteKey(seed, key);
2498
2815
  const start = {
2499
2816
  loanKey: BigInt(json.loan_key),
2500
2817
  borrowerPk: p.borrowerPk,
@@ -2503,15 +2820,16 @@ export class Essey {
2503
2820
  nonce: 1n,
2504
2821
  };
2505
2822
  const opening = rollTo(start, BigInt(json.coll.coll_note), seizeNonce);
2506
- return { owed: p.terms.owed, collAmt: p.collAmt, sk: own.sk, blinding: opening.blinding };
2507
- });
2823
+ return { owed: p.terms.owed, collAmt: p.collAmt, key, sk: own.sk, blinding: opening.blinding };
2824
+ };
2825
+ return this.collectFromSeizure(p.loan, 1, open, sweep);
2508
2826
  }
2509
2827
  /**
2510
2828
  * A seizure leaves the lock's nonce one past the one it folded and `coll_note` as it was. `out` 0 pays
2511
2829
  * `seize - pf - kf` to the lender, 1 pays `avail - seize` to the borrower, each at `outputBlind(blind, out, nonce)`.
2512
2830
  * The split is recomputed from the `p_spot` the seizing call claimed (`io.readSeizure`).
2513
2831
  */
2514
- async collectFromSeizure(loanId, out, open) {
2832
+ async collectFromSeizure(loanId, out, open, sweep) {
2515
2833
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2516
2834
  const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
2517
2835
  const seizure = this.io.readSeizure ?? notSetUp("missing config: no seizure reader");
@@ -2545,7 +2863,7 @@ export class Essey {
2545
2863
  pSpot: fault ? 1n : pSpot,
2546
2864
  expo: (await readPrice(String(json.market_id))).expo,
2547
2865
  risk: loanRisk(rates, decimals, { liquidate: MODE.LIQUIDATE, default: MODE.DEFAULT, fault: MODE.FAULT }[mode]),
2548
- fee: await this.feeParams(C),
2866
+ fee: await this.loanFee(C, json.coll_fee_commit),
2549
2867
  fault,
2550
2868
  });
2551
2869
  const value = out === 0 ? split.toLender : split.surplus;
@@ -2557,15 +2875,18 @@ export class Essey {
2557
2875
  const leaf = events.commitments.find((c) => BigInt(c.commitment) === commitment);
2558
2876
  if (!leaf)
2559
2877
  unknownObject("no seized note of this side is in the pool: another offer won, or the loan was topped up");
2560
- for (let i = 0; i < SEIZE_REWAITS && this.pacing && lastLanded(events, leaf.index); i++) {
2878
+ for (let i = 0; sweep &&
2879
+ i < SEIZE_REWAITS &&
2880
+ this.pacing &&
2881
+ seizeIsLast(BigInt(events.commitments.length), leaf.index, out); i++) {
2561
2882
  await this.pause(out === 0 ? "collect_seized" : "collect_surplus", loan, null);
2562
2883
  events = await pools(C);
2563
2884
  }
2564
- return this.claimLeaf(C, events, { ...note, index: Number(leaf.index) });
2885
+ return this.take(C, events, { ...note, key: opened.key, index: Number(leaf.index) }, sweep);
2565
2886
  }
2566
2887
  /** The seed index whose key is `pk`: the borrower key of a loan this seed opened. */
2567
2888
  indexOfPk(seed, pk) {
2568
- const n = readState(this.statePath).notes ?? 0;
2889
+ const n = readState(this.statePath, this.stateKey).notes ?? 0;
2569
2890
  for (let i = n - 1; i >= 0; i--)
2570
2891
  if (notePk(deriveNoteKey(seed, i).sk) === pk)
2571
2892
  return i;
@@ -2592,7 +2913,7 @@ export class Essey {
2592
2913
  const seed = this.seed();
2593
2914
  const { opening, index } = this.ownOpening(seed, json, borrowerPk, collAmt);
2594
2915
  const nonce = opening.nonce;
2595
- const fee = await this.feeParams(C);
2916
+ const fee = await this.loanFee(C, json.coll_fee_commit);
2596
2917
  const rates = {
2597
2918
  ltvBps: BigInt(json.ltv_bps),
2598
2919
  liqBps: BigInt(json.liq_bps),
@@ -2633,7 +2954,7 @@ export class Essey {
2633
2954
  }
2634
2955
  /** The seed index a loan this seed opened derives from: its loan key is `Poseidon(sk, blinding, 1)` of that index. */
2635
2956
  indexOfLoanKey(seed, loanKey) {
2636
- const n = readState(this.statePath).notes ?? 0;
2957
+ const n = readState(this.statePath, this.stateKey).notes ?? 0;
2637
2958
  for (let i = n - 1; i >= 0; i--) {
2638
2959
  const k = deriveNoteKey(seed, i);
2639
2960
  if (poseidonHash([k.sk, k.blinding, 1n]) === loanKey)
@@ -2650,7 +2971,7 @@ export class Essey {
2650
2971
  const json = row.json;
2651
2972
  const loanKey = BigInt(json.loan_key);
2652
2973
  this.indexOfLoanKey(this.seed(), loanKey);
2653
- const { member, credential } = readState(this.statePath);
2974
+ const { member, credential } = readState(this.statePath, this.stateKey);
2654
2975
  const n0 = actionHash(blake2b256, loanKey, BigInt(json.nonce), "cancel", new Uint8Array());
2655
2976
  const pass = membership({
2656
2977
  secrets: member,
@@ -2674,7 +2995,7 @@ export class Essey {
2674
2995
  /** The borrower's pass over `kind` and its args, at the loan's next action nonce. */
2675
2996
  async borrowerPass(json, kind, args) {
2676
2997
  const loanKey = BigInt(json.loan_key);
2677
- const { member, credential } = readState(this.statePath);
2998
+ const { member, credential } = readState(this.statePath, this.stateKey);
2678
2999
  if (!member || !credential)
2679
3000
  notSetUp("no credential: call credential.obtain first");
2680
3001
  const n0 = actionHash(blake2b256, loanKey, BigInt(json.nonce), kind, args);
@@ -2698,6 +3019,7 @@ export class Essey {
2698
3019
  * derives from the lock's note index and the round, so the seed alone reopens it.
2699
3020
  */
2700
3021
  async openRefi(p) {
3022
+ assertLoanGrid(p, this.config.closeStepMs ?? HOUR_MS);
2701
3023
  const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2702
3024
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2703
3025
  const loan = address(p.loan, "loan id");
@@ -2727,8 +3049,6 @@ export class Essey {
2727
3049
  data: requestPlaintext({
2728
3050
  ...request,
2729
3051
  borrowerPk: p.borrowerPk,
2730
- collAmt: opening.amount,
2731
- collBlind: opening.blinding,
2732
3052
  closeMs,
2733
3053
  market,
2734
3054
  coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
@@ -2769,17 +3089,17 @@ export class Essey {
2769
3089
  const pClaim = r.spot < r.ema ? r.spot : r.ema;
2770
3090
  const rates = await this.rates(market);
2771
3091
  const ltvBps = BigInt(json.ltv_bps) < rates.current.ltvBps ? BigInt(json.ltv_bps) : rates.current.ltvBps;
2772
- const fee = await this.feeParams(L);
3092
+ const fee = await this.loanFee(L, json.fee_commit);
2773
3093
  await this.keys();
2774
3094
  const noteIndex = this.reserve("notes");
2775
3095
  const mine = deriveNoteKey(seed, noteIndex);
2776
3096
  const padKey = deriveNoteKey(seed, this.reserve("notes"));
2777
- const nowS = BigInt(Math.floor((this.io.now ?? Date.now)() / 1000));
3097
+ const nowS = settleNowS((this.io.now ?? Date.now)(), q.closeMs);
2778
3098
  const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2779
3099
  const plan = (extHash) => loanRefi({
2780
3100
  slots,
2781
3101
  round: q.round,
2782
- request: q,
3102
+ request: { ...q, collAmt: opening.amount, collBlind: opening.blinding },
2783
3103
  old: p.terms,
2784
3104
  price: {
2785
3105
  pClaim,
@@ -2899,7 +3219,7 @@ export class Essey {
2899
3219
  const opening = { loanKey, borrowerPk: notePk(own.sk), amount: collAmt, blinding: own.blinding };
2900
3220
  if (collNote(opening) !== BigInt(json.coll.coll_note))
2901
3221
  throw new EsseyError("CT_MISMATCH", "refused: the amount does not open the locked note");
2902
- const fee = await this.feeParams(C);
3222
+ const fee = await this.loanFee(C, json.coll_fee_commit);
2903
3223
  await this.keys();
2904
3224
  const outIndex = this.reserve("notes");
2905
3225
  const out = deriveNoteKey(seed, outIndex);
@@ -2954,7 +3274,7 @@ export class Essey {
2954
3274
  const loanKey = BigInt(json.loan_key);
2955
3275
  const [C, L] = this.pairOf(json.market_id);
2956
3276
  const seed = await this.keys();
2957
- const mine = ownOpenings(await readPool(C), seed, noteEncKey(seed).encKey);
3277
+ const mine = ownOpenings(await readPool(C), seed, noteEncKey(seed).encKey, this.noteNext());
2958
3278
  const keyAt = (i) => deriveNoteKey(seed, i);
2959
3279
  const change = mine.find((o) => {
2960
3280
  if (o.keyIndex === 0)
@@ -3078,12 +3398,12 @@ export class Essey {
3078
3398
  const [C, L] = this.pairOf(json.market_id);
3079
3399
  const poolC = address(json.pool_c, "pool_c");
3080
3400
  const market = address(json.market_id, "market");
3081
- const expiryMs = await this.heartbeatExpiry(json, market, p.expiryMs);
3401
+ const expiryMs = await this.heartbeatExpiry(json, market, p.terms.maturityS, p.expiryMs);
3082
3402
  const { opening } = this.ownOpening(this.seed(), json, p.borrowerPk, p.collAmt);
3083
3403
  const k = p.k ?? 1;
3084
3404
  const reading = await readPrice(market);
3085
3405
  const floor = heartbeatFloor(reading, k);
3086
- const fee = await this.feeParams(C);
3406
+ const fee = await this.loanFee(C, json.coll_fee_commit);
3087
3407
  const rates = {
3088
3408
  ltvBps: BigInt(json.ltv_bps),
3089
3409
  liqBps: BigInt(json.liq_bps),
@@ -3109,7 +3429,7 @@ export class Essey {
3109
3429
  terms: p.terms,
3110
3430
  });
3111
3431
  const proved = await this.prover().prove("health", h.input);
3112
- return this.relayed(heartbeatBody({
3432
+ const landed = await this.relayed(heartbeatBody({
3113
3433
  pool: C,
3114
3434
  loan,
3115
3435
  market,
@@ -3121,14 +3441,43 @@ export class Essey {
3121
3441
  expiryMs,
3122
3442
  priceUpdate: await update(market),
3123
3443
  }));
3444
+ return { ...landed, expiryMs };
3445
+ }
3446
+ /**
3447
+ * PRV-15: until a loan's first heartbeat every keeper may read its terms (`keeper.move:204`), so this follows the
3448
+ * settle at once and unpaced. A heartbeat may follow a settle at once: `hb_at_ms` is 0 (`liquidation.move:199`).
3449
+ */
3450
+ async firstCover(p) {
3451
+ try {
3452
+ await this.untilSettled(p.loan, termsCommit(p.terms, p.borrowerPk));
3453
+ const { digest, ticket, expiryMs } = await this.heartbeatOwn(p);
3454
+ return { ok: true, digest, ticket, expiryMs };
3455
+ }
3456
+ catch (err) {
3457
+ const code = isEsseyError(err) ? err.code : "UNEXPECTED";
3458
+ return { ok: false, code, error: err instanceof Error ? err.message.slice(0, 200) : "unknown" };
3459
+ }
3460
+ }
3461
+ /** The loan reader is an indexer that may trail the landed settle. */
3462
+ async untilSettled(loanId, commit) {
3463
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
3464
+ const loan = address(loanId, "loan id");
3465
+ for (let i = 0; i < SETTLE_READS; i++) {
3466
+ if (i > 0)
3467
+ await this.sleep(SETTLE_READ_MS);
3468
+ const json = (await read(loan))?.json;
3469
+ if (Number(json?.state) === 2 && BigInt(json?.terms_commit ?? -1) === commit)
3470
+ return;
3471
+ }
3472
+ throw new EsseyError("STATE_REFUSED", "the loan read does not show the settle yet");
3124
3473
  }
3125
3474
  /**
3126
3475
  * `liquidation::heartbeat`'s clock rules, checked before proving: one heartbeat per gap (43_015), an expiry at
3127
3476
  * least one gap and at most `H_MAX_MS` ahead (43_005) and not before the stored one (43_019). The gap is
3128
- * `liquidation::hb_gap_ms`: 2 minutes on a stand-in market, 50 on any other. No expiry given takes an hour, or the
3129
- * stored expiry when that is later.
3477
+ * `liquidation::hb_gap_ms`: 2 minutes on a stand-in market, 50 on any other. No expiry given takes `coverExpiry`,
3478
+ * or the stored expiry when that is later.
3130
3479
  */
3131
- async heartbeatExpiry(json, market, asked) {
3480
+ async heartbeatExpiry(json, market, maturityS, asked) {
3132
3481
  const read = this.io.readMarket ?? notSetUp("missing config: no market reader");
3133
3482
  const standin = /::standin_oracle::StandinOracle$/.test((await read(market)).oracle ?? "");
3134
3483
  const gap = standin ? HB_GAP_STANDIN_MS : HB_GAP_MS;
@@ -3139,8 +3488,10 @@ export class Essey {
3139
3488
  const wait = (last + gap - now + 999n) / 1000n;
3140
3489
  throw new EsseyError("INVALID_ARGUMENT", `the last heartbeat is under one gap old; retry in ${wait} s`);
3141
3490
  }
3142
- const hour = now + 3600000n;
3143
- const expiry = asked ?? (stored > hour ? stored : hour);
3491
+ const fresh = coverExpiry(now, maturityS);
3492
+ if (asked === undefined && fresh < now + gap)
3493
+ throw new EsseyError("INVALID_ARGUMENT", "the loan is under one gap from maturity plus grace");
3494
+ const expiry = asked ?? (stored > fresh ? stored : fresh);
3144
3495
  if (expiry < now + gap || expiry > now + H_MAX_MS)
3145
3496
  throw new EsseyError("INVALID_ARGUMENT", "the expiry must be at least one gap and at most 24 h ahead");
3146
3497
  if (expiry < stored)
@@ -3166,7 +3517,7 @@ export class Essey {
3166
3517
  throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
3167
3518
  const [C, L] = this.pairOf(json.market_id);
3168
3519
  const ids = { loan, poolC: address(json.pool_c, "pool_c"), market: address(json.market_id, "market") };
3169
- const fee = await this.feeParams(C);
3520
+ const fee = await this.loanFee(C, json.coll_fee_commit);
3170
3521
  const { events, owned, seed } = await this.owned(C);
3171
3522
  const { opening } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
3172
3523
  const inputs = pickInputs(owned, p.add);
@@ -3384,8 +3735,8 @@ export class Essey {
3384
3735
  const market = address(json.market_id, "market");
3385
3736
  const reading = await readPrice(market);
3386
3737
  const asDefault = mode === MODE.DEFAULT;
3387
- const nowS = asDefault ? BigInt(Math.floor((this.io.now ?? Date.now)() / 1000)) : 0n;
3388
- const fee = await this.feeParams(C);
3738
+ const nowS = asDefault ? defaultNowS((this.io.now ?? Date.now)()) : 0n;
3739
+ const fee = await this.loanFee(C, json.coll_fee_commit);
3389
3740
  await this.keys();
3390
3741
  const keeperIndex = this.reserve("notes");
3391
3742
  const keeper = deriveNoteKey(seed, keeperIndex);
@@ -3487,17 +3838,19 @@ export class Essey {
3487
3838
  /** D-SPEC §6.2:599. The seller pass over `sale_room::open_args`, at action nonce 0; the relayer or the callback pays. */
3488
3839
  async openSale(p) {
3489
3840
  const asked = assertSaleOpen(p);
3841
+ assertSaleGrid(asked, this.config.closeStepMs ?? HOUR_MS);
3842
+ const nowMs = (this.io.now ?? Date.now)();
3490
3843
  const open = {
3491
3844
  ...asked,
3492
- closeMs: stepClose(asked.closeMs, (this.io.now ?? Date.now)(), SALE_MAX_WINDOW_MS, this.config.closeStepMs),
3845
+ closeMs: stepClose(nowMs + asked.bidWindowMs, nowMs, SALE_MAX_WINDOW_MS, this.config.closeStepMs),
3493
3846
  };
3494
3847
  requireSale(this.config);
3495
3848
  const pool = poolId(this.config, open.coin);
3849
+ const item = { id: address(open.itemId, "itemId"), type: open.itemType };
3850
+ const readRooms = this.io.readRooms ?? notSetUp("missing config: no room reader");
3496
3851
  const submit = (open.sponsored ?? this.sponsoring() !== null)
3497
- ? this.saleSponsor(pool)
3852
+ ? await this.saleSponsor(pool, item.id)
3498
3853
  : (this.io.submitSaleOpen ?? notSetUp("missing config: sale open has no submitter"));
3499
- const read = this.io.readRoom ?? notSetUp("missing config: no room reader");
3500
- const item = { id: address(open.itemId, "itemId"), type: open.itemType };
3501
3854
  const closeMs = BigInt(open.closeMs);
3502
3855
  const finishByMs = closeMs + BigInt(open.finishWindowMs);
3503
3856
  const typeName = asInvalid(() => {
@@ -3540,15 +3893,11 @@ export class Essey {
3540
3893
  });
3541
3894
  if (typeof landed.digest !== "string" || landed.digest.length === 0 || typeof landed.ticket !== "string")
3542
3895
  unknownObject("the sale open returned no digest");
3543
- if (typeof landed.id !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(landed.id))
3544
- unknownObject("the sale open returned no room");
3545
- const id = address(landed.id, "room id");
3546
- const row = await read(id);
3547
- if (!row)
3548
- unknownObject("the digest created no room");
3549
- assertRoomMatches(this.config, open, { id, json: row.json });
3550
- if (String(row.json.sale_key) !== saleKey.toString())
3551
- unknownObject("the room is not this open");
3896
+ const { id, json } = await this.listedByKey("room", "sale_key", saleKey, async (c) => {
3897
+ const page = await readRooms(c);
3898
+ return { rows: page.rooms, next: page.next };
3899
+ });
3900
+ assertRoomMatches(this.config, open, { id, json });
3552
3901
  return {
3553
3902
  id,
3554
3903
  digest: landed.digest,
@@ -3557,19 +3906,21 @@ export class Essey {
3557
3906
  };
3558
3907
  }
3559
3908
  /**
3560
- * The sponsored open (E-34): a fresh seed-derived sender receives the item, then signs `from_proof` and `open`
3561
- * while the relayer pays gas. Every reader is checked here, before any proof, reserve or delivery. An open that
3562
- * stops after the delivery leaves the item at that sender, which only its seed can move.
3909
+ * The sponsored open (E-34): a fresh seed-derived sender signs `from_proof` and `open` while the relayer pays gas.
3910
+ * PRV-35: an item at one of this seed's `itemAddress()` holders opens from that holder with no hand-over; any other
3911
+ * item is first delivered to a fresh deposit signer. Every reader is checked here, before any proof, reserve or
3912
+ * delivery. An open that stops after the delivery leaves the item at that sender, which only its seed can move.
3563
3913
  */
3564
- saleSponsor(pool) {
3914
+ async saleSponsor(pool, itemId) {
3565
3915
  const relayer = this.sponsorRelayer();
3566
- const deliver = this.io.deliverSaleItem ?? notSetUp("no deliverSaleItem: the SDK never holds the item's wallet");
3567
3916
  const readRef = this.io.readObjectRef ?? notSetUp("no object reader for the item's version");
3568
- const readOpened = this.io.readSaleOpened ?? notSetUp("no reader for the room an open created");
3569
3917
  const readShared = this.io.readSharedVersion ?? notSetUp("no chain reader for shared object versions");
3570
3918
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
3571
3919
  const keyRegistry = this.config.objects.keyRegistry ?? notSetUp("missing config: no KeyRegistry");
3572
- const used = this.addressUsed();
3920
+ const held = this.holderOf((await readRef(itemId)).owner);
3921
+ const deliver = held !== null
3922
+ ? null
3923
+ : (this.io.deliverSaleItem ?? notSetUp("no deliverSaleItem: the SDK never holds the item's wallet"));
3573
3924
  const packages = { pool: this.config.packages.pool, sale: this.config.packages.sale };
3574
3925
  const shared = (r) => ({
3575
3926
  objectId: r.id,
@@ -3577,9 +3928,10 @@ export class Essey {
3577
3928
  });
3578
3929
  return async (tx) => {
3579
3930
  const seed = this.seed();
3580
- const signer = depositSigner(seed, await this.freshSigner(seed, used));
3931
+ const signer = held !== null ? itemHolder(seed, held) : depositSigner(seed, this.freshSigner());
3581
3932
  const sender = signer.toSuiAddress();
3582
- await deliver({ item: tx.item, sender });
3933
+ if (deliver)
3934
+ await deliver({ item: tx.item, sender });
3583
3935
  const ref = await readRef(tx.item.id);
3584
3936
  if (ref.owner === null || normalizeSuiAddress(ref.owner) !== sender)
3585
3937
  throw new EsseyError("SERVICE_REFUSED", "refused: the item is not at the sale sender; nothing was signed");
@@ -3613,7 +3965,7 @@ export class Essey {
3613
3965
  txBytesB64: sponsored.txBytesB64,
3614
3966
  userSig: signature,
3615
3967
  });
3616
- return { id: (await readOpened(digest)).room, digest, ticket: "" };
3968
+ return { digest, ticket: "" };
3617
3969
  };
3618
3970
  }
3619
3971
  /** D-SPEC §6.2:600. */
@@ -3704,7 +4056,7 @@ export class Essey {
3704
4056
  if (seq >= room.maxBids)
3705
4057
  throw new EsseyError("INVALID_ARGUMENT", "the room is full");
3706
4058
  const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
3707
- const { member, credential } = readState(this.statePath);
4059
+ const { member, credential } = readState(this.statePath, this.stateKey);
3708
4060
  if (!member || !credential)
3709
4061
  notSetUp("no credential: call credential.obtain first");
3710
4062
  const relayer = this.relayerAddress();
@@ -3779,7 +4131,7 @@ export class Essey {
3779
4131
  /** `sale_room::seal_approve_bid`: the seller's SEAL pass over `seal_bid` of bid `seq`, bound to the viewer, nonce 0. */
3780
4132
  bidApprove(room, seq) {
3781
4133
  const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
3782
- const { member, credential } = readState(this.statePath);
4134
+ const { member, credential } = readState(this.statePath, this.stateKey);
3783
4135
  if (!member || !credential)
3784
4136
  notSetUp("no credential: call credential.obtain first");
3785
4137
  const scope = keyId(room.saleKey);
@@ -3875,7 +4227,7 @@ export class Essey {
3875
4227
  });
3876
4228
  }
3877
4229
  indexOfSellerKey(seed, sellerSk) {
3878
- const n = readState(this.statePath).notes ?? 0;
4230
+ const n = readState(this.statePath, this.stateKey).notes ?? 0;
3879
4231
  for (let i = n - 1; i >= 0; i--)
3880
4232
  if (deriveNoteKey(seed, i).sk === sellerSk)
3881
4233
  return i;
@@ -3955,17 +4307,18 @@ export class Essey {
3955
4307
  const w = itemClaim({
3956
4308
  vault: { roomField: BigInt(json.room_field), claim },
3957
4309
  holder,
3958
- recipient: p.recipient,
4310
+ recipient: p.recipient ?? this.itemAddress(),
3959
4311
  relayer: this.relayerAddress(),
3960
4312
  });
3961
4313
  const proof = (await this.prover().prove("item_claim", w.input)).proof;
3962
- return this.freeLoan(claimBody, {
4314
+ const landed = await this.freeLoan(claimBody, {
3963
4315
  pool: room.coin,
3964
4316
  vault,
3965
4317
  recipient: w.statement.recipient,
3966
4318
  nullifier: w.statement.nullifier,
3967
4319
  proved: { proof, publicSignals: w.publics.map(String) },
3968
4320
  });
4321
+ return { ...landed, to: w.statement.recipient };
3969
4322
  }
3970
4323
  async prepareOpen(body) {
3971
4324
  if (body.kind !== "loan_open")