@esseyonsui/sui-sdk-v3 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/essey.d.ts +101 -21
- package/dist/essey.d.ts.map +1 -1
- package/dist/essey.js +437 -163
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/v3/collateral/bodies.d.ts +2 -1
- package/dist/v3/collateral/bodies.d.ts.map +1 -1
- package/dist/v3/collateral/bodies.js +5 -5
- package/dist/v3/collateral/local-health.d.ts +2 -2
- package/dist/v3/collateral/local-health.js +1 -1
- package/dist/v3/collateral/math.d.ts +8 -9
- package/dist/v3/collateral/math.d.ts.map +1 -1
- package/dist/v3/collateral/math.js +65 -13
- package/dist/v3/index.d.ts +1 -0
- package/dist/v3/index.d.ts.map +1 -1
- package/dist/v3/index.js +1 -0
- package/dist/v3/kinds.d.ts +5 -2
- package/dist/v3/kinds.d.ts.map +1 -1
- package/dist/v3/kinds.js +7 -1
- package/dist/v3/loans/bodies.d.ts +16 -0
- package/dist/v3/loans/bodies.d.ts.map +1 -1
- package/dist/v3/loans/bodies.js +13 -0
- package/dist/v3/loans/open-plan.d.ts +2 -0
- package/dist/v3/loans/open-plan.d.ts.map +1 -1
- package/dist/v3/loans/open-plan.js +1 -1
- package/dist/v3/loans/refi-plan.d.ts.map +1 -1
- package/dist/v3/loans/refi-plan.js +2 -4
- package/dist/v3/loans/settle-plan.d.ts +7 -2
- package/dist/v3/loans/settle-plan.d.ts.map +1 -1
- package/dist/v3/loans/settle-plan.js +15 -15
- package/dist/v3/memo.d.ts +68 -0
- package/dist/v3/memo.d.ts.map +1 -0
- package/dist/v3/memo.js +147 -0
- package/dist/v3/sales/auctioneer.d.ts +8 -3
- package/dist/v3/sales/auctioneer.d.ts.map +1 -1
- package/dist/v3/sales/auctioneer.js +22 -5
- package/dist/v3/sales/bid.d.ts +3 -0
- package/dist/v3/sales/bid.d.ts.map +1 -1
- package/dist/v3/sales/bid.js +3 -0
- package/dist/v3/sales/bodies.d.ts +14 -2
- package/dist/v3/sales/bodies.d.ts.map +1 -1
- package/dist/v3/sales/bodies.js +11 -2
- package/dist/v3/sales/index.d.ts +3 -0
- package/dist/v3/sales/index.d.ts.map +1 -1
- package/dist/v3/sales/index.js +3 -0
- package/dist/v3/sales/listing.d.ts +19 -0
- package/dist/v3/sales/listing.d.ts.map +1 -0
- package/dist/v3/sales/listing.js +41 -0
- package/dist/v3/sales/memo.d.ts +4 -0
- package/dist/v3/sales/memo.d.ts.map +1 -0
- package/dist/v3/sales/memo.js +6 -0
- package/dist/v3/sales/open-kind.d.ts +4 -1
- package/dist/v3/sales/open-kind.d.ts.map +1 -1
- package/dist/v3/sales/open-kind.js +4 -3
- package/dist/v3/sales/package-gate.d.ts +14 -0
- package/dist/v3/sales/package-gate.d.ts.map +1 -0
- package/dist/v3/sales/package-gate.js +24 -0
- package/dist/v3/sales/rows.d.ts +1 -0
- package/dist/v3/sales/rows.d.ts.map +1 -1
- package/dist/v3/sales/rows.js +3 -1
- package/dist/v3/sales/seller.d.ts +34 -10
- package/dist/v3/sales/seller.d.ts.map +1 -1
- package/dist/v3/sales/seller.js +43 -16
- package/dist/v3/stage1.d.ts +3 -3
- package/dist/v3/stage1.d.ts.map +1 -1
- package/dist/v3/stage1.js +3 -4
- package/dist/v3/time-grid.d.ts +12 -1
- package/dist/v3/time-grid.d.ts.map +1 -1
- package/dist/v3/time-grid.js +17 -2
- package/package.json +1 -1
package/dist/essey.js
CHANGED
|
@@ -13,13 +13,14 @@ import { address, assertTestnet, decimal, fixedHeaders, getJson, postJson, servi
|
|
|
13
13
|
import { credentialSigned, parseCredential, renewOpensAt, requestCredential, solveChallenge, } from "./v3/credential/issue.js";
|
|
14
14
|
import { DOMAIN_KEEPER, DOMAIN_SENDER, DOMAIN_SPEND, FEE_PARAMS_ROOM, feeNonceLane, memberCommitment, } from "./v3/credential/membership.js";
|
|
15
15
|
import { passProof, transfer as transferBody, withdraw as withdrawBody, } from "./v3/bodies.js";
|
|
16
|
-
import { cancel as cancelLoan, slash as slashLoan, ctFault as ctFaultLoan, cancelRefi as cancelRefiLoan, claimDefault as claimDefaultLoan, offer as offerLoan, open as openLoan, reclaim as reclaimLoan, reclaimColl as reclaimCollLoan, refinance as refinanceLoan, settleRefi as settleRefiLoan, repay as repayLoan, settle as settleLoan, } from "./v3/loans/bodies.js";
|
|
16
|
+
import { cancel as cancelLoan, slash as slashLoan, ctFault as ctFaultLoan, cancelRefi as cancelRefiLoan, claimDefault as claimDefaultLoan, offer as offerLoan, open as openLoan, pick as pickLoan, reclaim as reclaimLoan, reclaimColl as reclaimCollLoan, refinance as refinanceLoan, settleRefi as settleRefiLoan, repay as repayLoan, settle as settleLoan, } from "./v3/loans/bodies.js";
|
|
17
17
|
import { DOM_LBLIND, DOM_TSALT, R } from "./v3/domains.js";
|
|
18
18
|
import { MODE_OPEN, MODE_TOPUP, NO_ADDRESS, collLockExt } from "./v3/ext.js";
|
|
19
19
|
import { defaultExt, faultExt, heartbeatExt, liquidateExt, openExt, releaseExt, topupByBorrowerExt, topupExt, } from "./v3/collateral/ext.js";
|
|
20
20
|
import { claimDefault as claimDefaultBody, faultLiquidate as faultLiquidateBody, heartbeat as heartbeatBody, liquidate as liquidateBody, release as releaseBody, topup as topupBody, topupBorrower as topupBorrowerBody, } from "./v3/collateral/bodies.js";
|
|
21
|
-
import { GRACE_S, coverExpiry, heartbeatFloor } from "./v3/collateral/math.js";
|
|
22
|
-
import { assertLoanGrid, assertRequestClose, assertRequestTerm,
|
|
21
|
+
import { COVER_STEP_MS, GRACE_S, coverExpiry, coverOverStored, heartbeatFloor, legacyHeartbeatFloor, } from "./v3/collateral/math.js";
|
|
22
|
+
import { assertLoanGrid, assertRequestClose, assertRequestTerm, closeWaitMs, defaultNowS, gridClose, settleNowS, } from "./v3/time-grid.js";
|
|
23
|
+
import { MEMO_KIND, memoKey, offerMemoBody, openOfferMemo, openRequestMemo, openSettleMemo, requestMemoBody, sealBidMemo, sealMemo, sealSaleMemo, settleMemoBody, } from "./v3/memo.js";
|
|
23
24
|
/**
|
|
24
25
|
* The Seal servers dry-run `keeper::check_loan` and answer "does not have access" when it aborts: a heartbeat still
|
|
25
26
|
* covers the loan at this price, the loan is not active, or the pass or badge does not match.
|
|
@@ -46,7 +47,7 @@ import { KEEPER_LAYOUT_VERSION, encodeKeeperPayload } from "./v3/keeper-payload.
|
|
|
46
47
|
import { LOAN_REPAY_KIND, loanRepay } from "./v3/loans/repay-plan.js";
|
|
47
48
|
import { reclaimColl, reclaimLock } from "./v3/loans/reclaim-plan.js";
|
|
48
49
|
import { collLock, keyId, openAction, requestKeyId, requestPlaintext } from "./v3/loans/open-plan.js";
|
|
49
|
-
import { LOAN_SETTLE_KIND, actionHash, decodeOffer, interest, loanSettle, offerOpens, sealOfferBind, settleArgs, openRefiArgs, readingBytes, settleRefiArgs, cancelRefiArgs, topupArgs, } from "./v3/loans/settle-plan.js";
|
|
50
|
+
import { LOAN_SETTLE_KIND, SETTLE_SLOTS, actionHash, decodeOffer, interest, loanSettle, offerOpens, sealOfferBind, settleArgs, openRefiArgs, readingBytes, settleRefiArgs, cancelRefiArgs, topupArgs, } from "./v3/loans/settle-plan.js";
|
|
50
51
|
import { lockRound } from "./v3/loans/lock-round.js";
|
|
51
52
|
import { LOAN_REFI_KIND, loanRefi } from "./v3/loans/refi-plan.js";
|
|
52
53
|
import { LOAN_OFFER_KIND, decodeRequest, lock4, lockField, loanExt, loanOffer, offerKeyId, offerPlaintext, offerRoom, sealListingBind, } from "./v3/loans/offer-plan.js";
|
|
@@ -58,13 +59,15 @@ import { marketRates } from "./v3/market.js";
|
|
|
58
59
|
import { afterPage, assertLoanOpen, assertRoomMatches, assertSaleOpen, coinByPool, openPosition, poolId, requireSale, summarizeLoan, summarizeRoom, viewLoanObject, viewPosition, viewRoomObject, } from "./v3/stage1.js";
|
|
59
60
|
import { plan as settlePlan } from "./v3/sales/auctioneer.js";
|
|
60
61
|
import { lockBid } from "./v3/sales/bid.js";
|
|
61
|
-
import { bidBody, cancelBody, claimBody, expireBody, finishBody, reclaimBody, slashBody, } from "./v3/sales/bodies.js";
|
|
62
|
+
import { bidBody, cancelBody, claimBody, expireBody, finishBody, pickBody, reclaimBody, slashBody, } from "./v3/sales/bodies.js";
|
|
62
63
|
import { itemClaim } from "./v3/sales/claim.js";
|
|
64
|
+
import { listingKeyId, listingPlaintext, readListing } from "./v3/sales/listing.js";
|
|
63
65
|
import { saleOpenKind } from "./v3/sales/open-kind.js";
|
|
64
66
|
import { SALE_STATE } from "./v3/sales/outcome.js";
|
|
67
|
+
import { saleKindGate, salePackageOf } from "./v3/sales/package-gate.js";
|
|
65
68
|
import { reclaim as saleReclaim } from "./v3/sales/reclaim.js";
|
|
66
69
|
import { bidAad, bidKeyId, bidPlaintext, openBid, sealBidBind } from "./v3/sales/rows.js";
|
|
67
|
-
import {
|
|
70
|
+
import { openArgs, openCommits, saleSecrets, saleTimes, typeNameOf } from "./v3/sales/seller.js";
|
|
68
71
|
import { splitDenominations } from "./v3/notes/denominations.js";
|
|
69
72
|
import { DEPOSIT_ROOM, carriesKind, depositKind, executeSponsored, sponsor, } from "./v3/notes/deposit.js";
|
|
70
73
|
import { SEED_BYTES, deriveNoteKey, depositSigner, itemHolder, noteEncKey, receiveKey, } from "./v3/notes/derive.js";
|
|
@@ -95,9 +98,8 @@ const POSSESSION_TTL_MS = 5 * 60_000;
|
|
|
95
98
|
/** NEEDS-BORIS: the relayer's default `sponsorWindowMs` (`services/relayer-v3/src/config.ts:261`); it serves no route that names its own. */
|
|
96
99
|
const SPONSOR_WINDOW_MS = 10 * 60_000;
|
|
97
100
|
const HOUR_MS = 3_600_000;
|
|
98
|
-
/**
|
|
99
|
-
const
|
|
100
|
-
const SALE_MAX_WINDOW_MS = 30 * 86_400_000;
|
|
101
|
+
/** Lane SDK-B's allowance from choosing a sale's close to its open landing (`R1-SDKB-ESSEY-CALLSITES.md` §3). */
|
|
102
|
+
const SALE_LAND_MARGIN_MS = 60_000;
|
|
101
103
|
/** Measured offer submit-to-land on testnet: median 56 s, p95 83 s. A later send aborts at close, after its proofs. */
|
|
102
104
|
const CLOSE_MARGIN_MS = 120000n;
|
|
103
105
|
const NO_TO = "no to address: the zero address is nobody's; nothing was sent";
|
|
@@ -111,6 +113,19 @@ function unknownObject(what) {
|
|
|
111
113
|
function wrongCoinObject() {
|
|
112
114
|
throw new EsseyError("INVALID_ARGUMENT", "wrong coin: the envelope pool is not the loan coin");
|
|
113
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* The original ids of the retired `pkg`, the address in its objects' types: the record's optional
|
|
118
|
+
* `previous.packageOrigins` (`services/v3api/src/config-route.ts` `PreviousPackages`).
|
|
119
|
+
*/
|
|
120
|
+
function previousOrigins(config, pkg) {
|
|
121
|
+
const record = config;
|
|
122
|
+
const id = record.previous?.packageOrigins?.[pkg];
|
|
123
|
+
return typeof id === "string" ? [normalizeSuiAddress(id)] : [];
|
|
124
|
+
}
|
|
125
|
+
/** `loan.move` `E_CLOSE_GRID`: the open landed a step later than its close was chosen for; a fresh close lands. */
|
|
126
|
+
const E_CLOSE_GRID = 42_046;
|
|
127
|
+
const lateClose = (err) => (isEsseyError(err, "RELAY_FAILED") || isEsseyError(err, "RELAY_REFUSED")) &&
|
|
128
|
+
err.detail?.abort?.code === E_CLOSE_GRID;
|
|
114
129
|
function readRequestPlain(plain) {
|
|
115
130
|
try {
|
|
116
131
|
return decodeRequest(plain);
|
|
@@ -514,15 +529,22 @@ function sweepTemps(path) {
|
|
|
514
529
|
}
|
|
515
530
|
const blake2b256 = (bytes) => blake2b(bytes, { dkLen: 32 });
|
|
516
531
|
const hexBytes = (hex) => Uint8Array.from(Buffer.from(hex.replace(/^0x/, ""), "hex"));
|
|
517
|
-
/** A Move `Option<u256>` read as JSON: null, the value, or `{ vec: [] | [value] }`. */
|
|
518
|
-
function optionU256(raw) {
|
|
532
|
+
/** A Move `Option<u256>` or `Option<u64>` read as JSON: null, the value, or `{ vec: [] | [value] }`. */
|
|
533
|
+
function optionU256(raw, what = "the vault claim") {
|
|
519
534
|
const inner = raw && typeof raw === "object" ? raw.vec?.[0] : raw;
|
|
520
535
|
if (inner === null || inner === undefined)
|
|
521
536
|
return null;
|
|
522
537
|
if (typeof inner !== "string" && typeof inner !== "number")
|
|
523
|
-
unknownObject(
|
|
538
|
+
unknownObject(`${what} is not a number`);
|
|
524
539
|
return BigInt(inner);
|
|
525
540
|
}
|
|
541
|
+
/** A Move `Option<vector<u8>>` read as JSON, base64 inside as `readRoom` gives `bids[i].sealed`; UNVERIFIED shape. */
|
|
542
|
+
function optionBytes(raw) {
|
|
543
|
+
const inner = raw && typeof raw === "object" ? raw.vec?.[0] : raw;
|
|
544
|
+
return typeof inner === "string" ? Uint8Array.from(Buffer.from(inner, "base64")) : undefined;
|
|
545
|
+
}
|
|
546
|
+
/** PRV-23 A: the round's `pick` (`loan.move:108`), null until `pick::pick` lands and after a slash clears it. */
|
|
547
|
+
const pickOf = (round) => optionU256(round?.pick, "the round's pick");
|
|
526
548
|
function asInvalid(run) {
|
|
527
549
|
try {
|
|
528
550
|
return run();
|
|
@@ -675,16 +697,6 @@ function payoutStopped(error, paid, rest) {
|
|
|
675
697
|
stopped.cause = error;
|
|
676
698
|
return stopped;
|
|
677
699
|
}
|
|
678
|
-
/**
|
|
679
|
-
* LOAN-01: close_ms is public, so an exact close publishes the caller's chosen window. It rounds up to a whole
|
|
680
|
-
* `step` (an hour unless the deployment sets `closeStepMs`), or down one step when up would pass the chain's
|
|
681
|
-
* longest window, which is still far above its shortest.
|
|
682
|
-
*/
|
|
683
|
-
function stepClose(closeMs, nowMs, maxWindowMs, step = HOUR_MS) {
|
|
684
|
-
const up = Math.ceil(closeMs / step) * step;
|
|
685
|
-
const over = up - nowMs > maxWindowMs && closeMs - nowMs <= maxWindowMs;
|
|
686
|
-
return over ? up - step : up;
|
|
687
|
-
}
|
|
688
700
|
function refusedBy(service, reply) {
|
|
689
701
|
const error = typeof reply.body.error === "string" ? reply.body.error : undefined;
|
|
690
702
|
return new EsseyError("SERVICE_REFUSED", `${service} refused: ${error ?? reply.status}`, {
|
|
@@ -753,7 +765,7 @@ export class Essey {
|
|
|
753
765
|
await this.refuseOffGridClose(p.loan);
|
|
754
766
|
const send = async () => {
|
|
755
767
|
await this.pause("offer", p.loan, closeOf(p.loan));
|
|
756
|
-
const { body, record, seq } = await this.planOffer(p.loan
|
|
768
|
+
const { body, record, seq } = await this.planOffer(p.loan);
|
|
757
769
|
return {
|
|
758
770
|
seq,
|
|
759
771
|
sent: this.paidLoan(offerLoan, body).then((landed) => ({ ...landed, offer: record })),
|
|
@@ -797,6 +809,7 @@ export class Essey {
|
|
|
797
809
|
keeperLiquidate: (p) => this.paced("liquidate", p.loan, null, () => this.keeperLiquidate(p.loan, p.via)),
|
|
798
810
|
reclaimCollateral: (p) => this.paced("reclaim_collateral", p.loan, null, () => this.reclaimOwnCollateral(p.loan, p.collAmt)),
|
|
799
811
|
recover: (p) => this.recoverOwnLoan(p.loan),
|
|
812
|
+
recoverRecords: () => this.recoverRecords(),
|
|
800
813
|
payBack: (p) => this.paced("repay", p.loan, async () => repayDeadline(p.terms), async () => this.paidLoan(repayLoan, await this.planRepay(p.loan, p.terms, p.borrowerPk))),
|
|
801
814
|
settle: (p) => this.freeLoan(settleLoan, p),
|
|
802
815
|
repay: (p) => this.paidLoan(repayLoan, p),
|
|
@@ -837,9 +850,9 @@ export class Essey {
|
|
|
837
850
|
open: (p) => this.openSale(p),
|
|
838
851
|
list: () => this.listSales(),
|
|
839
852
|
view: (id) => this.viewSale(id),
|
|
840
|
-
bid: (p) => this.paced("bid", p.room, async () => ({ atMs: Number((await this.saleRoom(p.room)).closeMs) }), () => this.placeBid(p.room, p.
|
|
853
|
+
bid: (p) => this.paced("bid", p.room, async () => ({ atMs: Number((await this.saleRoom(p.room, "bid")).closeMs) }), () => this.placeBid(p.room, p.maxPrice, p.amount)),
|
|
841
854
|
finish: (p) => this.finishSale(p),
|
|
842
|
-
slash: (p) => this.slashBid(p.room
|
|
855
|
+
slash: (p) => this.slashBid(p.room),
|
|
843
856
|
expire: (p) => this.expireSale(p.room, p.vault),
|
|
844
857
|
reclaim: (p) => this.paced("sale_reclaim", p.room, null, () => this.reclaimBid(p.room, p.bid, p.what ?? "lock")),
|
|
845
858
|
claim: (p) => this.claimItem(p),
|
|
@@ -1854,10 +1867,13 @@ export class Essey {
|
|
|
1854
1867
|
const plan = this.io.planLoanOpen ?? ((q) => this.planOpen(q));
|
|
1855
1868
|
if (!this.io.readLoans)
|
|
1856
1869
|
notSetUp("missing config: no loan reader");
|
|
1857
|
-
const
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1870
|
+
const send = async () => {
|
|
1871
|
+
const proved = await plan(p);
|
|
1872
|
+
if (proved.pool !== p.loanCoin)
|
|
1873
|
+
wrongCoinObject();
|
|
1874
|
+
return { proved, landed: await this.paidLoan(openLoan, { ...proved, wait: true }) };
|
|
1875
|
+
};
|
|
1876
|
+
const { proved, landed } = await send().catch((err) => (lateClose(err) ? send() : Promise.reject(err)));
|
|
1861
1877
|
const read = this.io.readLoans;
|
|
1862
1878
|
const row = await this.listedByKey("loan", "loan_key", proved.loanKey, async (c) => {
|
|
1863
1879
|
const page = await read(c);
|
|
@@ -1922,7 +1938,8 @@ export class Essey {
|
|
|
1922
1938
|
pathElements: tree.path(n.index),
|
|
1923
1939
|
}));
|
|
1924
1940
|
await this.keys();
|
|
1925
|
-
const
|
|
1941
|
+
const ownIndex = this.reserve("notes");
|
|
1942
|
+
const own = deriveNoteKey(seed, ownIndex);
|
|
1926
1943
|
const changeIndex = this.reserve("notes");
|
|
1927
1944
|
const change = deriveNoteKey(seed, changeIndex);
|
|
1928
1945
|
const borrowerPk = notePk(own.sk);
|
|
@@ -1935,17 +1952,6 @@ export class Essey {
|
|
|
1935
1952
|
termMs: BigInt(p.termMs),
|
|
1936
1953
|
salt: poseidonHash([own.sk, own.blinding, 2n]),
|
|
1937
1954
|
};
|
|
1938
|
-
const closeMs = this.loanClose(p.offerWindowMs);
|
|
1939
|
-
const reqSealed = await seal({
|
|
1940
|
-
id: requestKeyId(loanKey),
|
|
1941
|
-
data: requestPlaintext({
|
|
1942
|
-
...request,
|
|
1943
|
-
borrowerPk,
|
|
1944
|
-
closeMs,
|
|
1945
|
-
market,
|
|
1946
|
-
coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
|
|
1947
|
-
}),
|
|
1948
|
-
});
|
|
1949
1955
|
const keeperCt = await seal({
|
|
1950
1956
|
id: keeperKeyId(loanKey, 0n),
|
|
1951
1957
|
data: encodeKeeperPayload({
|
|
@@ -1988,7 +1994,33 @@ export class Essey {
|
|
|
1988
1994
|
request,
|
|
1989
1995
|
});
|
|
1990
1996
|
const reqCommit = requestCommit(request, borrowerPk, note);
|
|
1991
|
-
const
|
|
1997
|
+
const proved = async (circuit, input, publics) => ({
|
|
1998
|
+
proof: (await prover.prove(circuit, input)).proof,
|
|
1999
|
+
publicSignals: publics.map(String),
|
|
2000
|
+
});
|
|
2001
|
+
const lockProved = await proved("coll_lock", lock.input, lock.publics);
|
|
2002
|
+
const healthProved = await proved("health", open.input, open.publics);
|
|
2003
|
+
// The close goes last, after the slow proofs, so the open lands in the step it was chosen in (42_046).
|
|
2004
|
+
const closeMs = await this.loanClose(p.offerWindowMs);
|
|
2005
|
+
const reqSealed = await seal({
|
|
2006
|
+
id: requestKeyId(loanKey),
|
|
2007
|
+
data: requestPlaintext({
|
|
2008
|
+
...request,
|
|
2009
|
+
borrowerPk,
|
|
2010
|
+
closeMs,
|
|
2011
|
+
market,
|
|
2012
|
+
coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
|
|
2013
|
+
}),
|
|
2014
|
+
});
|
|
2015
|
+
const memo = sealMemo(memoKey(seed), { kind: MEMO_KIND.request, key: loanKey, round: 0n }, requestMemoBody({ keyIndex: ownIndex, collAmt: p.collateral, borrowerPk }));
|
|
2016
|
+
const passN0 = openAction(loanKey, {
|
|
2017
|
+
reqCommit,
|
|
2018
|
+
reqSealed,
|
|
2019
|
+
closeMs,
|
|
2020
|
+
market,
|
|
2021
|
+
collateralCommit: note,
|
|
2022
|
+
memo,
|
|
2023
|
+
});
|
|
1992
2024
|
const pass = membership({
|
|
1993
2025
|
secrets: member,
|
|
1994
2026
|
credential: credential,
|
|
@@ -1996,10 +2028,6 @@ export class Essey {
|
|
|
1996
2028
|
room: keyId(loanKey),
|
|
1997
2029
|
bind: keyId(passN0),
|
|
1998
2030
|
});
|
|
1999
|
-
const proved = async (circuit, input, publics) => ({
|
|
2000
|
-
proof: (await prover.prove(circuit, input)).proof,
|
|
2001
|
-
publicSignals: publics.map(String),
|
|
2002
|
-
});
|
|
2003
2031
|
return {
|
|
2004
2032
|
pool: L,
|
|
2005
2033
|
pass: {
|
|
@@ -2008,12 +2036,13 @@ export class Essey {
|
|
|
2008
2036
|
expiryMs: credential.expiryMs,
|
|
2009
2037
|
n0: passN0,
|
|
2010
2038
|
},
|
|
2011
|
-
collLock:
|
|
2012
|
-
health:
|
|
2039
|
+
collLock: lockProved,
|
|
2040
|
+
health: healthProved,
|
|
2013
2041
|
market,
|
|
2014
2042
|
loanKey,
|
|
2015
2043
|
reqCommit,
|
|
2016
2044
|
reqSealed,
|
|
2045
|
+
memo,
|
|
2017
2046
|
closeMs,
|
|
2018
2047
|
collateralCommit: note,
|
|
2019
2048
|
lock: lock.spend,
|
|
@@ -2024,11 +2053,34 @@ export class Essey {
|
|
|
2024
2053
|
priceUpdate: await update(market),
|
|
2025
2054
|
};
|
|
2026
2055
|
}
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
const
|
|
2030
|
-
return
|
|
2056
|
+
saleGate(kind, type) {
|
|
2057
|
+
const current = this.config.packageOrigins.sale ?? notSetUp("the sale package is not published yet");
|
|
2058
|
+
const previous = previousOrigins(this.config, "sale");
|
|
2059
|
+
return asInvalid(() => saleKindGate(kind, type, { current, previous }));
|
|
2031
2060
|
}
|
|
2061
|
+
/** DECISION-R1-MIGRATION A: a loan whose type names `previous.packageOrigins.loan` is draining. */
|
|
2062
|
+
retired(row) {
|
|
2063
|
+
const pkg = row?.type?.split("::")[0];
|
|
2064
|
+
return pkg !== undefined && previousOrigins(this.config, "loan").includes(normalizeSuiAddress(pkg));
|
|
2065
|
+
}
|
|
2066
|
+
/**
|
|
2067
|
+
* A draining loan takes no opening kind (request read, offer, refi open) and none whose call changed shape in R1
|
|
2068
|
+
* (pick, settle, refi settle); it still cancels, repays, releases, reclaims, collects, tops up and heartbeats.
|
|
2069
|
+
*/
|
|
2070
|
+
refuseRetired(row) {
|
|
2071
|
+
if (this.retired(row))
|
|
2072
|
+
throw new EsseyError("INVALID_ARGUMENT", "refused: this loan is on a retired loan package and only finishes there (cancel, repay, release, reclaim, collect, top up, heartbeat); nothing was sent");
|
|
2073
|
+
}
|
|
2074
|
+
/** PRV-27 (b): past a step boundary nearer than the landing margin first, then the close `loan::check_close` takes. */
|
|
2075
|
+
async loanClose(offerWindowMs) {
|
|
2076
|
+
const step = this.config.closeStepMs ?? HOUR_MS;
|
|
2077
|
+
const now = () => (this.io.now ?? Date.now)();
|
|
2078
|
+
const wait = closeWaitMs(now(), step, Number(CLOSE_MARGIN_MS));
|
|
2079
|
+
if (wait > 0)
|
|
2080
|
+
await this.sleep(wait);
|
|
2081
|
+
return gridClose(now(), offerWindowMs, step);
|
|
2082
|
+
}
|
|
2083
|
+
/** The coins of the market a loan names, as `C/L` in the deployment record. */
|
|
2032
2084
|
pairOf(market) {
|
|
2033
2085
|
const want = address(market, "market");
|
|
2034
2086
|
const hit = Object.entries(this.config.objects.markets).find(([, id]) => id && address(id, "market") === want);
|
|
@@ -2047,6 +2099,7 @@ export class Essey {
|
|
|
2047
2099
|
const row = await read(loan);
|
|
2048
2100
|
if (!row)
|
|
2049
2101
|
unknownObject("no loan with this id");
|
|
2102
|
+
this.refuseRetired(row);
|
|
2050
2103
|
const json = row.json;
|
|
2051
2104
|
const round = row.round;
|
|
2052
2105
|
const refi = Number(json.state) === 8;
|
|
@@ -2120,15 +2173,17 @@ export class Essey {
|
|
|
2120
2173
|
const offers = row?.round?.offers;
|
|
2121
2174
|
return offers !== undefined && BigInt(offers.length) > seq;
|
|
2122
2175
|
}
|
|
2123
|
-
/**
|
|
2124
|
-
|
|
2176
|
+
/**
|
|
2177
|
+
* The lender's `loan_offer`: the principal locked to the round from up to two own notes, its sealed terms pinned.
|
|
2178
|
+
* PRV-23 A, SCOPE-R1-MOVE-BATCH D10: the rate is the posted one, so offers differ in nothing the winner draw weighs.
|
|
2179
|
+
*/
|
|
2180
|
+
async planOffer(loanId) {
|
|
2125
2181
|
const q = await this.readRequest(loanId, true);
|
|
2126
2182
|
assertRequestTerm(q.termMs, this.config.closeStepMs ?? HOUR_MS);
|
|
2127
2183
|
const L = q.pair[1];
|
|
2128
2184
|
if (poolId(this.config, L) !== q.poolL)
|
|
2129
2185
|
wrongCoinObject();
|
|
2130
|
-
|
|
2131
|
-
throw new EsseyError("INVALID_ARGUMENT", "the rate is above the request's maximum");
|
|
2186
|
+
const rateBps = q.maxRateBps;
|
|
2132
2187
|
const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
|
|
2133
2188
|
const { member, credential } = readState(this.statePath, this.stateKey);
|
|
2134
2189
|
const relayer = this.relayerAddress();
|
|
@@ -2174,7 +2229,15 @@ export class Essey {
|
|
|
2174
2229
|
const changeValue = spent[0].amount + spent[1].amount - q.principal - relayerFee;
|
|
2175
2230
|
const encChange = bytesOf(sealOpening({ value: changeValue, blinding: change.blinding, index: changeIndex }, noteEncKey(seed).encPub));
|
|
2176
2231
|
const encFee = bytesOf(fillerEnc());
|
|
2177
|
-
const
|
|
2232
|
+
const record = {
|
|
2233
|
+
noteIndex: offerIndex,
|
|
2234
|
+
principal: q.principal,
|
|
2235
|
+
rateBps,
|
|
2236
|
+
termMs: q.termMs,
|
|
2237
|
+
borrowerPk: q.borrowerPk,
|
|
2238
|
+
};
|
|
2239
|
+
const memo = sealMemo(memoKey(seed), { kind: MEMO_KIND.offer, key: q.loanKey, round: q.round }, offerMemoBody(record));
|
|
2240
|
+
const extHash = loanExt(LOAN_OFFER_KIND, q.loan, q.poolL, q.round, relayer, [encChange, encFee], blake2b256(Uint8Array.from([...sealed, ...memo])));
|
|
2178
2241
|
const witness = await loanOffer({
|
|
2179
2242
|
root: tree.root,
|
|
2180
2243
|
ins: spent,
|
|
@@ -2203,13 +2266,6 @@ export class Essey {
|
|
|
2203
2266
|
publicSignals: publics.map(String),
|
|
2204
2267
|
});
|
|
2205
2268
|
const { spend } = witness;
|
|
2206
|
-
const record = {
|
|
2207
|
-
noteIndex: offerIndex,
|
|
2208
|
-
principal: q.principal,
|
|
2209
|
-
rateBps,
|
|
2210
|
-
termMs: q.termMs,
|
|
2211
|
-
borrowerPk: q.borrowerPk,
|
|
2212
|
-
};
|
|
2213
2269
|
return {
|
|
2214
2270
|
record,
|
|
2215
2271
|
seq: q.seq,
|
|
@@ -2232,6 +2288,7 @@ export class Essey {
|
|
|
2232
2288
|
feeCt: spend.feeCt,
|
|
2233
2289
|
commit: witness.commit,
|
|
2234
2290
|
sealed,
|
|
2291
|
+
memo,
|
|
2235
2292
|
encChange,
|
|
2236
2293
|
encFee,
|
|
2237
2294
|
},
|
|
@@ -2295,6 +2352,8 @@ export class Essey {
|
|
|
2295
2352
|
const offer = offers?.[Number(seq)];
|
|
2296
2353
|
if (!offer?.active)
|
|
2297
2354
|
throw new EsseyError("INVALID_ARGUMENT", "seq is not an active offer of this round");
|
|
2355
|
+
if (pickOf(row.round) !== seq)
|
|
2356
|
+
throw new EsseyError("INVALID_ARGUMENT", "refused: only the round's pick can be slashed (offer::slash aborts 42_050); nothing was sent");
|
|
2298
2357
|
const approve = this.offerApprove(loan, loanKey, round, seq, pair);
|
|
2299
2358
|
const sealed = Uint8Array.from(Buffer.from(offer.sealed, "base64"));
|
|
2300
2359
|
const plain = await decrypt({ sealed, approve }).catch(() => undefined);
|
|
@@ -2303,6 +2362,58 @@ export class Essey {
|
|
|
2303
2362
|
const derived = await derive({ id: offerKeyId(loanKey, round, seq), approve });
|
|
2304
2363
|
return this.freeLoan(slashLoan, { pool: pair[1], loan, round, seq, keys: this.pinnedKeys(derived) });
|
|
2305
2364
|
}
|
|
2365
|
+
/**
|
|
2366
|
+
* PRV-23 A: the round's pick, drawn first when none is stored, opened through Seal: the one offer key the borrower
|
|
2367
|
+
* reads. A pick that does not open its commit and lock is slashed, which clears it, and drawn again (DOS-02). The
|
|
2368
|
+
* slots carry the pick alone as active, the one-slot witness `loan::settle_rows` folds (`loan.move:507-513`).
|
|
2369
|
+
*/
|
|
2370
|
+
async pickedSlots(q) {
|
|
2371
|
+
const field = lockField(q.loanKey, q.round);
|
|
2372
|
+
const slashed = new Set();
|
|
2373
|
+
for (let draw = 0; draw < SETTLE_SLOTS; draw++) {
|
|
2374
|
+
const round = await this.untilPicked(q, slashed);
|
|
2375
|
+
const pick = pickOf(round);
|
|
2376
|
+
const o = round.offers[Number(pick)];
|
|
2377
|
+
const sealed = Uint8Array.from(Buffer.from(o.sealed, "base64"));
|
|
2378
|
+
const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
|
|
2379
|
+
const approve = this.offerApprove(q.loan, q.loanKey, q.round, pick, q.pair);
|
|
2380
|
+
const plain = await decrypt({ sealed, approve });
|
|
2381
|
+
if (offerOpens(plain, field, BigInt(o.commit), BigInt(o.lock)))
|
|
2382
|
+
return round.offers.map((s, i) => ({
|
|
2383
|
+
commit: BigInt(s.commit),
|
|
2384
|
+
lock: BigInt(s.lock),
|
|
2385
|
+
active: BigInt(i) === pick,
|
|
2386
|
+
open: BigInt(i) === pick ? decodeOffer(plain) : undefined,
|
|
2387
|
+
}));
|
|
2388
|
+
await this.slashOffer(q.loan, pick);
|
|
2389
|
+
slashed.add(pick);
|
|
2390
|
+
}
|
|
2391
|
+
throw new EsseyError("INVALID_ARGUMENT", "refused: no offer of this round opens its commit and lock");
|
|
2392
|
+
}
|
|
2393
|
+
/**
|
|
2394
|
+
* The round once a pick shows that is none of `slashed`. With no pick, `loan_pick` goes once, alone: `pick::pick`
|
|
2395
|
+
* takes `Random` and must end its PTB (`move/v3/loan/sources/pick.move:1-3`). The reader may trail both writes.
|
|
2396
|
+
*/
|
|
2397
|
+
async untilPicked(q, slashed) {
|
|
2398
|
+
const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
|
|
2399
|
+
let sent = false;
|
|
2400
|
+
for (let i = 0; i < SETTLE_READS; i++) {
|
|
2401
|
+
const round = (await read(q.loan))?.round;
|
|
2402
|
+
if (!round)
|
|
2403
|
+
unknownObject("the loan's round is missing");
|
|
2404
|
+
const pick = pickOf(round);
|
|
2405
|
+
const trailing = [...slashed].some((s) => round.offers[Number(s)]?.active) || (pick !== null && slashed.has(pick));
|
|
2406
|
+
if (!trailing && pick !== null)
|
|
2407
|
+
return round;
|
|
2408
|
+
if (!trailing && !sent) {
|
|
2409
|
+
await this.freeLoan(pickLoan, { pool: q.pair[1], loan: q.loan });
|
|
2410
|
+
sent = true;
|
|
2411
|
+
continue;
|
|
2412
|
+
}
|
|
2413
|
+
await this.sleep(SETTLE_READ_MS);
|
|
2414
|
+
}
|
|
2415
|
+
throw new EsseyError("STATE_REFUSED", "the loan read does not show the round's pick yet");
|
|
2416
|
+
}
|
|
2306
2417
|
/** Threshold many derived keys, each with its server's slot in `config.seal.servers` (`seal_servers::public_keys` order). */
|
|
2307
2418
|
pinnedKeys(derived) {
|
|
2308
2419
|
const servers = this.config.seal.servers.map((s) => s.objectId);
|
|
@@ -2366,6 +2477,7 @@ export class Essey {
|
|
|
2366
2477
|
const row = await read(loan);
|
|
2367
2478
|
if (!row)
|
|
2368
2479
|
unknownObject("no loan with this id");
|
|
2480
|
+
this.refuseRetired(row);
|
|
2369
2481
|
const json = row.json;
|
|
2370
2482
|
if (Number(json.state) !== 2 && Number(json.state) !== 8)
|
|
2371
2483
|
throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
|
|
@@ -2446,7 +2558,8 @@ export class Essey {
|
|
|
2446
2558
|
proof: `0x${Buffer.from(proof).toString("hex")}`,
|
|
2447
2559
|
};
|
|
2448
2560
|
const digest = await this.sponsoredSend(signer, txKindB64, wire, relayer);
|
|
2449
|
-
|
|
2561
|
+
// PRV-16: a badge keeps no pass tag (keeper.move:53-60); the fresh holder this mint alone used finds it.
|
|
2562
|
+
const row = await this.listedByKey("badge", "holder", holder, async (c) => {
|
|
2450
2563
|
const page = await readBadges(c);
|
|
2451
2564
|
return { rows: page.badges, next: page.next };
|
|
2452
2565
|
});
|
|
@@ -2483,12 +2596,15 @@ export class Essey {
|
|
|
2483
2596
|
const { price, standin } = await this.keeperFeed(market);
|
|
2484
2597
|
const prover = this.prover();
|
|
2485
2598
|
return async (viewer) => {
|
|
2599
|
+
// PRV-16: nonce 0 is the badge mint's; a read takes a fresh one, so no two reads show one tag (keeper.move:255-256).
|
|
2600
|
+
const nonce = drawSecret();
|
|
2486
2601
|
const pass = membership({
|
|
2487
2602
|
secrets: member,
|
|
2488
2603
|
credential: credential,
|
|
2489
2604
|
domain: DOMAIN_KEEPER,
|
|
2490
2605
|
room: keeper.registry.id,
|
|
2491
2606
|
bind: viewer,
|
|
2607
|
+
nonce,
|
|
2492
2608
|
});
|
|
2493
2609
|
const proved = await prover.prove("membership", pass.input);
|
|
2494
2610
|
return {
|
|
@@ -2504,6 +2620,7 @@ export class Essey {
|
|
|
2504
2620
|
{ pure: "u256", value: pass.publics[0].toString() },
|
|
2505
2621
|
{ pure: "u64", value: credential.expiryMs.toString() },
|
|
2506
2622
|
{ pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
|
|
2623
|
+
{ pure: "u256", value: nonce.toString() },
|
|
2507
2624
|
{ object: "0x6" },
|
|
2508
2625
|
],
|
|
2509
2626
|
};
|
|
@@ -2534,13 +2651,7 @@ export class Essey {
|
|
|
2534
2651
|
}
|
|
2535
2652
|
return notSetUp("no Pyth market in the deployment");
|
|
2536
2653
|
}
|
|
2537
|
-
/** The borrower's
|
|
2538
|
-
async openOffer(loan, loanKey, round, seq, sealed, pair) {
|
|
2539
|
-
const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
|
|
2540
|
-
const plain = await decrypt({ sealed, approve: this.offerApprove(loan, loanKey, round, seq, pair) });
|
|
2541
|
-
return decodeOffer(plain);
|
|
2542
|
-
}
|
|
2543
|
-
/** The borrower's `loan_settle` on round 0: the lowest eligible offer wins, keeper ciphertext v1 carries its terms. */
|
|
2654
|
+
/** The borrower's `loan_settle` on round 0: the round's pick wins, keeper ciphertext v1 carries its terms. */
|
|
2544
2655
|
async planSettle(id, collAmt) {
|
|
2545
2656
|
const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
|
|
2546
2657
|
const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
|
|
@@ -2548,19 +2659,12 @@ export class Essey {
|
|
|
2548
2659
|
// settle.move:131-135 refuses a settle until now_s * 1000 reaches close_ms.
|
|
2549
2660
|
if (BigInt(Math.floor((this.io.now ?? Date.now)() / 1000)) * 1000n < q.closeMs)
|
|
2550
2661
|
throw new EsseyError("INVALID_ARGUMENT", "refused: the offer window is still open");
|
|
2551
|
-
const row = await read(q.loan);
|
|
2552
|
-
const json = row.json;
|
|
2553
2662
|
const seed = this.seed();
|
|
2554
|
-
const
|
|
2555
|
-
|
|
2556
|
-
const slots =
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
const open = o.active
|
|
2560
|
-
? await this.openOffer(q.loan, q.loanKey, q.round, BigInt(i), sealed, q.pair)
|
|
2561
|
-
: undefined;
|
|
2562
|
-
slots.push({ commit: BigInt(o.commit), lock: BigInt(o.lock), active: o.active, open });
|
|
2563
|
-
}
|
|
2663
|
+
const first = (await read(q.loan)).json;
|
|
2664
|
+
this.ownOpening(seed, first, q.borrowerPk, collAmt);
|
|
2665
|
+
const slots = await this.pickedSlots(q);
|
|
2666
|
+
const json = (await read(q.loan)).json;
|
|
2667
|
+
const { opening, index: keyIndex } = this.ownOpening(seed, json, q.borrowerPk, collAmt);
|
|
2564
2668
|
const { member, credential } = readState(this.statePath, this.stateKey);
|
|
2565
2669
|
const L = q.pair[1];
|
|
2566
2670
|
const prover = this.prover();
|
|
@@ -2602,6 +2706,12 @@ export class Essey {
|
|
|
2602
2706
|
if (w.termsCommit !== draft.termsCommit)
|
|
2603
2707
|
throw new EsseyError("INVALID_ARGUMENT", "refused: the terms moved between drafts");
|
|
2604
2708
|
const settleProof = await prover.prove("loan_settle", w.input);
|
|
2709
|
+
const memo = this.settleMemo(seed, q.loanKey, q.round, {
|
|
2710
|
+
keyIndex,
|
|
2711
|
+
collAmt: opening.amount,
|
|
2712
|
+
borrowerPk: q.borrowerPk,
|
|
2713
|
+
terms: w.terms,
|
|
2714
|
+
});
|
|
2605
2715
|
const args = settleArgs({
|
|
2606
2716
|
loan: q.loan,
|
|
2607
2717
|
poolL: q.poolL,
|
|
@@ -2617,6 +2727,7 @@ export class Essey {
|
|
|
2617
2727
|
keeperCt,
|
|
2618
2728
|
encs,
|
|
2619
2729
|
nowS,
|
|
2730
|
+
memo,
|
|
2620
2731
|
});
|
|
2621
2732
|
const n0 = actionHash(blake2b256, q.loanKey, BigInt(json.nonce), "settle", args);
|
|
2622
2733
|
const room = keyId(q.loanKey);
|
|
@@ -2655,9 +2766,13 @@ export class Essey {
|
|
|
2655
2766
|
encPrincipal,
|
|
2656
2767
|
encFee,
|
|
2657
2768
|
nowS,
|
|
2769
|
+
memo,
|
|
2658
2770
|
},
|
|
2659
2771
|
};
|
|
2660
2772
|
}
|
|
2773
|
+
settleMemo(seed, loanKey, round, record) {
|
|
2774
|
+
return sealMemo(memoKey(seed), { kind: MEMO_KIND.settle, key: loanKey, round }, settleMemoBody(record));
|
|
2775
|
+
}
|
|
2661
2776
|
/** The borrower's `loan_repay`: `owed` to the lender's note by ECDH on its enc key, change back to own key. */
|
|
2662
2777
|
async planRepay(loanId, terms, borrowerPk) {
|
|
2663
2778
|
const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
|
|
@@ -3044,6 +3159,7 @@ export class Essey {
|
|
|
3044
3159
|
const row = await read(loan);
|
|
3045
3160
|
if (!row)
|
|
3046
3161
|
unknownObject("no loan with this id");
|
|
3162
|
+
this.refuseRetired(row);
|
|
3047
3163
|
const json = row.json;
|
|
3048
3164
|
if (Number(json.state) !== 2)
|
|
3049
3165
|
throw new EsseyError("INVALID_ARGUMENT", "the loan is not active");
|
|
@@ -3061,20 +3177,24 @@ export class Essey {
|
|
|
3061
3177
|
salt: poseidonHash([own.sk, own.blinding, 2n, round]),
|
|
3062
3178
|
};
|
|
3063
3179
|
const reqCommit = requestCommit(request, p.borrowerPk, collNote(opening));
|
|
3064
|
-
const
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
|
|
3074
|
-
|
|
3075
|
-
|
|
3076
|
-
|
|
3077
|
-
|
|
3180
|
+
const send = async () => {
|
|
3181
|
+
const closeMs = await this.loanClose(p.offerWindowMs);
|
|
3182
|
+
const reqSealed = await seal({
|
|
3183
|
+
id: requestKeyId(opening.loanKey),
|
|
3184
|
+
data: requestPlaintext({
|
|
3185
|
+
...request,
|
|
3186
|
+
borrowerPk: p.borrowerPk,
|
|
3187
|
+
closeMs,
|
|
3188
|
+
market,
|
|
3189
|
+
coinTypes: [this.config.coins[C].type, this.config.coins[L].type],
|
|
3190
|
+
}),
|
|
3191
|
+
});
|
|
3192
|
+
const args = openRefiArgs({ loan, poolL, reqCommit, reqSealed, closeMs });
|
|
3193
|
+
const pass = await this.borrowerPass(json, "refi", args);
|
|
3194
|
+
const body = { pool: L, loan, pass, reqCommit, reqSealed, closeMs };
|
|
3195
|
+
return { ...(await this.freeLoan(refinanceLoan, body)), round, closeMs };
|
|
3196
|
+
};
|
|
3197
|
+
return send().catch((err) => (lateClose(err) ? send() : Promise.reject(err)));
|
|
3078
3198
|
}
|
|
3079
3199
|
/**
|
|
3080
3200
|
* `refi::settle_refi`: the round's offers opened as `planSettle` opens them, the request read back through Seal, the
|
|
@@ -3086,23 +3206,17 @@ export class Essey {
|
|
|
3086
3206
|
const readReading = this.io.readReading ?? notSetUp("missing config: no reading reader");
|
|
3087
3207
|
const update = this.io.priceUpdate ?? notSetUp("missing config: no price update source");
|
|
3088
3208
|
const q = await this.readRequest(p.loan);
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
3209
|
+
if (BigInt((this.io.now ?? Date.now)()) < q.closeMs)
|
|
3210
|
+
throw new EsseyError("INVALID_ARGUMENT", "refused: the offer window is still open");
|
|
3211
|
+
const opened = (await read(q.loan)).json;
|
|
3212
|
+
if (termsCommit(p.terms, p.borrowerPk) !== BigInt(opened.terms_commit))
|
|
3092
3213
|
throw new EsseyError("CT_MISMATCH", "refused: the terms do not open the loan's terms_commit");
|
|
3093
|
-
const
|
|
3094
|
-
const
|
|
3095
|
-
for (const [i, o] of round.offers.entries()) {
|
|
3096
|
-
const sealed = Uint8Array.from(Buffer.from(o.sealed, "base64"));
|
|
3097
|
-
const open = o.active
|
|
3098
|
-
? await this.openOffer(q.loan, q.loanKey, q.round, BigInt(i), sealed, q.pair)
|
|
3099
|
-
: undefined;
|
|
3100
|
-
slots.push({ commit: BigInt(o.commit), lock: BigInt(o.lock), active: o.active, open });
|
|
3101
|
-
}
|
|
3214
|
+
const slots = await this.pickedSlots(q);
|
|
3215
|
+
const json = (await read(q.loan)).json;
|
|
3102
3216
|
const [C, L] = q.pair;
|
|
3103
3217
|
const market = address(json.market_id, "market");
|
|
3104
3218
|
const seed = this.seed();
|
|
3105
|
-
const { opening } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
|
|
3219
|
+
const { opening, index: keyIndex } = this.ownOpening(seed, json, p.borrowerPk, p.collAmt);
|
|
3106
3220
|
const r = await readReading(market);
|
|
3107
3221
|
const pClaim = r.spot < r.ema ? r.spot : r.ema;
|
|
3108
3222
|
const rates = await this.rates(market);
|
|
@@ -3160,6 +3274,12 @@ export class Essey {
|
|
|
3160
3274
|
if (w.termsCommit !== draft.termsCommit)
|
|
3161
3275
|
throw new EsseyError("INVALID_ARGUMENT", "refused: the terms moved between drafts");
|
|
3162
3276
|
const refiProof = await this.prover().prove("loan_refi", w.input);
|
|
3277
|
+
const memo = this.settleMemo(seed, q.loanKey, q.round, {
|
|
3278
|
+
keyIndex,
|
|
3279
|
+
collAmt: opening.amount,
|
|
3280
|
+
borrowerPk: p.borrowerPk,
|
|
3281
|
+
terms: w.terms,
|
|
3282
|
+
});
|
|
3163
3283
|
const args = settleRefiArgs({
|
|
3164
3284
|
loan: q.loan,
|
|
3165
3285
|
poolL: q.poolL,
|
|
@@ -3182,6 +3302,7 @@ export class Essey {
|
|
|
3182
3302
|
encs,
|
|
3183
3303
|
encsP,
|
|
3184
3304
|
nowS,
|
|
3305
|
+
memo,
|
|
3185
3306
|
});
|
|
3186
3307
|
const pass = await this.borrowerPass(json, "settle_refi", args);
|
|
3187
3308
|
const landed = await this.freeLoan(settleRefiLoan, {
|
|
@@ -3206,6 +3327,7 @@ export class Essey {
|
|
|
3206
3327
|
encs,
|
|
3207
3328
|
encsP,
|
|
3208
3329
|
nowS,
|
|
3330
|
+
memo,
|
|
3209
3331
|
priceUpdate: await update(market),
|
|
3210
3332
|
});
|
|
3211
3333
|
return { ...landed, rateBps: w.terms.rateBps, terms: w.terms };
|
|
@@ -3316,6 +3438,48 @@ export class Essey {
|
|
|
3316
3438
|
}
|
|
3317
3439
|
throw new EsseyError("CT_MISMATCH", "refused: no spend of own notes opens the locked note");
|
|
3318
3440
|
}
|
|
3441
|
+
/**
|
|
3442
|
+
* SCOPE-R1-MEMO D6: every listed loan's memos trial-opened under this seed's memo key. The AAD names the loan key,
|
|
3443
|
+
* round and slot, so a memo sealed for another seed, or copied into another loan, does not open.
|
|
3444
|
+
*/
|
|
3445
|
+
async recoverRecords() {
|
|
3446
|
+
const readLoans = this.io.readLoans ?? notSetUp("missing config: no loan reader");
|
|
3447
|
+
const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
|
|
3448
|
+
const key = memoKey(this.seed());
|
|
3449
|
+
const out = { loans: [], offers: [] };
|
|
3450
|
+
const bytes = (v) => typeof v === "string" ? Uint8Array.from(Buffer.from(v, "base64")) : new Uint8Array();
|
|
3451
|
+
let cursor = null;
|
|
3452
|
+
let pages = 0;
|
|
3453
|
+
for (;;) {
|
|
3454
|
+
const page = await readLoans(cursor);
|
|
3455
|
+
pages += 1;
|
|
3456
|
+
for (const row of page.loans) {
|
|
3457
|
+
const loan = address(row.id, "loan id");
|
|
3458
|
+
const json = row.json;
|
|
3459
|
+
const loanKey = BigInt(json.loan_key);
|
|
3460
|
+
const last = BigInt(json.round ?? 0);
|
|
3461
|
+
let record = null;
|
|
3462
|
+
for (let r = 0n; r <= last; r++) {
|
|
3463
|
+
const round = (r === last && row.round !== undefined ? row.round : (await read(loan, r))?.round);
|
|
3464
|
+
if (!round)
|
|
3465
|
+
continue;
|
|
3466
|
+
if (r === 0n)
|
|
3467
|
+
record = openRequestMemo(key, loanKey, bytes(round.req_memo)) ?? record;
|
|
3468
|
+
record = openSettleMemo(key, loanKey, r, bytes(round.settle_memo)) ?? record;
|
|
3469
|
+
(round.offers ?? []).forEach((o, seq) => {
|
|
3470
|
+
const offer = openOfferMemo(key, loanKey, r, bytes(o.memo));
|
|
3471
|
+
if (offer)
|
|
3472
|
+
out.offers.push({ loan, round: r, seq, record: offer });
|
|
3473
|
+
});
|
|
3474
|
+
}
|
|
3475
|
+
if (record)
|
|
3476
|
+
out.loans.push({ loan, record });
|
|
3477
|
+
}
|
|
3478
|
+
cursor = afterPage(page.next, pages);
|
|
3479
|
+
if (cursor === null)
|
|
3480
|
+
return out;
|
|
3481
|
+
}
|
|
3482
|
+
}
|
|
3319
3483
|
/** `reclaim::reclaim`: the lender's Lock4 among the round's resolved locks, refunded to a fresh own note. */
|
|
3320
3484
|
async reclaimOffer(loanId, offer, roundArg) {
|
|
3321
3485
|
const read = this.io.readLoan ?? notSetUp("missing config: no loan reader");
|
|
@@ -3418,9 +3582,9 @@ export class Essey {
|
|
|
3418
3582
|
const market = address(json.market_id, "market");
|
|
3419
3583
|
const expiryMs = await this.heartbeatExpiry(json, market, p.terms.maturityS, p.expiryMs);
|
|
3420
3584
|
const { opening } = this.ownOpening(this.seed(), json, p.borrowerPk, p.collAmt);
|
|
3421
|
-
const k = p.k ?? 1;
|
|
3422
3585
|
const reading = await readPrice(market);
|
|
3423
|
-
const
|
|
3586
|
+
const retired = this.retired(row);
|
|
3587
|
+
const floor = retired ? legacyHeartbeatFloor(reading) : heartbeatFloor(reading);
|
|
3424
3588
|
const fee = await this.loanFee(C, json.coll_fee_commit);
|
|
3425
3589
|
const rates = {
|
|
3426
3590
|
ltvBps: BigInt(json.ltv_bps),
|
|
@@ -3455,9 +3619,9 @@ export class Essey {
|
|
|
3455
3619
|
statement: h.statement,
|
|
3456
3620
|
wait: true,
|
|
3457
3621
|
encs,
|
|
3458
|
-
k,
|
|
3459
3622
|
expiryMs,
|
|
3460
3623
|
priceUpdate: await update(market),
|
|
3624
|
+
retired,
|
|
3461
3625
|
}));
|
|
3462
3626
|
return { ...landed, expiryMs };
|
|
3463
3627
|
}
|
|
@@ -3509,11 +3673,13 @@ export class Essey {
|
|
|
3509
3673
|
const fresh = coverExpiry(now, maturityS);
|
|
3510
3674
|
if (asked === undefined && fresh < now + gap)
|
|
3511
3675
|
throw new EsseyError("INVALID_ARGUMENT", "the loan is under one gap from maturity plus grace");
|
|
3512
|
-
const expiry = asked ?? (
|
|
3676
|
+
const expiry = asked ?? coverOverStored(fresh, stored);
|
|
3513
3677
|
if (expiry < now + gap || expiry > now + H_MAX_MS)
|
|
3514
3678
|
throw new EsseyError("INVALID_ARGUMENT", "the expiry must be at least one gap and at most 24 h ahead");
|
|
3515
3679
|
if (expiry < stored)
|
|
3516
3680
|
throw new EsseyError("INVALID_ARGUMENT", "the expiry cannot be earlier than the loan's current heartbeat expiry");
|
|
3681
|
+
if (expiry % COVER_STEP_MS !== 0n)
|
|
3682
|
+
throw new EsseyError("INVALID_ARGUMENT", "the expiry must be on the 5-minute cover step");
|
|
3517
3683
|
return expiry;
|
|
3518
3684
|
}
|
|
3519
3685
|
/**
|
|
@@ -3848,20 +4014,10 @@ export class Essey {
|
|
|
3848
4014
|
});
|
|
3849
4015
|
}
|
|
3850
4016
|
/** The seller keys and bounds salt of the sale opened at note index `index`, so the seed alone reopens them. */
|
|
3851
|
-
saleOpening(seed, index) {
|
|
3852
|
-
const own = deriveNoteKey(seed, index);
|
|
3853
|
-
const tagged = (t) => poseidonHash([own.sk, own.blinding, t]);
|
|
3854
|
-
return { sellerSk: own.sk, sellerSecret: tagged(7n), boundsSalt: tagged(8n) };
|
|
3855
|
-
}
|
|
3856
4017
|
/** D-SPEC §6.2:599. The seller pass over `sale_room::open_args`, at action nonce 0; the relayer or the callback pays. */
|
|
3857
4018
|
async openSale(p) {
|
|
3858
|
-
const
|
|
3859
|
-
|
|
3860
|
-
const nowMs = (this.io.now ?? Date.now)();
|
|
3861
|
-
const open = {
|
|
3862
|
-
...asked,
|
|
3863
|
-
closeMs: stepClose(nowMs + asked.bidWindowMs, nowMs, SALE_MAX_WINDOW_MS, this.config.closeStepMs),
|
|
3864
|
-
};
|
|
4019
|
+
const open = assertSaleOpen(p);
|
|
4020
|
+
await this.saleWindow(open);
|
|
3865
4021
|
requireSale(this.config);
|
|
3866
4022
|
const pool = poolId(this.config, open.coin);
|
|
3867
4023
|
const item = { id: address(open.itemId, "itemId"), type: open.itemType };
|
|
@@ -3869,22 +4025,26 @@ export class Essey {
|
|
|
3869
4025
|
const submit = (open.sponsored ?? this.sponsoring() !== null)
|
|
3870
4026
|
? await this.saleSponsor(pool, item.id)
|
|
3871
4027
|
: (this.io.submitSaleOpen ?? notSetUp("missing config: sale open has no submitter"));
|
|
3872
|
-
const
|
|
3873
|
-
const
|
|
3874
|
-
const typeName = asInvalid(() => {
|
|
3875
|
-
assertFinishWindow(closeMs, finishByMs);
|
|
3876
|
-
return typeNameOf(open.itemType);
|
|
3877
|
-
});
|
|
3878
|
-
const shape = { pool, item: { id: item.id, typeName }, closeMs, finishByMs, maxBids: open.maxBids };
|
|
4028
|
+
const typeName = asInvalid(() => typeNameOf(open.itemType));
|
|
4029
|
+
const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
|
|
3879
4030
|
const { secrets, credential } = this.member();
|
|
3880
4031
|
const prover = this.prover();
|
|
3881
4032
|
const seed = await this.keys();
|
|
3882
4033
|
const noteIndex = this.reserve("notes");
|
|
3883
|
-
const
|
|
3884
|
-
const
|
|
3885
|
-
const
|
|
4034
|
+
const s = saleSecrets(deriveNoteKey(seed, noteIndex));
|
|
4035
|
+
const commits = openCommits(s, open.price);
|
|
4036
|
+
const bounds = { lo: open.price, hi: open.price, salt: s.boundsSalt };
|
|
3886
4037
|
const saleKey = drawSecret();
|
|
3887
|
-
const
|
|
4038
|
+
const listing = await seal({
|
|
4039
|
+
id: listingKeyId(saleKey),
|
|
4040
|
+
data: listingPlaintext({ price: open.price, salt: s.postedSalt }),
|
|
4041
|
+
pkg: "sale",
|
|
4042
|
+
});
|
|
4043
|
+
const memo = sealSaleMemo(memoKey(seed), saleKey, { noteIndex, price: open.price });
|
|
4044
|
+
const t = await this.saleWindow(open);
|
|
4045
|
+
const { closeMs, finishByMs } = t;
|
|
4046
|
+
const shape = { pool, item: { id: item.id, typeName }, closeMs, finishByMs, maxBids: open.maxBids };
|
|
4047
|
+
const n0 = actionHash(blake2b256, saleKey, 0n, "open", openArgs({ ...shape, ...commits, listing, memo, saleKey }));
|
|
3888
4048
|
const pass = membership({
|
|
3889
4049
|
secrets,
|
|
3890
4050
|
credential,
|
|
@@ -3893,11 +4053,14 @@ export class Essey {
|
|
|
3893
4053
|
bind: keyId(n0),
|
|
3894
4054
|
});
|
|
3895
4055
|
const proved = await prover.prove("membership", pass.input);
|
|
4056
|
+
await this.untilLandable(t);
|
|
3896
4057
|
const landed = await submit({
|
|
3897
4058
|
coin: open.coin,
|
|
3898
4059
|
item,
|
|
3899
4060
|
saleKey,
|
|
3900
4061
|
...commits,
|
|
4062
|
+
listing,
|
|
4063
|
+
memo,
|
|
3901
4064
|
closeMs,
|
|
3902
4065
|
finishByMs,
|
|
3903
4066
|
maxBids: open.maxBids,
|
|
@@ -3915,7 +4078,8 @@ export class Essey {
|
|
|
3915
4078
|
const page = await readRooms(c);
|
|
3916
4079
|
return { rows: page.rooms, next: page.next };
|
|
3917
4080
|
});
|
|
3918
|
-
assertRoomMatches(this.config, open, { id, json });
|
|
4081
|
+
assertRoomMatches(this.config, { ...open, closeMs: Number(closeMs) }, { id, json });
|
|
4082
|
+
const seller = { sellerSk: s.sellerSk, sellerSecret: s.sellerSecret };
|
|
3919
4083
|
return {
|
|
3920
4084
|
id,
|
|
3921
4085
|
digest: landed.digest,
|
|
@@ -3923,6 +4087,20 @@ export class Essey {
|
|
|
3923
4087
|
sale: { room: id, noteIndex, seller, bounds },
|
|
3924
4088
|
};
|
|
3925
4089
|
}
|
|
4090
|
+
/** PRV-27 (b), `sale_room::check_grid` (44_041): the close and finish a sale opening about now must carry. */
|
|
4091
|
+
async saleWindow(open) {
|
|
4092
|
+
const nowMs = (this.io.now ?? Date.now)();
|
|
4093
|
+
const asked = { nowMs, bidWindowMs: open.bidWindowMs, finishWindowMs: open.finishWindowMs };
|
|
4094
|
+
return asInvalid(() => saleTimes({ ...asked, marginMs: SALE_LAND_MARGIN_MS }));
|
|
4095
|
+
}
|
|
4096
|
+
/** An open landing outside `[landFromMs, landByMs]` aborts 44_041: wait for the start, refuse past the end. */
|
|
4097
|
+
async untilLandable(t) {
|
|
4098
|
+
const now = BigInt((this.io.now ?? Date.now)());
|
|
4099
|
+
if (now < t.landFromMs)
|
|
4100
|
+
await this.sleep(Number(t.landFromMs - now));
|
|
4101
|
+
if (BigInt((this.io.now ?? Date.now)()) > t.landByMs)
|
|
4102
|
+
throw new EsseyError("INVALID_ARGUMENT", "refused: the open's proofs took past its close step, so it would land off the grid (44_041); nothing was sent");
|
|
4103
|
+
}
|
|
3926
4104
|
/**
|
|
3927
4105
|
* The sponsored open (E-34): a fresh seed-derived sender signs `from_proof` and `open` while the relayer pays gas.
|
|
3928
4106
|
* PRV-35: an item at one of this seed's `itemAddress()` holders opens from that holder with no hand-over; any other
|
|
@@ -4015,16 +4193,29 @@ export class Essey {
|
|
|
4015
4193
|
const bounds = this.io.roomBounds ? await this.io.roomBounds(key) : null;
|
|
4016
4194
|
return viewRoomObject(this.config, { id: key, json: row.json }, bounds);
|
|
4017
4195
|
}
|
|
4018
|
-
|
|
4196
|
+
/**
|
|
4197
|
+
* The room, refused for `kind` when its type names a retired sale package that does not take it
|
|
4198
|
+
* (DECISION-R1-MIGRATION A, `sales/package-gate.ts`). `legacy`: such a room's `finish` opens every active bid.
|
|
4199
|
+
*/
|
|
4200
|
+
async saleRoom(id, kind) {
|
|
4019
4201
|
requireSale(this.config);
|
|
4020
4202
|
const read = this.io.readRoom ?? notSetUp("missing config: no room reader");
|
|
4021
4203
|
const room = address(id, "room id");
|
|
4022
4204
|
const row = await read(room);
|
|
4023
4205
|
if (!row)
|
|
4024
4206
|
unknownObject("no room with this id");
|
|
4207
|
+
const { legacy } = row.type ? this.saleGate(kind, row.type) : { legacy: false };
|
|
4208
|
+
// A retired room's Seal policy is its own package's; an old package id stays callable (DECISION-R1-MIGRATION).
|
|
4209
|
+
const policyPkg = legacy ? salePackageOf(row.type) : this.config.packages.sale;
|
|
4025
4210
|
const json = row.json;
|
|
4026
4211
|
const bids = (json.bids ?? []);
|
|
4212
|
+
const pick = optionU256(json.pick, "the room's pick");
|
|
4027
4213
|
return {
|
|
4214
|
+
legacy,
|
|
4215
|
+
policyPkg,
|
|
4216
|
+
pick: pick === null ? null : Number(pick),
|
|
4217
|
+
postedCommit: BigInt(json.posted_commit ?? 0),
|
|
4218
|
+
listing: optionBytes(json.listing),
|
|
4028
4219
|
id: room,
|
|
4029
4220
|
coin: coinByPool(this.config, String(json.pool_id)),
|
|
4030
4221
|
saleKey: BigInt(json.sale_key),
|
|
@@ -4063,16 +4254,72 @@ export class Essey {
|
|
|
4063
4254
|
if (this.nowMs() + CLOSE_MARGIN_MS > closeMs)
|
|
4064
4255
|
throw new EsseyError("INVALID_ARGUMENT", `${what} has closed or closes within 2 minutes, too soon to prove and land; nothing was sent`);
|
|
4065
4256
|
}
|
|
4066
|
-
|
|
4067
|
-
|
|
4068
|
-
|
|
4069
|
-
|
|
4257
|
+
/**
|
|
4258
|
+
* `sale_room::seal_approve_listing`: a SEAL pass under a fresh non-zero nonce, bound to the viewer, as the loan
|
|
4259
|
+
* request read takes (`readRequest`), so two reads show two tags.
|
|
4260
|
+
*/
|
|
4261
|
+
async readRoomListing(room) {
|
|
4262
|
+
const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
|
|
4263
|
+
const passKey = this.config.objects.passKey ?? notSetUp("missing config: no PassKey");
|
|
4264
|
+
const { member, credential } = readState(this.statePath, this.stateKey);
|
|
4265
|
+
if (!member || !credential)
|
|
4266
|
+
notSetUp("no credential: call credential.obtain first");
|
|
4267
|
+
if (!room.listing)
|
|
4268
|
+
unknownObject("the room holds no sealed listing");
|
|
4269
|
+
const scope = keyId(room.saleKey);
|
|
4270
|
+
const prover = this.prover();
|
|
4271
|
+
return decrypt({
|
|
4272
|
+
sealed: room.listing,
|
|
4273
|
+
pkg: "sale",
|
|
4274
|
+
approve: async (viewer) => {
|
|
4275
|
+
const nonce = drawSecret();
|
|
4276
|
+
const bind = `0x${Buffer.from(sealListingBind(scope, viewer)).toString("hex")}`;
|
|
4277
|
+
const pass = membership({
|
|
4278
|
+
secrets: member,
|
|
4279
|
+
credential: credential,
|
|
4280
|
+
domain: DOMAIN_SENDER,
|
|
4281
|
+
room: scope,
|
|
4282
|
+
bind,
|
|
4283
|
+
nonce,
|
|
4284
|
+
});
|
|
4285
|
+
const proved = await prover.prove("membership", pass.input);
|
|
4286
|
+
return {
|
|
4287
|
+
target: `${this.config.packages.sale}::sale_room::seal_approve_listing`,
|
|
4288
|
+
typeArguments: [this.config.coins[room.coin].type],
|
|
4289
|
+
args: [
|
|
4290
|
+
{ pure: "vector<u8>", value: `0x${Buffer.from(listingKeyId(room.saleKey)).toString("hex")}` },
|
|
4291
|
+
{ object: room.id },
|
|
4292
|
+
{ object: passKey.id },
|
|
4293
|
+
{ pure: "u256", value: pass.publics[0].toString() },
|
|
4294
|
+
{ pure: "u256", value: nonce.toString() },
|
|
4295
|
+
{ pure: "u64", value: credential.expiryMs.toString() },
|
|
4296
|
+
{ pure: "vector<u8>", value: `0x${Buffer.from(proofBytes(proved.proof)).toString("hex")}` },
|
|
4297
|
+
{ object: "0x6" },
|
|
4298
|
+
],
|
|
4299
|
+
};
|
|
4300
|
+
},
|
|
4301
|
+
});
|
|
4302
|
+
}
|
|
4303
|
+
async placeBid(roomId, maxPrice, asked) {
|
|
4304
|
+
if (typeof maxPrice !== "bigint" || maxPrice <= 0n || (asked !== undefined && typeof asked !== "bigint"))
|
|
4305
|
+
throw new EsseyError("INVALID_ARGUMENT", "maxPrice must be above 0 and amount a bigint");
|
|
4306
|
+
const room = await this.saleRoom(roomId, "bid");
|
|
4070
4307
|
if (room.state !== SALE_STATE.open)
|
|
4071
4308
|
throw new EsseyError("INVALID_ARGUMENT", "the room is not taking bids");
|
|
4072
4309
|
this.assertBeforeClose(room.closeMs, "the room");
|
|
4073
4310
|
const seq = room.bids.length;
|
|
4074
4311
|
if (seq >= room.maxBids)
|
|
4075
4312
|
throw new EsseyError("INVALID_ARGUMENT", "the room is full");
|
|
4313
|
+
const plain = await this.readRoomListing(room);
|
|
4314
|
+
const listing = asInvalid(() => readListing(plain, room.postedCommit));
|
|
4315
|
+
if (!listing)
|
|
4316
|
+
throw new EsseyError("CT_MISMATCH", "refused: the listing does not open the room's posted price");
|
|
4317
|
+
const v = listing.price;
|
|
4318
|
+
if (v > maxPrice)
|
|
4319
|
+
throw new EsseyError("INVALID_ARGUMENT", "refused: the posted price is above maxPrice; nothing was sent");
|
|
4320
|
+
const amount = asked ?? v;
|
|
4321
|
+
if (amount < v)
|
|
4322
|
+
throw new EsseyError("INVALID_ARGUMENT", "the deposit must cover the posted price");
|
|
4076
4323
|
const seal = this.io.sealEncrypt ?? notSetUp("missing config: no Seal encryptor");
|
|
4077
4324
|
const { member, credential } = readState(this.statePath, this.stateKey);
|
|
4078
4325
|
if (!member || !credential)
|
|
@@ -4097,7 +4344,8 @@ export class Essey {
|
|
|
4097
4344
|
const record = { room: room.id, noteIndex: this.reserve("notes"), v, amount };
|
|
4098
4345
|
const changeIndex = this.reserve("notes");
|
|
4099
4346
|
const change = deriveNoteKey(seed, changeIndex);
|
|
4100
|
-
const secrets = this.bidSecrets(seed, record);
|
|
4347
|
+
const secrets = { ...this.bidSecrets(seed, record), s: listing.salt };
|
|
4348
|
+
const memo = sealBidMemo(memoKey(seed), room.saleKey, record);
|
|
4101
4349
|
const sealed = await seal({
|
|
4102
4350
|
id: bidKeyId(room.saleKey, BigInt(seq)),
|
|
4103
4351
|
data: bidPlaintext(secrets),
|
|
@@ -4110,12 +4358,13 @@ export class Essey {
|
|
|
4110
4358
|
const w = await lockBid({
|
|
4111
4359
|
root: tree.root,
|
|
4112
4360
|
ins: spent,
|
|
4113
|
-
room: { id: room.id, saleKey: room.saleKey, seq },
|
|
4361
|
+
room: { id: room.id, saleKey: room.saleKey, seq, postedCommit: room.postedCommit },
|
|
4114
4362
|
bid: secrets,
|
|
4115
4363
|
change: { pk: notePk(change.sk), blinding: change.blinding },
|
|
4116
4364
|
relayer,
|
|
4117
4365
|
relayerFee,
|
|
4118
4366
|
sealed,
|
|
4367
|
+
memo,
|
|
4119
4368
|
encs,
|
|
4120
4369
|
fee,
|
|
4121
4370
|
eph: drawEph(),
|
|
@@ -4142,6 +4391,7 @@ export class Essey {
|
|
|
4142
4391
|
proved: await proved("lock_bid", w.input, w.publics),
|
|
4143
4392
|
statement: w.statement,
|
|
4144
4393
|
sealed,
|
|
4394
|
+
memo,
|
|
4145
4395
|
encs,
|
|
4146
4396
|
});
|
|
4147
4397
|
return { ...landed, bid: record };
|
|
@@ -4165,7 +4415,7 @@ export class Essey {
|
|
|
4165
4415
|
});
|
|
4166
4416
|
const proved = await prover.prove("membership", pass.input);
|
|
4167
4417
|
return {
|
|
4168
|
-
target: `${
|
|
4418
|
+
target: `${room.policyPkg}::sale_room::seal_approve_bid`,
|
|
4169
4419
|
typeArguments: [this.config.coins[room.coin].type],
|
|
4170
4420
|
args: [
|
|
4171
4421
|
{
|
|
@@ -4184,17 +4434,19 @@ export class Essey {
|
|
|
4184
4434
|
};
|
|
4185
4435
|
}
|
|
4186
4436
|
/** `seal_approve_bid` releases keys from close until `finish_by_ms`, for an active bid (`sale_room.move:337-341`). */
|
|
4187
|
-
async closedRoom(roomId) {
|
|
4188
|
-
const room = await this.saleRoom(roomId);
|
|
4437
|
+
async closedRoom(roomId, kind) {
|
|
4438
|
+
const room = await this.saleRoom(roomId, kind);
|
|
4189
4439
|
const now = this.nowMs();
|
|
4190
4440
|
if (room.state !== SALE_STATE.open || now < room.closeMs || now >= room.finishByMs)
|
|
4191
4441
|
throw new EsseyError("INVALID_ARGUMENT", "the room is not between close and its finish deadline");
|
|
4192
4442
|
return room;
|
|
4193
4443
|
}
|
|
4194
|
-
|
|
4195
|
-
|
|
4196
|
-
|
|
4197
|
-
|
|
4444
|
+
/** PRV-24 A: only the room's pick is slashed (44_039); a slash clears it, so `finish` draws again. */
|
|
4445
|
+
async slashBid(roomId) {
|
|
4446
|
+
const room = await this.closedRoom(roomId, "slash");
|
|
4447
|
+
const seq = room.pick;
|
|
4448
|
+
if (seq === null || !room.bids[seq]?.active)
|
|
4449
|
+
throw new EsseyError("INVALID_ARGUMENT", "refused: the room has no pick to slash; nothing was sent");
|
|
4198
4450
|
const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
|
|
4199
4451
|
const derive = this.io.sealDerivedKeys ?? notSetUp("missing config: no Seal key deriver");
|
|
4200
4452
|
const bid = room.bids[seq];
|
|
@@ -4214,23 +4466,27 @@ export class Essey {
|
|
|
4214
4466
|
});
|
|
4215
4467
|
}
|
|
4216
4468
|
async finishSale(p) {
|
|
4217
|
-
const room = await this.
|
|
4469
|
+
const room = await this.pickedRoom(p.room);
|
|
4218
4470
|
const decrypt = this.io.sealDecrypt ?? notSetUp("missing config: no Seal decryptor");
|
|
4471
|
+
const opened = (i) => (room.legacy ? room.bids[i].active : i === room.pick);
|
|
4219
4472
|
const plains = [];
|
|
4220
4473
|
for (const [i, b] of room.bids.entries()) {
|
|
4221
|
-
if (
|
|
4474
|
+
if (opened(i) && typeof b.sealed !== "string")
|
|
4222
4475
|
notSetUp("the room reader gave no sealed bid");
|
|
4223
|
-
const sealed =
|
|
4476
|
+
const sealed = opened(i) ? Uint8Array.from(Buffer.from(b.sealed, "base64")) : undefined;
|
|
4224
4477
|
plains.push(sealed && (await decrypt({ sealed, approve: this.bidApprove(room, i), pkg: "sale" })));
|
|
4225
4478
|
}
|
|
4226
4479
|
const seed = this.seed();
|
|
4227
4480
|
const sellerIndex = this.indexOfSellerKey(seed, p.seller.sellerSk);
|
|
4228
4481
|
const fee = await this.feeParams(room.coin);
|
|
4229
4482
|
const eph = drawEph();
|
|
4230
|
-
const
|
|
4483
|
+
const planRoom = { ...room, pick: room.legacy ? "legacy" : room.pick };
|
|
4484
|
+
const planFor = (encs) => settlePlan({ room: planRoom, plains, seller: p.seller, bounds: p.bounds, encs, fee, eph });
|
|
4231
4485
|
const draft = await planFor([new Uint8Array(128), new Uint8Array(128)]);
|
|
4232
|
-
if (draft.slash.length > 0)
|
|
4233
|
-
|
|
4486
|
+
if (draft.slash.length > 0) {
|
|
4487
|
+
const which = room.legacy ? `bids ${draft.slash.join(", ")}` : `bid ${draft.slash[0]}`;
|
|
4488
|
+
throw new EsseyError("INVALID_ARGUMENT", `refused: slash ${which} first`);
|
|
4489
|
+
}
|
|
4234
4490
|
const encSeller = sealOpening({ ...draft.sellerNote, index: sellerIndex }, noteEncKey(seed).encPub);
|
|
4235
4491
|
const encs = [hexBytes(encSeller), hexBytes(fillerEnc())];
|
|
4236
4492
|
const w = await planFor(encs);
|
|
@@ -4244,6 +4500,24 @@ export class Essey {
|
|
|
4244
4500
|
encs,
|
|
4245
4501
|
});
|
|
4246
4502
|
}
|
|
4503
|
+
/**
|
|
4504
|
+
* PRV-24 A: a closed room with an active bid and no pick draws one first (`sale_pick`, alone: `sale_room::pick`
|
|
4505
|
+
* takes `Random`), then the room is read until the pick shows. A retired room, or one with no active bid, has none.
|
|
4506
|
+
*/
|
|
4507
|
+
async pickedRoom(roomId) {
|
|
4508
|
+
let room = await this.closedRoom(roomId, "finish");
|
|
4509
|
+
if (room.legacy || room.pick !== null || !room.bids.some((b) => b.active))
|
|
4510
|
+
return room;
|
|
4511
|
+
await this.freeLoan(pickBody, { pool: room.coin, room: room.id });
|
|
4512
|
+
for (let i = 0; i < SETTLE_READS && room.pick === null; i++) {
|
|
4513
|
+
if (i > 0)
|
|
4514
|
+
await this.sleep(SETTLE_READ_MS);
|
|
4515
|
+
room = await this.closedRoom(roomId, "finish");
|
|
4516
|
+
}
|
|
4517
|
+
if (room.pick === null)
|
|
4518
|
+
throw new EsseyError("STATE_REFUSED", "the room read does not show its pick yet");
|
|
4519
|
+
return room;
|
|
4520
|
+
}
|
|
4247
4521
|
indexOfSellerKey(seed, sellerSk) {
|
|
4248
4522
|
const n = readState(this.statePath, this.stateKey).notes ?? 0;
|
|
4249
4523
|
for (let i = n - 1; i >= 0; i--)
|
|
@@ -4252,13 +4526,13 @@ export class Essey {
|
|
|
4252
4526
|
return notSetUp("refused: sellerSk is not a note key of this seed, so the proceeds would not scan");
|
|
4253
4527
|
}
|
|
4254
4528
|
async expireSale(roomId, vault) {
|
|
4255
|
-
const room = await this.saleRoom(roomId);
|
|
4529
|
+
const room = await this.saleRoom(roomId, "expire");
|
|
4256
4530
|
if (room.state !== SALE_STATE.open || this.nowMs() < room.finishByMs)
|
|
4257
4531
|
throw new EsseyError("INVALID_ARGUMENT", "the room is not past its finish deadline");
|
|
4258
4532
|
return this.freeLoan(expireBody, { pool: room.coin, room: room.id, vault });
|
|
4259
4533
|
}
|
|
4260
4534
|
async cancelSale(roomId, vault) {
|
|
4261
|
-
const room = await this.saleRoom(roomId);
|
|
4535
|
+
const room = await this.saleRoom(roomId, "cancel");
|
|
4262
4536
|
if (room.state !== SALE_STATE.open || room.bids.length > 0)
|
|
4263
4537
|
throw new EsseyError("INVALID_ARGUMENT", "only an open room with no bid cancels");
|
|
4264
4538
|
// `sale_room::action_hash` is `loan::action_hash`'s encoding over `sale_key` (`sale_room.move:528-529`).
|
|
@@ -4266,7 +4540,7 @@ export class Essey {
|
|
|
4266
4540
|
return this.freeLoan(cancelBody, { pool: room.coin, room: room.id, vault, pass });
|
|
4267
4541
|
}
|
|
4268
4542
|
async reclaimBid(roomId, record, what) {
|
|
4269
|
-
const room = await this.saleRoom(roomId);
|
|
4543
|
+
const room = await this.saleRoom(roomId, "reclaim");
|
|
4270
4544
|
if (room.state !== SALE_STATE.settled && room.state !== SALE_STATE.expired)
|
|
4271
4545
|
throw new EsseyError("INVALID_ARGUMENT", "the room has not ended");
|
|
4272
4546
|
const seed = this.seed();
|
|
@@ -4314,7 +4588,7 @@ export class Essey {
|
|
|
4314
4588
|
const claim = optionU256(json.claim);
|
|
4315
4589
|
if (claim === null)
|
|
4316
4590
|
throw new EsseyError("INVALID_ARGUMENT", "the vault holds no claim yet");
|
|
4317
|
-
const room = await this.saleRoom(String(json.room_id));
|
|
4591
|
+
const room = await this.saleRoom(String(json.room_id), "claim");
|
|
4318
4592
|
let holder;
|
|
4319
4593
|
if (p.bid) {
|
|
4320
4594
|
const own = this.bidSecrets(this.seed(), p.bid);
|