@esseyonsui/sui-sdk-v3 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/README.md +45 -2
  2. package/dist/config.d.ts +82 -0
  3. package/dist/config.d.ts.map +1 -0
  4. package/dist/config.js +180 -0
  5. package/dist/errors.d.ts +38 -0
  6. package/dist/errors.d.ts.map +1 -0
  7. package/dist/errors.js +32 -0
  8. package/dist/essey.d.ts +866 -0
  9. package/dist/essey.d.ts.map +1 -0
  10. package/dist/essey.js +3593 -0
  11. package/dist/index.d.ts +9 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +4 -0
  14. package/dist/keeper.d.ts +54 -0
  15. package/dist/keeper.d.ts.map +1 -0
  16. package/dist/keeper.js +44 -0
  17. package/dist/network.d.ts +17 -0
  18. package/dist/network.d.ts.map +1 -0
  19. package/dist/network.js +62 -0
  20. package/dist/v3/addr-field.d.ts +3 -0
  21. package/dist/v3/addr-field.d.ts.map +1 -0
  22. package/dist/v3/addr-field.js +10 -0
  23. package/dist/v3/bodies.d.ts +54 -0
  24. package/dist/v3/bodies.d.ts.map +1 -0
  25. package/dist/v3/bodies.js +68 -0
  26. package/dist/v3/body-args.d.ts +29 -0
  27. package/dist/v3/body-args.d.ts.map +1 -0
  28. package/dist/v3/body-args.js +78 -0
  29. package/dist/v3/collateral/bodies.d.ts +78 -0
  30. package/dist/v3/collateral/bodies.d.ts.map +1 -0
  31. package/dist/v3/collateral/bodies.js +136 -0
  32. package/dist/v3/collateral/ext.d.ts +21 -0
  33. package/dist/v3/collateral/ext.d.ts.map +1 -0
  34. package/dist/v3/collateral/ext.js +19 -0
  35. package/dist/v3/collateral/health.d.ts +115 -0
  36. package/dist/v3/collateral/health.d.ts.map +1 -0
  37. package/dist/v3/collateral/health.js +255 -0
  38. package/dist/v3/collateral/index.d.ts +9 -0
  39. package/dist/v3/collateral/index.d.ts.map +1 -0
  40. package/dist/v3/collateral/index.js +8 -0
  41. package/dist/v3/collateral/local-health.d.ts +23 -0
  42. package/dist/v3/collateral/local-health.d.ts.map +1 -0
  43. package/dist/v3/collateral/local-health.js +27 -0
  44. package/dist/v3/collateral/math.d.ts +33 -0
  45. package/dist/v3/collateral/math.d.ts.map +1 -0
  46. package/dist/v3/collateral/math.js +38 -0
  47. package/dist/v3/collateral/openings.d.ts +27 -0
  48. package/dist/v3/collateral/openings.d.ts.map +1 -0
  49. package/dist/v3/collateral/openings.js +28 -0
  50. package/dist/v3/collateral/scan.d.ts +41 -0
  51. package/dist/v3/collateral/scan.d.ts.map +1 -0
  52. package/dist/v3/collateral/scan.js +76 -0
  53. package/dist/v3/collateral/seal.d.ts +31 -0
  54. package/dist/v3/collateral/seal.d.ts.map +1 -0
  55. package/dist/v3/collateral/seal.js +59 -0
  56. package/dist/v3/credential/issue.d.ts +27 -0
  57. package/dist/v3/credential/issue.d.ts.map +1 -0
  58. package/dist/v3/credential/issue.js +109 -0
  59. package/dist/v3/credential/membership.d.ts +37 -0
  60. package/dist/v3/credential/membership.d.ts.map +1 -0
  61. package/dist/v3/credential/membership.js +34 -0
  62. package/dist/v3/credential/pow.d.ts +10 -0
  63. package/dist/v3/credential/pow.d.ts.map +1 -0
  64. package/dist/v3/credential/pow.js +22 -0
  65. package/dist/v3/domains.d.ts +141 -0
  66. package/dist/v3/domains.d.ts.map +1 -0
  67. package/dist/v3/domains.js +158 -0
  68. package/dist/v3/ext.d.ts +29 -0
  69. package/dist/v3/ext.d.ts.map +1 -0
  70. package/dist/v3/ext.js +82 -0
  71. package/dist/v3/faucet.d.ts +66 -0
  72. package/dist/v3/faucet.d.ts.map +1 -0
  73. package/dist/v3/faucet.js +64 -0
  74. package/dist/v3/fee-witness.d.ts +5 -0
  75. package/dist/v3/fee-witness.d.ts.map +1 -0
  76. package/dist/v3/fee-witness.js +18 -0
  77. package/dist/v3/fees.d.ts +78 -0
  78. package/dist/v3/fees.d.ts.map +1 -0
  79. package/dist/v3/fees.js +190 -0
  80. package/dist/v3/index.d.ts +24 -0
  81. package/dist/v3/index.d.ts.map +1 -0
  82. package/dist/v3/index.js +23 -0
  83. package/dist/v3/inputs.d.ts +89 -0
  84. package/dist/v3/inputs.d.ts.map +1 -0
  85. package/dist/v3/inputs.js +152 -0
  86. package/dist/v3/keeper-badge.d.ts +48 -0
  87. package/dist/v3/keeper-badge.d.ts.map +1 -0
  88. package/dist/v3/keeper-badge.js +49 -0
  89. package/dist/v3/keeper-payload.d.ts +36 -0
  90. package/dist/v3/keeper-payload.d.ts.map +1 -0
  91. package/dist/v3/keeper-payload.js +116 -0
  92. package/dist/v3/kinds.d.ts +23 -0
  93. package/dist/v3/kinds.d.ts.map +1 -0
  94. package/dist/v3/kinds.js +50 -0
  95. package/dist/v3/loans/bodies.d.ts +215 -0
  96. package/dist/v3/loans/bodies.d.ts.map +1 -0
  97. package/dist/v3/loans/bodies.js +255 -0
  98. package/dist/v3/loans/offer-plan.d.ts +66 -0
  99. package/dist/v3/loans/offer-plan.d.ts.map +1 -0
  100. package/dist/v3/loans/offer-plan.js +141 -0
  101. package/dist/v3/loans/open-plan.d.ts +62 -0
  102. package/dist/v3/loans/open-plan.d.ts.map +1 -0
  103. package/dist/v3/loans/open-plan.js +92 -0
  104. package/dist/v3/loans/reclaim-plan.d.ts +65 -0
  105. package/dist/v3/loans/reclaim-plan.d.ts.map +1 -0
  106. package/dist/v3/loans/reclaim-plan.js +125 -0
  107. package/dist/v3/loans/refi-plan.d.ts +62 -0
  108. package/dist/v3/loans/refi-plan.d.ts.map +1 -0
  109. package/dist/v3/loans/refi-plan.js +157 -0
  110. package/dist/v3/loans/repay-plan.d.ts +40 -0
  111. package/dist/v3/loans/repay-plan.d.ts.map +1 -0
  112. package/dist/v3/loans/repay-plan.js +77 -0
  113. package/dist/v3/loans/settle-plan.d.ts +152 -0
  114. package/dist/v3/loans/settle-plan.d.ts.map +1 -0
  115. package/dist/v3/loans/settle-plan.js +210 -0
  116. package/dist/v3/market.d.ts +38 -0
  117. package/dist/v3/market.d.ts.map +1 -0
  118. package/dist/v3/market.js +30 -0
  119. package/dist/v3/notes/denominations.d.ts +13 -0
  120. package/dist/v3/notes/denominations.d.ts.map +1 -0
  121. package/dist/v3/notes/denominations.js +35 -0
  122. package/dist/v3/notes/deposit.d.ts +57 -0
  123. package/dist/v3/notes/deposit.d.ts.map +1 -0
  124. package/dist/v3/notes/deposit.js +103 -0
  125. package/dist/v3/notes/derive.d.ts +16 -0
  126. package/dist/v3/notes/derive.d.ts.map +1 -0
  127. package/dist/v3/notes/derive.js +34 -0
  128. package/dist/v3/notes/faucet.d.ts +3 -0
  129. package/dist/v3/notes/faucet.d.ts.map +1 -0
  130. package/dist/v3/notes/faucet.js +8 -0
  131. package/dist/v3/notes/index.d.ts +9 -0
  132. package/dist/v3/notes/index.d.ts.map +1 -0
  133. package/dist/v3/notes/index.js +8 -0
  134. package/dist/v3/notes/keys.d.ts +5 -0
  135. package/dist/v3/notes/keys.d.ts.map +1 -0
  136. package/dist/v3/notes/keys.js +11 -0
  137. package/dist/v3/notes/opening.d.ts +16 -0
  138. package/dist/v3/notes/opening.d.ts.map +1 -0
  139. package/dist/v3/notes/opening.js +62 -0
  140. package/dist/v3/notes/scan.d.ts +32 -0
  141. package/dist/v3/notes/scan.d.ts.map +1 -0
  142. package/dist/v3/notes/scan.js +71 -0
  143. package/dist/v3/notes/tree.d.ts +9 -0
  144. package/dist/v3/notes/tree.d.ts.map +1 -0
  145. package/dist/v3/notes/tree.js +31 -0
  146. package/dist/v3/notes/withdraw.d.ts +12 -0
  147. package/dist/v3/notes/withdraw.d.ts.map +1 -0
  148. package/dist/v3/notes/withdraw.js +27 -0
  149. package/dist/v3/proof-bytes.d.ts +4 -0
  150. package/dist/v3/proof-bytes.d.ts.map +1 -0
  151. package/dist/v3/proof-bytes.js +22 -0
  152. package/dist/v3/prover.d.ts +34 -0
  153. package/dist/v3/prover.d.ts.map +1 -0
  154. package/dist/v3/prover.js +76 -0
  155. package/dist/v3/relay/client.d.ts +57 -0
  156. package/dist/v3/relay/client.d.ts.map +1 -0
  157. package/dist/v3/relay/client.js +80 -0
  158. package/dist/v3/relay/possession.d.ts +21 -0
  159. package/dist/v3/relay/possession.d.ts.map +1 -0
  160. package/dist/v3/relay/possession.js +45 -0
  161. package/dist/v3/sales/auctioneer.d.ts +60 -0
  162. package/dist/v3/sales/auctioneer.d.ts.map +1 -0
  163. package/dist/v3/sales/auctioneer.js +130 -0
  164. package/dist/v3/sales/bcs.d.ts +4 -0
  165. package/dist/v3/sales/bcs.d.ts.map +1 -0
  166. package/dist/v3/sales/bcs.js +16 -0
  167. package/dist/v3/sales/bid.d.ts +51 -0
  168. package/dist/v3/sales/bid.d.ts.map +1 -0
  169. package/dist/v3/sales/bid.js +85 -0
  170. package/dist/v3/sales/bodies.d.ts +83 -0
  171. package/dist/v3/sales/bodies.d.ts.map +1 -0
  172. package/dist/v3/sales/bodies.js +78 -0
  173. package/dist/v3/sales/claim.d.ts +40 -0
  174. package/dist/v3/sales/claim.d.ts.map +1 -0
  175. package/dist/v3/sales/claim.js +44 -0
  176. package/dist/v3/sales/index.d.ts +10 -0
  177. package/dist/v3/sales/index.d.ts.map +1 -0
  178. package/dist/v3/sales/index.js +9 -0
  179. package/dist/v3/sales/open-kind.d.ts +42 -0
  180. package/dist/v3/sales/open-kind.d.ts.map +1 -0
  181. package/dist/v3/sales/open-kind.js +43 -0
  182. package/dist/v3/sales/outcome.d.ts +20 -0
  183. package/dist/v3/sales/outcome.d.ts.map +1 -0
  184. package/dist/v3/sales/outcome.js +21 -0
  185. package/dist/v3/sales/reclaim.d.ts +46 -0
  186. package/dist/v3/sales/reclaim.d.ts.map +1 -0
  187. package/dist/v3/sales/reclaim.js +57 -0
  188. package/dist/v3/sales/rows.d.ts +55 -0
  189. package/dist/v3/sales/rows.d.ts.map +1 -0
  190. package/dist/v3/sales/rows.js +98 -0
  191. package/dist/v3/sales/seller.d.ts +39 -0
  192. package/dist/v3/sales/seller.d.ts.map +1 -0
  193. package/dist/v3/sales/seller.js +67 -0
  194. package/dist/v3/stage1.d.ts +204 -0
  195. package/dist/v3/stage1.d.ts.map +1 -0
  196. package/dist/v3/stage1.js +575 -0
  197. package/package.json +33 -4
package/dist/essey.js ADDED
@@ -0,0 +1,3593 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { closeSync, existsSync, fstatSync, lstatSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { fromBase64, normalizeSuiAddress } from "@mysten/sui/utils";
5
+ import { poseidonHash } from "@mysten/sui/zklogin";
6
+ import { blake2b } from "@noble/hashes/blake2.js";
7
+ import { COINS, loadConfig } from "./config.js";
8
+ import { EsseyError, isEsseyError } from "./errors.js";
9
+ import { keeperSection, } from "./keeper.js";
10
+ import { address, assertTestnet, decimal, getJson, postJson, serviceUrl } from "./network.js";
11
+ import { credentialSigned, parseCredential, requestCredential, solveChallenge, } from "./v3/credential/issue.js";
12
+ import { DOMAIN_KEEPER, DOMAIN_SENDER, DOMAIN_SPEND, FEE_PARAMS_ROOM, memberCommitment, } from "./v3/credential/membership.js";
13
+ import { passProof, transfer as transferBody, withdraw as withdrawBody, } from "./v3/bodies.js";
14
+ 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
+ import { DOM_LBLIND, DOM_TSALT, R } from "./v3/domains.js";
16
+ import { MODE_OPEN, MODE_TOPUP, NO_ADDRESS, collLockExt } from "./v3/ext.js";
17
+ import { defaultExt, faultExt, heartbeatExt, liquidateExt, openExt, releaseExt, topupByBorrowerExt, topupExt, } from "./v3/collateral/ext.js";
18
+ 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 { heartbeatFloor } from "./v3/collateral/math.js";
20
+ import { MODE, health, lenderAmount, loanRisk, seizeSplit } from "./v3/collateral/health.js";
21
+ import { collLockPk, collNote, outputBlind, requestCommit, termsCommit, } from "./v3/collateral/openings.js";
22
+ import { fetchKeeperPlaintext, keeperKeyId, openingOf, rollTo } from "./v3/collateral/seal.js";
23
+ import { localHealth } from "./v3/collateral/local-health.js";
24
+ import { badgeApprove, badgeOf, mintBadgeKind } from "./v3/keeper-badge.js";
25
+ import { KEEPER_LAYOUT_VERSION, encodeKeeperPayload } from "./v3/keeper-payload.js";
26
+ import { LOAN_REPAY_KIND, loanRepay } from "./v3/loans/repay-plan.js";
27
+ import { reclaimColl, reclaimLock } from "./v3/loans/reclaim-plan.js";
28
+ import { collLock, keyId, openAction, requestKeyId, requestPlaintext } from "./v3/loans/open-plan.js";
29
+ import { LOAN_SETTLE_KIND, actionHash, decodeOffer, interest, loanSettle, sealOfferBind, settleArgs, openRefiArgs, readingBytes, settleRefiArgs, cancelRefiArgs, topupArgs, } from "./v3/loans/settle-plan.js";
30
+ import { LOAN_REFI_KIND, loanRefi } from "./v3/loans/refi-plan.js";
31
+ import { LOAN_OFFER_KIND, decodeRequest, lock4, lockField, loanExt, loanOffer, offerKeyId, offerPlaintext, offerRoom, sealListingBind, } from "./v3/loans/offer-plan.js";
32
+ import { proveFaucet } from "./v3/faucet.js";
33
+ import { ecdhBlind, feeOf, treasuryPoint, verifyFeeOpening, } from "./v3/fees.js";
34
+ import { JS4_LEVELS, deposit as depositInput, js4, membership, } from "./v3/inputs.js";
35
+ import { marketRates } from "./v3/market.js";
36
+ import { afterPage, assertLoanOpen, assertRoomMatches, assertSaleOpen, coinByPool, listPositions, openPosition, poolId, requireSale, summarizeLoan, summarizeRoom, viewLoanObject, viewPosition, viewRoomObject, } from "./v3/stage1.js";
37
+ import { plan as settlePlan } from "./v3/sales/auctioneer.js";
38
+ import { lockBid } from "./v3/sales/bid.js";
39
+ import { bidBody, cancelBody, claimBody, expireBody, finishBody, reclaimBody, slashBody, } from "./v3/sales/bodies.js";
40
+ import { itemClaim } from "./v3/sales/claim.js";
41
+ import { saleOpenKind } from "./v3/sales/open-kind.js";
42
+ import { SALE_STATE } from "./v3/sales/outcome.js";
43
+ import { reclaim as saleReclaim } from "./v3/sales/reclaim.js";
44
+ import { bidAad, bidKeyId, bidPlaintext, sealBidBind } from "./v3/sales/rows.js";
45
+ import { assertFinishWindow, openArgs, openCommits, typeNameOf } from "./v3/sales/seller.js";
46
+ import { splitDenominations } from "./v3/notes/denominations.js";
47
+ import { DEPOSIT_ROOM, carriesKind, depositKind, executeSponsored, sponsor, } from "./v3/notes/deposit.js";
48
+ import { SEED_BYTES, deriveNoteKey, depositSigner, noteEncKey } from "./v3/notes/derive.js";
49
+ import { faucetGrant } from "./v3/notes/faucet.js";
50
+ import { noteCommitment, noteNullifier, notePk } from "./v3/notes/keys.js";
51
+ import { fillerEnc, sealOpening } from "./v3/notes/opening.js";
52
+ import { orderedLeaves, ownNotes, usedIndices, } from "./v3/notes/scan.js";
53
+ import { poolTree } from "./v3/notes/tree.js";
54
+ import { exitValue, pickInputs, withdrawCost } from "./v3/notes/withdraw.js";
55
+ import { proofBytes } from "./v3/proof-bytes.js";
56
+ import { RelayClient, failure, } from "./v3/relay/client.js";
57
+ import { provePossession } from "./v3/relay/possession.js";
58
+ const FOLLOW_POLLS = 60;
59
+ const MAX_USED_SENDERS = 64;
60
+ const EPH_SHIFT = 3n;
61
+ const NO_RELAYER = "no relayer url: the deployment record names none yet; nothing was sent";
62
+ const NO_RELAYER_ADDRESS = "no relayer address: the deployment record names none yet; nothing was sent";
63
+ /** Half the relayer's 10 min sponsorship window (`services/relayer-v3/src/config.ts:261`), so a clock 5 min ahead still fits. */
64
+ const POSSESSION_TTL_MS = 5 * 60_000;
65
+ /** NEEDS-BORIS: the relayer's default `sponsorWindowMs` (`services/relayer-v3/src/config.ts:261`); it serves no route that names its own. */
66
+ const SPONSOR_WINDOW_MS = 10 * 60_000;
67
+ const NO_TO = "no to address: the zero address is nobody's; nothing was sent";
68
+ const NO_SEED = "refused: the state file holds notes, senders or stranded deposits but no seed; connect with the seed that made them. Nothing was written";
69
+ function notSetUp(what) {
70
+ throw new EsseyError("NOT_SET_UP", what);
71
+ }
72
+ function unknownObject(what) {
73
+ throw new EsseyError("SERVICE_REFUSED", `unknown object: ${what}`);
74
+ }
75
+ function wrongCoinObject() {
76
+ throw new EsseyError("INVALID_ARGUMENT", "wrong coin: the envelope pool is not the loan coin");
77
+ }
78
+ const isIndex = (n) => Number.isSafeInteger(n) && n >= 0;
79
+ const isSigned = (c, s) => c.commitment === s.commitment && c.enc === s.enc;
80
+ const landedIn = (events, r) => events.commitments.some((c) => r.signed.some((s) => isSigned(c, s)));
81
+ function setRecord(state, signer, record) {
82
+ const stranded = [
83
+ ...(state.stranded ?? []).filter((r) => r.signer !== signer),
84
+ ...(record ? [record] : []),
85
+ ];
86
+ state.stranded = stranded.length > 0 ? stranded : undefined;
87
+ }
88
+ function parseStranded(raw) {
89
+ const r = raw;
90
+ if (!COINS.includes(r.coin) ||
91
+ !isIndex(r.signer) ||
92
+ !isIndex(r.note) ||
93
+ typeof r.value !== "string" ||
94
+ !Array.isArray(r.signed) ||
95
+ r.signed.length === 0)
96
+ throw new Error("stranded");
97
+ const value = BigInt(r.value);
98
+ if (value <= 0n || value >= 1n << 64n)
99
+ throw new Error("stranded");
100
+ const signed = r.signed.map(parseSigned);
101
+ return { coin: r.coin, signer: r.signer, note: r.note, value, signed };
102
+ }
103
+ function parseSigned(raw) {
104
+ const { commitment, enc } = (raw ?? {});
105
+ if (typeof commitment !== "string" || typeof enc !== "string" || !/^0x[0-9a-f]+$/.test(enc))
106
+ throw new Error("stranded");
107
+ const value = BigInt(commitment);
108
+ if (value < 0n || value >= R)
109
+ throw new Error("stranded");
110
+ return { commitment: value, enc };
111
+ }
112
+ function parseBadge(raw) {
113
+ const { signer, id, expiresMs } = (raw ?? {});
114
+ if (!isIndex(signer) || typeof id !== "string" || !/^0x[0-9a-f]{64}$/.test(id))
115
+ throw new Error("badge");
116
+ return { signer: signer, id, expiresMs: decimal(expiresMs, "badge.expiresMs") };
117
+ }
118
+ const toJson = (state) => JSON.stringify(state, (_key, value) => (typeof value === "bigint" ? value.toString() : value));
119
+ /**
120
+ * Another caller's new state is empty between its "wx" open and its write (`createState`), so an empty file is read
121
+ * again for as long as a live lock holder is waited for (R1 F2). One that stays empty is refused like any other.
122
+ */
123
+ function stateText(path) {
124
+ const deadline = Date.now() + LOCK_WAIT_MS;
125
+ for (;;) {
126
+ const text = readFileSync(path, "utf8");
127
+ if (text !== "" || Date.now() > deadline)
128
+ return text;
129
+ Atomics.wait(pause, 0, 0, 1);
130
+ }
131
+ }
132
+ function readState(path) {
133
+ if (!existsSync(path))
134
+ return { v: 1 };
135
+ if ((statSync(path).mode & 0o077) !== 0)
136
+ throw new EsseyError("STATE_REFUSED", "refused: the state file must be mode 600");
137
+ try {
138
+ const raw = JSON.parse(stateText(path));
139
+ if (raw.v !== 1)
140
+ throw new Error("version");
141
+ const m = raw.member;
142
+ const member = m && { secret: BigInt(m.secret), nullSecret: BigInt(m.nullSecret) };
143
+ if (member && [member.secret, member.nullSecret].some((s) => s <= 0n || s >= R))
144
+ throw new Error("range");
145
+ const credential = raw.credential === undefined ? undefined : parseCredential(raw.credential);
146
+ if (raw.seed !== undefined && !(typeof raw.seed === "string" && /^[0-9a-f]{64}$/.test(raw.seed)))
147
+ throw new Error("seed");
148
+ const counters = [raw.notes, raw.signers];
149
+ if (counters.some((n) => n !== undefined && !isIndex(n)))
150
+ throw new Error("counter");
151
+ if (raw.stranded !== undefined && !Array.isArray(raw.stranded))
152
+ throw new Error("stranded");
153
+ return {
154
+ v: 1,
155
+ member,
156
+ slot: raw.slot,
157
+ credential,
158
+ seed: raw.seed,
159
+ notes: raw.notes,
160
+ signers: raw.signers,
161
+ stranded: raw.stranded?.map(parseStranded),
162
+ badge: raw.badge === undefined ? undefined : parseBadge(raw.badge),
163
+ };
164
+ }
165
+ catch {
166
+ throw new EsseyError("STATE_REFUSED", "refused: the state file is not readable as SDK state");
167
+ }
168
+ }
169
+ /**
170
+ * Written beside the target and renamed over it, so a failure leaves the old file whole. "wx" refuses
171
+ * an existing name instead of following a planted link with the member secrets.
172
+ */
173
+ function writeState(path, state, held) {
174
+ const tmp = `${path}.${randomBytes(16).toString("hex")}.tmp`;
175
+ const fd = openSync(tmp, "wx", 0o600);
176
+ try {
177
+ try {
178
+ writeFileSync(fd, toJson(state));
179
+ }
180
+ finally {
181
+ closeSync(fd);
182
+ }
183
+ held();
184
+ renameSync(tmp, path);
185
+ }
186
+ catch (error) {
187
+ rmSync(tmp, { force: true });
188
+ held();
189
+ const { code, syscall, message } = error;
190
+ if (code === "ENOENT" && syscall === "rename")
191
+ throw new EsseyError("STATE_REFUSED", `refused: the state file ${path} was not written: ${message}`);
192
+ throw error;
193
+ }
194
+ }
195
+ const LOCK_WAIT_MS = 5_000;
196
+ const SQLITE_BUSY = 5;
197
+ const SQLITE_NOTADB = 26;
198
+ const pause = new Int32Array(new SharedArrayBuffer(4));
199
+ /**
200
+ * One writer at a time across processes: an SQLite EXCLUSIVE transaction on `<state>.lock`, an fcntl lock the kernel
201
+ * drops when its holder dies however it dies. Nothing reads a pid (AUD-V3-124 A-R1-1, ruling 0086 §3 0103). Never
202
+ * open or close another fd on a lock SQLite may hold: closing any fd on a file drops this process's fcntl locks on it.
203
+ * SQLite opens a lock it cannot write read-only, where BEGIN EXCLUSIVE takes no write lock, so `hold` writes once
204
+ * (B-R1-1). That write only proves the handle can write, so it is rolled back: a commit would write the lock after
205
+ * `run` (B-R2-1). SQLite reads a name that starts with "file:" as a URI, whose query can turn the lock off, so such a
206
+ * path is refused (B-R2-2, ruling 0089). A "?" anywhere, a directory name included, is refused too (R3-4).
207
+ * The lock and the temps are named from the folder's own listing (ruling 0124): the entry with the state's (st_dev,
208
+ * st_ino), under the statePath's own folder prefix so only the kernel resolves the folder (R1b-1). Every spelling of
209
+ * one file then shares one lock. A final component that is not that listed name, or a case-insensitive match of it, is
210
+ * refused; the trailing-dot and 8.3 refusal (ruling 0122) is only a fast path. A missing state is first created empty
211
+ * by "wx", so the entry exists before any lock. Before SQLite opens the lock, a lock that is the state's own entry, or
212
+ * is not listed under its name, is refused: SQLite on such a lock deletes the state (0124 F2). The lock holds only
213
+ * while its name is still the lock inode opened, by lstat (st_dev, st_ino): checked once locked, right before the
214
+ * state's rename and after a failed write (R1c F1). The state must not be a symlink or have a second hard link. Once
215
+ * the work is written, a failure to end the transaction or close the lock is typed, and the call's change stays.
216
+ */
217
+ function withLock(path, run) {
218
+ if (path === "")
219
+ throw new EsseyError("STATE_REFUSED", "refused: the state path is empty");
220
+ if (/(^|\/)\.{0,2}$/.test(path))
221
+ throw new EsseyError("STATE_REFUSED", 'refused: the state path must name a file, not end in "/", "." or ".."');
222
+ if (/^file:/i.test(path) || path.includes("?"))
223
+ throw new EsseyError("STATE_REFUSED", 'refused: a state path must not start with "file:" or hold "?"');
224
+ if (isAliasName(path.slice(path.lastIndexOf("/") + 1)))
225
+ throw new EsseyError("STATE_REFUSED", 'refused: the state file name must not end in "." or a space, or be an 8.3 short name like STATE~1.JSO');
226
+ const file = listedState(path);
227
+ const lock = `${file}.lock`;
228
+ const db = openLock(lock);
229
+ let written = false;
230
+ try {
231
+ try {
232
+ const opened = statSync(lock, { throwIfNoEntry: false });
233
+ hold(db, lock);
234
+ const held = () => lockHeld(file, lock, opened);
235
+ try {
236
+ held();
237
+ pinned(file);
238
+ sweepTemps(file);
239
+ const result = run(file, held);
240
+ written = true;
241
+ return result;
242
+ }
243
+ finally {
244
+ db.exec("ROLLBACK");
245
+ }
246
+ }
247
+ finally {
248
+ db.close();
249
+ }
250
+ }
251
+ catch (error) {
252
+ if (!written)
253
+ throw error;
254
+ throw new EsseyError("STATE_REFUSED", `refused: the state file was written but ${lock} was not released: ${error.message}`);
255
+ }
256
+ }
257
+ /** A vfat alias of a long name: a trailing "." or space, or an 8.3 short name (a stem of at most 8 with "~<digit>"). */
258
+ const isAliasName = (name) => /[.\s]$/.test(name) || /^(?=[^.]*~\d)[^.]{1,8}(\.[^.]{0,3})?$/.test(name);
259
+ const sameFile = (a, b) => a !== undefined && b !== undefined && a.dev === b.dev && a.ino === b.ino;
260
+ /**
261
+ * The statePath as its folder lists it, with a lock SQLite can open without touching the state. A writer's rename
262
+ * between the two lstats of the state changes its inode, so the match is retried.
263
+ */
264
+ function listedState(path) {
265
+ const created = createState(path);
266
+ try {
267
+ const deadline = Date.now() + LOCK_WAIT_MS;
268
+ for (;;) {
269
+ const state = lstatSync(path, { throwIfNoEntry: false });
270
+ const names = state ? listed(path, state) : [];
271
+ if (state &&
272
+ sameFile(state, lstatSync(path, { throwIfNoEntry: false })) &&
273
+ settled(path, names, state)) {
274
+ const file = path.slice(0, path.lastIndexOf("/") + 1) + pick(path, names);
275
+ lockApart(file, state);
276
+ return file;
277
+ }
278
+ if (Date.now() > deadline)
279
+ throw new EsseyError("STATE_REFUSED", `refused: the state path ${path} changed while it was being locked`);
280
+ Atomics.wait(pause, 0, 0, 1);
281
+ }
282
+ }
283
+ catch (error) {
284
+ if (created && sameFile(lstatSync(path, { throwIfNoEntry: false }), created))
285
+ rmSync(path, { force: true });
286
+ throw error;
287
+ }
288
+ }
289
+ /** Creates a missing state as an empty one, never over an existing entry; returns it when this call created it. */
290
+ function createState(path) {
291
+ if (lstatSync(path, { throwIfNoEntry: false }))
292
+ return undefined;
293
+ let fd;
294
+ try {
295
+ fd = openSync(path, "wx", 0o600);
296
+ }
297
+ catch (error) {
298
+ if (error.code === "EEXIST")
299
+ return undefined;
300
+ throw new EsseyError("STATE_REFUSED", `refused: the state file ${path} cannot be created: ${error.message}`);
301
+ }
302
+ try {
303
+ writeFileSync(fd, toJson({ v: 1 }));
304
+ return fstatSync(fd);
305
+ }
306
+ finally {
307
+ closeSync(fd);
308
+ }
309
+ }
310
+ /** Every name the folder of `path` lists for the entry `of`. */
311
+ function listed(path, of) {
312
+ const dir = path.slice(0, path.lastIndexOf("/") + 1);
313
+ return readdirSync(dirname(path)).filter((f) => sameFile(lstatSync(dir + f, { throwIfNoEntry: false }), of));
314
+ }
315
+ /**
316
+ * ext4 hands the inode number one writer's rename frees to the next writer's temp, so the state shows its first
317
+ * (st_dev, st_ino) again after a listing that met another file under its name (R1 F1). No name of that listing
318
+ * reaches the state now, read after the state's second lstat: a temp that had the number is gone once it is the
319
+ * state. Such a listing is taken again; a listed name or an alias still reaches the state.
320
+ */
321
+ function settled(path, names, state) {
322
+ const dir = path.slice(0, path.lastIndexOf("/") + 1);
323
+ return names.some((f) => sameFile(lstatSync(dir + f, { throwIfNoEntry: false }), state));
324
+ }
325
+ /** The final component of `path` if listed, else the listed name it matches case-insensitively; anything else refuses. */
326
+ function pick(path, names) {
327
+ const name = path.slice(path.lastIndexOf("/") + 1);
328
+ const hit = names.includes(name) ? name : names.find((f) => f.toLowerCase() === name.toLowerCase());
329
+ if (hit === undefined)
330
+ throw new EsseyError("STATE_REFUSED", `refused: ${name} reaches a state file its folder lists as ${names.join(", ")}; give that name`);
331
+ return hit;
332
+ }
333
+ /**
334
+ * Refuses a folder that cannot keep the state and its lock apart, before SQLite opens the lock. A missing lock is
335
+ * created by "wx", so the probe is a new inode under the lock's exact name, and its fd is closed before SQLite opens it.
336
+ */
337
+ function lockApart(file, state) {
338
+ const lock = `${file}.lock`;
339
+ const created = lstatSync(lock, { throwIfNoEntry: false }) ? undefined : createLock(lock);
340
+ const now = lstatSync(lock, { throwIfNoEntry: false });
341
+ if (now?.isFile() === false)
342
+ throw new EsseyError("STATE_REFUSED", `refused: ${lock} is not a regular file`);
343
+ if (!now || sameFile(now, state) || sameFile(now, lstatSync(file, { throwIfNoEntry: false })))
344
+ throw new EsseyError("STATE_REFUSED", `refused: this file system cannot keep ${file} and ${lock} as two files; nothing was opened or written`);
345
+ const name = lock.slice(lock.lastIndexOf("/") + 1);
346
+ const names = listed(lock, now);
347
+ if (names.some((f) => f.toLowerCase() === name.toLowerCase()))
348
+ return;
349
+ if (sameFile(now, created))
350
+ rmSync(lock, { force: true });
351
+ throw new EsseyError("STATE_REFUSED", `refused: this file system lists ${name} as ${names.join(", ") || "nothing"}, so it cannot keep the lock and its journal apart; nothing was opened`);
352
+ }
353
+ function createLock(lock) {
354
+ let fd;
355
+ try {
356
+ fd = openSync(lock, "wx", 0o644);
357
+ }
358
+ catch (error) {
359
+ if (error.code === "EEXIST")
360
+ return undefined;
361
+ throw lockRefused(lock, error);
362
+ }
363
+ try {
364
+ return fstatSync(fd);
365
+ }
366
+ finally {
367
+ closeSync(fd);
368
+ }
369
+ }
370
+ function lockHeld(path, lock, opened) {
371
+ if (!sameFile(lstatSync(lock, { throwIfNoEntry: false }), opened))
372
+ throw new EsseyError("STATE_REFUSED", `refused: the state path ${path} changed while it was being locked`);
373
+ }
374
+ function pinned(path) {
375
+ const file = lstatSync(path, { throwIfNoEntry: false });
376
+ if (file?.isSymbolicLink())
377
+ throw new EsseyError("STATE_REFUSED", `refused: the state path ${path} is a symlink; give the path of the state file itself`);
378
+ if (file && file.nlink > 1)
379
+ throw new EsseyError("STATE_REFUSED", `refused: the state file ${path} has ${file.nlink} names (hard links); keep one name per state file`);
380
+ }
381
+ function openLock(lock) {
382
+ const { DatabaseSync } = process.getBuiltinModule("node:sqlite");
383
+ try {
384
+ return new DatabaseSync(lock, { timeout: 0 });
385
+ }
386
+ catch (error) {
387
+ throw lockRefused(lock, error);
388
+ }
389
+ }
390
+ function hold(db, lock) {
391
+ const deadline = Date.now() + LOCK_WAIT_MS;
392
+ for (;;) {
393
+ try {
394
+ db.exec("BEGIN EXCLUSIVE");
395
+ db.exec("PRAGMA user_version = 1");
396
+ return;
397
+ }
398
+ catch (error) {
399
+ if ((error.errcode ?? 0) % 256 !== SQLITE_BUSY)
400
+ throw lockRefused(lock, error);
401
+ if (Date.now() > deadline)
402
+ throw new EsseyError("STATE_REFUSED", `refused: ${lock} has been held by a live process for over ${LOCK_WAIT_MS} ms`);
403
+ Atomics.wait(pause, 0, 0, 1);
404
+ }
405
+ }
406
+ }
407
+ const lockRefused = (lock, error) => new EsseyError("STATE_REFUSED", error.errcode === SQLITE_NOTADB
408
+ ? `refused: ${lock} is not an SQLite lock; delete it only after confirming no Essey process holds it`
409
+ : `refused: ${lock} cannot lock this state file: ${error.message}`);
410
+ /**
411
+ * Under the lock no writer of this path is mid-write, so its temp files are a dead writer's. Links are never ours. A
412
+ * listed `<stem>.<32 hex>.tmp` is ours when the kernel resolves its stem to the state's own (st_dev, st_ino): a
413
+ * case-folding folder lists a temp in its writer's case (R1d F1, S10), and writers before ruling 0124 named temps after
414
+ * vfat aliases (`state.json.`, `STATE~1.JSO`, ruling 0122). The name deleted is that listed name under the statePath's
415
+ * own folder prefix: `join` folds `..` lexically, which deleted outside the folder (R1c F2).
416
+ */
417
+ function sweepTemps(path) {
418
+ const dir = path.slice(0, path.lastIndexOf("/") + 1);
419
+ const state = lstatSync(path, { throwIfNoEntry: false });
420
+ for (const file of readdirSync(dirname(path))) {
421
+ const suffix = /\.[0-9a-f]{32}\.tmp$/.exec(file)?.[0];
422
+ if (!suffix ||
423
+ !sameFile(lstatSync(dir + file.slice(0, -suffix.length), { throwIfNoEntry: false }), state))
424
+ continue;
425
+ if (lstatSync(dir + file, { throwIfNoEntry: false })?.isFile())
426
+ rmSync(dir + file, { force: true });
427
+ }
428
+ }
429
+ const blake2b256 = (bytes) => blake2b(bytes, { dkLen: 32 });
430
+ const hexBytes = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
431
+ /** A Move `Option<u256>` read as JSON: null, the value, or `{ vec: [] | [value] }`. */
432
+ function optionU256(raw) {
433
+ const inner = raw && typeof raw === "object" ? raw.vec?.[0] : raw;
434
+ if (inner === null || inner === undefined)
435
+ return null;
436
+ if (typeof inner !== "string" && typeof inner !== "number")
437
+ unknownObject("the vault claim is not a u256");
438
+ return BigInt(inner);
439
+ }
440
+ function asInvalid(run) {
441
+ try {
442
+ return run();
443
+ }
444
+ catch (err) {
445
+ throw new EsseyError("INVALID_ARGUMENT", err instanceof Error ? err.message.slice(0, 200) : "unknown");
446
+ }
447
+ }
448
+ function drawSecret() {
449
+ for (;;) {
450
+ const n = BigInt(`0x${randomBytes(32).toString("hex")}`) >> 2n;
451
+ if (n > 0n && n < R)
452
+ return n;
453
+ }
454
+ }
455
+ function drawEph() {
456
+ for (;;) {
457
+ const n = BigInt(`0x${randomBytes(32).toString("hex")}`) >> EPH_SHIFT;
458
+ if (n > 0n)
459
+ return n;
460
+ }
461
+ }
462
+ function coinOf(coin) {
463
+ if (!COINS.includes(coin))
464
+ throw new EsseyError("INVALID_ARGUMENT", "coin is not tusdsui, usdc or sui");
465
+ return coin;
466
+ }
467
+ /** A zero-value input: js4 skips its root check (`circuits/v3/lib/joinsplit.circom:56-59`). */
468
+ const dummyInput = () => ({
469
+ amount: 0n,
470
+ sk: drawSecret(),
471
+ blinding: drawSecret(),
472
+ pathIndex: 0n,
473
+ pathElements: Array.from({ length: JS4_LEVELS }, () => 0n),
474
+ });
475
+ function relayerUrl(choice, config) {
476
+ if (choice === "onion")
477
+ throw new EsseyError("ONION_UNAVAILABLE", "refused: this build has no Tor transport; nothing was sent");
478
+ return choice === "clear" ? config.relayer.url : choice;
479
+ }
480
+ /**
481
+ * A deposit answered a digest for an earlier piece, or left a stranded record. Depositing the whole amount
482
+ * again repeats them. A digest is not confirmation the note is in the pool.
483
+ */
484
+ function partial(error, landed, pieces, stranded) {
485
+ if (landed.length === 0 && !stranded)
486
+ return error;
487
+ const at = landed.length + 1;
488
+ const inner = isEsseyError(error) ? error : undefined;
489
+ const thrown = error instanceof Error ? error.message : "it threw";
490
+ const why = inner ? [inner.code, inner.detail?.error].filter(Boolean).join(" ") : thrown;
491
+ const next = stranded
492
+ ? "has a stranded record and may be funded: run recoverStranded before depositing it again"
493
+ : "left no stranded record";
494
+ const stopped = new EsseyError("DEPOSIT_PARTIAL", `deposit stopped at piece ${at} of ${pieces.length}: ${why}. Pieces landed before it: ${landed.length}, listed in detail.landed; do not deposit them again. Piece ${at} ${next}`, {
495
+ ...inner?.detail,
496
+ landed: landed.map((l, i) => ({ digest: l.digest, value: pieces[i].toString() })),
497
+ stopped: pieces[landed.length].toString(),
498
+ stranded,
499
+ untried: pieces.slice(at).map(String),
500
+ });
501
+ stopped.cause = error;
502
+ return stopped;
503
+ }
504
+ /**
505
+ * `address()` pads a short value and takes zero, and `pool::withdraw` pays what it is given
506
+ * (`move/v3/pool/sources/pool.move:312`).
507
+ */
508
+ const RECEIVE_PREFIX = "v3note:";
509
+ /** `v3note:<pk decimal>:<33-byte compressed enc key hex>:<index>`, as `notes.receiveAddress` writes it. */
510
+ function receiveTarget(to) {
511
+ const m = typeof to === "string" ? /^v3note:([0-9]{1,78}):((?:02|03)[0-9a-f]{64}):([0-9]{1,15})$/.exec(to) : null;
512
+ if (!m)
513
+ throw new EsseyError("INVALID_ARGUMENT", "to is not a v3note receive address; nothing was sent");
514
+ const pk = BigInt(m[1]);
515
+ if (pk >= R)
516
+ throw new EsseyError("INVALID_ARGUMENT", "to is not a v3note receive address; nothing was sent");
517
+ return { pk, encPub: Uint8Array.from(Buffer.from(m[2], "hex")), index: Number(m[3]) };
518
+ }
519
+ function payee(to) {
520
+ if (typeof to !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(to))
521
+ throw new EsseyError("INVALID_ARGUMENT", "to is not 0x and 64 hex digits; nothing was sent");
522
+ const recipient = to.toLowerCase();
523
+ if (recipient === NO_ADDRESS)
524
+ throw new EsseyError("INVALID_ARGUMENT", NO_TO);
525
+ return recipient;
526
+ }
527
+ function refusedBy(service, reply) {
528
+ const error = typeof reply.body.error === "string" ? reply.body.error : undefined;
529
+ return new EsseyError("SERVICE_REFUSED", `${service} refused: ${error ?? reply.status}`, {
530
+ status: reply.status,
531
+ error,
532
+ });
533
+ }
534
+ export class Essey {
535
+ config;
536
+ statePath;
537
+ apiOrigin;
538
+ fetch;
539
+ io;
540
+ relay;
541
+ relayerBase;
542
+ seedOption;
543
+ credential;
544
+ fees;
545
+ relayer;
546
+ markets;
547
+ loans;
548
+ notes;
549
+ /** D-SPEC §6.2:598-600. Sealed sale rooms. */
550
+ sales;
551
+ keeper;
552
+ constructor(config, statePath, apiOrigin, fetch, io, relay, relayerBase, seedOption) {
553
+ this.config = config;
554
+ this.statePath = statePath;
555
+ this.apiOrigin = apiOrigin;
556
+ this.fetch = fetch;
557
+ this.io = io;
558
+ this.relay = relay;
559
+ this.relayerBase = relayerBase;
560
+ this.seedOption = seedOption;
561
+ this.credential = {
562
+ obtain: (o) => this.obtain(o?.invite, o?.role ?? "member"),
563
+ status: () => this.info(readState(this.statePath).credential),
564
+ list: () => this.listCredentials(),
565
+ view: () => this.viewCredential(),
566
+ renew: () => this.renew(),
567
+ };
568
+ this.fees = { params: (coin) => this.feeParams(coin) };
569
+ this.relayer = {
570
+ info: async () => this.relayClient().info(),
571
+ status: async (ticket) => this.relayClient().status(ticket),
572
+ };
573
+ this.markets = { rates: (market) => this.rates(market) };
574
+ this.loans = {
575
+ prepareOpen: (body) => this.prepareOpen(body),
576
+ open: (p) => ("loanCoin" in p ? this.openRequest(p) : this.paidLoan(openLoan, p)),
577
+ offer: (p) => this.paidLoan(offerLoan, p),
578
+ request: (id) => this.readRequest(id),
579
+ lend: async (p) => {
580
+ const { body, record } = await this.planOffer(p.loan, BigInt(p.rateBps));
581
+ return { ...(await this.paidLoan(offerLoan, body)), offer: record };
582
+ },
583
+ collect: (p) => this.collect(p.loan, p.offer),
584
+ collectSeized: (p) => this.collectSeized(p.loan, p.offer),
585
+ collectSurplus: (p) => this.collectSurplus(p),
586
+ accept: async (id) => {
587
+ const { body, rateBps, terms, borrowerPk, collAmt } = await this.planSettle(id);
588
+ return { ...(await this.freeLoan(settleLoan, body)), rateBps, terms, borrowerPk, collAmt };
589
+ },
590
+ release: (p) => this.releaseCollateral(p.loan, p.terms, p.borrowerPk, p.collAmt),
591
+ cancelOwn: (id) => this.cancelOwn(id),
592
+ slash: (p) => this.slashOffer(p.loan, BigInt(p.seq)),
593
+ fault: (p) => this.ctFault(p.loan, p.via),
594
+ openRefi: (p) => this.openRefi(p),
595
+ cancelRefi: (id) => this.cancelRefiOwn(id),
596
+ settleRefi: (p) => this.settleRefiOwn(p),
597
+ reclaimOffer: (p) => this.reclaimOffer(p.loan, p.offer, p.round),
598
+ heartbeat: (p) => this.heartbeatOwn(p),
599
+ topup: (p) => this.topupOwn(p),
600
+ liquidate: (p) => this.borrowerSeize(p, MODE.LIQUIDATE),
601
+ seizeDefault: (p) => this.borrowerSeize(p, MODE.DEFAULT),
602
+ faultLiquidate: (p) => this.faultLiquidate(p.loan, p.offer),
603
+ keeperLiquidate: (p) => this.keeperLiquidate(p.loan, p.via),
604
+ reclaimCollateral: (p) => this.reclaimOwnCollateral(p.loan, p.collAmt),
605
+ payBack: async (p) => this.paidLoan(repayLoan, await this.planRepay(p.loan, p.terms, p.borrowerPk)),
606
+ settle: (p) => this.freeLoan(settleLoan, p),
607
+ repay: (p) => this.paidLoan(repayLoan, p),
608
+ reclaim: (p) => this.paidLoan(reclaimLoan, p),
609
+ reclaimColl: (p) => this.freeLoan(reclaimCollLoan, p),
610
+ cancel: (p) => this.freeLoan(cancelLoan, p),
611
+ claimDefault: (p) => this.freeLoan(claimDefaultLoan, p),
612
+ list: () => this.listLoans(),
613
+ view: (id) => this.viewLoan(id),
614
+ };
615
+ this.notes = {
616
+ faucet: (coin) => this.faucet(coin),
617
+ deposit: (coin, amount, o) => this.deposit(coin, amount, o?.denominations),
618
+ scan: (coin) => this.scan(coin),
619
+ open: (coin, index) => this.openNote(coin, index),
620
+ list: (coin) => this.listNotes(coin),
621
+ view: (coin, index) => this.viewNote(coin, index),
622
+ withdraw: (coin, amount, to) => this.withdraw(coin, amount, to),
623
+ receiveAddress: () => this.receiveAddress(),
624
+ transfer: (coin, amount, to) => this.transfer(coin, amount, to),
625
+ exit: (coin, to) => this.exit(coin, to),
626
+ recoverStranded: () => this.recoverStranded(),
627
+ };
628
+ this.sales = {
629
+ open: (p) => this.openSale(p),
630
+ list: () => this.listSales(),
631
+ view: (id) => this.viewSale(id),
632
+ bid: (p) => this.placeBid(p.room, p.v, p.amount),
633
+ finish: (p) => this.finishSale(p),
634
+ slash: (p) => this.slashBid(p.room, p.seq),
635
+ expire: (p) => this.expireSale(p.room, p.vault),
636
+ reclaim: (p) => this.reclaimBid(p.room, p.bid, p.what ?? "lock"),
637
+ claim: (p) => this.claimItem(p),
638
+ cancel: (p) => this.cancelSale(p.room, p.vault),
639
+ };
640
+ this.keeper = {
641
+ ...keeperSection(io.keeper, io.now ?? Date.now),
642
+ mintBadge: () => this.mintBadge(),
643
+ badge: () => this.heldBadge(),
644
+ judge: (p) => this.judge(p.loan, p.via),
645
+ };
646
+ }
647
+ static async connect(o, io = {}) {
648
+ assertTestnet(o.network);
649
+ const fetch = io.fetch ?? ((url, init) => globalThis.fetch(url, init));
650
+ if (o.seed !== undefined && !(o.seed instanceof Uint8Array && o.seed.length === SEED_BYTES))
651
+ throw new EsseyError("INVALID_ARGUMENT", "seed must be 32 bytes");
652
+ readState(o.statePath);
653
+ const { config, apiOrigin } = await loadConfig(o.config, fetch);
654
+ const url = relayerUrl(o.relayer ?? "clear", config);
655
+ const relay = url === null ? null : new RelayClient({ url, fetch, submitDelayMs: o.submitDelayMs });
656
+ const relayerBase = url === null ? null : serviceUrl(url, "relayer url").origin;
657
+ return new Essey(config, o.statePath, apiOrigin, fetch, io, relay, relayerBase, o.seed && Uint8Array.from(o.seed));
658
+ }
659
+ relayClient() {
660
+ return this.relay ?? notSetUp(NO_RELAYER);
661
+ }
662
+ relayerAddress() {
663
+ return this.config.relayer.address ?? notSetUp(NO_RELAYER_ADDRESS);
664
+ }
665
+ sponsoring() {
666
+ const { address } = this.config.relayer;
667
+ if (this.relayerBase === null || address === null)
668
+ return null;
669
+ return { base: this.relayerBase, address };
670
+ }
671
+ sponsorRelayer() {
672
+ return this.sponsoring() ?? notSetUp(this.relayerBase === null ? NO_RELAYER : NO_RELAYER_ADDRESS);
673
+ }
674
+ api() {
675
+ return this.apiOrigin ?? notSetUp("no v3api origin: connect with the /v3/config URL");
676
+ }
677
+ info(c) {
678
+ return c ? { role: c.role, expiryMs: c.expiryMs, epoch: c.epoch } : null;
679
+ }
680
+ /** A seed option never works on a file that stores another seed. */
681
+ ownSeed(state) {
682
+ if (!this.seedOption || state.seed === undefined)
683
+ return;
684
+ if (state.seed !== Buffer.from(this.seedOption).toString("hex"))
685
+ throw new EsseyError("STATE_REFUSED", "refused: the state file belongs to another seed");
686
+ }
687
+ /**
688
+ * Every read-modify-write of the state file: re-read and written under the lock, with no await inside, so a
689
+ * change made by another call or process meanwhile is never written over. A seed stored meanwhile by a
690
+ * seedless open of the same file refuses a seed option's write here, before it changes anything.
691
+ */
692
+ update(change) {
693
+ return withLock(this.statePath, (file, held) => {
694
+ const state = readState(file);
695
+ this.ownSeed(state);
696
+ const result = change(state);
697
+ writeState(file, state, held);
698
+ return result;
699
+ });
700
+ }
701
+ /** The secrets and the slot are on disk before the issuer sees the commitment, so a pinned slot is never lost. */
702
+ async obtain(invite, role) {
703
+ const api = this.api();
704
+ const member = this.update((s) => (s.member ??= { secret: drawSecret(), nullSecret: drawSecret() }));
705
+ const slot = invite === undefined ? await solveChallenge(this.fetch, api) : { invite };
706
+ this.update((s) => {
707
+ s.slot = slot;
708
+ });
709
+ return this.issue(api, member, slot, role);
710
+ }
711
+ async renew() {
712
+ const { member, slot, credential } = readState(this.statePath);
713
+ if (!slot || !credential)
714
+ notSetUp("no credential to renew: call credential.obtain first");
715
+ return this.issue(this.api(), member, slot, credential.role);
716
+ }
717
+ async issue(api, member, slot, role) {
718
+ const now = (this.io.now ?? Date.now)();
719
+ const credential = await requestCredential(this.fetch, api, slot, memberCommitment(member), role, now);
720
+ this.update((s) => {
721
+ s.credential = credential;
722
+ });
723
+ return this.info(credential);
724
+ }
725
+ /** The opening for one coin, returned only after it matches the commit read from chain (D §5.4). */
726
+ async feeParams(coin) {
727
+ if (!COINS.includes(coin))
728
+ throw new EsseyError("INVALID_ARGUMENT", "coin is not tusdsui, usdc or sui");
729
+ const api = this.api();
730
+ const { member, credential } = readState(this.statePath);
731
+ if (!member || !credential)
732
+ notSetUp("no credential: call credential.obtain first");
733
+ const prover = this.io.prover ?? this.missingProver("membership");
734
+ const readFeeCommit = this.io.readFeeCommit ?? notSetUp("no chain reader: the FeeConfig objects are not published yet");
735
+ const challenge = await getJson(this.fetch, `${api}/v3/fee-params/challenge`);
736
+ const nonce = challenge.body.nonce;
737
+ if (challenge.status !== 200 || typeof nonce !== "string")
738
+ throw refusedBy("v3api", challenge);
739
+ const { input, publics } = membership({
740
+ secrets: member,
741
+ credential: credential,
742
+ // A keeper credential proves only the KEEPER domain (membership.circom: role 1 exactly when domain 3).
743
+ domain: credential.role === "keeper" ? DOMAIN_KEEPER : DOMAIN_SENDER,
744
+ room: FEE_PARAMS_ROOM,
745
+ bind: nonce,
746
+ });
747
+ const reply = await postJson(this.fetch, `${api}/v3/fee-params`, {
748
+ coin,
749
+ nonce,
750
+ publicInputs: publics.map(String),
751
+ proof: passProof(await prover.prove("membership", input)),
752
+ });
753
+ if (reply.status !== 200 || reply.body.ok !== true || reply.body.coin !== coin)
754
+ throw refusedBy("v3api", reply);
755
+ return verifyFeeOpening(reply.body, await readFeeCommit(coin));
756
+ }
757
+ async rates(market) {
758
+ const id = address(market, "market");
759
+ const read = this.io.readMarket ?? notSetUp("no chain reader: the Market objects are not published yet");
760
+ return marketRates(id, await read(id), (this.io.now ?? Date.now)());
761
+ }
762
+ /**
763
+ * A drawn seed is on disk before any key derived from it is used. A seed option is never stored, so a file
764
+ * that already holds counters or records but no seed was made by one: no new seed is drawn over it.
765
+ */
766
+ seed() {
767
+ if (this.seedOption) {
768
+ this.ownSeed(readState(this.statePath));
769
+ return this.seedOption;
770
+ }
771
+ const stored = readState(this.statePath).seed ??
772
+ this.update((s) => {
773
+ if (s.seed !== undefined)
774
+ return s.seed;
775
+ if (s.notes || s.signers || s.stranded?.length)
776
+ throw new EsseyError("STATE_REFUSED", NO_SEED);
777
+ return (s.seed = randomBytes(SEED_BYTES).toString("hex"));
778
+ });
779
+ return Uint8Array.from(Buffer.from(stored, "hex"));
780
+ }
781
+ /**
782
+ * The seed may have made notes from another state file, or from this one before it was restored from a
783
+ * backup: the counter resumes past every index the seed has on chain before any is reserved.
784
+ */
785
+ async keys() {
786
+ const seed = this.seed();
787
+ const read = this.io.readPool ?? notSetUp("no pool reader: the note counter resumes past the chain");
788
+ const { encKey } = noteEncKey(seed);
789
+ let next = 0;
790
+ for (const coin of COINS)
791
+ for (const used of usedIndices(await read(coin), seed, encKey))
792
+ next = Math.max(next, used + 1);
793
+ if (next > (readState(this.statePath).notes ?? 0))
794
+ this.update((s) => {
795
+ s.notes = Math.max(next, s.notes ?? 0);
796
+ });
797
+ return seed;
798
+ }
799
+ addressUsed() {
800
+ if (this.io.readAddressUsed || !this.seedOption)
801
+ return this.io.readAddressUsed;
802
+ return notSetUp("no readAddressUsed: a seed option may have used a deposit sender");
803
+ }
804
+ /** A deposit sender the chain has never seen, so no two deposits share one. */
805
+ async freshSigner(seed, used) {
806
+ for (let i = 0; i < MAX_USED_SENDERS; i++) {
807
+ const signer = this.reserve("signers");
808
+ if (!used || !(await used(depositSigner(seed, signer).toSuiAddress())))
809
+ return signer;
810
+ }
811
+ throw new EsseyError("STATE_REFUSED", "refused: every deposit sender tried is already used; nothing was sent");
812
+ }
813
+ /** Write-ahead: a deposit is on disk as stranded before its value moves, and leaves once it has landed. */
814
+ strand(s, on) {
815
+ this.update((state) => setRecord(state, s.signer, on ? s : undefined));
816
+ }
817
+ /**
818
+ * Appends to the record on disk, never over it (AUD-V3-124 R2d-1). A fresh deposit never takes over a record
819
+ * already at its sender (R2e-2). A recovery signs nothing once its record is gone, and is refused once another
820
+ * call moved it to another index.
821
+ */
822
+ addSigned(piece, entry, recovery) {
823
+ return this.update((state) => {
824
+ const disk = state.stranded?.find((r) => r.signer === piece.signer);
825
+ if (!recovery && disk)
826
+ throw new EsseyError("STATE_REFUSED", `refused: a stranded deposit record already holds sender ${piece.signer}; nothing was funded. Run recoverStranded`);
827
+ if (recovery && !disk)
828
+ return false;
829
+ if (disk && (disk.note !== piece.note || disk.value !== piece.value))
830
+ throw new EsseyError("STATE_REFUSED", "refused: another call moved this record; nothing was signed");
831
+ setRecord(state, piece.signer, { ...piece, signed: [...(disk?.signed ?? []), entry] });
832
+ return true;
833
+ });
834
+ }
835
+ /** Write-ahead: an index is on disk before anything derived from it leaves this process. */
836
+ reserve(counter) {
837
+ return this.update((state) => {
838
+ const index = state[counter] ?? 0;
839
+ state[counter] = index + 1;
840
+ return index;
841
+ });
842
+ }
843
+ member() {
844
+ const { member, credential } = readState(this.statePath);
845
+ if (!member || !credential)
846
+ notSetUp("no credential: call credential.obtain first");
847
+ return { secrets: member, credential: credential };
848
+ }
849
+ prover() {
850
+ if (this.io.prover)
851
+ return this.io.prover;
852
+ const ready = ["membership", "deposit", "js4"].every((name) => {
853
+ const row = this.config.circuits[name];
854
+ return typeof row?.wasm?.url === "string" && typeof row?.zkey?.url === "string";
855
+ });
856
+ if (ready)
857
+ return notSetUp("no prover: circuit pins are in the config; build io.prover with v3.loadCircuitArtifacts and v3.groth16Prover");
858
+ return notSetUp("no prover: the circuit artifacts are not in the config yet");
859
+ }
860
+ /** Pins in the config still need a prover. An empty `circuits` object is the pre-bring-up record. */
861
+ missingProver(circuit) {
862
+ const row = this.config.circuits[circuit];
863
+ if (typeof row?.wasm?.url === "string" && typeof row.zkey?.url === "string")
864
+ return notSetUp(`no prover: ${circuit} pins are in the config; build io.prover with v3.loadCircuitArtifacts and v3.groth16Prover`);
865
+ return notSetUp(`no prover: ${circuit} artifacts are not in the config yet`);
866
+ }
867
+ async faucet(coin) {
868
+ const api = this.api();
869
+ const relayer = this.relayerAddress();
870
+ const { secrets, credential } = this.member();
871
+ const prover = this.prover();
872
+ const seed = await this.keys();
873
+ const fee = await this.feeParams(coinOf(coin));
874
+ const value = faucetGrant(coin, this.config);
875
+ const index = this.reserve("notes");
876
+ const keys = deriveNoteKey(seed, index);
877
+ const dep = await depositInput({
878
+ value,
879
+ pk: notePk(keys.sk),
880
+ blinding: keys.blinding,
881
+ faucet: true,
882
+ fee,
883
+ eph: drawEph(),
884
+ });
885
+ const proved = await prover.prove("deposit", dep.input);
886
+ const opening = { value: value - dep.lane.fee, blinding: keys.blinding, index };
887
+ const body = await proveFaucet(prover, {
888
+ secrets,
889
+ credential,
890
+ coin,
891
+ nowMs: (this.io.now ?? Date.now)(),
892
+ relayer,
893
+ deposit: {
894
+ publics: dep.publics,
895
+ lane: dep.lane,
896
+ proved: { proof: proved.proof, publicSignals: dep.publics.map(String) },
897
+ },
898
+ encOut: sealOpening(opening, noteEncKey(seed).encPub),
899
+ encFee: fillerEnc(),
900
+ });
901
+ const reply = await postJson(this.fetch, `${api}/v3/faucet`, body);
902
+ if (reply.status === 404)
903
+ throw new EsseyError("SERVICE_REFUSED", "v3api refused: the faucet is not served; nothing landed", {
904
+ status: 404,
905
+ error: "NOT_FOUND",
906
+ });
907
+ if (reply.status !== 200 || reply.body.ok !== true || typeof reply.body.digest !== "string")
908
+ throw refusedBy("v3api", reply);
909
+ return { digest: reply.body.digest, ticket: "" };
910
+ }
911
+ async deposit(coin, amount, denominations) {
912
+ if (amount <= 0n || amount >= 1n << 64n)
913
+ throw new EsseyError("INVALID_ARGUMENT", "amount is not a u64 above 0");
914
+ const list = this.config.denominations[coinOf(coin)];
915
+ const pieces = (denominations ?? list !== undefined) ? splitDenominations(amount, list ?? []) : [amount];
916
+ const relayer = this.sponsorRelayer();
917
+ const fund = this.io.fundDeposit ?? notSetUp("no fundDeposit: the SDK never holds the paying wallet");
918
+ const used = this.addressUsed();
919
+ const seed = await this.keys();
920
+ const read = this.io.readPool;
921
+ const ctx = await this.depositContext(coin);
922
+ const landed = [];
923
+ for (const value of pieces) {
924
+ let signer;
925
+ try {
926
+ signer = await this.freshSigner(seed, used);
927
+ const note = this.reserve("notes");
928
+ const piece = { coin, signer, note, value, signed: [] };
929
+ const { digest, ticket } = (await this.depositPiece(ctx, seed, piece, relayer, read, fund));
930
+ landed.push({ digest, ticket });
931
+ }
932
+ catch (error) {
933
+ throw partial(error, landed, pieces, this.strandedAt(signer));
934
+ }
935
+ }
936
+ return landed;
937
+ }
938
+ async depositContext(coin) {
939
+ const pkg = this.config.packages.pool;
940
+ const poolId = this.config.objects.pools[coin];
941
+ const feeConfigId = this.config.objects.feeConfigs?.[coin];
942
+ if (!pkg || !poolId || !feeConfigId)
943
+ notSetUp("the pool is not published yet");
944
+ const readShared = this.io.readSharedVersion ?? notSetUp("no chain reader for shared object versions");
945
+ const { secrets, credential } = this.member();
946
+ const prover = this.prover();
947
+ const fee = await this.feeParams(coin);
948
+ return {
949
+ pkg: pkg,
950
+ coinType: this.config.coins[coin].type,
951
+ pool: { objectId: poolId, initialSharedVersion: await readShared(poolId) },
952
+ feeConfig: { objectId: feeConfigId, initialSharedVersion: await readShared(feeConfigId) },
953
+ secrets,
954
+ credential,
955
+ prover,
956
+ fee,
957
+ };
958
+ }
959
+ /**
960
+ * The sponsor accepts before any value moves, so a refusal strands nothing. The pass nonce is the sender's
961
+ * index, so a fresh deposit's tag is new to the relayer's per-tag limit. A recovery sends its record's tag
962
+ * again: the relayer refuses it `RATE_LIMITED` until one window after that tag's last sponsorship
963
+ * (`services/relayer-v3/src/server.ts:238,575,586`), and `SPONSOR_REFUSED` while it remembers the sender (`:559-560`).
964
+ */
965
+ async depositPiece(ctx, seed, piece, relayer, read, fund) {
966
+ const { secrets, credential, prover, fee } = ctx;
967
+ const signer = depositSigner(seed, piece.signer);
968
+ const sender = signer.toSuiAddress();
969
+ const keys = deriveNoteKey(seed, piece.note);
970
+ const dep = await depositInput({
971
+ value: piece.value,
972
+ pk: notePk(keys.sk),
973
+ blinding: keys.blinding,
974
+ fee,
975
+ eph: drawEph(),
976
+ });
977
+ const proved = await prover.prove("deposit", dep.input);
978
+ const opening = { value: piece.value - dep.lane.fee, blinding: keys.blinding, index: piece.note };
979
+ const encNote = sealOpening(opening, noteEncKey(seed).encPub);
980
+ const txKindB64 = await depositKind({
981
+ pkg: ctx.pkg,
982
+ coinType: ctx.coinType,
983
+ pool: ctx.pool,
984
+ feeConfig: ctx.feeConfig,
985
+ value: piece.value,
986
+ proof: proofBytes(proved.proof),
987
+ note: dep.publics[0],
988
+ feeNote: dep.publics[1],
989
+ ephX: dep.lane.ephX,
990
+ ephY: dep.lane.ephY,
991
+ feeCt: dep.lane.fee_ct,
992
+ feeCommit: dep.lane.fee_commit,
993
+ encNote,
994
+ encFee: fillerEnc(),
995
+ });
996
+ const pass = membership({
997
+ secrets,
998
+ credential,
999
+ domain: DOMAIN_SENDER,
1000
+ room: DEPOSIT_ROOM,
1001
+ bind: sender,
1002
+ nonce: BigInt(piece.signer),
1003
+ });
1004
+ const passProved = await prover.prove("membership", pass.input);
1005
+ const passWire = {
1006
+ tag: pass.publics[0].toString(),
1007
+ expiryMs: credential.expiryMs.toString(),
1008
+ proof: `0x${Buffer.from(proofBytes(passProved.proof)).toString("hex")}`,
1009
+ };
1010
+ const possession = await provePossession({
1011
+ signer,
1012
+ kind: fromBase64(txKindB64),
1013
+ relayer: relayer.address,
1014
+ expiryMs: (this.io.now ?? Date.now)() + POSSESSION_TTL_MS,
1015
+ });
1016
+ const sponsored = await sponsor(this.fetch, relayer.base, {
1017
+ txKindB64,
1018
+ sender,
1019
+ pass: passWire,
1020
+ possession,
1021
+ });
1022
+ if (!carriesKind(sponsored.txBytesB64, txKindB64, sender, relayer.address))
1023
+ throw new EsseyError("RELAY_REFUSED", "refused: the sponsored bytes are not this deposit; nothing was signed");
1024
+ const mine = { commitment: dep.publics[0], enc: encNote };
1025
+ if (!this.addSigned(piece, mine, !fund))
1026
+ return undefined;
1027
+ if (fund)
1028
+ await fund({ coin: piece.coin, value: piece.value, sender });
1029
+ const { signature } = await signer.signTransaction(fromBase64(sponsored.txBytesB64));
1030
+ const digest = await executeSponsored(this.fetch, relayer.base, {
1031
+ txBytesB64: sponsored.txBytesB64,
1032
+ userSig: signature,
1033
+ });
1034
+ const inPool = (await read(piece.coin)).commitments.some((c) => isSigned(c, mine));
1035
+ if (inPool)
1036
+ this.strand(piece, false);
1037
+ return { digest, ticket: "", inPool };
1038
+ }
1039
+ /**
1040
+ * One record that cannot land never holds up the others. With no relayer set up, records already in the pool
1041
+ * are still cleared; one that would need the relayer refuses the call once every record has been looked at.
1042
+ */
1043
+ async recoverStranded() {
1044
+ const read = this.io.readPool ?? notSetUp("no pool reader: a stranded deposit may already have landed");
1045
+ const relayer = this.sponsoring();
1046
+ const seed = this.seed();
1047
+ const outcomes = [];
1048
+ let unsent = false;
1049
+ for (const piece of readState(this.statePath).stranded ?? []) {
1050
+ try {
1051
+ const outcome = await this.recoverOne(piece, seed, read, relayer);
1052
+ if (outcome)
1053
+ outcomes.push(outcome);
1054
+ else
1055
+ unsent = true;
1056
+ }
1057
+ catch (error) {
1058
+ outcomes.push({ ...piece, ...this.unlanded(error) });
1059
+ }
1060
+ }
1061
+ if (unsent)
1062
+ this.sponsorRelayer();
1063
+ return outcomes;
1064
+ }
1065
+ /** The tag was last sponsored no later than now, so its window has ended one window from now. */
1066
+ unlanded(error) {
1067
+ const code = isEsseyError(error, "RELAY_REFUSED") ? error.detail?.error : undefined;
1068
+ if (code === "RATE_LIMITED")
1069
+ return { outcome: "retry_after", atMs: (this.io.now ?? Date.now)() + SPONSOR_WINDOW_MS, error };
1070
+ if (code === "SPONSOR_REFUSED")
1071
+ return { outcome: "retry_after", error };
1072
+ return { outcome: "failed", error };
1073
+ }
1074
+ /**
1075
+ * A record leaves only once a note it signed is in the pool. Another note at its index (the same
1076
+ * seed on another state file) moves it to a fresh index. An unused sender may still be funded late, or by a
1077
+ * deposit running now, so its record stays for the next call.
1078
+ */
1079
+ async recoverOne(listed, seed, read, relayer) {
1080
+ const events = await read(listed.coin);
1081
+ const piece = this.record(listed.signer);
1082
+ if (!piece)
1083
+ return this.gone(listed, read);
1084
+ if (landedIn(events, piece)) {
1085
+ this.strand(piece, false);
1086
+ return { ...piece, outcome: "already landed" };
1087
+ }
1088
+ if (!relayer)
1089
+ return undefined;
1090
+ const taken = usedIndices(events, seed, noteEncKey(seed).encKey).includes(piece.note);
1091
+ const record = taken ? await this.reindex(piece) : piece;
1092
+ if (!record)
1093
+ return this.gone(piece, read);
1094
+ const sender = depositSigner(seed, record.signer).toSuiAddress();
1095
+ if (this.io.readAddressUsed && !(await this.io.readAddressUsed(sender)))
1096
+ return { ...record, outcome: "unfunded" };
1097
+ const sent = await this.depositPiece(await this.depositContext(record.coin), seed, record, relayer, read);
1098
+ if (!sent)
1099
+ return this.gone(record, read);
1100
+ return { ...record, outcome: sent.inPool ? "landed" : "unconfirmed", digest: sent.digest };
1101
+ }
1102
+ record(signer) {
1103
+ return readState(this.statePath).stranded?.find((r) => r.signer === signer);
1104
+ }
1105
+ /** A state file that cannot be read may hold the record, so it counts as held. */
1106
+ strandedAt(signer) {
1107
+ if (signer === undefined)
1108
+ return false;
1109
+ try {
1110
+ return this.record(signer) !== undefined;
1111
+ }
1112
+ catch {
1113
+ return true;
1114
+ }
1115
+ }
1116
+ /** "already landed" only on a pool match of an entry this call knew; anything else removed the record (R2e-3). */
1117
+ async gone(piece, read) {
1118
+ const landed = landedIn(await read(piece.coin), piece);
1119
+ return { ...piece, outcome: landed ? "already landed" : "record gone" };
1120
+ }
1121
+ /**
1122
+ * Re-reads the record under the lock (R2e-1): one a landing removed is never written back, and one another
1123
+ * call already moved is not moved again. The new index is on disk before anything derived from it leaves.
1124
+ */
1125
+ async reindex(piece) {
1126
+ await this.keys();
1127
+ return this.update((state) => {
1128
+ const disk = state.stranded?.find((r) => r.signer === piece.signer);
1129
+ if (!disk || disk.note !== piece.note)
1130
+ return disk;
1131
+ const moved = { ...disk, note: state.notes ?? 0 };
1132
+ state.notes = moved.note + 1;
1133
+ setRecord(state, piece.signer, moved);
1134
+ return moved;
1135
+ });
1136
+ }
1137
+ async owned(coin) {
1138
+ const read = this.io.readPool ?? notSetUp("no pool reader: the pool events are read by the caller");
1139
+ const seed = this.seed();
1140
+ const events = await read(coin);
1141
+ return { events, owned: ownNotes(events, seed, noteEncKey(seed).encKey), seed };
1142
+ }
1143
+ async scan(coin) {
1144
+ const summary = {};
1145
+ for (const c of coin === undefined ? COINS : [coinOf(coin)]) {
1146
+ const { owned } = await this.owned(c);
1147
+ summary[c] = { balance: owned.reduce((sum, n) => sum + n.value, 0n), notes: owned.length };
1148
+ }
1149
+ return summary;
1150
+ }
1151
+ async withdraw(coin, amount, to) {
1152
+ if (amount <= 0n)
1153
+ throw new EsseyError("INVALID_ARGUMENT", "amount must be above 0");
1154
+ return this.spend(coin, { to }, (owned, rates, relayerFee) => ({
1155
+ value: amount,
1156
+ inputs: pickInputs(owned, withdrawCost(amount, rates, relayerFee)),
1157
+ }));
1158
+ }
1159
+ receiveAddress() {
1160
+ const seed = this.seed();
1161
+ const index = this.reserve("notes");
1162
+ const pk = notePk(deriveNoteKey(seed, index).sk);
1163
+ return `${RECEIVE_PREFIX}${pk}:${Buffer.from(noteEncKey(seed).encPub).toString("hex")}:${index}`;
1164
+ }
1165
+ async transfer(coin, amount, to) {
1166
+ if (amount <= 0n)
1167
+ throw new EsseyError("INVALID_ARGUMENT", "amount must be above 0");
1168
+ const payTo = receiveTarget(to);
1169
+ return this.spend(coin, { payTo }, (owned, rates, relayerFee) => ({
1170
+ value: amount,
1171
+ inputs: pickInputs(owned, withdrawCost(amount, rates, relayerFee)),
1172
+ }));
1173
+ }
1174
+ async exit(coin, to) {
1175
+ return this.spend(coin, { to }, (owned, rates, relayerFee) => {
1176
+ if (owned.length > 2)
1177
+ throw new EsseyError("INVALID_ARGUMENT", "refused: exit spends at most two notes");
1178
+ const value = exitValue(owned.reduce((sum, n) => sum + n.value, 0n), rates, relayerFee);
1179
+ if (value === 0n)
1180
+ throw new EsseyError("INVALID_ARGUMENT", "refused: nothing to exit after fees");
1181
+ return { value, inputs: owned };
1182
+ });
1183
+ }
1184
+ /** js4 with the withdraw field (`src/v3/inputs.ts:39`); the change note's index is on disk before the body leaves. */
1185
+ async spend(coin, dest, choose, extra = []) {
1186
+ const recipient = "to" in dest ? payee(dest.to) : undefined;
1187
+ const relayerFee = decimal(this.config.relayerFee[coinOf(coin)], "config relayerFee");
1188
+ const relay = this.relayClient();
1189
+ const relayer = this.relayerAddress();
1190
+ const prover = this.prover();
1191
+ const fee = await this.feeParams(coin);
1192
+ const { events, owned, seed } = await this.owned(coin);
1193
+ const { value, inputs } = choose([...owned, ...extra], fee, relayerFee);
1194
+ const tree = poolTree(orderedLeaves(events));
1195
+ const ins = inputs.map((n) => ({
1196
+ amount: n.value,
1197
+ sk: n.sk,
1198
+ blinding: n.blinding,
1199
+ pathIndex: BigInt(n.index),
1200
+ pathElements: tree.path(n.index),
1201
+ }));
1202
+ await this.keys();
1203
+ const index = this.reserve("notes");
1204
+ const change = deriveNoteKey(seed, index);
1205
+ const paidBlinding = drawSecret();
1206
+ const js = await js4({
1207
+ root: tree.root,
1208
+ ins: [ins[0], ins[1] ?? dummyInput()],
1209
+ out0: "payTo" in dest
1210
+ ? { amount: value, pk: dest.payTo.pk, blinding: paidBlinding }
1211
+ : { amount: 0n, pk: notePk(drawSecret()), blinding: drawSecret() },
1212
+ out1: { pk: notePk(change.sk), blinding: change.blinding },
1213
+ pad: { pk: notePk(drawSecret()), blinding: drawSecret() },
1214
+ ...(recipient ? { withdraw: { amount: value, recipient } } : {}),
1215
+ relayer,
1216
+ relayerFee,
1217
+ fee,
1218
+ eph: drawEph(),
1219
+ });
1220
+ const changeValue = BigInt(js.input.outAmount1);
1221
+ const encChange = sealOpening({ value: changeValue, blinding: change.blinding, index }, noteEncKey(seed).encPub);
1222
+ const proved = await prover.prove("js4", js.input);
1223
+ const encPaid = "payTo" in dest
1224
+ ? sealOpening({ value, blinding: paidBlinding, index: dest.payTo.index }, dest.payTo.encPub)
1225
+ : fillerEnc();
1226
+ const body = ("payTo" in dest ? transferBody : withdrawBody)({
1227
+ pool: coin,
1228
+ proved: { proof: proved.proof, publicSignals: js.publics.map(String) },
1229
+ statement: js.statement,
1230
+ encs: [encPaid, encChange, fillerEnc(), fillerEnc()],
1231
+ relayerFee,
1232
+ wait: true,
1233
+ });
1234
+ const sent = await relay.submit(body);
1235
+ return "digest" in sent ? sent : this.follow(relay, sent, "withdraw");
1236
+ }
1237
+ /** A 202 carries no digest (`src/v3/relay/client.ts:100`): the ticket is followed until it lands. */
1238
+ async follow(relay, queued, what) {
1239
+ for (let i = 0; i < FOLLOW_POLLS; i++) {
1240
+ await new Promise((resolve) => setTimeout(resolve, queued.etaMs));
1241
+ const s = await relay.status(queued.ticket);
1242
+ if (s.state === "landed" && s.digest)
1243
+ return { digest: s.digest, ticket: queued.ticket };
1244
+ if (s.state === "failed")
1245
+ throw failure({ error: s.error, submitted: s.submitted === true }, "the ticket failed");
1246
+ if (s.state === "expired")
1247
+ throw new EsseyError("RELAY_FAILED", `the relayer forgot the ticket; the ${what}'s outcome is unknown`);
1248
+ }
1249
+ throw new EsseyError("RELAY_FAILED", `the ${what} is still queued; its outcome is unknown`);
1250
+ }
1251
+ /** A kind in `FEE_FREE` sends "0". Every other loan kind sends this pool's configured constant. */
1252
+ coinFee(coin) {
1253
+ return decimal(this.config.relayerFee[coinOf(coin)], "config relayerFee");
1254
+ }
1255
+ async relayed(body) {
1256
+ const relay = this.relayClient();
1257
+ const sent = await relay.submit(body);
1258
+ return "digest" in sent ? sent : this.follow(relay, sent, "loan");
1259
+ }
1260
+ paidLoan(build, p) {
1261
+ const { wait, ...rest } = p;
1262
+ return this.relayed(build({ ...rest, wait: wait ?? true, relayerFee: this.coinFee(p.pool) }));
1263
+ }
1264
+ freeLoan(build, p) {
1265
+ const { wait, ...rest } = p;
1266
+ return this.relayed(build({ ...rest, wait: wait ?? true }));
1267
+ }
1268
+ /** D-SPEC §6.2:574. One credential, or none. A signature that no longer covers the commitment is tampered. */
1269
+ async listCredentials() {
1270
+ const info = await this.checkedCredential();
1271
+ return info ? [info] : [];
1272
+ }
1273
+ /** D-SPEC §6.2:574. */
1274
+ async viewCredential() {
1275
+ return (await this.checkedCredential()) ?? unknownObject("no credential is stored");
1276
+ }
1277
+ async checkedCredential() {
1278
+ const { member, credential } = readState(this.statePath);
1279
+ if (!credential)
1280
+ return null;
1281
+ if (!member)
1282
+ notSetUp("missing config: the state file has a credential and no member secrets");
1283
+ if (!(await credentialSigned(credential, memberCommitment(member))))
1284
+ throw new EsseyError("CREDENTIAL_REFUSED", "refused: tampered view data");
1285
+ return this.info(credential);
1286
+ }
1287
+ async poolOf(coin) {
1288
+ poolId(this.config, coin);
1289
+ const read = this.io.readPool ?? notSetUp("missing config: no pool reader");
1290
+ const seed = this.seed();
1291
+ return { events: await read(coin), seed };
1292
+ }
1293
+ /** D-SPEC §6.2:582. */
1294
+ async openNote(coin, index) {
1295
+ const { events, seed } = await this.poolOf(coin);
1296
+ return openPosition(coin, index, events, seed);
1297
+ }
1298
+ /** D-SPEC §6.2:582. */
1299
+ async listNotes(coin) {
1300
+ const coins = coin === undefined ? [...COINS] : [coin];
1301
+ const out = [];
1302
+ for (const c of coins) {
1303
+ const { events, seed } = await this.poolOf(c);
1304
+ out.push(...listPositions(c, events, seed));
1305
+ }
1306
+ return out;
1307
+ }
1308
+ /** D-SPEC §6.2:582. */
1309
+ async viewNote(coin, index) {
1310
+ const { events, seed } = await this.poolOf(coin);
1311
+ return viewPosition(coin, index, events, seed);
1312
+ }
1313
+ /** D-SPEC §6.2:588. The envelope is `v3.loans.open`; the id is whatever the digest created. */
1314
+ async openRequest(p) {
1315
+ assertLoanOpen(p);
1316
+ poolId(this.config, p.loanCoin);
1317
+ poolId(this.config, p.collateralCoin);
1318
+ if (this.config.relayer.url === null)
1319
+ notSetUp("missing config: the deployment record names no relayer");
1320
+ const plan = this.io.planLoanOpen ?? ((q) => this.planOpen(q));
1321
+ const read = this.io.readCreated ?? notSetUp("missing config: no loan reader");
1322
+ const proved = await plan(p);
1323
+ if (proved.pool !== p.loanCoin)
1324
+ wrongCoinObject();
1325
+ const landed = await this.paidLoan(openLoan, { ...proved, wait: true });
1326
+ const id = await read(landed.digest);
1327
+ if (typeof id !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(id))
1328
+ unknownObject("the digest created no loan");
1329
+ return { ...landed, id: address(id, "loan id") };
1330
+ }
1331
+ /**
1332
+ * The borrower's `loan_open`: a CollLock spend of up to two own notes into the lock, the Health OPEN rows, the
1333
+ * sealed request and keeper ciphertexts, and the borrower pass. The loan key, the lock blinding and the request
1334
+ * salt derive from one reserved note index, so the seed alone reopens the loan.
1335
+ */
1336
+ async planOpen(p) {
1337
+ const [C, L] = [p.collateralCoin, p.loanCoin];
1338
+ const market = address(this.config.objects.markets[`${C}/${L}`] ?? notSetUp("no market for this pair"), "market");
1339
+ const poolC = poolId(this.config, C);
1340
+ const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
1341
+ const readPrice = this.io.readPrice ?? notSetUp("missing config: no price reader");
1342
+ const update = this.io.priceUpdate ?? notSetUp("missing config: no price update source");
1343
+ const { member, credential } = readState(this.statePath);
1344
+ if (!member || !credential)
1345
+ notSetUp("no credential: call credential.obtain first");
1346
+ const relayer = this.relayerAddress();
1347
+ const prover = this.prover();
1348
+ const reading = await readPrice(market);
1349
+ const pClaim = reading.spot < reading.ema ? reading.spot : reading.ema;
1350
+ const rates = await this.rates(market);
1351
+ const fee = await this.feeParams(C);
1352
+ const { events, owned, seed } = await this.owned(C);
1353
+ const inputs = pickInputs(owned, p.collateral);
1354
+ const tree = poolTree(orderedLeaves(events));
1355
+ const ins = inputs.map((n) => ({
1356
+ amount: n.value,
1357
+ sk: n.sk,
1358
+ blinding: n.blinding,
1359
+ pathIndex: BigInt(n.index),
1360
+ pathElements: tree.path(n.index),
1361
+ }));
1362
+ await this.keys();
1363
+ const own = deriveNoteKey(seed, this.reserve("notes"));
1364
+ const changeIndex = this.reserve("notes");
1365
+ const change = deriveNoteKey(seed, changeIndex);
1366
+ const borrowerPk = notePk(own.sk);
1367
+ const loanKey = poseidonHash([own.sk, own.blinding, 1n]);
1368
+ const opening = { loanKey, borrowerPk, amount: p.collateral, blinding: own.blinding, nonce: 0n };
1369
+ const note = collNote(opening);
1370
+ const request = {
1371
+ principal: p.principal,
1372
+ maxRateBps: BigInt(p.maxRateBps),
1373
+ termMs: BigInt(p.termMs),
1374
+ salt: poseidonHash([own.sk, own.blinding, 2n]),
1375
+ };
1376
+ const closeMs = BigInt((this.io.now ?? Date.now)() + p.offerWindowMs);
1377
+ const reqSealed = await seal({
1378
+ id: requestKeyId(loanKey),
1379
+ data: requestPlaintext({
1380
+ ...request,
1381
+ borrowerPk,
1382
+ collAmt: p.collateral,
1383
+ collBlind: own.blinding,
1384
+ closeMs,
1385
+ market,
1386
+ coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
1387
+ }),
1388
+ });
1389
+ const keeperCt = await seal({
1390
+ id: keeperKeyId(loanKey, 0n),
1391
+ data: encodeKeeperPayload({
1392
+ version: KEEPER_LAYOUT_VERSION,
1393
+ loanKey,
1394
+ borrowerPk,
1395
+ collAmt: p.collateral,
1396
+ collBlind: own.blinding,
1397
+ nonceAtCt: 1n,
1398
+ }),
1399
+ });
1400
+ const ids = { loan: keyId(loanKey), poolC, market };
1401
+ const lock = await collLock({
1402
+ root: tree.root,
1403
+ ins: [ins[0], ins[1] ?? dummyInput()],
1404
+ lock: { amount: p.collateral, pk: collLockPk(loanKey, borrowerPk), blinding: own.blinding },
1405
+ change: { pk: notePk(change.sk), blinding: change.blinding },
1406
+ relayerFee: this.coinFee(L),
1407
+ loanKey,
1408
+ extHash: collLockExt(MODE_OPEN, ids.loan, poolC, market, relayer),
1409
+ fee,
1410
+ eph: drawEph(),
1411
+ });
1412
+ const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
1413
+ const encChange = bytesOf(sealOpening({ value: lock.changeAmount, blinding: change.blinding, index: changeIndex }, noteEncKey(seed).encPub));
1414
+ const encFee = bytesOf(fillerEnc());
1415
+ const decimals = {
1416
+ cDec: BigInt(this.config.coins[C].decimals),
1417
+ lDec: BigInt(this.config.coins[L].decimals),
1418
+ };
1419
+ const open = await health({
1420
+ mode: MODE.OPEN,
1421
+ opening,
1422
+ risk: loanRisk(rates.current, decimals, MODE.OPEN),
1423
+ price: { spot: pClaim, ema: pClaim, expo: reading.expo },
1424
+ timeS: 0n,
1425
+ extHash: openExt(ids, keeperCt, encChange, encFee),
1426
+ fee,
1427
+ eph: drawEph(),
1428
+ request,
1429
+ });
1430
+ const reqCommit = requestCommit(request, borrowerPk, note);
1431
+ const passN0 = openAction(loanKey, { reqCommit, reqSealed, closeMs, market, collateralCommit: note });
1432
+ const pass = membership({
1433
+ secrets: member,
1434
+ credential: credential,
1435
+ domain: DOMAIN_SPEND,
1436
+ room: keyId(loanKey),
1437
+ bind: keyId(passN0),
1438
+ });
1439
+ const proved = async (circuit, input, publics) => ({
1440
+ proof: (await prover.prove(circuit, input)).proof,
1441
+ publicSignals: publics.map(String),
1442
+ });
1443
+ return {
1444
+ pool: L,
1445
+ pass: {
1446
+ proved: await proved("membership", pass.input, pass.publics),
1447
+ tag: pass.publics[0],
1448
+ expiryMs: credential.expiryMs,
1449
+ n0: passN0,
1450
+ },
1451
+ collLock: await proved("coll_lock", lock.input, lock.publics),
1452
+ health: await proved("health", open.input, open.publics),
1453
+ market,
1454
+ loanKey,
1455
+ reqCommit,
1456
+ reqSealed,
1457
+ closeMs,
1458
+ collateralCommit: note,
1459
+ lock: lock.spend,
1460
+ encs: [encChange, encFee],
1461
+ keeperCt,
1462
+ pClaim,
1463
+ statement: open.statement,
1464
+ priceUpdate: await update(market),
1465
+ };
1466
+ }
1467
+ /** The coins of the market a loan names, as `C/L` in the deployment record. */
1468
+ pairOf(market) {
1469
+ const want = address(market, "market");
1470
+ const hit = Object.entries(this.config.objects.markets).find(([, id]) => id && address(id, "market") === want);
1471
+ if (!hit)
1472
+ unknownObject("the loan's market is not in the deployment record");
1473
+ return hit[0].split("/");
1474
+ }
1475
+ async readRequest(id) {
1476
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
1477
+ const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
1478
+ const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
1479
+ const { member, credential } = readState(this.statePath);
1480
+ if (!member || !credential)
1481
+ notSetUp("no credential: call credential.obtain first");
1482
+ const loan = address(id, "loan id");
1483
+ const row = await read(loan);
1484
+ if (!row)
1485
+ unknownObject("no loan with this id");
1486
+ const json = row.json;
1487
+ const round = row.round;
1488
+ const refi = Number(json.state) === 8;
1489
+ if (Number(json.state) !== 1 && !refi)
1490
+ throw new EsseyError("INVALID_ARGUMENT", "the loan is not bidding");
1491
+ if (!round)
1492
+ unknownObject("the loan's round is missing");
1493
+ const loanKey = BigInt(json.loan_key);
1494
+ const pair = this.pairOf(json.market_id);
1495
+ const room = keyId(loanKey);
1496
+ const prover = this.prover();
1497
+ const keyIdBytes = requestKeyId(loanKey);
1498
+ const plain = await decrypt({
1499
+ sealed: Uint8Array.from(Buffer.from(round.req_sealed, "base64")),
1500
+ approve: async (viewer) => {
1501
+ const nonce = drawSecret();
1502
+ const bind = `0x${Buffer.from(sealListingBind(room, viewer)).toString("hex")}`;
1503
+ const pass = membership({
1504
+ secrets: member,
1505
+ credential: credential,
1506
+ domain: DOMAIN_SENDER,
1507
+ room,
1508
+ bind,
1509
+ nonce,
1510
+ });
1511
+ const proved = await prover.prove("membership", pass.input);
1512
+ return {
1513
+ target: `${this.config.packages.loan}::seal_policy::seal_approve_request`,
1514
+ typeArguments: pair.map((c) => this.config.coins[c].type),
1515
+ args: [
1516
+ { pure: "vector<u8>", value: `0x${Buffer.from(keyIdBytes).toString("hex")}` },
1517
+ { object: loan },
1518
+ { object: passKey.id },
1519
+ { pure: "u256", value: pass.publics[0].toString() },
1520
+ { pure: "u256", value: nonce.toString() },
1521
+ { pure: "u64", value: credential.expiryMs.toString() },
1522
+ { pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
1523
+ { object: "0x6" },
1524
+ ],
1525
+ };
1526
+ },
1527
+ });
1528
+ const q = decodeRequest(plain);
1529
+ const note = collNote({ loanKey, borrowerPk: q.borrowerPk, amount: q.collAmt, blinding: q.collBlind });
1530
+ const locked = refi ? json.coll.coll_note : json.collateral_commit;
1531
+ if (note !== BigInt(locked))
1532
+ throw new EsseyError("CT_MISMATCH", "refused: the request opens another lock");
1533
+ const request = { principal: q.principal, maxRateBps: q.maxRateBps, termMs: q.termMs, salt: q.salt };
1534
+ if (requestCommit(request, q.borrowerPk, note) !== BigInt(round.req_commit))
1535
+ throw new EsseyError("CT_MISMATCH", "refused: the request does not open the loan's commit");
1536
+ return {
1537
+ loan,
1538
+ loanKey,
1539
+ round: BigInt(json.round),
1540
+ seq: BigInt(round.offers.length),
1541
+ pair,
1542
+ poolL: address(json.pool_l, "pool_l"),
1543
+ ...request,
1544
+ borrowerPk: q.borrowerPk,
1545
+ collAmt: q.collAmt,
1546
+ collBlind: q.collBlind,
1547
+ collNote: note,
1548
+ closeMs: q.closeMs,
1549
+ };
1550
+ }
1551
+ /** The lender's `loan_offer`: the principal locked to the round from up to two own notes, its sealed terms pinned. */
1552
+ async planOffer(loanId, rateBps) {
1553
+ const q = await this.readRequest(loanId);
1554
+ const L = q.pair[1];
1555
+ if (poolId(this.config, L) !== q.poolL)
1556
+ wrongCoinObject();
1557
+ if (rateBps > q.maxRateBps)
1558
+ throw new EsseyError("INVALID_ARGUMENT", "the rate is above the request's maximum");
1559
+ const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
1560
+ const { member, credential } = readState(this.statePath);
1561
+ const relayer = this.relayerAddress();
1562
+ const relayerFee = this.coinFee(L);
1563
+ const prover = this.prover();
1564
+ const fee = await this.feeParams(L);
1565
+ const { events, owned, seed } = await this.owned(L);
1566
+ const inputs = pickInputs(owned, q.principal + relayerFee);
1567
+ const tree = poolTree(orderedLeaves(events));
1568
+ const ins = inputs.map((n) => ({
1569
+ amount: n.value,
1570
+ sk: n.sk,
1571
+ blinding: n.blinding,
1572
+ pathIndex: BigInt(n.index),
1573
+ pathElements: tree.path(n.index),
1574
+ }));
1575
+ const spent = [ins[0], ins[1] ?? dummyInput()];
1576
+ const n0 = noteNullifier(noteCommitment(spent[0].amount, notePk(spent[0].sk), spent[0].blinding), spent[0].sk, spent[0].pathIndex);
1577
+ await this.keys();
1578
+ const offerIndex = this.reserve("notes");
1579
+ const own = deriveNoteKey(seed, offerIndex);
1580
+ const changeIndex = this.reserve("notes");
1581
+ const change = deriveNoteKey(seed, changeIndex);
1582
+ const enc = await treasuryPoint(poseidonHash([own.sk, own.blinding, 6n]) >> 2n);
1583
+ const offer = {
1584
+ rateBps,
1585
+ salt: poseidonHash([own.sk, own.blinding, 5n]),
1586
+ lenderPk: notePk(own.sk),
1587
+ encX: enc.tx,
1588
+ encY: enc.ty,
1589
+ ns: poseidonHash([own.sk, own.blinding, 3n]),
1590
+ b: poseidonHash([own.sk, own.blinding, 4n]),
1591
+ amount: q.principal,
1592
+ };
1593
+ const n0Le = Uint8Array.from(Buffer.from(n0.toString(16).padStart(64, "0"), "hex").reverse());
1594
+ const sealed = await seal({
1595
+ id: offerKeyId(q.loanKey, q.round, q.seq),
1596
+ data: offerPlaintext(offer),
1597
+ aad: n0Le,
1598
+ });
1599
+ const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
1600
+ const changeValue = spent[0].amount + spent[1].amount - q.principal - relayerFee;
1601
+ const encChange = bytesOf(sealOpening({ value: changeValue, blinding: change.blinding, index: changeIndex }, noteEncKey(seed).encPub));
1602
+ const encFee = bytesOf(fillerEnc());
1603
+ const extHash = loanExt(LOAN_OFFER_KIND, q.loan, q.poolL, q.round, relayer, [encChange, encFee], blake2b256(sealed));
1604
+ const witness = await loanOffer({
1605
+ root: tree.root,
1606
+ ins: spent,
1607
+ request: { ...q, collNote: q.collNote },
1608
+ loanKey: q.loanKey,
1609
+ round: q.round,
1610
+ offer,
1611
+ change: { pk: notePk(change.sk), blinding: change.blinding },
1612
+ relayerFee,
1613
+ extHash,
1614
+ fee,
1615
+ eph: drawEph(),
1616
+ });
1617
+ if (witness.changeAmount !== changeValue)
1618
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the offer's fee lane is not free");
1619
+ const passRoom = offerRoom(q.loanKey, q.round);
1620
+ const pass = membership({
1621
+ secrets: member,
1622
+ credential: credential,
1623
+ domain: DOMAIN_SPEND,
1624
+ room: passRoom,
1625
+ bind: keyId(n0),
1626
+ });
1627
+ const proved = async (circuit, input, publics) => ({
1628
+ proof: (await prover.prove(circuit, input)).proof,
1629
+ publicSignals: publics.map(String),
1630
+ });
1631
+ const { spend } = witness;
1632
+ const record = {
1633
+ noteIndex: offerIndex,
1634
+ principal: q.principal,
1635
+ rateBps,
1636
+ termMs: q.termMs,
1637
+ borrowerPk: q.borrowerPk,
1638
+ };
1639
+ return {
1640
+ record,
1641
+ body: {
1642
+ pool: L,
1643
+ loan: q.loan,
1644
+ membership: await proved("membership", pass.input, pass.publics),
1645
+ offer: await proved("loan_offer", witness.input, witness.publics),
1646
+ tag: pass.publics[0],
1647
+ expiryMs: credential.expiryMs,
1648
+ passRoom,
1649
+ root: spend.root,
1650
+ nullifier0: spend.n0,
1651
+ nullifier1: spend.n1,
1652
+ lock: spend.note,
1653
+ change: spend.change,
1654
+ feeNote: spend.feeNote,
1655
+ ephX: spend.ephX,
1656
+ ephY: spend.ephY,
1657
+ feeCt: spend.feeCt,
1658
+ commit: witness.commit,
1659
+ sealed,
1660
+ encChange,
1661
+ encFee,
1662
+ },
1663
+ };
1664
+ }
1665
+ /** `seal_policy::seal_approve_offer` for offer `seq`: the borrower's SEAL pass over `seal_offer` bound to the viewer. */
1666
+ offerApprove(loan, loanKey, round, seq, pair) {
1667
+ const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
1668
+ const { member, credential } = readState(this.statePath);
1669
+ const room = keyId(loanKey);
1670
+ const prover = this.prover();
1671
+ return async (viewer) => {
1672
+ const bind = `0x${Buffer.from(sealOfferBind(blake2b256, room, round, seq, viewer)).toString("hex")}`;
1673
+ const pass = membership({
1674
+ secrets: member,
1675
+ credential: credential,
1676
+ domain: DOMAIN_SENDER,
1677
+ room,
1678
+ bind,
1679
+ });
1680
+ const proved = await prover.prove("membership", pass.input);
1681
+ return {
1682
+ target: `${this.config.packages.loan}::seal_policy::seal_approve_offer`,
1683
+ typeArguments: pair.map((c) => this.config.coins[c].type),
1684
+ args: [
1685
+ {
1686
+ pure: "vector<u8>",
1687
+ value: `0x${Buffer.from(offerKeyId(loanKey, round, seq)).toString("hex")}`,
1688
+ },
1689
+ { object: loan },
1690
+ { pure: "u64", value: seq.toString() },
1691
+ { object: passKey.id },
1692
+ { pure: "u256", value: pass.publics[0].toString() },
1693
+ { pure: "u64", value: credential.expiryMs.toString() },
1694
+ { pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
1695
+ { object: "0x6" },
1696
+ ],
1697
+ };
1698
+ };
1699
+ }
1700
+ /**
1701
+ * Offer `seq` of the current round, once closed, whose sealed plaintext does not open its commit (`offer::slash`):
1702
+ * the borrower asks Seal for the offer key's derived keys under the same policy as its read, and the chain decrypts
1703
+ * with them. An honest offer aborts 42_013. No penalty: the lock is reclaimed once the round resolves.
1704
+ */
1705
+ async slashOffer(loanId, seq) {
1706
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
1707
+ const derive = this.io.sealDerivedKeys ?? notSetUp("missing config: no Seal key deriver");
1708
+ const loan = address(loanId, "loan id");
1709
+ const row = await read(loan);
1710
+ if (!row)
1711
+ unknownObject("no loan with this id");
1712
+ const json = row.json;
1713
+ const loanKey = BigInt(json.loan_key);
1714
+ this.indexOfLoanKey(this.seed(), loanKey);
1715
+ const round = BigInt(json.round);
1716
+ const pair = this.pairOf(json.market_id);
1717
+ const derived = await derive({
1718
+ id: offerKeyId(loanKey, round, seq),
1719
+ approve: this.offerApprove(loan, loanKey, round, seq, pair),
1720
+ });
1721
+ return this.freeLoan(slashLoan, { pool: pair[1], loan, round, seq, keys: this.pinnedKeys(derived) });
1722
+ }
1723
+ /** Threshold many derived keys, each with its server's slot in `config.seal.servers` (`seal_servers::public_keys` order). */
1724
+ pinnedKeys(derived) {
1725
+ const servers = this.config.seal.servers.map((s) => s.objectId);
1726
+ return [...derived].slice(0, this.config.seal.threshold).map(([objectId, key]) => {
1727
+ const index = servers.indexOf(objectId);
1728
+ if (index < 0)
1729
+ throw new EsseyError("CT_MISMATCH", "refused: a derived key from a server the loan does not pin");
1730
+ return { index, key };
1731
+ });
1732
+ }
1733
+ /**
1734
+ * B §7.5: the keeper asks Seal for the retained borrower ciphertext's derived keys under the keeper policy, and the
1735
+ * chain decrypts with them (`keeper::prove_ct_fault`). A ciphertext that opens its lock and terms aborts 43_212.
1736
+ */
1737
+ async ctFault(loanId, via) {
1738
+ const derive = this.io.sealDerivedKeys ?? notSetUp("missing config: no Seal key deriver");
1739
+ const { loan, json } = await this.activeLoan(loanId);
1740
+ const retained = json.coll?.borrower_ct;
1741
+ if (!retained)
1742
+ throw new EsseyError("INVALID_ARGUMENT", "the loan holds no borrower ciphertext");
1743
+ const id = keeperKeyId(BigInt(json.loan_key), BigInt(retained.version));
1744
+ const derived = await derive({ id, ...(await this.keeperApproval(json, loan, id, via)) });
1745
+ const pool = this.pairOf(json.market_id)[1];
1746
+ return this.freeLoan(ctFaultLoan, { pool, loan, keys: this.pinnedKeys(derived) });
1747
+ }
1748
+ async activeLoan(loanId) {
1749
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
1750
+ const loan = address(loanId, "loan id");
1751
+ const row = await read(loan);
1752
+ if (!row)
1753
+ unknownObject("no loan with this id");
1754
+ const json = row.json;
1755
+ if (Number(json.state) !== 2 && Number(json.state) !== 8)
1756
+ throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
1757
+ return { loan, json };
1758
+ }
1759
+ /** Either policy entry for key id `id`; the badge one carries the signer its Seal session must be made by. */
1760
+ async keeperApproval(json, loan, id, via = "pass") {
1761
+ const market = address(json.market_id, "market");
1762
+ const pair = this.pairOf(json.market_id);
1763
+ if (via === "pass")
1764
+ return { approve: await this.keeperApprove(loan, market, id, pair) };
1765
+ const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
1766
+ const held = readState(this.statePath).badge;
1767
+ if (!held || BigInt((this.io.now ?? Date.now)()) >= held.expiresMs)
1768
+ notSetUp("no live keeper badge: call keeper.mintBadge");
1769
+ const signer = depositSigner(this.seed(), held.signer);
1770
+ const holder = signer.toSuiAddress();
1771
+ const call = badgeApprove({
1772
+ pkg: this.config.packages.loan,
1773
+ typeArguments: pair.map((c) => this.config.coins[c].type),
1774
+ id,
1775
+ loan,
1776
+ market,
1777
+ price: await this.keeperPrice(market),
1778
+ badge: held.id,
1779
+ passKey: keeper.passKey.id,
1780
+ registry: keeper.registry.id,
1781
+ });
1782
+ const approve = async (viewer) => {
1783
+ if (normalizeSuiAddress(viewer) !== holder)
1784
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the Seal session is not the badge holder's");
1785
+ return call;
1786
+ };
1787
+ return { approve, signer };
1788
+ }
1789
+ heldBadge() {
1790
+ const held = readState(this.statePath).badge;
1791
+ if (!held)
1792
+ return null;
1793
+ const holder = depositSigner(this.seed(), held.signer).toSuiAddress();
1794
+ return { badge: held.id, holder, expiresMs: held.expiresMs };
1795
+ }
1796
+ /**
1797
+ * E-35: a KEEPER pass bound to a fresh deposit signer mints that signer a badge (`keeper.move:73-104`). The relayer
1798
+ * sponsors each sender once (`services/relayer-v3/src/server.ts:679-680`), so every mint takes a new signer index.
1799
+ */
1800
+ async mintBadge() {
1801
+ const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
1802
+ const pkg = this.config.packages.loan ?? notSetUp("the loan package is not published yet");
1803
+ const readBadge = this.io.readBadge ?? notSetUp("missing config: no badge reader");
1804
+ const relayer = this.sponsorRelayer();
1805
+ const { secrets, credential } = this.member();
1806
+ if (credential.role !== "keeper")
1807
+ notSetUp("no keeper credential");
1808
+ const prover = this.prover();
1809
+ const seed = this.seed();
1810
+ const index = await this.freshSigner(seed, this.io.readAddressUsed);
1811
+ const signer = depositSigner(seed, index);
1812
+ const holder = signer.toSuiAddress();
1813
+ const room = keeper.registry.id;
1814
+ const pass = membership({ secrets, credential, domain: DOMAIN_KEEPER, room, bind: holder });
1815
+ const proof = proofBytes((await prover.prove("membership", pass.input)).proof);
1816
+ const shared = (r) => ({
1817
+ objectId: r.id,
1818
+ initialSharedVersion: r.initialSharedVersion,
1819
+ });
1820
+ const txKindB64 = await mintBadgeKind({
1821
+ pkg,
1822
+ registry: shared(keeper.registry),
1823
+ passKey: shared(keeper.passKey),
1824
+ tag: pass.publics[0],
1825
+ passExpiresMs: credential.expiryMs,
1826
+ proof,
1827
+ });
1828
+ const wire = {
1829
+ tag: pass.publics[0].toString(),
1830
+ expiryMs: credential.expiryMs.toString(),
1831
+ proof: `0x${Buffer.from(proof).toString("hex")}`,
1832
+ };
1833
+ const digest = await this.sponsoredSend(signer, txKindB64, wire, relayer);
1834
+ const row = await readBadge(digest);
1835
+ if (!row)
1836
+ throw new EsseyError("SERVICE_REFUSED", `the mint ${digest} created no badge`);
1837
+ const { id, expiresMs } = badgeOf(row, { holder, registry: room });
1838
+ this.update((s) => {
1839
+ s.badge = { signer: index, id, expiresMs };
1840
+ });
1841
+ return { digest, badge: id, holder, expiresMs };
1842
+ }
1843
+ /** Sponsor, check the bytes are this kind from `signer` on the relayer's gas, sign, execute. */
1844
+ async sponsoredSend(signer, txKindB64, pass, relayer) {
1845
+ const sender = signer.toSuiAddress();
1846
+ const possession = await provePossession({
1847
+ signer,
1848
+ kind: fromBase64(txKindB64),
1849
+ relayer: relayer.address,
1850
+ expiryMs: (this.io.now ?? Date.now)() + POSSESSION_TTL_MS,
1851
+ });
1852
+ const sponsored = await sponsor(this.fetch, relayer.base, { txKindB64, sender, pass, possession });
1853
+ if (!carriesKind(sponsored.txBytesB64, txKindB64, sender, relayer.address))
1854
+ throw new EsseyError("RELAY_REFUSED", "refused: the sponsored bytes are not this call; nothing was signed");
1855
+ const { signature } = await signer.signTransaction(fromBase64(sponsored.txBytesB64));
1856
+ return executeSponsored(this.fetch, relayer.base, {
1857
+ txBytesB64: sponsored.txBytesB64,
1858
+ userSig: signature,
1859
+ });
1860
+ }
1861
+ /** `keeper::seal_approve_keeper_proof`: a KEEPER pass for the deployment's keeper registry, bound to the viewer. */
1862
+ async keeperApprove(loan, market, id, pair) {
1863
+ const keeper = this.config.objects.keeper ?? notSetUp("missing config: no keeper PassKey");
1864
+ const { member, credential } = readState(this.statePath);
1865
+ if (!member || credential?.role !== "keeper")
1866
+ notSetUp("no keeper credential");
1867
+ const price = await this.keeperPrice(market);
1868
+ const prover = this.prover();
1869
+ return async (viewer) => {
1870
+ const pass = membership({
1871
+ secrets: member,
1872
+ credential: credential,
1873
+ domain: DOMAIN_KEEPER,
1874
+ room: keeper.registry.id,
1875
+ bind: viewer,
1876
+ });
1877
+ const proved = await prover.prove("membership", pass.input);
1878
+ return {
1879
+ target: `${this.config.packages.loan}::keeper::seal_approve_keeper_proof`,
1880
+ typeArguments: pair.map((c) => this.config.coins[c].type),
1881
+ args: [
1882
+ { pure: "vector<u8>", value: `0x${Buffer.from(id).toString("hex")}` },
1883
+ { object: loan },
1884
+ { object: market },
1885
+ { object: price },
1886
+ { object: keeper.passKey.id },
1887
+ { object: keeper.registry.id },
1888
+ { pure: "u256", value: pass.publics[0].toString() },
1889
+ { pure: "u64", value: credential.expiryMs.toString() },
1890
+ { pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
1891
+ { object: "0x6" },
1892
+ ],
1893
+ };
1894
+ };
1895
+ }
1896
+ /**
1897
+ * The PriceInfoObject the keeper policy takes: the market's own feed on a Pyth market. On any other market only
1898
+ * the expired-heartbeat and zero-floor branches can pass, and they read no price (`keeper.move` `check_loan`), so
1899
+ * the feed of a Pyth market in the deployment stands in for the argument.
1900
+ */
1901
+ async keeperPrice(market) {
1902
+ const read = this.io.readMarket ?? notSetUp("missing config: no market reader");
1903
+ const feed = async (id) => {
1904
+ const m = await read(id);
1905
+ return /::pyth_oracle::PythOracle(Inverse)?$/.test(m.oracle ?? "") ? m.feed_id : undefined;
1906
+ };
1907
+ const own = await feed(market);
1908
+ if (own)
1909
+ return own;
1910
+ for (const id of Object.values(this.config.objects.markets)) {
1911
+ const other = id && (await feed(id));
1912
+ if (other)
1913
+ return other;
1914
+ }
1915
+ return notSetUp("no Pyth market in the deployment");
1916
+ }
1917
+ /** The borrower's read of offer `seq` after close (`seal_policy::seal_approve_offer`): pass nonce 0 is its open tag. */
1918
+ async openOffer(loan, loanKey, round, seq, sealed, pair) {
1919
+ const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
1920
+ const plain = await decrypt({ sealed, approve: this.offerApprove(loan, loanKey, round, seq, pair) });
1921
+ return decodeOffer(plain);
1922
+ }
1923
+ /** The borrower's `loan_settle` on round 0: the lowest eligible offer wins, keeper ciphertext v1 carries its terms. */
1924
+ async planSettle(id) {
1925
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
1926
+ const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
1927
+ const q = await this.readRequest(id);
1928
+ const row = await read(q.loan);
1929
+ const json = row.json;
1930
+ const round = row.round;
1931
+ const slots = [];
1932
+ for (const [i, o] of round.offers.entries()) {
1933
+ const sealed = Uint8Array.from(Buffer.from(o.sealed, "base64"));
1934
+ const open = o.active
1935
+ ? await this.openOffer(q.loan, q.loanKey, q.round, BigInt(i), sealed, q.pair)
1936
+ : undefined;
1937
+ slots.push({ commit: BigInt(o.commit), lock: BigInt(o.lock), active: o.active, open });
1938
+ }
1939
+ const { member, credential } = readState(this.statePath);
1940
+ const L = q.pair[1];
1941
+ const prover = this.prover();
1942
+ const fee = await this.feeParams(L);
1943
+ const seed = this.seed();
1944
+ await this.keys();
1945
+ const noteIndex = this.reserve("notes");
1946
+ const mine = deriveNoteKey(seed, noteIndex);
1947
+ const nowS = BigInt(Math.floor((this.io.now ?? Date.now)() / 1000));
1948
+ const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
1949
+ const plan = (extHash) => loanSettle({
1950
+ slots,
1951
+ request: q,
1952
+ loanKey: q.loanKey,
1953
+ borrowerNote: { pk: notePk(mine.sk), blinding: mine.blinding },
1954
+ e: drawEph(),
1955
+ nowS,
1956
+ extHash,
1957
+ fee,
1958
+ eph: drawEph(),
1959
+ });
1960
+ const draft = await plan(0n);
1961
+ const keeperCt = await seal({
1962
+ id: keeperKeyId(q.loanKey, 1n),
1963
+ data: encodeKeeperPayload({
1964
+ version: KEEPER_LAYOUT_VERSION,
1965
+ loanKey: q.loanKey,
1966
+ borrowerPk: q.borrowerPk,
1967
+ collAmt: q.collAmt,
1968
+ collBlind: q.collBlind,
1969
+ nonceAtCt: 1n,
1970
+ terms: draft.terms,
1971
+ }),
1972
+ });
1973
+ const encPrincipal = bytesOf(sealOpening({ value: draft.principalValue, blinding: mine.blinding, index: noteIndex }, noteEncKey(seed).encPub));
1974
+ const encFee = bytesOf(fillerEnc());
1975
+ const encs = [encPrincipal, encFee];
1976
+ const ext = loanExt(LOAN_SETTLE_KIND, q.loan, q.poolL, 0n, NO_ADDRESS, encs, blake2b256(keeperCt));
1977
+ const w = await plan(ext);
1978
+ if (w.termsCommit !== draft.termsCommit)
1979
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the terms moved between drafts");
1980
+ const settleProof = await prover.prove("loan_settle", w.input);
1981
+ const args = settleArgs({
1982
+ loan: q.loan,
1983
+ poolL: q.poolL,
1984
+ proof: proofBytes(settleProof.proof),
1985
+ termsCommit: w.termsCommit,
1986
+ principalNote: w.principalNote,
1987
+ feeNote: w.feeNote,
1988
+ winNull: w.winNull,
1989
+ d: w.d,
1990
+ ephX: w.ephX,
1991
+ ephY: w.ephY,
1992
+ feeCt: w.feeCt,
1993
+ keeperCt,
1994
+ encs,
1995
+ nowS,
1996
+ });
1997
+ const n0 = actionHash(blake2b256, q.loanKey, BigInt(json.nonce), "settle", args);
1998
+ const room = keyId(q.loanKey);
1999
+ const pass = membership({
2000
+ secrets: member,
2001
+ credential: credential,
2002
+ domain: DOMAIN_SPEND,
2003
+ room,
2004
+ bind: keyId(n0),
2005
+ });
2006
+ const passProved = await prover.prove("membership", pass.input);
2007
+ return {
2008
+ rateBps: w.terms.rateBps,
2009
+ terms: w.terms,
2010
+ borrowerPk: q.borrowerPk,
2011
+ collAmt: q.collAmt,
2012
+ body: {
2013
+ pool: L,
2014
+ loan: q.loan,
2015
+ settle: { proof: settleProof.proof, publicSignals: w.publics.map(String) },
2016
+ pass: {
2017
+ proved: { proof: passProved.proof, publicSignals: pass.publics.map(String) },
2018
+ tag: pass.publics[0],
2019
+ expiryMs: credential.expiryMs,
2020
+ n0,
2021
+ },
2022
+ termsCommit: w.termsCommit,
2023
+ principalNote: w.principalNote,
2024
+ feeNote: w.feeNote,
2025
+ winNull: w.winNull,
2026
+ d: w.d,
2027
+ ephX: w.ephX,
2028
+ ephY: w.ephY,
2029
+ feeCt: w.feeCt,
2030
+ keeperCt,
2031
+ encPrincipal,
2032
+ encFee,
2033
+ nowS,
2034
+ },
2035
+ };
2036
+ }
2037
+ /** The borrower's `loan_repay`: `owed` to the lender's note by ECDH on its enc key, change back to own key. */
2038
+ async planRepay(loanId, terms, borrowerPk) {
2039
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2040
+ const loan = address(loanId, "loan id");
2041
+ const row = await read(loan);
2042
+ if (!row)
2043
+ unknownObject("no loan with this id");
2044
+ const json = row.json;
2045
+ const pair = this.pairOf(json.market_id);
2046
+ const L = pair[1];
2047
+ const poolL = address(json.pool_l, "pool_l");
2048
+ if (poolId(this.config, L) !== poolL)
2049
+ wrongCoinObject();
2050
+ if (termsCommit(terms, borrowerPk) !== BigInt(json.terms_commit))
2051
+ throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
2052
+ const relayer = this.relayerAddress();
2053
+ const relayerFee = this.coinFee(L);
2054
+ const prover = this.prover();
2055
+ const fee = await this.feeParams(L);
2056
+ const { events, owned, seed } = await this.owned(L);
2057
+ const tree = poolTree(orderedLeaves(events));
2058
+ const inputs = pickInputs(owned, terms.owed + relayerFee + feeOf({ base: terms.owed, bps: fee.bps, min: fee.min, max: fee.max }).fee);
2059
+ const ins = inputs.map((n) => ({
2060
+ amount: n.value,
2061
+ sk: n.sk,
2062
+ blinding: n.blinding,
2063
+ pathIndex: BigInt(n.index),
2064
+ pathElements: tree.path(n.index),
2065
+ }));
2066
+ await this.keys();
2067
+ const changeIndex = this.reserve("notes");
2068
+ const change = deriveNoteKey(seed, changeIndex);
2069
+ const pad = { pk: notePk(drawSecret()), blinding: drawSecret() };
2070
+ const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2071
+ const spent = [ins[0], ins[1] ?? dummyInput()];
2072
+ const base = {
2073
+ root: tree.root,
2074
+ ins: spent,
2075
+ terms,
2076
+ borrowerPk,
2077
+ change: { pk: notePk(change.sk), blinding: change.blinding },
2078
+ pad,
2079
+ relayerFee,
2080
+ fee,
2081
+ };
2082
+ const draft = await loanRepay({ ...base, eL: drawEph(), extHash: 0n, eph: drawEph() });
2083
+ const encs = [
2084
+ bytesOf(fillerEnc()),
2085
+ bytesOf(sealOpening({ value: draft.changeAmount, blinding: change.blinding, index: changeIndex }, noteEncKey(seed).encPub)),
2086
+ bytesOf(fillerEnc()),
2087
+ bytesOf(fillerEnc()),
2088
+ ];
2089
+ const extHash = loanExt(LOAN_REPAY_KIND, loan, poolL, BigInt(json.round), relayer, encs, new Uint8Array());
2090
+ const w = await loanRepay({ ...base, eL: drawEph(), extHash, eph: drawEph() });
2091
+ const proved = await prover.prove("loan_repay", w.input);
2092
+ return {
2093
+ pool: L,
2094
+ loan,
2095
+ repay: { proof: proved.proof, publicSignals: w.publics.map(String) },
2096
+ root: tree.root,
2097
+ nullifier0: w.n0,
2098
+ nullifier1: w.n1,
2099
+ lenderNote: w.lenderNote,
2100
+ change: w.change,
2101
+ feeNote: w.feeNote,
2102
+ pad: w.pad,
2103
+ ephL0: w.ephL[0],
2104
+ ephL1: w.ephL[1],
2105
+ ephX: w.ephX,
2106
+ ephY: w.ephY,
2107
+ feeCt: w.feeCt,
2108
+ encs,
2109
+ };
2110
+ }
2111
+ /**
2112
+ * The repaid note is `Poseidon(owed, lenderPk, H(DOM_LBLIND, S.x))` with `S = encSk · repay_eph`
2113
+ * (`loan_repay.circom`), and a refi payoff the same over a `payoff_eph` pair (`loan_refi.circom`); either ciphertext
2114
+ * is filler, so the scan never sees it. It is spent into an own note.
2115
+ */
2116
+ async collect(loanId, offer) {
2117
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2118
+ const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
2119
+ const loan = address(loanId, "loan id");
2120
+ const row = await read(loan);
2121
+ if (!row)
2122
+ unknownObject("no loan with this id");
2123
+ const json = row.json;
2124
+ const flat = (v) => (v ?? []).flat(2).map((x) => BigInt(x));
2125
+ // Only `loan::set_repaid` writes repay_eph (loan.move:483-486), and RELEASE then moves the loan to CLOSED.
2126
+ const ephs = [flat(json.repay_eph), flat(json.payoff_eph)].flatMap((xs) => Array.from({ length: Math.floor(xs.length / 2) }, (_, i) => [xs[2 * i], xs[2 * i + 1]]));
2127
+ const L = this.pairOf(String(json.market_id))[1];
2128
+ const seed = this.seed();
2129
+ const own = deriveNoteKey(seed, offer.noteIndex);
2130
+ const owed = interest(offer.principal, offer.rateBps, offer.termMs).owed;
2131
+ const events = await pools(L);
2132
+ let blinding = 0n;
2133
+ let commitment = 0n;
2134
+ let leaf;
2135
+ for (const [ex, ey] of ephs) {
2136
+ const k = await ecdhBlind(ex, ey, poseidonHash([own.sk, own.blinding, 6n]) >> 2n);
2137
+ blinding = poseidonHash([DOM_LBLIND, k.sx]);
2138
+ commitment = noteCommitment(owed, notePk(own.sk), blinding);
2139
+ leaf = events.commitments.find((c) => BigInt(c.commitment) === commitment);
2140
+ if (leaf)
2141
+ break;
2142
+ }
2143
+ if (!leaf)
2144
+ 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");
2145
+ return this.claimLeaf(L, events, { value: owed, sk: own.sk, blinding, index: Number(leaf.index) });
2146
+ }
2147
+ /** Spends a note no ciphertext names, found by its commitment, to the receive address. */
2148
+ async claimLeaf(coin, events, note) {
2149
+ const commitment = noteCommitment(note.value, notePk(note.sk), note.blinding);
2150
+ const n = noteNullifier(commitment, note.sk, BigInt(note.index));
2151
+ if (events.nullifiers.some((x) => BigInt(x) === n))
2152
+ throw new EsseyError("INVALID_ARGUMENT", "already collected");
2153
+ const payTo = receiveTarget(this.receiveAddress());
2154
+ let value = 0n;
2155
+ const landed = await this.spend(coin, { payTo }, (_owned, rates, relayerFee) => {
2156
+ value = exitValue(note.value, rates, relayerFee);
2157
+ if (value === 0n)
2158
+ throw new EsseyError("INVALID_ARGUMENT", "refused: nothing to collect after fees");
2159
+ return { value, inputs: [note] };
2160
+ }, [note]);
2161
+ return { ...landed, value };
2162
+ }
2163
+ /** The lender's lock opening at nonce 1: the settle delivery, with the amount the latest TOPUP delivery re-states. */
2164
+ async lenderLock(json, own) {
2165
+ const topups = this.io.readTopupDelivery ?? notSetUp("missing config: no topup delivery reader");
2166
+ const d = json.delivery ?? unknownObject("the loan holds no settle delivery");
2167
+ const encSk = poseidonHash([own.sk, own.blinding, 6n]) >> 2n;
2168
+ const k = await ecdhBlind(BigInt(d.ex), BigInt(d.ey), encSk);
2169
+ const topped = await topups(String(json.id));
2170
+ return {
2171
+ amount: topped ? await lenderAmount(encSk, topped) : (BigInt(d.ct1) - poseidonHash([k.sx, 1n]) + R) % R,
2172
+ blinding: (BigInt(d.ct2) - poseidonHash([k.sx, 2n]) + R) % R,
2173
+ };
2174
+ }
2175
+ /** B §5.5 out0 of a seizure, the lender's, from its lock opening; each heartbeat and TOPUP rolled the blinding one step. */
2176
+ collectSeized(loanId, offer) {
2177
+ return this.collectFromSeizure(loanId, 0, async (json, seizeNonce) => {
2178
+ const own = deriveNoteKey(this.seed(), offer.noteIndex);
2179
+ const lock = await this.lenderLock(json, own);
2180
+ let blinding = lock.blinding;
2181
+ for (let n = 1n; n < seizeNonce; n++)
2182
+ blinding = outputBlind(blinding, 0, n);
2183
+ return {
2184
+ owed: interest(offer.principal, offer.rateBps, offer.termMs).owed,
2185
+ collAmt: lock.amount,
2186
+ sk: own.sk,
2187
+ blinding,
2188
+ };
2189
+ });
2190
+ }
2191
+ /** B §5.5 out1 of a seizure, the borrower's surplus `avail - seize`, from its own opening rolled to the seizing nonce. */
2192
+ collectSurplus(p) {
2193
+ return this.collectFromSeizure(p.loan, 1, async (json, seizeNonce) => {
2194
+ if (termsCommit(p.terms, p.borrowerPk) !== BigInt(json.terms_commit))
2195
+ throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
2196
+ const seed = this.seed();
2197
+ const own = deriveNoteKey(seed, this.indexOfPk(seed, p.borrowerPk));
2198
+ const start = {
2199
+ loanKey: BigInt(json.loan_key),
2200
+ borrowerPk: p.borrowerPk,
2201
+ amount: p.collAmt,
2202
+ blinding: own.blinding,
2203
+ nonce: 1n,
2204
+ };
2205
+ const opening = rollTo(start, BigInt(json.coll.coll_note), seizeNonce);
2206
+ return { owed: p.terms.owed, collAmt: p.collAmt, sk: own.sk, blinding: opening.blinding };
2207
+ });
2208
+ }
2209
+ /**
2210
+ * A seizure leaves the lock's nonce one past the one it folded and `coll_note` as it was. `out` 0 pays
2211
+ * `seize - pf - kf` to the lender, 1 pays `avail - seize` to the borrower, each at `outputBlind(blind, out, nonce)`.
2212
+ * The split is recomputed from the `p_spot` the seizing call claimed (`io.readSeizure`).
2213
+ */
2214
+ async collectFromSeizure(loanId, out, open) {
2215
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2216
+ const pools = this.io.readPool ?? notSetUp("missing config: no pool reader");
2217
+ const seizure = this.io.readSeizure ?? notSetUp("missing config: no seizure reader");
2218
+ const readPrice = this.io.readPrice ?? notSetUp("missing config: no price reader");
2219
+ const loan = address(loanId, "loan id");
2220
+ const row = await read(loan);
2221
+ if (!row)
2222
+ unknownObject("no loan with this id");
2223
+ const json = row.json;
2224
+ if (Number(json.state) !== 4 && Number(json.state) !== 5)
2225
+ throw new EsseyError("INVALID_ARGUMENT", "the loan was not liquidated or defaulted");
2226
+ const { mode, pSpot } = await seizure(loan);
2227
+ const fault = mode === "fault";
2228
+ const [C, L] = this.pairOf(String(json.market_id));
2229
+ const seizeNonce = BigInt(json.coll.nonce) - 1n;
2230
+ const opened = await open(json, seizeNonce);
2231
+ const rates = {
2232
+ ltvBps: BigInt(json.ltv_bps),
2233
+ liqBps: BigInt(json.liq_bps),
2234
+ bonusBps: BigInt(json.bonus_bps),
2235
+ keeperLiqBps: BigInt(json.keeper_liq_bps),
2236
+ keeperDefaultBps: BigInt(json.keeper_default_bps),
2237
+ };
2238
+ const decimals = {
2239
+ cDec: BigInt(this.config.coins[C].decimals),
2240
+ lDec: BigInt(this.config.coins[L].decimals),
2241
+ };
2242
+ const split = seizeSplit({
2243
+ owed: fault ? 0n : opened.owed,
2244
+ avail: opened.collAmt,
2245
+ pSpot: fault ? 1n : pSpot,
2246
+ expo: (await readPrice(String(json.market_id))).expo,
2247
+ risk: loanRisk(rates, decimals, { liquidate: MODE.LIQUIDATE, default: MODE.DEFAULT, fault: MODE.FAULT }[mode]),
2248
+ fee: await this.feeParams(C),
2249
+ fault,
2250
+ });
2251
+ const value = out === 0 ? split.toLender : split.surplus;
2252
+ if (value === 0n)
2253
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the seizure left this side nothing");
2254
+ const note = { value, sk: opened.sk, blinding: outputBlind(opened.blinding, out, seizeNonce) };
2255
+ const commitment = noteCommitment(note.value, notePk(note.sk), note.blinding);
2256
+ const events = await pools(C);
2257
+ const leaf = events.commitments.find((c) => BigInt(c.commitment) === commitment);
2258
+ if (!leaf)
2259
+ unknownObject("no seized note of this side is in the pool: another offer won, or the loan was topped up");
2260
+ return this.claimLeaf(C, events, { ...note, index: Number(leaf.index) });
2261
+ }
2262
+ /** The seed index whose key is `pk`: the borrower key of a loan this seed opened. */
2263
+ indexOfPk(seed, pk) {
2264
+ const n = readState(this.statePath).notes ?? 0;
2265
+ for (let i = n - 1; i >= 0; i--)
2266
+ if (notePk(deriveNoteKey(seed, i).sk) === pk)
2267
+ return i;
2268
+ return unknownObject("this seed holds no key for the loan's borrower");
2269
+ }
2270
+ /**
2271
+ * Health RELEASE (`liquidation::release`): out0 pays the whole collateral to the borrower key with blinding
2272
+ * `outputBlind(collBlind, 0, nonce)`, sealed at that key's index so the scan finds it. No pass: the proof opens the lock.
2273
+ */
2274
+ async releaseCollateral(loanId, terms, borrowerPk, collAmt) {
2275
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2276
+ const loan = address(loanId, "loan id");
2277
+ const row = await read(loan);
2278
+ if (!row)
2279
+ unknownObject("no loan with this id");
2280
+ const json = row.json;
2281
+ if (Number(json.state) !== 3)
2282
+ throw new EsseyError("INVALID_ARGUMENT", "the loan is not repaid");
2283
+ if (termsCommit(terms, borrowerPk) !== BigInt(json.terms_commit))
2284
+ throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
2285
+ const [C, L] = this.pairOf(json.market_id);
2286
+ const poolC = address(json.pool_c, "pool_c");
2287
+ const market = address(json.market_id, "market");
2288
+ const seed = this.seed();
2289
+ const { opening, index } = this.ownOpening(seed, json, borrowerPk, collAmt);
2290
+ const nonce = opening.nonce;
2291
+ const fee = await this.feeParams(C);
2292
+ const rates = {
2293
+ ltvBps: BigInt(json.ltv_bps),
2294
+ liqBps: BigInt(json.liq_bps),
2295
+ bonusBps: BigInt(json.bonus_bps),
2296
+ keeperLiqBps: BigInt(json.keeper_liq_bps),
2297
+ keeperDefaultBps: BigInt(json.keeper_default_bps),
2298
+ };
2299
+ const decimals = {
2300
+ cDec: BigInt(this.config.coins[C].decimals),
2301
+ lDec: BigInt(this.config.coins[L].decimals),
2302
+ };
2303
+ const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2304
+ const encs = [
2305
+ bytesOf(sealOpening({ value: collAmt, blinding: outputBlind(opening.blinding, 0, nonce), index }, noteEncKey(seed).encPub)),
2306
+ bytesOf(fillerEnc()),
2307
+ ];
2308
+ const h = await health({
2309
+ mode: MODE.RELEASE,
2310
+ opening,
2311
+ risk: loanRisk(rates, decimals, MODE.RELEASE),
2312
+ price: { spot: 0n, ema: 0n, expo: 0n },
2313
+ timeS: 0n,
2314
+ extHash: releaseExt({ loan, poolC, market }, encs),
2315
+ fee,
2316
+ eph: drawEph(),
2317
+ terms,
2318
+ });
2319
+ const proved = await this.prover().prove("health", h.input);
2320
+ return this.relayed(releaseBody({
2321
+ pool: C,
2322
+ loan,
2323
+ market,
2324
+ proved: { proof: proved.proof, publicSignals: h.publics.map(String) },
2325
+ statement: h.statement,
2326
+ wait: true,
2327
+ encs,
2328
+ }));
2329
+ }
2330
+ /** The seed index a loan this seed opened derives from: its loan key is `Poseidon(sk, blinding, 1)` of that index. */
2331
+ indexOfLoanKey(seed, loanKey) {
2332
+ const n = readState(this.statePath).notes ?? 0;
2333
+ for (let i = n - 1; i >= 0; i--) {
2334
+ const k = deriveNoteKey(seed, i);
2335
+ if (poseidonHash([k.sk, k.blinding, 1n]) === loanKey)
2336
+ return i;
2337
+ }
2338
+ return unknownObject("this seed did not open the loan");
2339
+ }
2340
+ async cancelOwn(loanId) {
2341
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2342
+ const loan = address(loanId, "loan id");
2343
+ const row = await read(loan);
2344
+ if (!row)
2345
+ unknownObject("no loan with this id");
2346
+ const json = row.json;
2347
+ const loanKey = BigInt(json.loan_key);
2348
+ this.indexOfLoanKey(this.seed(), loanKey);
2349
+ const { member, credential } = readState(this.statePath);
2350
+ const n0 = actionHash(blake2b256, loanKey, BigInt(json.nonce), "cancel", new Uint8Array());
2351
+ const pass = membership({
2352
+ secrets: member,
2353
+ credential: credential,
2354
+ domain: DOMAIN_SPEND,
2355
+ room: keyId(loanKey),
2356
+ bind: keyId(n0),
2357
+ });
2358
+ const proved = await this.prover().prove("membership", pass.input);
2359
+ return this.freeLoan(cancelLoan, {
2360
+ pool: this.pairOf(json.market_id)[1],
2361
+ loan,
2362
+ pass: {
2363
+ proved: { proof: proved.proof, publicSignals: pass.publics.map(String) },
2364
+ tag: pass.publics[0],
2365
+ expiryMs: credential.expiryMs,
2366
+ n0,
2367
+ },
2368
+ });
2369
+ }
2370
+ /** The borrower's pass over `kind` and its args, at the loan's next action nonce. */
2371
+ async borrowerPass(json, kind, args) {
2372
+ const loanKey = BigInt(json.loan_key);
2373
+ const { member, credential } = readState(this.statePath);
2374
+ if (!member || !credential)
2375
+ notSetUp("no credential: call credential.obtain first");
2376
+ const n0 = actionHash(blake2b256, loanKey, BigInt(json.nonce), kind, args);
2377
+ const pass = membership({
2378
+ secrets: member,
2379
+ credential: credential,
2380
+ domain: DOMAIN_SPEND,
2381
+ room: keyId(loanKey),
2382
+ bind: keyId(n0),
2383
+ });
2384
+ const proved = await this.prover().prove("membership", pass.input);
2385
+ return {
2386
+ proved: { proof: proved.proof, publicSignals: pass.publics.map(String) },
2387
+ tag: pass.publics[0],
2388
+ expiryMs: credential.expiryMs,
2389
+ n0,
2390
+ };
2391
+ }
2392
+ /**
2393
+ * `refi::open_refi`: the request of round r+1 over the lock as it stands, sealed under the loan's request key. The salt
2394
+ * derives from the lock's note index and the round, so the seed alone reopens it.
2395
+ */
2396
+ async openRefi(p) {
2397
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2398
+ const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2399
+ const loan = address(p.loan, "loan id");
2400
+ const row = await read(loan);
2401
+ if (!row)
2402
+ unknownObject("no loan with this id");
2403
+ const json = row.json;
2404
+ if (Number(json.state) !== 2)
2405
+ throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
2406
+ const [C, L] = this.pairOf(json.market_id);
2407
+ const poolL = address(json.pool_l, "pool_l");
2408
+ const market = address(json.market_id, "market");
2409
+ const seed = this.seed();
2410
+ const { opening, index } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
2411
+ const own = deriveNoteKey(seed, index);
2412
+ const round = BigInt(json.round) + 1n;
2413
+ const request = {
2414
+ principal: p.principal,
2415
+ maxRateBps: BigInt(p.maxRateBps),
2416
+ termMs: BigInt(p.termMs),
2417
+ salt: poseidonHash([own.sk, own.blinding, 2n, round]),
2418
+ };
2419
+ const reqCommit = requestCommit(request, p.borrowerPk, collNote(opening));
2420
+ const closeMs = BigInt((this.io.now ?? Date.now)() + p.offerWindowMs);
2421
+ const reqSealed = await seal({
2422
+ id: requestKeyId(opening.loanKey),
2423
+ data: requestPlaintext({
2424
+ ...request,
2425
+ borrowerPk: p.borrowerPk,
2426
+ collAmt: opening.amount,
2427
+ collBlind: opening.blinding,
2428
+ closeMs,
2429
+ market,
2430
+ coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
2431
+ }),
2432
+ });
2433
+ const pass = await this.borrowerPass(json, "refi", openRefiArgs({ loan, poolL, reqCommit, reqSealed, closeMs }));
2434
+ const landed = await this.freeLoan(refinanceLoan, { pool: L, loan, pass, reqCommit, reqSealed, closeMs });
2435
+ return { ...landed, round, closeMs };
2436
+ }
2437
+ /**
2438
+ * `refi::settle_refi`: the round's offers opened as `planSettle` opens them, the request read back through Seal, the
2439
+ * payoff to the old lender's enc key, and a pass bound to the exact reading the market's oracle builds.
2440
+ */
2441
+ async settleRefiOwn(p) {
2442
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2443
+ const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2444
+ const readReading = this.io.readReading ?? notSetUp("missing config: no reading reader");
2445
+ const update = this.io.priceUpdate ?? notSetUp("missing config: no price update source");
2446
+ const q = await this.readRequest(p.loan);
2447
+ const row = await read(q.loan);
2448
+ const json = row.json;
2449
+ if (termsCommit(p.terms, p.borrowerPk) !== BigInt(json.terms_commit))
2450
+ throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
2451
+ const round = row.round;
2452
+ const slots = [];
2453
+ for (const [i, o] of round.offers.entries()) {
2454
+ const sealed = Uint8Array.from(Buffer.from(o.sealed, "base64"));
2455
+ const open = o.active
2456
+ ? await this.openOffer(q.loan, q.loanKey, q.round, BigInt(i), sealed, q.pair)
2457
+ : undefined;
2458
+ slots.push({ commit: BigInt(o.commit), lock: BigInt(o.lock), active: o.active, open });
2459
+ }
2460
+ const [C, L] = q.pair;
2461
+ const market = address(json.market_id, "market");
2462
+ const seed = this.seed();
2463
+ const { opening } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
2464
+ const r = await readReading(market);
2465
+ const pClaim = r.spot < r.ema ? r.spot : r.ema;
2466
+ const rates = await this.rates(market);
2467
+ const ltvBps = BigInt(json.ltv_bps) < rates.current.ltvBps ? BigInt(json.ltv_bps) : rates.current.ltvBps;
2468
+ const fee = await this.feeParams(L);
2469
+ await this.keys();
2470
+ const noteIndex = this.reserve("notes");
2471
+ const mine = deriveNoteKey(seed, noteIndex);
2472
+ const padKey = deriveNoteKey(seed, this.reserve("notes"));
2473
+ const nowS = BigInt(Math.floor((this.io.now ?? Date.now)() / 1000));
2474
+ const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2475
+ const plan = (extHash) => loanRefi({
2476
+ slots,
2477
+ round: q.round,
2478
+ request: q,
2479
+ old: p.terms,
2480
+ price: {
2481
+ pClaim,
2482
+ expo: r.expo,
2483
+ cDec: BigInt(this.config.coins[C].decimals),
2484
+ lDec: BigInt(this.config.coins[L].decimals),
2485
+ ltvBps,
2486
+ },
2487
+ loanKey: q.loanKey,
2488
+ borrowerNote: { pk: notePk(mine.sk), blinding: mine.blinding },
2489
+ pad: { pk: notePk(padKey.sk), blinding: padKey.blinding },
2490
+ e: drawEph(),
2491
+ eP: drawEph(),
2492
+ nowS,
2493
+ extHash,
2494
+ fee,
2495
+ eph: drawEph(),
2496
+ });
2497
+ const draft = await plan(0n);
2498
+ const version = json.coll.keeper_ct == null ? 0n : BigInt(json.coll.keeper_ct_version) + 1n;
2499
+ const keeperCt = await seal({
2500
+ id: keeperKeyId(q.loanKey, version),
2501
+ data: encodeKeeperPayload({
2502
+ version: KEEPER_LAYOUT_VERSION,
2503
+ loanKey: q.loanKey,
2504
+ borrowerPk: p.borrowerPk,
2505
+ collAmt: opening.amount,
2506
+ collBlind: opening.blinding,
2507
+ nonceAtCt: opening.nonce,
2508
+ terms: draft.terms,
2509
+ }),
2510
+ });
2511
+ const encs = [
2512
+ bytesOf(sealOpening({ value: draft.borrowerValue, blinding: mine.blinding, index: noteIndex }, noteEncKey(seed).encPub)),
2513
+ bytesOf(fillerEnc()),
2514
+ ];
2515
+ const encsP = [bytesOf(fillerEnc()), bytesOf(fillerEnc())];
2516
+ const ext = loanExt(LOAN_REFI_KIND, q.loan, q.poolL, q.round, NO_ADDRESS, [...encs, ...encsP], blake2b256(keeperCt));
2517
+ const w = await plan(ext);
2518
+ if (w.termsCommit !== draft.termsCommit)
2519
+ throw new EsseyError("INVALID_ARGUMENT", "refused: the terms moved between drafts");
2520
+ const refiProof = await this.prover().prove("loan_refi", w.input);
2521
+ const args = settleRefiArgs({
2522
+ loan: q.loan,
2523
+ poolL: q.poolL,
2524
+ market,
2525
+ reading: readingBytes(r),
2526
+ proof: proofBytes(refiProof.proof),
2527
+ termsCommit: w.termsCommit,
2528
+ borrowerNote: w.borrowerNote,
2529
+ feeNote: w.feeNote,
2530
+ winNull: w.winNull,
2531
+ d: w.d,
2532
+ ephX: w.ephX,
2533
+ ephY: w.ephY,
2534
+ feeCt: w.feeCt,
2535
+ payoffNote: w.payoffNote,
2536
+ pad: w.pad,
2537
+ ephP: w.ephP,
2538
+ pClaim,
2539
+ keeperCt,
2540
+ encs,
2541
+ encsP,
2542
+ nowS,
2543
+ });
2544
+ const pass = await this.borrowerPass(json, "settle_refi", args);
2545
+ const landed = await this.freeLoan(settleRefiLoan, {
2546
+ pool: L,
2547
+ loan: q.loan,
2548
+ market,
2549
+ pass,
2550
+ refi: { proof: refiProof.proof, publicSignals: w.publics.map(String) },
2551
+ termsCommit: w.termsCommit,
2552
+ borrowerNote: w.borrowerNote,
2553
+ feeNote: w.feeNote,
2554
+ winNull: w.winNull,
2555
+ d: w.d,
2556
+ ephX: w.ephX,
2557
+ ephY: w.ephY,
2558
+ feeCt: w.feeCt,
2559
+ payoffNote: w.payoffNote,
2560
+ pad: w.pad,
2561
+ ephP: w.ephP,
2562
+ pClaim,
2563
+ keeperCt,
2564
+ encs,
2565
+ encsP,
2566
+ nowS,
2567
+ priceUpdate: await update(market),
2568
+ });
2569
+ return { ...landed, rateBps: w.terms.rateBps, terms: w.terms };
2570
+ }
2571
+ async cancelRefiOwn(id) {
2572
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2573
+ const loan = address(id, "loan id");
2574
+ const row = await read(loan);
2575
+ if (!row)
2576
+ unknownObject("no loan with this id");
2577
+ const json = row.json;
2578
+ this.indexOfLoanKey(this.seed(), BigInt(json.loan_key));
2579
+ const poolL = address(json.pool_l, "pool_l");
2580
+ const pass = await this.borrowerPass(json, "cancel_refi", cancelRefiArgs(loan, poolL));
2581
+ return this.freeLoan(cancelRefiLoan, { pool: this.pairOf(json.market_id)[1], loan, pass });
2582
+ }
2583
+ /** `reclaim_coll::reclaim_coll` on a CANCELLED loan: the lock's nullifier, the whole collateral to a fresh own note. */
2584
+ async reclaimOwnCollateral(loanId, collAmt) {
2585
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2586
+ const loan = address(loanId, "loan id");
2587
+ const row = await read(loan);
2588
+ if (!row)
2589
+ unknownObject("no loan with this id");
2590
+ const json = row.json;
2591
+ const loanKey = BigInt(json.loan_key);
2592
+ const C = this.pairOf(json.market_id)[0];
2593
+ const seed = this.seed();
2594
+ const own = deriveNoteKey(seed, this.indexOfLoanKey(seed, loanKey));
2595
+ const opening = { loanKey, borrowerPk: notePk(own.sk), amount: collAmt, blinding: own.blinding };
2596
+ if (collNote(opening) !== BigInt(json.coll.coll_note))
2597
+ throw new EsseyError("CT_MISMATCH", "refused: the amount does not open the locked note");
2598
+ const fee = await this.feeParams(C);
2599
+ await this.keys();
2600
+ const outIndex = this.reserve("notes");
2601
+ const out = deriveNoteKey(seed, outIndex);
2602
+ const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2603
+ const plan = (encs) => reclaimColl({
2604
+ loanKey,
2605
+ collAmt,
2606
+ borrowerSk: own.sk,
2607
+ collBlind: own.blinding,
2608
+ out: { pk: notePk(out.sk), blinding: out.blinding },
2609
+ encs,
2610
+ fee,
2611
+ eph,
2612
+ });
2613
+ const eph = drawEph();
2614
+ const draft = await plan([new Uint8Array(128), new Uint8Array(128)]);
2615
+ const encs = [
2616
+ bytesOf(sealOpening({ value: draft.outAmt, blinding: out.blinding, index: outIndex }, noteEncKey(seed).encPub)),
2617
+ bytesOf(fillerEnc()),
2618
+ ];
2619
+ const w = await plan(encs);
2620
+ const proved = await this.prover().prove("reclaim_coll", w.input);
2621
+ return this.freeLoan(reclaimCollLoan, {
2622
+ pool: C,
2623
+ loan,
2624
+ proved: { proof: proved.proof, publicSignals: w.publics.map(String) },
2625
+ nullifier: w.n,
2626
+ outNote: w.outNote,
2627
+ feeNote: w.feeNote,
2628
+ ephX: w.ephX,
2629
+ ephY: w.ephY,
2630
+ feeCt: w.feeCt,
2631
+ encOut: encs[0],
2632
+ encFee: encs[1],
2633
+ });
2634
+ }
2635
+ /** `reclaim::reclaim`: the lender's Lock4 among the round's resolved locks, refunded to a fresh own note. */
2636
+ async reclaimOffer(loanId, offer, roundArg) {
2637
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2638
+ const loan = address(loanId, "loan id");
2639
+ const row = await read(loan);
2640
+ if (!row)
2641
+ unknownObject("no loan with this id");
2642
+ const json = row.json;
2643
+ const round = roundArg ?? BigInt(json.round);
2644
+ if (round !== BigInt(json.round))
2645
+ notSetUp("this reader returns the current round only");
2646
+ const offers = row.round.offers;
2647
+ const L = this.pairOf(json.market_id)[1];
2648
+ const loanKey = BigInt(json.loan_key);
2649
+ const seed = this.seed();
2650
+ const own = deriveNoteKey(seed, offer.noteIndex);
2651
+ const field = lockField(loanKey, round);
2652
+ const ns = poseidonHash([own.sk, own.blinding, 3n]);
2653
+ const b = poseidonHash([own.sk, own.blinding, 4n]);
2654
+ const mine = lock4(field, notePk(own.sk), ns, offer.principal, b);
2655
+ const locks = offers.map((o) => BigInt(o.lock));
2656
+ const slot = locks.indexOf(mine);
2657
+ if (slot < 0)
2658
+ unknownObject("the record's lock is not in this round");
2659
+ const relayer = this.relayerAddress();
2660
+ const relayerFee = this.coinFee(L);
2661
+ const fee = await this.feeParams(L);
2662
+ await this.keys();
2663
+ const outIndex = this.reserve("notes");
2664
+ const out = deriveNoteKey(seed, outIndex);
2665
+ const eph = drawEph();
2666
+ const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2667
+ const plan = (encs) => reclaimLock({
2668
+ locks,
2669
+ slot,
2670
+ field,
2671
+ amount: offer.principal,
2672
+ ownerSk: own.sk,
2673
+ ns,
2674
+ b,
2675
+ out: { pk: notePk(out.sk), blinding: out.blinding },
2676
+ relayer,
2677
+ relayerFee,
2678
+ encs,
2679
+ fee,
2680
+ eph,
2681
+ });
2682
+ const draft = await plan([new Uint8Array(128), new Uint8Array(128)]);
2683
+ const encs = [
2684
+ bytesOf(sealOpening({ value: draft.outAmt, blinding: out.blinding, index: outIndex }, noteEncKey(seed).encPub)),
2685
+ bytesOf(fillerEnc()),
2686
+ ];
2687
+ const w = await plan(encs);
2688
+ const proved = await this.prover().prove("reclaim", w.input);
2689
+ return this.paidLoan(reclaimLoan, {
2690
+ pool: L,
2691
+ loan,
2692
+ proved: { proof: proved.proof, publicSignals: w.publics.map(String) },
2693
+ round,
2694
+ nullifier: w.n,
2695
+ refund: w.outNote,
2696
+ feeCommit: w.feeCommit,
2697
+ ephX: w.ephX,
2698
+ ephY: w.ephY,
2699
+ feeCt: w.feeCt,
2700
+ feeNote: w.feeNote,
2701
+ encRefund: encs[0],
2702
+ encFee: encs[1],
2703
+ });
2704
+ }
2705
+ /**
2706
+ * The lock as it stands: the open blinding at nonce 1, rolled one re-lock per heartbeat (`rollTo` refuses an opening
2707
+ * that does not reach the stored `coll_note`).
2708
+ */
2709
+ ownOpening(seed, json, borrowerPk, collAmt) {
2710
+ const index = this.indexOfPk(seed, borrowerPk);
2711
+ const own = deriveNoteKey(seed, index);
2712
+ const start = {
2713
+ loanKey: BigInt(json.loan_key),
2714
+ borrowerPk,
2715
+ amount: collAmt,
2716
+ blinding: own.blinding,
2717
+ nonce: 1n,
2718
+ };
2719
+ return { opening: rollTo(start, BigInt(json.coll.coll_note), BigInt(json.coll.nonce)), index };
2720
+ }
2721
+ async heartbeatOwn(p) {
2722
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2723
+ const readPrice = this.io.readPrice ?? notSetUp("missing config: no price reader");
2724
+ const update = this.io.priceUpdate ?? notSetUp("missing config: no price update source");
2725
+ const loan = address(p.loan, "loan id");
2726
+ const row = await read(loan);
2727
+ if (!row)
2728
+ unknownObject("no loan with this id");
2729
+ const json = row.json;
2730
+ if (Number(json.state) !== 2)
2731
+ throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
2732
+ if (termsCommit(p.terms, p.borrowerPk) !== BigInt(json.terms_commit))
2733
+ throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
2734
+ const [C, L] = this.pairOf(json.market_id);
2735
+ const poolC = address(json.pool_c, "pool_c");
2736
+ const market = address(json.market_id, "market");
2737
+ const { opening } = this.ownOpening(this.seed(), json, p.borrowerPk, p.collAmt);
2738
+ const k = p.k ?? 1;
2739
+ const expiryMs = p.expiryMs ?? BigInt((this.io.now ?? Date.now)() + 3_600_000);
2740
+ const reading = await readPrice(market);
2741
+ const floor = heartbeatFloor(reading, k);
2742
+ const fee = await this.feeParams(C);
2743
+ const rates = {
2744
+ ltvBps: BigInt(json.ltv_bps),
2745
+ liqBps: BigInt(json.liq_bps),
2746
+ bonusBps: BigInt(json.bonus_bps),
2747
+ keeperLiqBps: BigInt(json.keeper_liq_bps),
2748
+ keeperDefaultBps: BigInt(json.keeper_default_bps),
2749
+ };
2750
+ const decimals = {
2751
+ cDec: BigInt(this.config.coins[C].decimals),
2752
+ lDec: BigInt(this.config.coins[L].decimals),
2753
+ };
2754
+ const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2755
+ const encs = [bytesOf(fillerEnc()), bytesOf(fillerEnc())];
2756
+ const h = await health({
2757
+ mode: MODE.HEARTBEAT,
2758
+ opening,
2759
+ risk: loanRisk(rates, decimals, MODE.HEARTBEAT),
2760
+ price: { spot: floor, ema: floor, expo: reading.expo },
2761
+ timeS: expiryMs / 1000n,
2762
+ extHash: heartbeatExt({ loan, poolC, market }, encs),
2763
+ fee,
2764
+ eph: drawEph(),
2765
+ terms: p.terms,
2766
+ });
2767
+ const proved = await this.prover().prove("health", h.input);
2768
+ return this.relayed(heartbeatBody({
2769
+ pool: C,
2770
+ loan,
2771
+ market,
2772
+ proved: { proof: proved.proof, publicSignals: h.publics.map(String) },
2773
+ statement: h.statement,
2774
+ wait: true,
2775
+ encs,
2776
+ k,
2777
+ expiryMs,
2778
+ priceUpdate: await update(market),
2779
+ }));
2780
+ }
2781
+ /**
2782
+ * TOPUP (`liquidation::topup`, no pass): a CollLock spend of own collateral-coin notes into `add_note` under the
2783
+ * loan's lock key, then Health TOPUP re-locks the stored lock and `add_note` into one note. The new keeper
2784
+ * ciphertext opens that note at the next nonce.
2785
+ */
2786
+ async topupOwn(p) {
2787
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
2788
+ const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
2789
+ const loan = address(p.loan, "loan id");
2790
+ const row = await read(loan);
2791
+ if (!row)
2792
+ unknownObject("no loan with this id");
2793
+ const json = row.json;
2794
+ if (Number(json.state) !== 2)
2795
+ throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
2796
+ if (termsCommit(p.terms, p.borrowerPk) !== BigInt(json.terms_commit))
2797
+ throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
2798
+ const [C, L] = this.pairOf(json.market_id);
2799
+ const ids = { loan, poolC: address(json.pool_c, "pool_c"), market: address(json.market_id, "market") };
2800
+ const fee = await this.feeParams(C);
2801
+ const { events, owned, seed } = await this.owned(C);
2802
+ const { opening } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
2803
+ const inputs = pickInputs(owned, p.add);
2804
+ const tree = poolTree(orderedLeaves(events));
2805
+ const ins = inputs.map((n) => ({
2806
+ amount: n.value,
2807
+ sk: n.sk,
2808
+ blinding: n.blinding,
2809
+ pathIndex: BigInt(n.index),
2810
+ pathElements: tree.path(n.index),
2811
+ }));
2812
+ await this.keys();
2813
+ const addKey = deriveNoteKey(seed, this.reserve("notes"));
2814
+ const changeIndex = this.reserve("notes");
2815
+ const change = deriveNoteKey(seed, changeIndex);
2816
+ const lock = await collLock({
2817
+ root: tree.root,
2818
+ ins: [ins[0], ins[1] ?? dummyInput()],
2819
+ lock: { amount: p.add, pk: collLockPk(opening.loanKey, p.borrowerPk), blinding: addKey.blinding },
2820
+ change: { pk: notePk(change.sk), blinding: change.blinding },
2821
+ relayerFee: 0n,
2822
+ loanKey: opening.loanKey,
2823
+ extHash: collLockExt(MODE_TOPUP, ids.loan, ids.poolC, ids.market),
2824
+ fee,
2825
+ eph: drawEph(),
2826
+ });
2827
+ const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
2828
+ const encChange = bytesOf(sealOpening({ value: lock.changeAmount, blinding: change.blinding, index: changeIndex }, noteEncKey(seed).encPub));
2829
+ const encFee = bytesOf(fillerEnc());
2830
+ const version = json.coll.keeper_ct == null ? 0n : BigInt(json.coll.keeper_ct_version) + 1n;
2831
+ const keeperCt = await seal({
2832
+ id: keeperKeyId(opening.loanKey, version),
2833
+ data: encodeKeeperPayload({
2834
+ version: KEEPER_LAYOUT_VERSION,
2835
+ loanKey: opening.loanKey,
2836
+ borrowerPk: p.borrowerPk,
2837
+ collAmt: p.collAmt + p.add,
2838
+ collBlind: outputBlind(opening.blinding, 0, opening.nonce),
2839
+ nonceAtCt: opening.nonce + 1n,
2840
+ terms: p.terms,
2841
+ }),
2842
+ });
2843
+ const encs = [bytesOf(fillerEnc()), bytesOf(fillerEnc())];
2844
+ const decimals = {
2845
+ cDec: BigInt(this.config.coins[C].decimals),
2846
+ lDec: BigInt(this.config.coins[L].decimals),
2847
+ };
2848
+ const rates = {
2849
+ ltvBps: BigInt(json.ltv_bps),
2850
+ liqBps: BigInt(json.liq_bps),
2851
+ bonusBps: BigInt(json.bonus_bps),
2852
+ keeperLiqBps: BigInt(json.keeper_liq_bps),
2853
+ keeperDefaultBps: BigInt(json.keeper_default_bps),
2854
+ };
2855
+ const h = await health({
2856
+ mode: MODE.TOPUP,
2857
+ opening,
2858
+ risk: loanRisk(rates, decimals, MODE.TOPUP),
2859
+ price: { spot: 0n, ema: 0n, expo: 0n },
2860
+ timeS: 0n,
2861
+ extHash: (p.asBorrower ? topupByBorrowerExt : topupExt)(ids, keeperCt, encChange, encFee, encs),
2862
+ fee,
2863
+ eph: drawEph(),
2864
+ terms: p.terms,
2865
+ add: { amount: p.add, blinding: addKey.blinding, ephL: drawEph() },
2866
+ });
2867
+ const prover = this.prover();
2868
+ const [lockProof, healthProof] = [
2869
+ await prover.prove("coll_lock", lock.input),
2870
+ await prover.prove("health", h.input),
2871
+ ];
2872
+ const body = {
2873
+ pool: C,
2874
+ loan,
2875
+ market: ids.market,
2876
+ proved: { proof: healthProof.proof, publicSignals: h.publics.map(String) },
2877
+ statement: h.statement,
2878
+ wait: true,
2879
+ lock: lock.spend,
2880
+ lockProved: { proof: lockProof.proof, publicSignals: lock.publics.map(String) },
2881
+ lockEncs: [encChange, encFee],
2882
+ keeperCt,
2883
+ encs,
2884
+ };
2885
+ if (!p.asBorrower)
2886
+ return this.relayed(topupBody(body));
2887
+ const s = lock.spend;
2888
+ const args = topupArgs({
2889
+ ...ids,
2890
+ lockProof: proofBytes(lockProof.proof),
2891
+ fields: [s.root, s.n0, s.n1, s.note, s.change, s.feeNote, s.ephX, s.ephY, s.feeCt],
2892
+ encChange,
2893
+ encFee,
2894
+ keeperCt,
2895
+ proof: proofBytes(healthProof.proof),
2896
+ outs: h.statement.outs,
2897
+ delivery: h.statement.delivery,
2898
+ encs,
2899
+ });
2900
+ return this.relayed(topupBorrowerBody({ ...body, pass: await this.borrowerPass(json, "topup", args) }));
2901
+ }
2902
+ /**
2903
+ * LIQUIDATE (`liquidation::liquidate`) by whoever holds the opening and terms: what a keeper reads out of the keeper
2904
+ * ciphertext. Claims are the reading itself, inside the 0.5% up window. Outs: lender, borrower remainder, keeper
2905
+ * fee to a fresh own note; ciphertexts in insert order `[lender, fee, borrower, keeper]`.
2906
+ */
2907
+ borrowerSeize(p, mode) {
2908
+ return this.seize(p.loan, mode, async (json, seed) => ({
2909
+ terms: p.terms,
2910
+ borrowerPk: p.borrowerPk,
2911
+ opening: this.ownOpening(seed, json, p.borrowerPk, p.collAmt).opening,
2912
+ }));
2913
+ }
2914
+ /**
2915
+ * B §7.5 FAULT, the lender: the terms rebuild from its offer keys, the settle `now_s` and the request's borrower key
2916
+ * (`settle-plan.ts` terms), and the lock opens from the settle delivery rolled to the lock's nonce.
2917
+ */
2918
+ faultLiquidate(loanId, offer) {
2919
+ const settleTime = this.io.readSettleTime ?? notSetUp("missing config: no settle time reader");
2920
+ const borrowerPk = offer.borrowerPk ?? notSetUp("the offer record holds no borrower key");
2921
+ return this.seize(loanId, MODE.FAULT, async (json, seed, loan) => {
2922
+ if (!json.coll?.faulted)
2923
+ throw new EsseyError("INVALID_ARGUMENT", "the loan is not marked FAULT");
2924
+ const own = deriveNoteKey(seed, offer.noteIndex);
2925
+ const enc = await treasuryPoint(poseidonHash([own.sk, own.blinding, 6n]) >> 2n);
2926
+ const loanKey = BigInt(json.loan_key);
2927
+ const term = interest(offer.principal, offer.rateBps, offer.termMs);
2928
+ const terms = {
2929
+ principal: offer.principal,
2930
+ rateBps: offer.rateBps,
2931
+ owed: term.owed,
2932
+ maturityS: (await settleTime(loan)) + term.qTerm,
2933
+ lenderPk: notePk(own.sk),
2934
+ lenderEncX: enc.tx,
2935
+ lenderEncY: enc.ty,
2936
+ salt: poseidonHash([DOM_TSALT, lockField(loanKey, 0n), poseidonHash([own.sk, own.blinding, 3n])]),
2937
+ };
2938
+ const start = { loanKey, borrowerPk, ...(await this.lenderLock(json, own)), nonce: 1n };
2939
+ return {
2940
+ terms,
2941
+ borrowerPk,
2942
+ opening: rollTo(start, BigInt(json.coll.coll_note), BigInt(json.coll.nonce)),
2943
+ };
2944
+ });
2945
+ }
2946
+ /** The keeper reads the current keeper ciphertext under its pass or badge, rolls the opening to the lock's nonce and seizes. */
2947
+ keeperLiquidate(loanId, via) {
2948
+ return this.seize(loanId, MODE.LIQUIDATE, (json, _seed, loan) => this.keeperOpening(json, loan, via));
2949
+ }
2950
+ /** Any read that does not open the lock and the terms commit throws CT_MISMATCH. */
2951
+ async keeperOpening(json, loan, via) {
2952
+ const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
2953
+ const readCt = this.io.readKeeperCt ?? notSetUp("missing config: no keeper ciphertext reader");
2954
+ const loanKey = BigInt(json.loan_key);
2955
+ const version = BigInt(json.coll.keeper_ct_version);
2956
+ const { approve, signer } = await this.keeperApproval(json, loan, keeperKeyId(loanKey, version), via);
2957
+ const sealed = { loan, loanKey, keeperCt: await readCt(loan), keeperCtVersion: version };
2958
+ const payload = await fetchKeeperPlaintext(sealed, {
2959
+ decrypt: (r) => decrypt({ sealed: r.sealed, approve, signer }),
2960
+ });
2961
+ if (!payload.terms)
2962
+ throw new EsseyError("CT_MISMATCH", "refused: the keeper plaintext carries no terms");
2963
+ if (termsCommit(payload.terms, payload.borrowerPk) !== BigInt(json.terms_commit))
2964
+ throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
2965
+ const opening = rollTo(openingOf(payload), BigInt(json.coll.coll_note), BigInt(json.coll.nonce));
2966
+ return { terms: payload.terms, borrowerPk: payload.borrowerPk, opening };
2967
+ }
2968
+ /**
2969
+ * A keeper's read of an uncovered loan, sending nothing: LIQUIDATE when the opening is over the line at both prices
2970
+ * (`health.circom:282-283`, the check `health()` refuses HEALTH_NOT_UNDERWATER on), FAULT when a read that does not
2971
+ * open is of the retained borrower ciphertext, which `prove_ct_fault` judges (`keeper.move:203-243`).
2972
+ */
2973
+ async judge(loanId, via) {
2974
+ const readPrice = this.io.readPrice ?? notSetUp("missing config: no price reader");
2975
+ const { loan, json } = await this.activeLoan(loanId);
2976
+ let opened;
2977
+ try {
2978
+ opened = await this.keeperOpening(json, loan, via);
2979
+ }
2980
+ catch (err) {
2981
+ if (!isEsseyError(err, "CT_MISMATCH"))
2982
+ throw err;
2983
+ const retained = json.coll.borrower_ct;
2984
+ const own = !!retained && BigInt(retained.version) === BigInt(json.coll.keeper_ct_version);
2985
+ return own ? { action: "fault" } : { action: "skip", reason: "third-party-ct" };
2986
+ }
2987
+ const [C, L] = this.pairOf(json.market_id);
2988
+ const line = {
2989
+ cDec: BigInt(this.config.coins[C].decimals),
2990
+ lDec: BigInt(this.config.coins[L].decimals),
2991
+ liqBps: BigInt(json.liq_bps),
2992
+ };
2993
+ const reading = await readPrice(address(json.market_id, "market"));
2994
+ const { underwater } = localHealth(opened.opening.amount, opened.terms.owed, line, reading);
2995
+ return underwater ? { action: "liquidate" } : { action: "skip", reason: "healthy" };
2996
+ }
2997
+ /** A seizure by whoever holds the opening and the terms; its keeper fee is sealed to this seed. */
2998
+ async seize(loanId, mode, open) {
2999
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
3000
+ const readPrice = this.io.readPrice ?? notSetUp("missing config: no price reader");
3001
+ const update = this.io.priceUpdate ?? notSetUp("missing config: no price update source");
3002
+ const loan = address(loanId, "loan id");
3003
+ const row = await read(loan);
3004
+ if (!row)
3005
+ unknownObject("no loan with this id");
3006
+ const json = row.json;
3007
+ if (Number(json.state) !== 2 && Number(json.state) !== 8)
3008
+ throw new EsseyError("INVALID_ARGUMENT", "the loan is not seizable");
3009
+ const seed = this.seed();
3010
+ const { terms, borrowerPk, opening } = await open(json, seed, loan);
3011
+ if (termsCommit(terms, borrowerPk) !== BigInt(json.terms_commit))
3012
+ throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
3013
+ const [C, L] = this.pairOf(json.market_id);
3014
+ const poolC = address(json.pool_c, "pool_c");
3015
+ const market = address(json.market_id, "market");
3016
+ const reading = await readPrice(market);
3017
+ const asDefault = mode === MODE.DEFAULT;
3018
+ const nowS = asDefault ? BigInt(Math.floor((this.io.now ?? Date.now)() / 1000)) : 0n;
3019
+ const fee = await this.feeParams(C);
3020
+ await this.keys();
3021
+ const keeperIndex = this.reserve("notes");
3022
+ const keeper = deriveNoteKey(seed, keeperIndex);
3023
+ const rates = {
3024
+ ltvBps: BigInt(json.ltv_bps),
3025
+ liqBps: BigInt(json.liq_bps),
3026
+ bonusBps: BigInt(json.bonus_bps),
3027
+ keeperLiqBps: BigInt(json.keeper_liq_bps),
3028
+ keeperDefaultBps: BigInt(json.keeper_default_bps),
3029
+ };
3030
+ const decimals = {
3031
+ cDec: BigInt(this.config.coins[C].decimals),
3032
+ lDec: BigInt(this.config.coins[L].decimals),
3033
+ };
3034
+ const bytesOf = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
3035
+ const common = {
3036
+ mode,
3037
+ opening,
3038
+ risk: loanRisk(rates, decimals, mode),
3039
+ price: reading,
3040
+ timeS: nowS,
3041
+ fee,
3042
+ eph: drawEph(),
3043
+ terms,
3044
+ keeper: { pk: notePk(keeper.sk), blinding: keeper.blinding },
3045
+ };
3046
+ const draft = await health({ ...common, extHash: 0n });
3047
+ const encs = [
3048
+ bytesOf(fillerEnc()),
3049
+ bytesOf(fillerEnc()),
3050
+ bytesOf(fillerEnc()),
3051
+ bytesOf(sealOpening({ value: draft.notes[2].amount, blinding: keeper.blinding, index: keeperIndex }, noteEncKey(seed).encPub)),
3052
+ ];
3053
+ const extOf = { [MODE.LIQUIDATE]: liquidateExt, [MODE.DEFAULT]: defaultExt, [MODE.FAULT]: faultExt }[mode];
3054
+ const h = await health({ ...common, extHash: extOf({ loan, poolC, market }, encs) });
3055
+ const proved = await this.prover().prove("health", h.input);
3056
+ const seize = {
3057
+ pool: C,
3058
+ loan,
3059
+ market,
3060
+ proved: { proof: proved.proof, publicSignals: h.publics.map(String) },
3061
+ statement: h.statement,
3062
+ wait: true,
3063
+ encs,
3064
+ pSpot: reading.spot,
3065
+ pEma: reading.ema,
3066
+ priceUpdate: await update(market),
3067
+ };
3068
+ if (asDefault)
3069
+ return this.relayed(claimDefaultBody({ ...seize, nowS }));
3070
+ return this.relayed(mode === MODE.FAULT ? faultLiquidateBody(seize) : liquidateBody(seize));
3071
+ }
3072
+ /** D-SPEC §6.2:589. */
3073
+ async listLoans() {
3074
+ const read = this.io.readLoans ?? notSetUp("missing config: no loan reader");
3075
+ const out = [];
3076
+ let cursor = null;
3077
+ let pages = 0;
3078
+ for (;;) {
3079
+ const page = await read(cursor);
3080
+ pages += 1;
3081
+ for (const row of page.loans)
3082
+ out.push(summarizeLoan(this.config, row));
3083
+ cursor = afterPage(page.next, pages);
3084
+ if (cursor === null)
3085
+ break;
3086
+ }
3087
+ return out;
3088
+ }
3089
+ /** D-SPEC §6.2:589. */
3090
+ async viewLoan(id) {
3091
+ const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
3092
+ const key = address(id, "loan id");
3093
+ const row = await read(key);
3094
+ if (!row)
3095
+ unknownObject("no loan with this id");
3096
+ const price = this.io.readPrice ?? notSetUp("missing config: no price reader");
3097
+ const fields = row.json;
3098
+ if (fields === null || typeof fields !== "object" || Array.isArray(fields))
3099
+ return viewLoanObject(this.config, { id: key, json: row.json, round: row.round }, {
3100
+ reading: { spot: 0n, ema: 0n, expo: 0n },
3101
+ nowMs: 0n,
3102
+ opening: null,
3103
+ });
3104
+ const reading = await price(address(String(fields.market_id ?? ""), "market"));
3105
+ const opening = this.io.loanOpening ? await this.io.loanOpening(key) : null;
3106
+ return viewLoanObject(this.config, { id: key, json: row.json, round: row.round }, {
3107
+ reading,
3108
+ nowMs: BigInt((this.io.now ?? Date.now)()),
3109
+ opening,
3110
+ });
3111
+ }
3112
+ /** The seller keys and bounds salt of the sale opened at note index `index`, so the seed alone reopens them. */
3113
+ saleOpening(seed, index) {
3114
+ const own = deriveNoteKey(seed, index);
3115
+ const tagged = (t) => poseidonHash([own.sk, own.blinding, t]);
3116
+ return { sellerSk: own.sk, sellerSecret: tagged(7n), boundsSalt: tagged(8n) };
3117
+ }
3118
+ /** D-SPEC §6.2:599. The seller pass over `sale_room::open_args`, at action nonce 0; the relayer or the callback pays. */
3119
+ async openSale(p) {
3120
+ const open = assertSaleOpen(p);
3121
+ requireSale(this.config);
3122
+ const pool = poolId(this.config, open.coin);
3123
+ const submit = (open.sponsored ?? this.sponsoring() !== null)
3124
+ ? this.saleSponsor(pool)
3125
+ : (this.io.submitSaleOpen ?? notSetUp("missing config: sale open has no submitter"));
3126
+ const read = this.io.readRoom ?? notSetUp("missing config: no room reader");
3127
+ const item = { id: address(open.itemId, "itemId"), type: open.itemType };
3128
+ const closeMs = BigInt(open.closeMs);
3129
+ const finishByMs = closeMs + BigInt(open.finishWindowMs);
3130
+ const typeName = asInvalid(() => {
3131
+ assertFinishWindow(closeMs, finishByMs);
3132
+ return typeNameOf(open.itemType);
3133
+ });
3134
+ const shape = { pool, item: { id: item.id, typeName }, closeMs, finishByMs, maxBids: open.maxBids };
3135
+ const { secrets, credential } = this.member();
3136
+ const prover = this.prover();
3137
+ const seed = await this.keys();
3138
+ const noteIndex = this.reserve("notes");
3139
+ const { boundsSalt, ...seller } = this.saleOpening(seed, noteIndex);
3140
+ const bounds = { lo: open.minPrice, hi: open.maxPrice, salt: boundsSalt };
3141
+ const commits = openCommits({ ...seller, boundsSalt }, bounds);
3142
+ const saleKey = drawSecret();
3143
+ const n0 = actionHash(blake2b256, saleKey, 0n, "open", openArgs({ ...shape, ...commits, saleKey }));
3144
+ const pass = membership({
3145
+ secrets,
3146
+ credential,
3147
+ domain: DOMAIN_SPEND,
3148
+ room: keyId(saleKey),
3149
+ bind: keyId(n0),
3150
+ });
3151
+ const proved = await prover.prove("membership", pass.input);
3152
+ const landed = await submit({
3153
+ coin: open.coin,
3154
+ item,
3155
+ saleKey,
3156
+ ...commits,
3157
+ closeMs,
3158
+ finishByMs,
3159
+ maxBids: open.maxBids,
3160
+ pass: {
3161
+ tag: pass.publics[0],
3162
+ expiryMs: credential.expiryMs,
3163
+ proof: proofBytes(proved.proof),
3164
+ room: keyId(saleKey),
3165
+ n0,
3166
+ },
3167
+ });
3168
+ if (typeof landed.digest !== "string" || landed.digest.length === 0 || typeof landed.ticket !== "string")
3169
+ unknownObject("the sale open returned no digest");
3170
+ if (typeof landed.id !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(landed.id))
3171
+ unknownObject("the sale open returned no room");
3172
+ const id = address(landed.id, "room id");
3173
+ const row = await read(id);
3174
+ if (!row)
3175
+ unknownObject("the digest created no room");
3176
+ assertRoomMatches(this.config, open, { id, json: row.json });
3177
+ if (String(row.json.sale_key) !== saleKey.toString())
3178
+ unknownObject("the room is not this open");
3179
+ return {
3180
+ id,
3181
+ digest: landed.digest,
3182
+ ticket: landed.ticket,
3183
+ sale: { room: id, noteIndex, seller, bounds },
3184
+ };
3185
+ }
3186
+ /**
3187
+ * The sponsored open (E-34): a fresh seed-derived sender receives the item, then signs `from_proof` and `open`
3188
+ * while the relayer pays gas. Every reader is checked here, before any proof, reserve or delivery. An open that
3189
+ * stops after the delivery leaves the item at that sender, which only its seed can move.
3190
+ */
3191
+ saleSponsor(pool) {
3192
+ const relayer = this.sponsorRelayer();
3193
+ const deliver = this.io.deliverSaleItem ?? notSetUp("no deliverSaleItem: the SDK never holds the item's wallet");
3194
+ const readRef = this.io.readObjectRef ?? notSetUp("no object reader for the item's version");
3195
+ const readOpened = this.io.readSaleOpened ?? notSetUp("no reader for the room an open created");
3196
+ const readShared = this.io.readSharedVersion ?? notSetUp("no chain reader for shared object versions");
3197
+ const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
3198
+ const keyRegistry = this.config.objects.keyRegistry ?? notSetUp("missing config: no KeyRegistry");
3199
+ const used = this.addressUsed();
3200
+ const packages = { pool: this.config.packages.pool, sale: this.config.packages.sale };
3201
+ const shared = (r) => ({
3202
+ objectId: r.id,
3203
+ initialSharedVersion: r.initialSharedVersion,
3204
+ });
3205
+ return async (tx) => {
3206
+ const seed = this.seed();
3207
+ const signer = depositSigner(seed, await this.freshSigner(seed, used));
3208
+ const sender = signer.toSuiAddress();
3209
+ await deliver({ item: tx.item, sender });
3210
+ const ref = await readRef(tx.item.id);
3211
+ if (ref.owner === null || normalizeSuiAddress(ref.owner) !== sender)
3212
+ throw new EsseyError("SERVICE_REFUSED", "refused: the item is not at the sale sender; nothing was signed");
3213
+ const txKindB64 = await saleOpenKind({
3214
+ ...tx,
3215
+ packages,
3216
+ objects: {
3217
+ passKey: shared(passKey),
3218
+ keyRegistry: shared(keyRegistry),
3219
+ pool: { objectId: pool, initialSharedVersion: await readShared(pool) },
3220
+ },
3221
+ coinType: this.config.coins[tx.coin].type,
3222
+ item: { objectId: tx.item.id, version: ref.version, digest: ref.digest, type: tx.item.type },
3223
+ });
3224
+ const possession = await provePossession({
3225
+ signer,
3226
+ kind: fromBase64(txKindB64),
3227
+ relayer: relayer.address,
3228
+ expiryMs: (this.io.now ?? Date.now)() + POSSESSION_TTL_MS,
3229
+ });
3230
+ const pass = {
3231
+ tag: tx.pass.tag.toString(),
3232
+ expiryMs: tx.pass.expiryMs.toString(),
3233
+ proof: `0x${Buffer.from(tx.pass.proof).toString("hex")}`,
3234
+ };
3235
+ const sponsored = await sponsor(this.fetch, relayer.base, { txKindB64, sender, pass, possession });
3236
+ if (!carriesKind(sponsored.txBytesB64, txKindB64, sender, relayer.address))
3237
+ throw new EsseyError("RELAY_REFUSED", "refused: the sponsored bytes are not this open; nothing was signed");
3238
+ const { signature } = await signer.signTransaction(fromBase64(sponsored.txBytesB64));
3239
+ const digest = await executeSponsored(this.fetch, relayer.base, {
3240
+ txBytesB64: sponsored.txBytesB64,
3241
+ userSig: signature,
3242
+ });
3243
+ return { id: (await readOpened(digest)).room, digest, ticket: "" };
3244
+ };
3245
+ }
3246
+ /** D-SPEC §6.2:600. */
3247
+ async listSales() {
3248
+ requireSale(this.config);
3249
+ const read = this.io.readRooms ?? notSetUp("missing config: no room reader");
3250
+ const out = [];
3251
+ let cursor = null;
3252
+ let pages = 0;
3253
+ for (;;) {
3254
+ const page = await read(cursor);
3255
+ pages += 1;
3256
+ for (const row of page.rooms)
3257
+ out.push(summarizeRoom(this.config, row));
3258
+ cursor = afterPage(page.next, pages);
3259
+ if (cursor === null)
3260
+ break;
3261
+ }
3262
+ return out;
3263
+ }
3264
+ /** D-SPEC §6.2:600. */
3265
+ async viewSale(id) {
3266
+ requireSale(this.config);
3267
+ const read = this.io.readRoom ?? notSetUp("missing config: no room reader");
3268
+ const key = address(id, "room id");
3269
+ const row = await read(key);
3270
+ if (!row)
3271
+ unknownObject("no room with this id");
3272
+ const bounds = this.io.roomBounds ? await this.io.roomBounds(key) : null;
3273
+ return viewRoomObject(this.config, { id: key, json: row.json }, bounds);
3274
+ }
3275
+ async saleRoom(id) {
3276
+ requireSale(this.config);
3277
+ const read = this.io.readRoom ?? notSetUp("missing config: no room reader");
3278
+ const room = address(id, "room id");
3279
+ const row = await read(room);
3280
+ if (!row)
3281
+ unknownObject("no room with this id");
3282
+ const json = row.json;
3283
+ const bids = (json.bids ?? []);
3284
+ return {
3285
+ id: room,
3286
+ coin: coinByPool(this.config, String(json.pool_id)),
3287
+ saleKey: BigInt(json.sale_key),
3288
+ state: Number(json.state),
3289
+ nonce: BigInt(json.nonce),
3290
+ closeMs: BigInt(json.close_ms),
3291
+ finishByMs: BigInt(json.finish_by_ms),
3292
+ maxBids: Number(json.max_bids),
3293
+ residual: BigInt(json.residual ?? 0),
3294
+ boundsCommit: BigInt(json.bounds_commit),
3295
+ sellerCommit: BigInt(json.seller_commit),
3296
+ bids: bids.map((b) => ({
3297
+ ...b,
3298
+ commit: BigInt(b.commit),
3299
+ lock: BigInt(b.lock),
3300
+ active: b.active === true,
3301
+ })),
3302
+ };
3303
+ }
3304
+ bidSecrets(seed, record) {
3305
+ const own = deriveNoteKey(seed, record.noteIndex);
3306
+ const tagged = (t) => poseidonHash([own.sk, own.blinding, t]);
3307
+ return {
3308
+ v: record.v,
3309
+ amount: record.amount,
3310
+ ownerSk: own.sk,
3311
+ ns: tagged(3n),
3312
+ b: tagged(4n),
3313
+ s: tagged(5n),
3314
+ };
3315
+ }
3316
+ nowMs() {
3317
+ return BigInt((this.io.now ?? Date.now)());
3318
+ }
3319
+ async placeBid(roomId, v, amount) {
3320
+ if (typeof v !== "bigint" || typeof amount !== "bigint" || v <= 0n || v > amount)
3321
+ throw new EsseyError("INVALID_ARGUMENT", "the bid must be above 0 and at most the deposit");
3322
+ const room = await this.saleRoom(roomId);
3323
+ if (room.state !== SALE_STATE.open || this.nowMs() >= room.closeMs)
3324
+ throw new EsseyError("INVALID_ARGUMENT", "the room is not taking bids");
3325
+ const seq = room.bids.length;
3326
+ if (seq >= room.maxBids)
3327
+ throw new EsseyError("INVALID_ARGUMENT", "the room is full");
3328
+ const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
3329
+ const { member, credential } = readState(this.statePath);
3330
+ if (!member || !credential)
3331
+ notSetUp("no credential: call credential.obtain first");
3332
+ const relayer = this.relayerAddress();
3333
+ const relayerFee = this.coinFee(room.coin);
3334
+ const prover = this.prover();
3335
+ const fee = await this.feeParams(room.coin);
3336
+ const { events, owned, seed } = await this.owned(room.coin);
3337
+ const inputs = pickInputs(owned, amount + relayerFee);
3338
+ const tree = poolTree(orderedLeaves(events));
3339
+ const ins = inputs.map((n) => ({
3340
+ amount: n.value,
3341
+ sk: n.sk,
3342
+ blinding: n.blinding,
3343
+ pathIndex: BigInt(n.index),
3344
+ pathElements: tree.path(n.index),
3345
+ }));
3346
+ const spent = [ins[0], ins[1] ?? dummyInput()];
3347
+ const n0 = noteNullifier(noteCommitment(spent[0].amount, notePk(spent[0].sk), spent[0].blinding), spent[0].sk, spent[0].pathIndex);
3348
+ await this.keys();
3349
+ const record = { room: room.id, noteIndex: this.reserve("notes"), v, amount };
3350
+ const changeIndex = this.reserve("notes");
3351
+ const change = deriveNoteKey(seed, changeIndex);
3352
+ const secrets = this.bidSecrets(seed, record);
3353
+ const sealed = await seal({
3354
+ id: bidKeyId(room.saleKey, BigInt(seq)),
3355
+ data: bidPlaintext(secrets),
3356
+ aad: bidAad(n0),
3357
+ pkg: "sale",
3358
+ });
3359
+ const changeValue = spent[0].amount + spent[1].amount - amount - relayerFee;
3360
+ const encChange = sealOpening({ value: changeValue, blinding: change.blinding, index: changeIndex }, noteEncKey(seed).encPub);
3361
+ const encs = [hexBytes(encChange), hexBytes(fillerEnc())];
3362
+ const w = await lockBid({
3363
+ root: tree.root,
3364
+ ins: spent,
3365
+ room: { id: room.id, saleKey: room.saleKey, seq },
3366
+ bid: secrets,
3367
+ change: { pk: notePk(change.sk), blinding: change.blinding },
3368
+ relayer,
3369
+ relayerFee,
3370
+ sealed,
3371
+ encs,
3372
+ fee,
3373
+ eph: drawEph(),
3374
+ });
3375
+ const pass = membership({
3376
+ secrets: member,
3377
+ credential: credential,
3378
+ domain: DOMAIN_SPEND,
3379
+ room: keyId(room.saleKey),
3380
+ bind: keyId(n0),
3381
+ });
3382
+ const proved = async (circuit, input, publics) => ({
3383
+ proof: (await prover.prove(circuit, input)).proof,
3384
+ publicSignals: publics.map(String),
3385
+ });
3386
+ const landed = await this.paidLoan(bidBody, {
3387
+ pool: room.coin,
3388
+ room: room.id,
3389
+ pass: {
3390
+ proved: await proved("membership", pass.input, pass.publics),
3391
+ tag: pass.publics[0],
3392
+ expiryMs: credential.expiryMs,
3393
+ },
3394
+ proved: await proved("lock_bid", w.input, w.publics),
3395
+ statement: w.statement,
3396
+ sealed,
3397
+ encs,
3398
+ });
3399
+ return { ...landed, bid: record };
3400
+ }
3401
+ /** `sale_room::seal_approve_bid`: the seller's SEAL pass over `seal_bid` of bid `seq`, bound to the viewer, nonce 0. */
3402
+ bidApprove(room, seq) {
3403
+ const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
3404
+ const { member, credential } = readState(this.statePath);
3405
+ if (!member || !credential)
3406
+ notSetUp("no credential: call credential.obtain first");
3407
+ const scope = keyId(room.saleKey);
3408
+ const prover = this.prover();
3409
+ return async (viewer) => {
3410
+ const bind = `0x${Buffer.from(sealBidBind(scope, BigInt(seq), viewer)).toString("hex")}`;
3411
+ const pass = membership({
3412
+ secrets: member,
3413
+ credential: credential,
3414
+ domain: DOMAIN_SENDER,
3415
+ room: scope,
3416
+ bind,
3417
+ });
3418
+ const proved = await prover.prove("membership", pass.input);
3419
+ return {
3420
+ target: `${this.config.packages.sale}::sale_room::seal_approve_bid`,
3421
+ typeArguments: [this.config.coins[room.coin].type],
3422
+ args: [
3423
+ {
3424
+ pure: "vector<u8>",
3425
+ value: `0x${Buffer.from(bidKeyId(room.saleKey, BigInt(seq))).toString("hex")}`,
3426
+ },
3427
+ { object: room.id },
3428
+ { pure: "u64", value: seq.toString() },
3429
+ { object: passKey.id },
3430
+ { pure: "u256", value: pass.publics[0].toString() },
3431
+ { pure: "u64", value: credential.expiryMs.toString() },
3432
+ { pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
3433
+ { object: "0x6" },
3434
+ ],
3435
+ };
3436
+ };
3437
+ }
3438
+ /** `seal_approve_bid` releases keys from close until `finish_by_ms`, for an active bid (`sale_room.move:337-341`). */
3439
+ async closedRoom(roomId) {
3440
+ const room = await this.saleRoom(roomId);
3441
+ const now = this.nowMs();
3442
+ if (room.state !== SALE_STATE.open || now < room.closeMs || now >= room.finishByMs)
3443
+ throw new EsseyError("INVALID_ARGUMENT", "the room is not between close and its finish deadline");
3444
+ return room;
3445
+ }
3446
+ async slashBid(roomId, seq) {
3447
+ const room = await this.closedRoom(roomId);
3448
+ if (!Number.isInteger(seq) || !room.bids[seq]?.active)
3449
+ throw new EsseyError("INVALID_ARGUMENT", "seq is not an active bid of this room");
3450
+ const derive = this.io.sealDerivedKeys ?? notSetUp("missing config: no Seal key deriver");
3451
+ const derived = await derive({
3452
+ id: bidKeyId(room.saleKey, BigInt(seq)),
3453
+ approve: this.bidApprove(room, seq),
3454
+ pkg: "sale",
3455
+ });
3456
+ return this.freeLoan(slashBody, {
3457
+ pool: room.coin,
3458
+ room: room.id,
3459
+ seq: BigInt(seq),
3460
+ keys: this.pinnedKeys(derived),
3461
+ });
3462
+ }
3463
+ async finishSale(p) {
3464
+ const room = await this.closedRoom(p.room);
3465
+ const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
3466
+ const plains = [];
3467
+ for (const [i, b] of room.bids.entries()) {
3468
+ if (b.active && typeof b.sealed !== "string")
3469
+ notSetUp("the room reader gave no sealed bid");
3470
+ const sealed = b.active ? Uint8Array.from(Buffer.from(b.sealed, "base64")) : undefined;
3471
+ plains.push(sealed && (await decrypt({ sealed, approve: this.bidApprove(room, i), pkg: "sale" })));
3472
+ }
3473
+ const seed = this.seed();
3474
+ const sellerIndex = this.indexOfSellerKey(seed, p.seller.sellerSk);
3475
+ const fee = await this.feeParams(room.coin);
3476
+ const eph = drawEph();
3477
+ const planFor = (encs) => settlePlan({ room, plains, seller: p.seller, bounds: p.bounds, encs, fee, eph });
3478
+ const draft = await planFor([new Uint8Array(128), new Uint8Array(128)]);
3479
+ if (draft.slash.length > 0)
3480
+ throw new EsseyError("INVALID_ARGUMENT", `refused: slash bids ${draft.slash.join(", ")} first`);
3481
+ const encSeller = sealOpening({ ...draft.sellerNote, index: sellerIndex }, noteEncKey(seed).encPub);
3482
+ const encs = [hexBytes(encSeller), hexBytes(fillerEnc())];
3483
+ const w = await planFor(encs);
3484
+ const proof = (await this.prover().prove("sale_settle", w.input)).proof;
3485
+ return this.freeLoan(finishBody, {
3486
+ pool: room.coin,
3487
+ room: room.id,
3488
+ vault: p.vault,
3489
+ proved: { proof, publicSignals: w.publics.map(String) },
3490
+ statement: w.statement,
3491
+ encs,
3492
+ });
3493
+ }
3494
+ indexOfSellerKey(seed, sellerSk) {
3495
+ const n = readState(this.statePath).notes ?? 0;
3496
+ for (let i = n - 1; i >= 0; i--)
3497
+ if (deriveNoteKey(seed, i).sk === sellerSk)
3498
+ return i;
3499
+ return notSetUp("refused: sellerSk is not a note key of this seed, so the proceeds would not scan");
3500
+ }
3501
+ async expireSale(roomId, vault) {
3502
+ const room = await this.saleRoom(roomId);
3503
+ if (room.state !== SALE_STATE.open || this.nowMs() < room.finishByMs)
3504
+ throw new EsseyError("INVALID_ARGUMENT", "the room is not past its finish deadline");
3505
+ return this.freeLoan(expireBody, { pool: room.coin, room: room.id, vault });
3506
+ }
3507
+ async cancelSale(roomId, vault) {
3508
+ const room = await this.saleRoom(roomId);
3509
+ if (room.state !== SALE_STATE.open || room.bids.length > 0)
3510
+ throw new EsseyError("INVALID_ARGUMENT", "only an open room with no bid cancels");
3511
+ // `sale_room::action_hash` is `loan::action_hash`'s encoding over `sale_key` (`sale_room.move:528-529`).
3512
+ const pass = await this.borrowerPass({ loan_key: room.saleKey, nonce: room.nonce }, "cancel", new Uint8Array());
3513
+ return this.freeLoan(cancelBody, { pool: room.coin, room: room.id, vault, pass });
3514
+ }
3515
+ async reclaimBid(roomId, record, what) {
3516
+ const room = await this.saleRoom(roomId);
3517
+ if (room.state !== SALE_STATE.settled && room.state !== SALE_STATE.expired)
3518
+ throw new EsseyError("INVALID_ARGUMENT", "the room has not ended");
3519
+ const seed = this.seed();
3520
+ const relayer = this.relayerAddress();
3521
+ const relayerFee = this.coinFee(room.coin);
3522
+ const fee = await this.feeParams(room.coin);
3523
+ await this.keys();
3524
+ const outIndex = this.reserve("notes");
3525
+ const out = deriveNoteKey(seed, outIndex);
3526
+ const eph = drawEph();
3527
+ const planFor = (encs) => saleReclaim({
3528
+ room: { saleKey: room.saleKey, locks: room.bids.map((b) => b.lock), residual: room.residual },
3529
+ bid: this.bidSecrets(seed, record),
3530
+ what,
3531
+ out: { pk: notePk(out.sk), blinding: out.blinding },
3532
+ relayer,
3533
+ relayerFee,
3534
+ encs,
3535
+ fee,
3536
+ eph,
3537
+ });
3538
+ const draft = await planFor([new Uint8Array(128), new Uint8Array(128)]);
3539
+ const encOut = sealOpening({ value: draft.outAmt, blinding: out.blinding, index: outIndex }, noteEncKey(seed).encPub);
3540
+ const encs = [hexBytes(encOut), hexBytes(fillerEnc())];
3541
+ const w = await planFor(encs);
3542
+ const proof = (await this.prover().prove("reclaim", w.input)).proof;
3543
+ const landed = await this.paidLoan(reclaimBody, {
3544
+ pool: room.coin,
3545
+ room: room.id,
3546
+ proved: { proof, publicSignals: w.publics.map(String) },
3547
+ statement: w.statement,
3548
+ encs,
3549
+ });
3550
+ return { ...landed, value: w.outAmt };
3551
+ }
3552
+ async claimItem(p) {
3553
+ if (!p.bid === !p.seller)
3554
+ throw new EsseyError("INVALID_ARGUMENT", "claim with a bid record or seller keys, not both");
3555
+ const read = this.io.readVault ?? notSetUp("missing config: no vault reader");
3556
+ const vault = address(p.vault, "vault id");
3557
+ const row = await read(vault);
3558
+ if (!row)
3559
+ unknownObject("no vault with this id");
3560
+ const json = row.json;
3561
+ const claim = optionU256(json.claim);
3562
+ if (claim === null)
3563
+ throw new EsseyError("INVALID_ARGUMENT", "the vault holds no claim yet");
3564
+ const room = await this.saleRoom(String(json.room_id));
3565
+ let holder;
3566
+ if (p.bid) {
3567
+ const own = this.bidSecrets(this.seed(), p.bid);
3568
+ holder = { ownerSk: own.ownerSk, ns: own.ns };
3569
+ }
3570
+ else
3571
+ holder = p.seller;
3572
+ const w = itemClaim({
3573
+ vault: { roomField: BigInt(json.room_field), claim },
3574
+ holder,
3575
+ recipient: p.recipient,
3576
+ relayer: this.relayerAddress(),
3577
+ });
3578
+ const proof = (await this.prover().prove("item_claim", w.input)).proof;
3579
+ return this.freeLoan(claimBody, {
3580
+ pool: room.coin,
3581
+ vault,
3582
+ recipient: w.statement.recipient,
3583
+ nullifier: w.statement.nullifier,
3584
+ proved: { proof, publicSignals: w.publics.map(String) },
3585
+ });
3586
+ }
3587
+ async prepareOpen(body) {
3588
+ if (body.kind !== "loan_open")
3589
+ throw new EsseyError("INVALID_ARGUMENT", "body is not a loan_open");
3590
+ const rates = await this.rates(body.args.market ?? "");
3591
+ return { rates, submit: async () => this.relayClient().submit(body) };
3592
+ }
3593
+ }