Sealed settlement v2
The v2 surface: the sale_room_v2 and private_room_v2 builders, the two composers that build a pool spend and its relayer body in one call (buildPoolBidV2, buildOfferV2), the Settle(16) prover and keys, the host's Seal open, and the pieces they take from the membership, wallet and prover modules. How they fit together is in Private flows with the SDK; the v1 sale-room surface, ShieldedWallet included, is in Sale rooms.
Signatures below are copied from the source; descriptions are the source's own doc comments. A refusal before signing is an EsseyError thrown, or { ok: false, error } returned, before anything is sealed, proved or sent; a chain refusal is not thrown, it returns Landed with ok: false and an abort.
From shielded/spend-v2.ts#
Exported by index.ts.
BidV2Body#
The relayer's wire form of a v2 pool bid (payload.ts bidV2Of): a BidBody plus the commit, the claim commitment and the spend-bound credentials.
export type BidV2Body = BidBody & {
kind: "bid_v2";
member: WirePass;
gate: WirePass | null;
commit: string;
claimCommit: string;
};LoanOfferV2Body#
export type LoanOfferV2Body = BidBody & {
kind: "loan_offer_v2";
member: WirePass;
gate: WirePass | null;
commit: string;
repayPubkey: string;
repayBlinding: string;
};SpendWire#
A proved spend plus what the room half of the body carries; member is the room credential bound to its n0.
export type SpendWire = {
proved: Proved;
ext: BidExt;
sealed: Uint8Array;
member: WirePass;
gate: WirePass | null;
commit: bigint;
};bidV2Body#
POST body for a relayed v2 pool bid (kind: "bid_v2"), decimal and 0x-hex strings like the other kinds. Refuses a missing member and a claim commitment that is not 32 bytes (room abort 19).
export function bidV2Body(o: SpendWire & { claimCommit: Uint8Array }): BidV2BodyloanOfferV2Body#
POST body for a relayed v2 loan offer (kind: "loan_offer_v2"). repayPubkey and repayBlinding must be canonical field elements.
export function loanOfferV2Body(
o: SpendWire & { repayPubkey: bigint; repayBlinding: bigint },
): LoanOfferV2BodypoolSpendOf#
The finished pool spend poolBidV2Tx / offerV2Tx take: the proof as its 128 Sui bytes, rows from the signals.
export function poolSpendOf(
proved: Proved,
ext: Pick<BidExt, "relayer" | "fee" | "encOut1" | "encOut2">,
): SpendV2Openings#
The notes the caller must be able to find again: the change (null when none) and the refund collect returns.
export type V2Openings = { change: Note | null; refund: Note };PoolBidV2Request#
export type PoolBidV2Request = {
cfg: Pick<SaleRoomV2Config, "pkg" | "keyServers" | "threshold">;
/** The pool this wallet's notes are in; the room must take bids from it (room abort 18). */
pool: Pick<ShieldedPoolConfig, "pool" | "coinType">;
room: Pick<
SaleRoomV2View,
| "id"
| "coinType"
| "pool"
| "shieldedOnly"
| "state"
| "minPrice"
| "maxPrice"
| "maxBids"
| "bids"
| "nextSeq"
| "sellerTag"
| "needsSellerTag"
>;
price: bigint;
fee: bigint;
relayer: string;
claimTo: string;
/** `wirePass(await provedPassFor({ ..., room: room.id, binding: { n0 } }))` and the gate pass, or null. */
credential: BidCredential;
salt?: bigint;
};room.pool is what readSaleRoomV2 read. On chain it is none until the room's first pool bid or the seller's note names a pool, so a fresh shieldedOnly room builds with pool: null; once set, it must be this wallet's pool. room.shieldedOnly decides whether the room takes pool bids at all.
BuiltPoolBidV2#
export type BuiltPoolBidV2 =
| {
ok: true;
spend: Spend;
body: BidV2Body;
openings: V2Openings;
tag: bigint;
/** The sealed bid's opening; `claim.salt` is `claimSaltOf(keys.claimKey, tag)`, so a seed recomputes it. */
entry: EntryOpening;
claim: { claimTo: string; salt: Uint8Array };
spends: OwnedNote[];
}
| { ok: false; error: string };buildPoolBidV2#
A sealed bid of price paid from the pool: the finished Spend, the bid_v2 relayer body and what to keep. The spend escrows room.maxPrice; the notes must cover maxPrice + fee + 2 × insertFee.
export async function buildPoolBidV2(
wallet: WalletState,
req: PoolBidV2Request,
deps: Deps,
): Promise<BuiltPoolBidV2>Returned as { ok: false, error }, in this order, before anything is sealed or proved:
| refusal | chain abort |
|---|---|
shieldedOnly is false: the room takes address bids only | room 17 |
| the room takes bids from another pool | room 18 |
| the room is priced in another coin than the wallet holds | none: the proof would not verify |
| the room is not open | room 2 |
| the seller has not attested yet | room 23 |
| the room has taken all its bids | room 6 |
| the price is outside the floor and ceiling | none: the finish drops the bid |
no one or two unspent notes cover maxPrice + fee + 2 × insertFee | none |
the sealed entry would be refused on chain (sealedEntryFault: other package, room, seq, servers, threshold, length or aad) | room.move pin_sealed |
the wallet's tree is not at the pool's current root (STALE_TREE) | none: scan and build again |
| the prover proved another statement | none |
credential returned no member | the relayer refuses the body |
OfferV2Request#
export type OfferV2Request = {
cfg: Pick<PrivateLoanV2Config, "pkg" | "keyServers" | "threshold">;
/** The loan coin's pool this wallet's notes are in; the room is funded from it (room abort 4). */
pool: Pick<ShieldedPoolConfig, "pool" | "coinType">;
room: Pick<
PrivateLoanV2View,
"id" | "loanPool" | "loanType" | "state" | "principal" | "maxRateBps" | "offers" | "nextSeq"
>;
rateBps: bigint;
fee: bigint;
relayer: string;
/** `wirePass(await provedPassFor({ ..., room: room.id, binding: { n0 } }))` and the gate pass, or null. */
credential: BidCredential;
salt?: bigint;
};BuiltOfferV2#
export type BuiltOfferV2 =
| {
ok: true;
spend: Spend;
body: LoanOfferV2Body;
/** `repay` is the note the borrower's repayment lands in, under this wallet's spend key. */
openings: V2Openings & { repay: { pubkey: bigint; blinding: bigint } };
tag: bigint;
entry: EntryOpening;
spends: OwnedNote[];
}
| { ok: false; error: string };buildOfferV2#
A sealed offer at rateBps funding principal from the pool: the Spend, the loan_offer_v2 body and what to keep. The spend escrows room.principal; the notes must cover principal + fee + 2 × insertFee.
export async function buildOfferV2(
wallet: WalletState,
req: OfferV2Request,
deps: Deps,
): Promise<BuiltOfferV2>| refusal | chain abort |
|---|---|
| the room is funded from another pool | room 4 |
| the room borrows another coin than the wallet holds | none: the proof would not verify |
the room is not taking offers (state is not bidding) | room 2 |
| the room has taken all 16 offers | room 13 |
the rate is above maxRateBps | none: the settle drops the offer |
notes, sealed entry, stale tree, prover, member | as for buildPoolBidV2 |
From shielded/wallet.ts#
Exported by index.ts. The rest of ShieldedWallet is in Sale rooms.
WirePass#
A room credential as the relayer's payload.ts reads it (PassWire): decimal tag and expiry, hex proof.
export type WirePass = { tag: string; expiryMs: string; proof: string };wirePass#
export function wirePass(pass: {
tag: bigint;
proof: Uint8Array;
credential: { expiryMs: bigint };
}): WirePassBidCredential#
Proves the bidder's room credential (and the Access gate's, or null) bound to the spend's n0 (membership Binding { n0 }); called once per proof attempt, since a stale-root re-prove has a new n0.
export type BidCredential = (n0: bigint) => Promise<{ member: WirePass; gate: WirePass | null }>;ShieldedWallet.keys#
The Keys derived from the seed, a public property. newDeposit(wallet.keys, amount) in the settle takes it, and (await wallet.scan()).state.keys is the same object. It is secret, like the seed: it holds every key the seed derives. Never log it, serialise it into tool output, or send it off the machine.
readonly keys: Keys;ShieldedWallet.spendDeps#
What buildPoolBidV2 / buildOfferV2 take: this wallet's hash, prover and pool root, and a sealer for seal. Throws NOT_SET_UP when the wallet has no prover.
spendDeps(seal: Pick<SaleRoomConfig, "keyServers" | "threshold">): DepsShieldedWallet.lenderCiphertext#
Ciphertext for a repayment note this seed spends, stored against room before it is published. The note is { amount, pubkey: keys.pubkey, blinding }, so openings.repay.blinding of a won offer and the room's owed name the repayment note.
lenderCiphertext(amount: bigint, blinding: bigint, room: string): Uint8ArrayFrom shielded/bid.ts#
Exported by index.ts.
Proved#
export type Proved = { proof: SnarkjsProof; publicSignals: string[] };WalletState#
insertFee is the pool's insert_fee, read from the pool object. (await wallet.scan()).state is one. It is secret: keys is every key the seed derives, and notes carry the full opening of every note. Never log it, serialise it into tool output, or send it off the machine.
export type WalletState = { keys: Keys; notes: OwnedNote[]; tree: Tree; levels: number; insertFee: bigint };Deps#
poolRoot reads pool::root from the chain; a proof is only built against that root. wallet.spendDeps(cfg) is one.
export type Deps = { hash: Hash; sealer: Sealer; prover: Prover; poolRoot: () => Promise<bigint> };STALE_TREE#
The wallet's scan is behind the pool: rescan, then build again (fresh.ts).
export const STALE_TREE = "the wallet's tree is not at the pool's current root";wireBidExt#
BidExt as the relayer's payload.ts reads it: decimal and 0x-hex strings.
export const wireBidExt = (ext: BidExt): BidBody["ext"] =>From shielded/relay-client.ts#
Exported by index.ts.
RelayerEndpoint#
The route a body is posted to and the address the proof pays. Relayer (Sale rooms) adds minFee.
export type RelayerEndpoint = { url: string; address: string };STALE_ROOT#
The relayer's refusal of a proof against a root it has not read as current.
export const STALE_ROOT = "root is not the pool's current root";RelayBody#
Every body the relayer takes: a v1 bid or withdraw, a v2 bid or offer (buildPoolBidV2 and buildOfferV2 return one as body), or a relayed v2 settle.
export type RelayBody = BidBody | WithdrawBody | BidV2Body | LoanOfferV2Body | SettleRelayedV2Body;Sent#
What sendToRelayer returns. ok: true carries the digest of the transaction the relayer executed. Otherwise from says who refused and sent whether anything could have reached the chain:
from | sent | When |
|---|---|---|
"client" | "no" | Refused here, before anything was posted: the body's ext.relayer is not the endpoint's address (the proof pays another relayer, which this one would refuse). |
"relayer" | "no" | The relayer answered { ok: false, error, submitted: false }: it refused before signing. error is its reason: STALE_ROOT; fee below MIN_FEE (the route's floor; the message does not carry the number); fee at or above the pool's max_fee; ext.relayer is not this relayer; or the abort its dry run of the transaction foresaw, as the room-abort text. |
"relayer" | "unknown" | The relayer signed and executed, and the execute failed (submitted: true): the spend may have landed. Read the pool's nullifiers before building again. |
"transport" | "unknown" | No usable answer: a network error or the timeout (timeoutMs, 30,000 ms by default; error is the message, cut to 200 characters), or an answer that is not the relayer's (unexpected answer (HTTP <status>)). |
Only sent: "no" means nothing was signed.
export type Sent =
| { ok: true; digest: string }
| { ok: false; error: string; sent: "no" | "unknown"; from: "client" | "relayer" | "transport" };sendToRelayer#
POSTs body as JSON to relayer.url and reads the answer into a Sent. A body with ext must pay this relayer (it refuses any other); a settle_relayed_v2 body has no ext and goes as is. It never throws: a failed request is from: "transport". ShieldedWallet.bid, withdraw and exit call it inside relayFresh, which rebuilds on STALE_ROOT; the v2 composers return the body and leave the send to you. The SUI route is TESTNET_RELAYER; the usdc and usdsui routes are built from GET /v1/private/config as in Private flows.
export async function sendToRelayer(
relayer: RelayerEndpoint,
body: RelayBody,
opts: { fetch?: typeof fetch; timeoutMs?: number } = {},
): Promise<Sent>From shielded/deposit.ts#
Exported by index.ts.
Deposit#
export type Deposit = { note: Note; encNote: Uint8Array };newDeposit#
A new note for the owner of keys: amount, keys.pubkey and a fresh random blinding, with the opening encrypted to keys.encPub so a scan from the seed finds it. ShieldedWallet.depositTx makes one for every deposit; the borrower's settle takes one for the principal (SettleV2Args.principalPubkey, principalBlinding and encNote are note.pubkey, note.blinding and encNote). Throws on an amount of 0 or less.
A deposit's amount and blinding are public on chain by design: pool::deposit takes the coin and blinding: u256 as plain arguments (move/privacy/sources/pool.move:204-210). ShieldedWallet.depositTx returns only deposit: { commitment, amount }.
export function newDeposit(keys: Keys, amount: bigint): DepositFrom private-flows.ts#
Exported by index.ts. The shapes the v2 builders share with v1.
Pass#
A room credential for a builder: { tag: pass.tag, expiryMs: pass.credential.expiryMs, proof: pass.proof } from a ProvedPass.
export type Pass = { tag: bigint; expiryMs: bigint; proof: Uint8Array };Spend#
export type Spend = {
proof: Uint8Array;
rows: Rows;
relayer: string;
fee: bigint;
encOut1: Uint8Array;
encOut2: Uint8Array;
};SaleRoomRef#
export type SaleRoomRef = { id: string; itemType: string; coinType: string };GatedSaleTerms#
export type GatedSaleTerms = {
item: TransactionArgument;
minPrice: bigint;
maxPrice: bigint;
closeMs: bigint;
finishWindowMs: bigint;
maxBids: bigint;
shieldedOnly: boolean;
gate: Pass | null;
};LoanRoomRef#
export type LoanRoomRef = { id: string; collateralType: string; loanType: string };OpenLoan#
export type OpenLoan = {
market: string;
reading: TransactionArgument;
loanPool: string;
/** ADV-2: the collateral coin's ShieldedPool<C>; pinned on the room, claim_default must pass the same one. */
collPool: string;
collateral: TransactionArgument;
principal: bigint;
maxRateBps: bigint;
termMs: bigint;
offerWindowMs: bigint;
/** null in PUBLIC mode; else the borrower's gate pass (sender-bound). */
gate: Pass | null;
};From sale-room-v2.ts#
Exported by index.ts.
SaleRoomV2Config#
A sale_room_v2 package and what its room.move pins: the Seal servers and threshold (is_room_ciphertext), the shared SettleVerifier finish takes, the Access the room is gated by.
export type SaleRoomV2Config = {
pkg: string;
privacyPkg: string;
verifier: string;
access: string;
passKey: string;
keyServers: string[];
threshold: number;
/** `ShieldedPool<C>` per coin; a pool takes v2 bids only once `pool::allow_room<C, PoolRoom>` has run (ABI §4). */
pools?: Partial<Record<CoinKey, string>>;
};TESTNET_SALE_ROOM_V2#
T10 sale_room_v2, published immutable 2026-11-08; TEST-ONLY verifier. pkg 0xeeacf6d88596fedfdcd66cc6510c3c84e08d249bdb1d2b956f3c931a33feb714, verifier 0x6d27cc34ce3423a02222f18795c4141504b9c1f46ac4d02277449af723f3ffa7; privacyPkg, access, passKey, keyServers and threshold are TESTNET_SALE_ROOM's; pools has the USDC, USDSUI and SUI shielded pools. The same object is saleRoomV2 in GET /v1/private/config.
SALE_ROOM_V2_RULES#
room.move MAX_BIDS_CEILING (= the circuit's 16 slots), MIN_FINISH_WINDOW_MS and MAX_OPEN_MS.
export const SALE_ROOM_V2_RULES = {
maxBidsCeiling: SETTLE_SLOTS,
minFinishWindowMs: 1_800_000,
maxOpenMs: 30 * 86_400_000,
} as const;SALE_ROOM_V2_STATE#
export const SALE_ROOM_V2_STATE = { open: 0, finished: 1, cancelled: 2, expired: 3 } as const;requireV2#
Throws NOT_SET_UP for an undefined config: how a caller refuses to run without one.
export function requireV2<T>(cfg: T | undefined, what: string): TpoolOf#
The pool id configured for coin, or NO_POOL.
export function poolOf(cfg: { pools?: Partial<Record<CoinKey, string>> }, coin: CoinKey): stringsalePayloadV2#
room.move payload_of: essey.sale_room.v2/bid ‖ bcs(commit) ‖ bcs(claim_commit) ‖ bcs(sealed).
export function salePayloadV2(commit: bigint, claimCommit: Uint8Array, sealed: Uint8Array): Uint8ArraysaleBidStatementV2#
The pool statement a v2 pool bid proves: ExtData::Bid.sealed_hash is blake2b256 of the PAYLOAD, not of sealed.
export const saleBidStatementV2 = (
rows: Rows,
maxPrice: bigint,
insertFee: bigint,
ext: BidExt,
payload: Uint8Array,
) => bidStatement(rows, maxPrice, insertFee, ext, payload);saleStatementV2#
room.move public_inputs: commits in bid order, lo = min_price, hi = max_price, rule 1, the claim, field_of(room).
export function saleStatementV2(
room: Pick<SaleRoomV2View, "id" | "minPrice" | "maxPrice" | "bids">,
claim: SettleClaim,
): SettleStatementopenSaleV2Tx#
open(access, gate, item, min_price, max_price, close_ms, finish_window_ms, max_bids, shielded_only, clock): v1's shape on the v2 package; returns the room id result. Pool bids need shieldedOnly: true (room abort 17).
export function openSaleV2Tx(
tx: Transaction,
cfg: SaleRoomV2Config,
types: Omit<SaleRoomRef, "id">,
terms: GatedSaleTerms,
)attestSellerV2Tx#
attest_seller(room, member): the seller's own sender-bound room credential, before any bid (room abort 23). Signed by the seller's wallet: room.move refuses another sender (abort 8) and a spend-bound credential.
export function attestSellerV2Tx(tx: Transaction, cfg: SaleRoomV2Config, room: SaleRoomRef, pass: Pass)bidV2Tx#
bid(room, access, gate, member, commit, sealed, deposit, clock): an address bid, sender-bound passes.
export function bidV2Tx(
tx: Transaction,
cfg: SaleRoomV2Config,
room: SaleRoomRef,
o: { pass: Pass; gate: Pass | null; commit: bigint; sealed: Uint8Array; deposit: TransactionArgument },
)poolBidV2Tx#
pool_bid(pool, room, access, gate, member, <spend>, refund_pubkey, refund_blinding, enc_out1, enc_out2, commit, claim_commit, sealed, clock): both passes bound to the spend's n0; the proof binds salePayloadV2. buildPoolBidV2 returns the spend; its openings.refund is the refund note, entry and claim the rest.
export function poolBidV2Tx(
tx: Transaction,
cfg: SaleRoomV2Config,
room: SaleRoomRef,
o: {
pool: string;
gate: Pass | null;
member: Pass;
spend: Spend;
refundPubkey: bigint;
refundBlinding: bigint;
commit: bigint;
claimCommit: Uint8Array;
sealed: Uint8Array;
},
)finishV2Tx#
finish(verifier, pool, room, has_winner, winner, price, proof, clock): the seller, after close.
export function finishV2Tx(
tx: Transaction,
cfg: SaleRoomV2Config,
room: SaleRoomRef,
o: { pool: string; claim: SettleClaim; proof: Uint8Array },
)slashBidV2Tx#
slash(pool, room, index, key_indices, derived_keys, clock): the keys are for bid_key_id(room, bids[index].seq). Exactly threshold shares (slashShares).
export function slashBidV2Tx(
tx: Transaction,
cfg: SaleRoomV2Config,
room: SaleRoomRef,
o: { pool: string; index: number; shares: FinishShares },
)saleSealApproveV2Tx#
The Seal dry run: one seal_approve(id, room, clock) per entry the host asks a key for (bid_key_id(room, seq)).
export function saleSealApproveV2Tx(cfg: Pick<SaleRoomV2Config, "pkg">, room: SaleRoomRef, seqs: bigint[])SaleBidV2#
export type SaleBidV2 = {
index: number;
seq: bigint;
commit: bigint;
/** 32 bytes for a pool bid, empty for an address bid. */
claimCommit: Uint8Array;
tag: bigint;
bidder: string | null;
/** The stored ciphertext as wire bytes (`sealedBytesOf`); null when the JSON carries no readable EncryptedObject. */
sealed: Uint8Array | null;
};SaleRoomV2View#
export type SaleRoomV2View = {
id: string;
itemType: string;
coinType: string;
seller: string;
itemId: string | null;
minPrice: bigint;
maxPrice: bigint;
closeMs: number;
finishByMs: number;
maxBids: number;
state: number;
shieldedOnly: boolean;
pool: string | null;
nextSeq: bigint;
bids: SaleBidV2[];
winner: { address: string | null } | null;
price: bigint;
sellerTag: bigint | null;
needsSellerTag: boolean;
};readSaleRoomV2#
Throws NOT_FOUND when the object is not a SaleRoom of cfg.pkg.
export async function readSaleRoomV2(
client: SuiGrpcClient,
cfg: SaleRoomV2Config,
roomId: string,
): Promise<SaleRoomV2View>saleRoomV2Functions#
Every Move function this module can name, for an agent lane's allow-list: open, attest_seller, bid, pool_bid, finish, slash, seal_approve.
export const saleRoomV2Functions = (cfg: Pick<SaleRoomV2Config, "pkg">): string[] =>collectTx and claimTx (shielded/pool.ts) serve the v2 room with pkg set to the v2 sale package; see Sale rooms.
From private-loan-v2.ts#
Exported by index.ts.
PrivateLoanV2Config#
A private_room_v2 package and what its room.move pins. esseyPkg is the published essey_sui whose Market and price Reading open takes.
export type PrivateLoanV2Config = {
pkg: string;
privacyPkg: string;
esseyPkg: string;
verifier: string;
access: string;
passKey: string;
keyServers: string[];
threshold: number;
/** `ShieldedPool<L>` per loan coin; a pool takes v2 offers once `pool::allow_room<L, PrivateLoanW>` has run. */
pools?: Partial<Record<CoinKey, string>>;
};TESTNET_PRIVATE_LOAN_V2#
T10 private_room_v2, published immutable 2026-11-08; TEST-ONLY verifier. pkg 0x5e2dbc14e6687bb550e2f69fcdd328c21b252fdcf9c9dddce0f8aa33f37e9050, esseyPkg 0x6786d695be37759278a0769b311fd9381b44baaea86f6a969619a7df8c9a61b4, verifier 0xd56ab7c8f077b660ca9c0655e1e57c2d39812ae40c82394311635243ba02a84c; keyServers are the sale room's three, which room.move pins. The same object is privateLoanV2 in GET /v1/private/config.
LOAN_ROOM_V2_STATE#
export const LOAN_ROOM_V2_STATE = {
attesting: 0,
bidding: 1,
active: 2,
repaid: 3,
liquidated: 4,
defaulted: 5,
cancelled: 6,
} as const;LOAN_ROOM_V2_RULES#
room.move MAX_OFFERS (= the circuit's 16 slots) and SETTLE_WINDOW_MS.
export const LOAN_ROOM_V2_RULES = { maxOffers: 16, settleWindowMs: 86_400_000 } as const;loanPayloadV2#
room.move payload_of: essey.private_loan.v2/offer ‖ bcs(commit) ‖ bcs(repay_pubkey) ‖ bcs(repay_blinding) ‖ bcs(sealed).
export function loanPayloadV2(
commit: bigint,
repayPubkey: bigint,
repayBlinding: bigint,
sealed: Uint8Array,
): Uint8ArrayloanRepayPayloadV2#
room.move repay_payload: what a repayV2Tx spend binds.
export const loanRepayPayloadV2 = (owed: bigint) => cat(utf8("essey.private_loan.v2/repay"), u64le(owed));loanOfferStatementV2#
The pool statement an offer proves: a bid-form spend of exactly principal bound to loanPayloadV2.
export const loanOfferStatementV2 = (
rows: Rows,
principal: bigint,
insertFee: bigint,
ext: BidExt,
payload: Uint8Array,
) => bidStatement(rows, principal, insertFee, ext, payload);actionHashV2#
room.move action_hash: blake2b256(essey.private_loan.v2/ ‖ kind ‖ "/" ‖ room id ‖ bcs(nonce) ‖ args) as u256 mod R.
export function actionHashV2(
roomId: string,
nonce: bigint,
kind: "settle" | "cancel",
args: Uint8Array,
): bigintSettleV2Args#
export type SettleV2Args = {
winner: bigint;
rateBps: bigint;
principalPubkey: bigint;
principalBlinding: bigint;
encNote: Uint8Array;
proof: Uint8Array;
};settleActionV2#
room.move settle_action: the value a relayed borrower credential is bound to; proof is part of it.
export function settleActionV2(roomId: string, nonce: bigint, a: SettleV2Args): bigintcancelActionV2#
export const cancelActionV2 = (roomId: string, nonce: bigint) =>loanStatementV2#
room.move public_rows: commits in offer order, lo 0, hi = max_rate_bps, rule 2, hasWinner 1, the claim, field_of(room).
export function loanStatementV2(
room: Pick<PrivateLoanV2View, "id" | "maxRateBps" | "offers">,
winner: number,
rateBps: bigint,
): SettleStatementopenPrivateLoanV2Tx#
open(access, gate, market, reading, loan_pool, coll_pool, collateral, principal, max_rate_bps, term_ms, offer_window_ms, clock): the borrower, v1's shape on the v2 package; returns the room id result.
export function openPrivateLoanV2Tx(
tx: Transaction,
cfg: PrivateLoanV2Config,
types: Omit<LoanRoomRef, "id">,
o: OpenLoan,
)attestBorrowerV2Tx#
attest_borrower(room, pass): the borrower's sender-bound room credential; attesting becomes bidding.
export function attestBorrowerV2Tx(tx: Transaction, cfg: PrivateLoanV2Config, room: LoanRoomRef, pass: Pass)offerV2Tx#
offer(room, pool, access, gate, pass, <spend>, refund_pubkey, refund_blinding, enc_out1, enc_out2, commit, sealed, repay_pubkey, repay_blinding, clock): both passes bound to the spend's n0; the proof binds loanPayloadV2. buildOfferV2 returns the spend and openings.repay.
export function offerV2Tx(
tx: Transaction,
cfg: PrivateLoanV2Config,
room: LoanRoomRef,
o: {
loanPool: string;
pass: Pass;
gate: Pass | null;
spend: Spend;
refundPubkey: bigint;
refundBlinding: bigint;
commit: bigint;
sealed: Uint8Array;
repayPubkey: bigint;
repayBlinding: bigint;
},
)settleV2Tx#
settle(room, pool, verifier, winner, rate_bps, principal_pubkey, principal_blinding, enc_note, proof, clock): the borrower.
export function settleV2Tx(
tx: Transaction,
cfg: PrivateLoanV2Config,
room: LoanRoomRef,
o: { loanPool: string } & SettleV2Args,
)settleRelayedV2Tx#
settle_relayed(room, pool, verifier, pass, winner, rate_bps, principal_pubkey, principal_blinding, enc_note, proof, clock): anyone may send it; the pass is bound to settleActionV2 over exactly these arguments and the room's nonce.
export function settleRelayedV2Tx(
tx: Transaction,
cfg: PrivateLoanV2Config,
room: LoanRoomRef,
o: { loanPool: string; nonce: bigint; pass: Pass } & SettleV2Args,
)repayV2Tx#
repay(room, pool, <spend>, enc_out1, enc_out2, lender_enc): the borrower repays exactly owed from its notes. The spend proves bidStatement(rows, owed, insertFee, { ...ext, refundPubkey: 0n, refundBlinding: 0n }, loanRepayPayloadV2(owed)).
export function repayV2Tx(
tx: Transaction,
cfg: Pick<PrivateLoanV2Config, "pkg">,
room: LoanRoomRef,
o: { loanPool: string; spend: Spend; lenderEnc: Uint8Array },
)repayCoinV2Tx#
repay_coin(room, pool, payment, lender_enc): public repay of owed plus the insert fee from a coin; change stays.
export function repayCoinV2Tx(
tx: Transaction,
cfg: Pick<PrivateLoanV2Config, "pkg">,
room: LoanRoomRef,
o: { loanPool: string; payment: TransactionArgument; lenderEnc: Uint8Array },
)slashOfferV2Tx#
slash(room, pool, index, key_indices, derived_keys, clock): the keys are for offer_key_id(room, offers[index].seq).
export function slashOfferV2Tx(
tx: Transaction,
cfg: PrivateLoanV2Config,
room: LoanRoomRef,
o: { loanPool: string; index: number; shares: FinishShares },
)loanSealApproveV2Tx#
The Seal dry run: one seal_approve(id, room, clock) per offer the borrower asks a key for.
export function loanSealApproveV2Tx(
cfg: Pick<PrivateLoanV2Config, "pkg">,
room: LoanRoomRef,
seqs: bigint[],
)SettleRelayedV2Body#
POST body for a relayed v2 settle, decimal and 0x-hex strings like the other kinds. The relayer rebuilds the call from these fields and binds the pass to its OWN settleActionV2; action is the client's value for it to compare. No losing value travels: winner, rateBps and the proof are the only settlement data.
export type SettleRelayedV2Body = {
kind: "settle_relayed_v2";
room: string;
nonce: string;
action: string;
pass: WirePass;
winner: string;
rateBps: string;
principalPubkey: string;
principalBlinding: string;
encNote: string;
proof: string;
};settleRelayedV2Body#
export function settleRelayedV2Body(
o: { room: string; nonce: bigint; pass: WirePass } & SettleV2Args,
): SettleRelayedV2BodysendToRelayer posts it to the route as is: a body with ext must pay the relayer it is sent to; this one carries no ext.
LoanOfferV2#
export type LoanOfferV2 = {
index: number;
seq: bigint;
tag: bigint;
commit: bigint;
repayPubkey: bigint;
repayBlinding: bigint;
refundPubkey: bigint;
refundBlinding: bigint;
/** The stored ciphertext as wire bytes (`sealedBytesOf`); null when the JSON carries no readable EncryptedObject. */
sealed: Uint8Array | null;
};PrivateLoanV2View#
export type PrivateLoanV2View = {
id: string;
collateralType: string;
loanType: string;
marketId: string;
loanPool: string;
collPool: string;
borrower: string;
borrowerTag: bigint | null;
collateral: bigint;
principal: bigint;
maxRateBps: bigint;
termMs: number;
closeMs: number;
state: number;
nonce: bigint;
nextSeq: bigint;
offers: LoanOfferV2[];
rateBps: bigint;
owed: bigint;
maturityMs: number;
};readPrivateLoanV2#
Throws NOT_FOUND when the object is not a PrivateLoanRoom of cfg.pkg.
export async function readPrivateLoanV2(
client: SuiGrpcClient,
cfg: PrivateLoanV2Config,
roomId: string,
): Promise<PrivateLoanV2View>privateLoanV2Functions#
Every Move function this module can name, for an agent lane's allow-list: open, attest_borrower, offer, settle, settle_relayed, repay, repay_coin, slash, seal_approve.
export const privateLoanV2Functions = (cfg: Pick<PrivateLoanV2Config, "pkg">): string[] =>From settle-v2.ts#
Exported by index.ts.
Constants#
Settle(16): one commitment slot per possible entry, so a v2 room never holds more than 16. SETTLE_PLAIN_LEN is u64 LE value ‖ 32-byte LE salt, what every v2 Seal ciphertext holds (room.move PLAIN_LEN). SETTLE_VK_HASH_TESTONLY is blake2b256 of the Settle(16) Sui verifying key both v2 room.move files pin as VK_HASH; a TEST-ONLY throwaway key.
export const SETTLE_SLOTS = 16;
export const SETTLE_PLAIN_LEN = 40;
export const RULE_HIGHEST_WINS = 1n;
export const RULE_LOWEST_WINS = 2n;
export type SettleRule = typeof RULE_HIGHEST_WINS | typeof RULE_LOWEST_WINS;
export type EntryKind = "bid" | "offer";
export const SETTLE_VK_HASH_TESTONLY = "4ffdaf5a4880767bdf59b01c0e42563b3887549b5de6b878d4f219b168944008";SettleClaim#
export type SettleClaim = { hasWinner: boolean; winner: number; winValue: bigint };SettleStatement#
export type SettleStatement = SettleClaim & {
/** Entry commitments in the room's vector order; slots past `commits.length` are 0 in the statement. */
commits: bigint[];
lo: bigint;
hi: bigint;
rule: SettleRule;
/** `field_of(object::id(room))`: the room id as u256 mod R (`fieldOfId`). */
room: bigint;
};fieldOfId#
export const fieldOfId = (roomId: string) => BigInt(normalizeSuiAddress(roomId)) % R;settleRows#
The 24 rows in §1 order: commits[16], n, lo, hi, rule, hasWinner, winner, winValue, room.
export function settleRows(s: SettleStatement): bigint[]settleDigests#
§8: hSet = Poseidon(16)(commits), hClaim = Poseidon(8)(the eight claim rows); publicSignals order [hSet, hClaim].
export function settleDigests(rows: bigint[], hash: Hash = poseidonHash): { hSet: bigint; hClaim: bigint }settlePublicInputs#
bcs(hSet) ‖ bcs(hClaim), the 64 bytes room.move hands to groth16::public_proof_inputs_from_bytes.
export function settlePublicInputs(rows: bigint[], hash: Hash = poseidonHash): Uint8ArraysettleCircuitInput#
proto/settle_circuit/lib.mjs circuitInput: the statement plus the private openings, every slot padded to 16.
export function settleCircuitInput(
s: SettleStatement,
values: bigint[],
salts: bigint[],
): SettleCircuitInputselectWinner#
The rule both contracts settle by and the circuit proves: eligible is lo <= value <= hi; rule 1 takes the highest eligible value (sale), rule 2 the lowest (loan); a later equal value never beats an earlier one.
export function selectWinner(
rule: SettleRule,
values: bigint[],
bounds: { lo: bigint; hi: bigint },
): SettleClaimEntryOpening#
export type EntryOpening = { value: bigint; salt: bigint };EntryFault#
room.move opens, in its order: no plaintext, wrong length, salt not a field element, Poseidon mismatch.
export type EntryFault = "none" | "length" | "salt" | "commit";randomSalt#
A salt below R, so the chain's salt < R check and the circuit's field arithmetic agree on it.
export const randomSalt = (): bigint => randomField();commitV2#
Refuses a value that is not a u64 and a salt that is not below R.
export function commitV2(value: bigint, salt: bigint, hash: Hash = poseidonHash): bigintplaintextV2#
export function plaintextV2(o: EntryOpening): Uint8ArrayparsePlaintextV2#
export function parsePlaintextV2(p: Uint8Array): EntryOpeningentryFault#
Why room.move slash would take this entry; null when the plaintext opens the commitment (EBidWellFormed).
export function entryFault(
plain: Uint8Array | null,
commit: bigint,
hash: Hash = poseidonHash,
): EntryFault | nullentryKeyId#
room.move bid_key_id / offer_key_id: room id bytes ‖ "bid" or "offer" ‖ bcs(seq: u64). One key opens one entry.
export function entryKeyId(roomId: string, kind: EntryKind, seq: bigint): Uint8Array
export const entryKeyIdHex = (roomId: string, kind: EntryKind, seq: bigint) =>seqOfKeyId#
The seq a key id names, or null when it is not room ‖ kind ‖ bcs(seq) for this room.
export function seqOfKeyId(id: Uint8Array, roomId: string, kind: EntryKind): bigint | nullpoolAadV2#
The AAD room.move pins on a pool entry: bcs(n0), the spend's first nullifier. An address bid's is the sender.
export const poolAadV2 = (n0: bigint) => bcs.u256().serialize(n0).toBytes();sealEntryV2#
The 40-byte opening sealed under the entry's own identity for the room's NEXT seq (next_seq view).
export type EntrySealTarget = { pkg: string; roomId: string; kind: EntryKind; seq: bigint };
export const sealEntryV2 = (sealer: Sealer, t: EntrySealTarget, opening: EntryOpening, aad: Uint8Array) =>sealedEntryFault#
What room.move is_room_ciphertext / pin_sealed would reject in sealed; null when the chain would take it.
export type EntrySealPins = EntrySealTarget & { keyServers: string[]; threshold: number };
export function sealedEntryFault(sealed: Uint8Array, pins: EntrySealPins, aad: Uint8Array): string | nullSettleProver#
export type SettleProverPaths = ProverPaths;
export type SettleProof = { proof: Uint8Array; publicSignals: [bigint, bigint]; snarkjs: SnarkjsProof };
export type SettleProver = {
prove(s: SettleStatement, values: bigint[], salts: bigint[]): Promise<SettleProof>;
close(): Promise<void>;
};settleProver#
snarkjs over the Settle(16) wasm and zkey (TEST-ONLY key, settleProvingKeys); one proof at a time. paths.snarkjs omitted loads the SDK's own. prove refuses a proof whose public signals are not the statement's digests, and a proof that is not 128 Sui bytes.
export async function settleProver(
paths: SettleProverPaths,
hash: Hash = poseidonHash,
): Promise<SettleProver>SettleKeysTestOnly#
export type SettleKeysManifestTestOnly = {
name: string;
version: string;
label: "TEST-ONLY single-party";
license: string;
circuits: { settle: BundleCircuit };
};
export type SettleKeysTestOnly = {
manifest: SettleKeysManifestTestOnly;
wasm: string;
zkey: string;
vkey: string;
/** The bytes `create_verifier` takes, and their blake2b256 (= the manifest's and the Move `VK_HASH`). */
vkBytes: Uint8Array;
suiVkHash: string;
};settleManifestOf#
Refuses, with PROOF_BUNDLE_REFUSED, a manifest that is not the settle keys'; the proof-bundle manifest is refused with "use fetchProofBundle".
export function settleManifestOf(raw: unknown): SettleKeysManifestTestOnlysettleProvingKeys#
The Settle(16) keys on disk, refused unless every file matches the manifest's sha256 and byte count and the verifying key hashes to expectVkHash (the Move VK_HASH, default SETTLE_VK_HASH_TESTONLY), as fetchProofBundle does.
export function settleProvingKeys(o: { dir: string; expectVkHash?: string }): SettleKeysTestOnlyfetchSettleKeys#
Downloads manifest.json and the three Settle(16) key files into dir with settleProvingKeys' checks on each, so a later run loads them from disk; a wrong file is deleted before the refusal. The testnet baseUrl is https://cdn.jsdelivr.net/npm/@esseyonsui/settle-keys-testonly@0.1.0. fetchProofBundle refuses this manifest by name ("use fetchSettleKeys").
export type FetchSettleKeysOptions = {
/** Where `manifest.json` lives; every `path` in it is read relative to this. */
baseUrl: string;
dir: string;
expectVkHash?: string;
fetch?: typeof fetch;
};
export async function fetchSettleKeys(o: FetchSettleKeysOptions): Promise<SettleKeysTestOnly>From settle-host-v2.ts#
Exported by index.ts. The host side: the seller or the borrower opening its room's entries after the close.
HostSealConfig#
The Seal setup a v2 room pins (room.move KEY_SERVERS, THRESHOLD, the package the ids are namespaced under). TESTNET_SALE_ROOM_V2 and TESTNET_PRIVATE_LOAN_V2 are both one.
export type HostSealConfig = { pkg: string; keyServers: string[]; threshold: number };SealedEntry, OpenedEntry, OpenedEntries#
fault null: the plaintext opens the commitment and opening holds it; set: what slash would remove it for.
export type SealedEntry = { index: number; seq: bigint; commit: bigint; sealed: Uint8Array };
export type OpenedEntry = SealedEntry & {
plain: Uint8Array | null;
fault: EntryFault | null;
opening: EntryOpening | null;
};
export type OpenedEntries =
{ ok: true; entries: OpenedEntry[]; malformed: number[] } | { ok: false; fault: OpenFault; error: string };
export type EntrySeal = Pick<SealClient, "fetchKeys" | "decrypt">;openEntries#
One fetchKeys for every entry's own id (txBytes must carry one seal_approve per id), then a local decrypt per ciphertext. A ciphertext that does not open is "none", as the chain's bf::decrypt would report it.
export async function openEntries(
seal: EntrySeal,
a: {
roomId: string;
kind: EntryKind;
threshold: number;
session: SessionKey;
txBytes: Uint8Array;
entries: SealedEntry[];
hash?: Hash;
},
): Promise<OpenedEntries>SettlePlan, settlePlan#
The claim to prove over these entries, or the indices to slash first: the proof opens every commitment.
export type SettlePlan =
{ ok: true; claim: SettleClaim; values: bigint[]; salts: bigint[] } | { ok: false; malformed: number[] };
export function settlePlan(
rule: SettleRule,
opened: OpenedEntry[],
bounds: { lo: bigint; hi: bigint },
): SettlePlanhostSession#
A Seal SessionKey for cfg.pkg under signer, ten minutes.
export function hostSession(client: SuiGrpcClient, cfg: Pick<HostSealConfig, "pkg">, signer: Signer)openRoomEntries#
The host's keys for every entry under one session, then openEntries; approve is the room's seal_approve PTB (saleSealApproveV2Tx or loanSealApproveV2Tx over the same seqs).
export async function openRoomEntries(
client: SuiGrpcClient,
cfg: HostSealConfig,
signer: Signer,
a: { roomId: string; kind: EntryKind; entries: SealedEntry[]; approve: Transaction; seal?: EntrySeal },
): Promise<OpenedEntries>slashShares#
The derived keys for ONE entry, as room.move slash verifies them: exactly threshold, in KEY_SERVERS order.
export async function slashShares(
client: SuiGrpcClient,
cfg: HostSealConfig,
signer: Signer,
a: {
roomId: string;
kind: EntryKind;
seq: bigint;
approve: Transaction;
servers?: number[];
seal?: Pick<SealClient, "getDerivedKeys">;
},
): Promise<FinishShares>bytesOf, jsonOption, sealedBytesOf#
A Move vector<u8> as the node's JSON renders it: a byte array or base64. Option<T> as the node's JSON renders it: the value or null. sealedBytesOf is the inverse of bf::parse_encrypted_object, so the host can hand a stored entry's bytes to SealClient.decrypt; readSaleRoomV2 and readPrivateLoanV2 apply it to every entry.
export function bytesOf(v: unknown): Uint8Array
export function jsonOption<T>(v: unknown, of: (x: unknown) => T): T | null
export function sealedBytesOf(j: SealedJson): Uint8ArrayFrom shielded/prover.ts#
Exported by index.ts.
ProverPaths#
wasm and zkey are gitignored build output; snarkjs omitted is the SDK's own.
export type ProverPaths = { snarkjs?: string; wasm: string; zkey: string };snarkjsUrl#
The snarkjs this package depends on, as the URL import() takes; NOT_SET_UP names the install when it is absent (npm install snarkjs@0.7.6, or pass ProverPaths.snarkjs).
export function snarkjsUrl(): stringloadSnarkjs#
export const loadSnarkjs = async (path?: string) => (await import(path ?? snarkjsUrl())) as Snarkjs;snarkjsProver#
The spend prover over the circuit's wasm and zkey (fetchProofBundle(...).spend); one proof at a time. close terminates snarkjs's bn128 worker threads.
export type RealProver = { prover: Prover; close(): Promise<void> };
export async function snarkjsProver(paths: ProverPaths): Promise<RealProver>suiVerifyingKey#
snarkjs vkey.json -> the bytes pool::create_pool takes; hash is what pool.move's VK_HASH must equal.
export function suiVerifyingKey(vkeyPath: string): { bytes: Uint8Array; hash: string }From membership/membership.ts and membership/tx.ts#
Exported by index.ts.
MemberSecrets#
export type MemberSecrets = { secret: bigint; nullSecret: bigint };MemberSecretStore#
Where a member keeps its secrets. They are made ONCE and reused for every pass, every epoch and every issuer key: the issuer pins the first commitment per account (409 ALREADY_ISSUED for any other), and the tag in a room is a function of nullSecret alone, so a member that lost them cannot bid again until an operator reset cools down.
export type MemberSecretStore = { get(): string | undefined; set(v: string): void };persistentMemberSecrets#
The member's secrets from store, made with random (31 bytes, below R) only when the store is empty. Saved as { secret, nullSecret } decimal strings; a stored value outside (0, R) and a random that is not 31 bytes throw.
export function persistentMemberSecrets(store: MemberSecretStore, random: () => Uint8Array): MemberSecretsBinding#
export type Binding = { sender: string } | { n0: bigint };provedPassFor#
The whole client half of a dregg credential in one call: ask the issuer to sign this holder's commitment, then prove membership locally against room. The issuer never sees secrets.nullSecret, so the proof cannot be made for anyone else, and the issuer cannot link the account to the tag. paths are the membership circuit's wasm and zkey (fetchProofBundle(...).membership).
export async function provedPassFor(args: {
service: CredentialSource;
hash: Hash;
/** Omit to load the snarkjs this package depends on. */
snarkjs?: Snarkjs;
paths: ProverPaths;
holder: string;
room: string;
secrets: MemberSecrets;
/** Omit for a sender-bound credential (room::bid, pool::deposit). */
binding?: Binding;
/** Omit for a room bid (nonce 0). A deposit passes a fresh field element. */
nonce?: bigint;
vkey?: unknown;
}): Promise<ProvedPass>ProvedPass#
A credential already proved for one room: proveMembership's output, the address it is bound to, and the issuer credential it was proved from.
export type ProvedPass = {
holder: string;
tag: bigint;
proof: Uint8Array;
credential: IssuerPass;
nonce?: bigint;
};From deployment.ts#
Exported by index.ts. deploymentOf and EsseyDeployment are in Connection and keys.
readerTarget#
The Move target of the oracle reader a loan room's reading is built with: ${oraclePkg}::${reader} when the deployment has an oraclePkg (the 2026-11-05 cutover publishes essey_oracle_pyth on its own), else ${pkg}::${reader}. Its arguments are deployment.pkg, the market's reader from GET /v1/private/config and deployment.oraclePkg.
export function readerTarget(pkg: string, reader: string, oraclePkg?: string | null): stringFrom chain.ts#
Exported by index.ts. The rest is in Chain helpers, errors, aborts.
walletGasMode#
Where a wallet's gas for budget comes from: a SUI coin object that covers it when the wallet has one ("coins"), else its address balance ("address-balance"; the public faucet and coin::send_funds fund address balances, not coin objects).
export async function walletGasMode(
client: Pick<SuiGrpcClient, "listCoins">,
owner: string,
budget: bigint,
): Promise<GasMode>executeAsWallet#
A wallet key's transaction (a seller, a depositor, anyone finishing a room). Without gasBudget the build dry-runs it to price the gas, so an abort it foresees throws and nothing is signed. With one, the gas source is walletGasMode's and nothing is simulated, so an abort lands with its digest.
export async function executeAsWallet(
chain: ExecChain,
tx: Transaction,
signer: Signer,
opts: { gasBudget?: bigint } = {},
): Promise<Landed>