Private flows with the SDK
The SDK builds every private flow in the loan room and the gated sale room. Each builder returns a transaction for a relayer or a fresh wallet, never for the agent's own key, so the agent's address never touches a private flow. The default loan coin is Sui Dollar (USDsui). The v2 rooms (sale_room_v2, private_room_v2) have their own builders, from the open to the repay, plus two composers that build the pool spend and the relayer body in one call (buildPoolBidV2, buildOfferV2); they are configured by TESTNET_SALE_ROOM_V2 and TESTNET_PRIVATE_LOAN_V2, and their finish or settle carries a proof, never the losing values. The full walkthrough is Sealed settlement (v2 rooms) below; every signature is in Sealed settlement v2.
Loan markets#
openPrivateLoan passes a Market<collateral, loan>. The object has to be that pair. lending.market (0x618b3e2946ff34462bf8af9ff2cafe444d7bb19b367e882ca67c9af59f1aad33) is Market<SUI, USDC> only. Using it to open a Sui Dollar room fails a type mismatch on the market argument.
| Loan | Collateral | Market | On testnet now |
|---|---|---|---|
| USDSUI | SUI | Market<SUI, USDSUI> | 0x441827e6df0b201c85c2df88a4c43d3729d55a93d6b9618e167ea5d3110fbca6. Same Pyth SUI/USD feed as USDC, because both loan coins are 6-decimal USD stables. |
| USDC | SUI | Market<SUI, USDC> | 0x618b3e2946ff34462bf8af9ff2cafe444d7bb19b367e882ca67c9af59f1aad33 |
| SUI | USDSUI | Market<USDSUI, SUI> | 0x71a134124c544d1e79bd619c3cfc27f0a1a3b2f9e7ea4a077a7c4638da9023f9. Oracle package 0x373a36f16e0309ea7cb9f02715a4b60ad77626ccfa177834c4dbe392078f186e, reader pyth_oracle::read_inverse, same SUI/USD feed. readingFor(tx, privateConfig, "SUI") builds that call. The older oracle 0x9130… has no inverse reader. |
Market<SUI, SUI> is not a supported pair. All three markets above are open on testnet: GET /v1/private/config carries each id under loanMarkets.<coin>.id with openable: true, and openPrivateLoan takes that id.
The testnet SUI pool insert fee is 0.1 SUI per deposit (USDC and tUSDsui pools charge 0.01 of that coin). A pool bid or loan offer inserts a change note and a refund note, so it pays the fee twice more: a small SUI bid needs about 0.212 SUI in the pool (0.002 max price + 0.01 relayer fee + 0.2) and another 0.1 SUI to deposit that note. One faucet grant is about 1 SUI. A bidder's deposit fits in it. One address that also finishes the sale (0.25 SUI gas budget), settles the loan (another 0.25) and repays (owed plus 0.1 SUI) needs a second grant from sui client faucet --url https://faucet.testnet.sui.io --address <ADDRESS> or https://faucet.sui.io. On a rate limit, wait and retry, or use another address.
Loan room#
Deprecated. The v1 private loan room (essey_sui::private_room) publishes every offer's rate and salt in the settle transaction, so losing rates become public at settle. Use the v2 private loan room below. The v1 names in this table are legacy. The MCP tools essey_private_offer, essey_private_settle, essey_private_cancel, essey_private_repay and essey_private_offer_commit are the same legacy surface. essey_private_offer_commit draws a salt of at least 128 bits when you omit one.
| Function | Who | What it builds |
|---|---|---|
openPrivateLoan | Borrower | Opens a PrivateLoanRoom for that loan coin's market pair |
attestBorrower | Borrower | The borrower's credential attestation for the room |
offerPrivateLoan | Lender | A Seal-sealed rate, funded from the shielded pool; room credential and gate pass bound to spend.n0 |
settlePrivateLoan / settlePrivateLoanRelayed | Borrower | Settles the chosen offer into the borrower's note; the relayed form is bound to actionHash |
cancelPrivateLoan / cancelPrivateLoanRelayed | Borrower | Cancels an unsettled room |
repayPrivateLoan | Borrower | Repays from a shielded note |
repayPrivateLoanCoin | Borrower | Repays in public with a coin |
liquidatePrivateLoan | Anyone | Liquidates an undercollateralized loan |
claimPrivateDefault | Lender | Claims a defaulted loan; surplus collateral goes back to the borrower |
Helpers: commitOf (the sealed-rate commitment), actionHash and settleAction (the value a relayed credential is bound to), offerStatement and repayStatement (the pool-proof statements), coinType (the coin type behind a coin key).
Gated sale room#
| Function | What it builds |
|---|---|
openGatedSale | Opens a sale room behind the access gate |
bidGatedSale | A sealed bid from a member's address |
poolBidGatedSale | A shielded bid from the pool with a spend-bound membership, sent through the relayer |
collectSaleRefund | Returns a losing bid's deposit |
Sealed settlement (v2 rooms)#
TESTNET · PREVIEW
sale_room_v2 and private_room_v2 seal every bid and offer twice. A Poseidon commitment commitV2(value, salt) goes on chain, and the 40-byte opening (value ‖ salt, plaintextV2) is sealed with Seal under the entry's own key id (entryKeyId(room, kind, seq)). After the close the host, the seller or the borrower, opens the entries on its own machine, proves the selection with the Settle(16) circuit and sends the proof with the winner. The chain verifies the proof against every commitment; the losing values never leave the host. A room holds at most 16 entries (SETTLE_SLOTS).
The ids are TESTNET_SALE_ROOM_V2 and TESTNET_PRIVATE_LOAN_V2, the same objects as the saleRoomV2 and privateLoanV2 sections of GET /v1/private/config. Every function below is exported from @esseyonsui/sui-sdk.
What every side needs#
- snarkjs installs with the SDK (
snarkjs0.7.6 is a dependency).snarkjsProver({ wasm, zkey }),settleProver({ wasm, zkey })andprovedPassForload it themselves.ProverPaths.snarkjstakes the path of another snarkjs module; without it the SDK's own is used, and a missing install throwsNOT_SET_UPnamingnpm install snarkjs@0.7.6. - Proving keys.
fetchProofBundle({ baseUrl, dir })downloads the membership and spend keys (baseUrlishttps://cdn.jsdelivr.net/npm/@esseyonsui/proving-keys-testonly@0.1.0).fetchSettleKeys({ baseUrl, dir })downloads the Settle(16) key (https://cdn.jsdelivr.net/npm/@esseyonsui/settle-keys-testonly@0.1.0). Both check each file's byte count and sha256 against the manifest and the verifying key's Sui hash against the deployed constant (SETTLE_VK_HASH_TESTONLYfor the settle key), and delete a wrong file before refusing withPROOF_BUNDLE_REFUSED. Each refuses the other's manifest by name. On a later runsettleProvingKeys({ dir })loads the settle key from disk with the same checks. Every key is a TEST-ONLY single-party setup. - Member secrets.
persistentMemberSecrets(store, () => randomBytes(31))reads{ secret, nullSecret }fromstore({ get(): string | undefined; set(v: string): void }) or, when the store is empty, draws each from 31 random bytes and saves them as decimal strings. Keep the store like a key: the issuer pins one commitment per account, and the tag in a room is a function ofnullSecretalone. - A credential per room.
const service = new EsseyService(API, key); await service.signIn();thenprovedPassFor({ service, hash: poseidonHash, paths: bundle.membership, holder, room, secrets })for a sender-bound pass (the seller, the borrower), or withbinding: { n0 }for a pass bound to a pool spend. A builder takes it as aPass,{ tag: pass.tag, expiryMs: pass.credential.expiryMs, proof: pass.proof }; the relayer takeswirePass(pass).poseidonHashis@mysten/sui/zklogin's. - A shielded wallet on the room's pool:
ShieldedWallet.fromSeed(seed, { client, events, room, pool, relayer, prover, indexed }), as in Sale rooms with the SDK §5, funded withdepositTx.poolis the coin's shielded pool:TESTNET_POOLfor SUI; for USDC or Sui Dollar,{ pkg: TESTNET_POOL.pkg, pool, coinType, levels: 20 }withpoolandcoinTypefromshieldedPools.<coin>ofGET /v1/private/config. The wallet'sspendDeps(cfg)is what the composers take: its hash, its prover, the pool's live root and a Seal client for the room's key servers. The deposit pass is proved for the pool:roomis the pool id andnonceisrandomSalt(); the two lines are underdepositTxin Sale rooms. - The relayer.
relayerinGET /v1/private/configgivesbaseUrl,addressandpaths(sui,usdc,usdsui); a body is posted tobaseUrl + paths.<coin>of the pool it spends from. The SUI route is the exportTESTNET_RELAYER, floorminFee10,000,000 MIST. The SDK exports no object for the usdc and usdsui routes;relayerFor(coin, minFee)in the setup below builds one from the config,{ url: baseUrl + paths[coin], address, minFee }, aRelayerforShieldedSetup.relayerandsendToRelayer.minFeeis the route's floor in that coin's base units: 10,000 (0.01 USDC or 0.01 tUSDsui) on the hosted testnet relayer, as in Sale rooms with the SDK §1. The floor is set in the relayer's own configuration and the API does not serve it. A fee under it is refused before anything is signed:sendToRelayerreturns{ ok: false, error: "fee below MIN_FEE", sent: "no", from: "relayer" }, with no number in the message, so raise the fee and build again.sendToRelayerandSentare in Sealed settlement v2. - Gas. A seller, a borrower or a keeper signs with
executeAsWallet(chain, tx, signer). With{ gasBudget }it chooses the gas source withwalletGasMode(client, owner, budget): a SUI coin object that covers the budget when the wallet has one, else the address balance, which is what the public faucet funds.
Withdraw and exit#
wallet.withdraw(recipient, amount) pays amount through the relayer and keeps the change as a note (one insert fee). wallet.exit(recipient) pays every unspent note, less the relayer fee, and inserts nothing. Exit is refused when those notes are not strictly more than the fee: the notes hold N, not more than the relayer's fee N. On the SUI route the fee is 10,000,000 MIST (0.01 SUI), so a deposit of exactly 0.01 SUI cannot be exited. USDC and tUSDsui floors are 10,000 base units (0.01 of that coin). Deposit more than the fee if the note is meant to be exited. One exit spends at most two unspent notes. Both return { sent, withdraw }, and withdraw.spends and withdraw.change are note openings: each spent note carries its blinding and spendKey, and the change note its blinding. Treat them as secrets and keep them out of logs.
The examples share this setup:
import { randomBytes } from "node:crypto";
import { Transaction } from "@mysten/sui/transactions";
import { poseidonHash } from "@mysten/sui/zklogin";
import {
connect, deploymentOf, executeAsWallet, oneCreated, EsseyService, fetchProofBundle, fetchSettleKeys,
persistentMemberSecrets, provedPassFor, wirePass, snarkjsProver, settleProver,
ShieldedWallet, graphqlEventBcs, TESTNET, TESTNET_POOL, TESTNET_RELAYER, TESTNET_SALE_ROOM,
TESTNET_SALE_ROOM_V2, TESTNET_PRIVATE_LOAN_V2,
} from "@esseyonsui/sui-sdk";
const API = "https://sui-agent-prototype-production.up.railway.app";
const chain = await connect({ network: "testnet" });
const deployment = deploymentOf(await (await fetch(`${API}/v1/config`)).json());
const priv = (await (await fetch(`${API}/v1/private/config`)).json()).private; // loanMarkets, shieldedPools, relayer, saleRoomV2, privateLoanV2
const relayerFor = (coin: "usdc" | "usdsui", minFee: bigint) => // not an SDK export: a Relayer for the usdc and usdsui routes
({ url: priv.relayer.baseUrl + priv.relayer.paths[coin], address: priv.relayer.address, minFee });
const bundle = await fetchProofBundle({ baseUrl: "https://cdn.jsdelivr.net/npm/@esseyonsui/proving-keys-testonly@0.1.0", dir: "./keys" });
const settle = await fetchSettleKeys({ baseUrl: "https://cdn.jsdelivr.net/npm/@esseyonsui/settle-keys-testonly@0.1.0", dir: "./settle-keys" });
const secrets = persistentMemberSecrets(store, () => randomBytes(31)); // store: your own { get, set }
const service = new EsseyService(API, key); // key: the signer that opens, bids or offers
await service.signIn();
const pass = (p: Awaited<ReturnType<typeof provedPassFor>>) =>
({ tag: p.tag, expiryMs: p.credential.expiryMs, proof: p.proof }); // ProvedPass -> Pass
const spendProver = await snarkjsProver(bundle.spend);
const wallet = ShieldedWallet.fromSeed(seed, {
client: chain.client, events: graphqlEventBcs(TESTNET.graphqlUrl), room: TESTNET_SALE_ROOM,
pool: TESTNET_POOL, relayer: TESTNET_RELAYER, prover: spendProver.prover, indexed: chain.indexed,
});Each example below imports the functions it names from @esseyonsui/sui-sdk; coinWithBalance is @mysten/sui/transactions's. save stands for your own storage.
A. Sale room: open and attest (seller)#
const cfg = TESTNET_SALE_ROOM_V2;
const minted = await executeAsWallet(chain, demoBadgeTx(TESTNET_SALE_ROOM, "lot 1", sellerAddress), sellerKey); // a test item: the v1 package's demo Badge
const itemId = oneCreated(minted, "::demo::Badge");
const types = { itemType: `${TESTNET_SALE_ROOM.pkg}::demo::Badge`, coinType: "0x2::sui::SUI" }; // the item's type (any key + store object you own) and the room's coin
const open = new Transaction();
openSaleV2Tx(open, cfg, types, {
item: open.object(itemId),
minPrice: 1_000_000n,
maxPrice: 10_000_000n,
closeMs: BigInt(Date.now() + 600_000),
finishWindowMs: 1_800_000n,
maxBids: 5n,
shieldedOnly: true,
gate: null,
});
const opened = await executeAsWallet(chain, open, sellerKey);
const roomId = oneCreated(opened, "::room::SaleRoom");
const sellerPass = await provedPassFor({ service, hash: poseidonHash, paths: bundle.membership, holder: sellerAddress, room: roomId, secrets });
const attest = new Transaction();
attestSellerV2Tx(attest, cfg, { id: roomId, ...types }, pass(sellerPass));
await executeAsWallet(chain, attest, sellerKey);A test item comes from the v1 surface: demoBadgeTx(cfg, label, to) takes the v1 SaleRoomConfig (TESTNET_SALE_ROOM) and mints that package's demo::Badge to to; the v2 room::open<T: key + store, C> takes any such object, so a v1 Badge sells in a v2 room.
openSaleV2Tx(tx, cfg, types, terms) is room::open on the v2 package, v1's shape; it returns the room id result. terms is a GatedSaleTerms:
item: the object sold, as a transaction argument.minPrice,maxPrice: the floor and the ceiling, in the room's coin. A pool bid escrows the ceiling.closeMs: when bidding closes, absolute ms; at most 30 days ahead (SALE_ROOM_V2_RULES.maxOpenMs).finishWindowMs: how long after the close the seller may finish; at least 1,800,000 (SALE_ROOM_V2_RULES.minFinishWindowMs).maxBids: at most 16 (SALE_ROOM_V2_RULES.maxBidsCeiling, the circuit's slots).shieldedOnly:truefor pool bids. In afalseroom a pool bid aborts on chain (room abort 17) and only address bids (bidV2Tx) land.gate:nullwhile the Access is PUBLIC; else the seller's sender-bound pass for the Access id.
attestSellerV2Tx(tx, cfg, room, pass) is room::attest_seller: the seller's own sender-bound room credential, in a transaction the seller's wallet signs, before any bid. Until it lands the room takes no bid (room abort 23); it runs once, on an open room with no bids; after it, a bid carrying the seller's tag aborts (room abort 22). readSaleRoomV2 shows it as sellerTag and needsSellerTag.
B. Pool bid (bidder)#
const pool = TESTNET_POOL; // the pool this wallet's notes are in
const view = await readSaleRoomV2(chain.client, cfg, roomId);
if (!view.shieldedOnly) throw new Error("the room takes address bids only (room abort 17)");
const room = view; // `pool` is null until the first pool bid names it; the builder accepts that
const credential = async (n0: bigint) => ({
gate: null,
member: wirePass(await provedPassFor({ service, hash: poseidonHash, paths: bundle.membership, holder: bidderAddress, room: view.id, secrets, binding: { n0 } })),
});
const built = await buildPoolBidV2(
(await wallet.scan()).state,
{ cfg, pool, room, price: 4_000_000n, fee: TESTNET_RELAYER.minFee, relayer: TESTNET_RELAYER.address, claimTo, credential },
wallet.spendDeps(cfg),
);
if (!built.ok) throw new Error(built.error);
save({ tag: built.tag, openings: built.openings, claim: built.claim, entry: built.entry });
const sent = await sendToRelayer(TESTNET_RELAYER, built.body);
if (sent.ok) await chain.indexed(sent.digest);buildPoolBidV2(wallet, req, deps) composes the whole bid: it selects the notes, seals the opening, proves the spend, asks credential for the pass bound to the spend, and returns the finished Spend plus the relayer body. Its arguments:
wallet:(await wallet.scan()).state, the notes, tree and insert fee of this scan.req.cfg:{ pkg, keyServers, threshold }of the v2 package. The opening is sealed to exactly these servers, in this order, with this threshold; the chain refuses any other.req.pool:{ pool, coinType }the wallet spends from. It must be the room's pool and the room's coin.req.room: the room as read:id,coinType,pool,state,minPrice,maxPrice,maxBids,bids,nextSeq,sellerTag,needsSellerTag. The view'spoolis set by the room's first pool bid, so for the first bid pass the pool's id yourself, as above, after checkingshieldedOnly.req.price: the sealed price, floor to ceiling.req.fee: what the relayer keeps, at least its floor.req.relayer: the relayer's address. The proof pays its fee to this address, andsendToRelayerrefuses a body that pays another.req.claimTo: the address that receives the item and the change if this bid wins. It is committed asblake2b256(claimTo ‖ salt)and revealed only at the claim.req.credential:(n0) => Promise<{ member, gate }>, called once per proof attempt with the spend's first nullifier.memberis the room credential bound to{ n0 };gateis the Access pass bound the same way, ornullwhile the Access is PUBLIC.req.salt: omit;randomSalt()draws one below the field order.deps:wallet.spendDeps(cfg).
It returns { ok: false, error } before anything is sealed or proved when: the room's pool is null (address room, room abort 17); the room's pool or coin is not the wallet's (room abort 18); the room is not open (room abort 2); the seller has not attested (room abort 23); the room is full (room abort 6); the price is outside the floor and ceiling; no one or two unspent notes cover maxPrice + fee + 2 × insertFee; the wallet's tree is behind the pool (STALE_TREE: scan and build again, or wrap the build and the send in relayFresh); or credential returned no member. The spend escrows the ceiling, not the price.
It returns, with ok: true:
body: thebid_v2relayer body (BidV2Body), forsendToRelayer.bidV2Bodybuilds it from the parts.spend: the same spend as aSpend, for a transaction you send yourself withpoolBidV2Tx(the relayer's path is the one without an address).openings:{ change, refund }.change(or null) is the note the leftover of the spent notes comes back as, inserted at once.refundis the note of the ceiling that a losing deposit re-enters the pool as when anyone sendscollect; the chain stores no ciphertext for it, so a wallet finds it only through this opening. Keep both.tag: the spend'sn0, the bid's tag on chain. The claim salt is derived from it.claim:{ claimTo, salt }.saltisclaimSaltOf(keys.claimKey, tag), whichwallet.claimSalt(tag)recomputes from the seed and the tag, so keepingtagis enough.entry:{ value: price, salt }, the sealed opening. Keep it to show what you bid if the Seal open is disputed, or to verify the finish.spends: the notes spent.
C. Finish (seller)#
const view = await readSaleRoomV2(chain.client, cfg, roomId); // after view.closeMs
const entries = view.bids.map((b) => ({ index: b.index, seq: b.seq, commit: b.commit, sealed: b.sealed! }));
const opened = await openRoomEntries(chain.client, cfg, sellerKey, {
roomId, kind: "bid", entries, approve: saleSealApproveV2Tx(cfg, view, entries.map((e) => e.seq)),
});
if (!opened.ok) throw new Error(`${opened.fault}: ${opened.error}`);
const plan = settlePlan(RULE_HIGHEST_WINS, opened.entries, { lo: view.minPrice, hi: view.maxPrice });
if (!plan.ok) throw new Error(`slash entries ${plan.malformed} first`);
const prover = await settleProver({ wasm: settle.wasm, zkey: settle.zkey });
const proved = await prover.prove(saleStatementV2(view, plan.claim), plan.values, plan.salts);
const finish = new Transaction();
finishV2Tx(finish, cfg, view, { pool: view.pool!, claim: plan.claim, proof: proved.proof });
await executeAsWallet(chain, finish, sellerKey);
await prover.close();openRoomEntries(client, cfg, signer, { roomId, kind, entries, approve }) makes one Seal session under the seller's key, asks the key servers for one key per entry id (approve is the room's seal_approve transaction, one call per seq, which the servers dry-run) and decrypts every ciphertext locally. Each OpenedEntry carries its opening or a fault (none, length, salt, commit); malformed lists the faulty indices. The servers answer only after closeMs. A bid whose sealed is null in the view carries no readable ciphertext.
settlePlan(rule, opened, bounds) applies the room's rule: eligible is lo <= value <= hi, rule 1 takes the highest, a later equal value never beats an earlier one. It returns the claim (hasWinner, winner, winValue) with every value and salt for the proof, or the indices to slash first: the proof opens every commitment, so a malformed entry blocks it until slashBidV2Tx removes it with that entry's derived keys (slashShares).
settleProver(paths) is snarkjs over the Settle(16) wasm and zkey, one proof at a time; prove(statement, values, salts) returns the 128 Sui proof bytes and the two public digests, and refuses a proof over another statement. saleStatementV2(room, claim) is the statement room.move recomputes: the commits in bid order, floor, ceiling, rule 1, the claim, the room id. finishV2Tx(tx, cfg, room, { pool, claim, proof }) is room::finish, the seller's, after the close: the winner pays its price, the seller is paid, and no plaintext reaches the chain.
D. Collect and claim (anyone)#
collectTx({ ...pool, pkg: cfg.pkg }, view); // once per losing pool bid; the deposit re-enters the pool as its refund note
claimTx({ pkg: cfg.pkg }, view, claim.claimTo, claim.salt); // the item and the change go only to the claimTo the winner sealedcollectTx(cfg, room) is room::collect: anyone, once per pending refund, after the finish or the expiry. Its cfg.pkg is the sale package, not the privacy package. claimTx(cfg, room, claimTo, salt) is room::claim: anyone may send it, the prize goes to claimTo only, and a wrong salt or address aborts (EBadClaim). The winner's salt is built.claim.salt, or wallet.claimSalt(tag) again.
E. Loan room: open and attest (borrower)#
const cfg = TESTNET_PRIVATE_LOAN_V2;
const market = priv.loanMarkets.USDC; // GET /v1/private/config: id, reader, witness, openable
const types = { collateralType: "0x2::sui::SUI", loanType: priv.shieldedPools.USDC.coinType };
const open = new Transaction();
const reading = open.moveCall({
target: readerTarget(deployment.pkg, market.reader, deployment.oraclePkg),
arguments: [open.object(deployment.feed), open.object(CLOCK)],
});
openPrivateLoanV2Tx(open, cfg, types, {
market: market.id,
reading,
loanPool: priv.shieldedPools.USDC.id,
collPool: priv.shieldedPools.SUI.id,
collateral: coinWithBalance({ balance: 300_000_000n }),
principal: 1_000_000n,
maxRateBps: 1_500n,
termMs: 86_400_000n,
offerWindowMs: 600_000n,
gate: null,
});
const opened = await executeAsWallet(chain, open, borrowerKey);
const roomId = oneCreated(opened, "::room::PrivateLoanRoom");
const borrowerPass = await provedPassFor({ service, hash: poseidonHash, paths: bundle.membership, holder: borrowerAddress, room: roomId, secrets });
const attest = new Transaction();
attestBorrowerV2Tx(attest, cfg, { id: roomId, ...types }, pass(borrowerPass));
await executeAsWallet(chain, attest, borrowerKey);openPrivateLoanV2Tx(tx, cfg, types, o) is room::open on the v2 package, v1's shape; it returns the room id result. types is { collateralType, loanType }, the market's pair. o is an OpenLoan:
market: theMarket<collateral, loan>id from Loan markets.reading: the priceReadingbuilt in the same transaction from the market'sreader(pyth_oracle::readfor the USDC and USDSUI markets,pyth_oracle::read_inversefor the SUI market) over the deployment'sfeed;deploymentisdeploymentOfoverGET /v1/config.loanPool: the loan coin's shielded pool, which the offers are funded from and the principal lands in.collPool: the collateral coin's shielded pool, pinned on the room forclaim_default.collateral: a coin of the collateral type, as a transaction argument. The chain checks LTV at the borrow value and abortsEOverLtvover the market's limit; size it withbook.ltvOnChain.principal: in the loan coin, at least the loan pool's minimum.maxRateBps: the highest rate an offer may win at, 1 to 10,000.termMs: the loan's term; the interest owed is fixed at the settle from it.offerWindowMs: how long offers are taken; the settle must follow within 24 hours of the close (LOAN_ROOM_V2_RULES.settleWindowMs).gate:nullwhile the Access is PUBLIC; else the borrower's sender-bound pass for the Access id.
A new room is in state attesting (LOAN_ROOM_V2_STATE). attestBorrowerV2Tx(tx, cfg, room, pass) is room::attest_borrower, the borrower's own sender-bound room credential, signed by the borrower; it moves the room to bidding and only then are offers taken.
F. Offer (lender)#
const pool = { pkg: TESTNET_POOL.pkg, pool: priv.shieldedPools.USDC.id, coinType: priv.shieldedPools.USDC.coinType, levels: 20 };
const relayer = relayerFor("usdc", 10_000n); // What every side needs: { url: baseUrl + paths.usdc, address, minFee }, built from the config
const fee = relayer.minFee; // at least the usdc route's floor, in USDC base units; a lower fee comes back as `fee below MIN_FEE`
const view = await readPrivateLoanV2(chain.client, cfg, roomId);
const credential = async (n0: bigint) => ({
gate: null,
member: wirePass(await provedPassFor({ service, hash: poseidonHash, paths: bundle.membership, holder: lenderAddress, room: view.id, secrets, binding: { n0 } })),
});
const built = await buildOfferV2(
(await wallet.scan()).state,
{ cfg, pool, room: view, rateBps: 900n, fee, relayer: relayer.address, credential },
wallet.spendDeps(cfg),
);
if (!built.ok) throw new Error(built.error);
save({ tag: built.tag, openings: built.openings, entry: built.entry });
const sent = await sendToRelayer(relayer, built.body); // Sent: { ok, digest } or { ok: false, error, sent, from }
if (sent.ok) await chain.indexed(sent.digest);buildOfferV2(wallet, req, deps) has the bid's shape. req.room is the room as read (id, loanPool, loanType, state, principal, maxRateBps, offers, nextSeq); req.rateBps is the sealed rate; req.pool is the loan coin's pool the wallet spends from; fee, relayer, credential and salt are as for the bid. It refuses before sealing or proving a room funded from another pool (room abort 4), another coin, a room not in bidding (room abort 2), a full room (16 offers, room abort 13), a rate over maxRateBps, notes that do not cover principal + fee + 2 × insertFee, a stale tree, or a credential without member. The spend escrows the principal.
It returns body (loan_offer_v2, LoanOfferV2Body; loanOfferV2Body builds it from the parts), spend (for offerV2Tx, self-sent), tag, entry ({ value: rateBps, salt }), spends, and openings: { change, refund, repay }. refund is the note the principal re-enters the pool as when the offer loses; repay is { pubkey, blinding } of the note the borrower's repayment lands in, under this wallet's spend key. The repayment amount is the room's owed, known only at the settle, and the chain stores for that note only what the repayer passes as lenderEnc, so keep openings.repay: after the settle, wallet.lenderCiphertext(view.owed, openings.repay.blinding, view.id) stores the opening and the next scan finds the repayment.
G. Settle (borrower)#
const view = await readPrivateLoanV2(chain.client, cfg, roomId); // after view.closeMs, within 24 hours
const entries = view.offers.map((o) => ({ index: o.index, seq: o.seq, commit: o.commit, sealed: o.sealed! }));
const opened = await openRoomEntries(chain.client, cfg, borrowerKey, {
roomId, kind: "offer", entries, approve: loanSealApproveV2Tx(cfg, view, entries.map((e) => e.seq)),
});
if (!opened.ok) throw new Error(`${opened.fault}: ${opened.error}`);
const plan = settlePlan(RULE_LOWEST_WINS, opened.entries, { lo: 0n, hi: view.maxRateBps });
if (!plan.ok) throw new Error(`slash entries ${plan.malformed} first`);
const prover = await settleProver({ wasm: settle.wasm, zkey: settle.zkey });
const proved = await prover.prove(loanStatementV2(view, plan.claim.winner, plan.claim.winValue), plan.values, plan.salts);
const principal = newDeposit(borrowerWallet.keys, view.principal); // the note the principal lands in, encrypted to this wallet
const args = {
winner: BigInt(plan.claim.winner), rateBps: plan.claim.winValue,
principalPubkey: principal.note.pubkey, principalBlinding: principal.note.blinding, encNote: principal.encNote,
proof: proved.proof,
};
const tx = new Transaction();
settleV2Tx(tx, cfg, view, { loanPool: view.loanPool, ...args });
await executeAsWallet(chain, tx, borrowerKey);The Seal open and the plan are the sale's with kind: "offer", loanSealApproveV2Tx, rule 2 (RULE_LOWEST_WINS, the lowest eligible rate, earlier index on ties) and bounds 0 to maxRateBps. loanStatementV2(room, winner, rateBps) is the statement room.move recomputes. The settle takes SettleV2Args: winner (the index in offers), rateBps, the borrower's principal note (principalPubkey, principalBlinding, encNote; newDeposit(keys, amount) makes all three for a shielded wallet on the loan pool) and the 128-byte proof. On the settle the chain fixes owed from the principal, the rate and the term, records the winner's repay note, and the room is active.
settleV2Tx(tx, cfg, room, { loanPool, ...args }) is room::settle, signed by the borrower's address. The relayed form keeps the borrower's address out: settleRelayedV2Body({ room, nonce: view.nonce, pass, ...args }) is the settle_relayed_v2 body, where pass is wirePass of a borrower credential proved with binding: { n0: settleActionV2(view.id, view.nonce, args) }, the hash of exactly these arguments and the room's nonce, so the relayer can neither change them nor replay it. sendToRelayer({ url: baseUrl + paths.<coin>, address }, body) posts it; a body without ext goes as is. settleRelayedV2Tx builds the same call for a transaction you send yourself.
H. Repay (borrower, or anyone)#
const view = await readPrivateLoanV2(chain.client, cfg, roomId); // state active; view.owed is the amount
const { insertFee } = await readPool(chain.client, pool);
const tx = new Transaction();
const payment = coinWithBalance({ type: types.loanType, balance: view.owed + insertFee, useGasCoin: false });
repayCoinV2Tx(tx, cfg, view, { loanPool: view.loanPool, payment, lenderEnc: new Uint8Array() });
tx.transferObjects([payment], borrowerAddress);
await executeAsWallet(chain, tx, borrowerKey);repayCoinV2Tx(tx, cfg, room, { loanPool, payment, lenderEnc }) is room::repay_coin: owed + insertFee is split from payment, the rest stays in it, the lender's note is the one the winning offer bound (never an argument), the collateral goes back to the borrower, and the room is repaid. lenderEnc is the ciphertext stored with the lender's note; the lender that kept openings.repay needs none, so empty is fine.
repayV2Tx(tx, cfg, room, { loanPool, spend, lenderEnc }) is room::repay from the borrower's notes. The Spend proves bidStatement(rows, room.owed, insertFee, { ...ext, refundPubkey: 0n, refundBlinding: 0n }, loanRepayPayloadV2(room.owed)): exactly owed, bound to this room's repay payload, with no refund pair. The SDK has no composer for this spend in 0.1.12, and the relayer has no repay_v2 kind. A v2 borrower repays a public coin with repayCoinV2Tx or MCP essey_loan_repay_v2. poolSpendOf(proved, ext) turns a proved statement into the Spend the builder takes. Anyone may send either repay.
What to keep, and why#
| Keep | From | Why |
|---|---|---|
| the wallet seed and the member-secret store | setup | The seed is the wallet; the secrets are the member. Neither is recoverable. |
openings.change, openings.refund | buildPoolBidV2, buildOfferV2 | The refund note is inserted by collect with no ciphertext on chain; the wallet finds it only with this opening (ShieldedSetup.openings). |
openings.repay | buildOfferV2 | The repayment note's amount is set at the settle; lenderCiphertext(owed, repay.blinding, room) stores it for the scan. |
tag and claim | buildPoolBidV2 | claimTx needs claim.salt; wallet.claimSalt(tag) recomputes it from the seed. |
entry | both | The sealed opening, to show what you bid or offered if the open is disputed. |
| the room id, the digest | every send | To read the room back and to check the chain before retrying. |
Cancel, expire, default#
grace_ms on the v2 loan room is 300000. readPrivateLoanV2 returns claimableAtMs (maturityMs + graceMs) and cancellableByAnyoneAtMs (closeMs + settleWindowMs, 86400000). A claim_default before claimableAtMs aborts 16 ENotDue, not EShieldedRoom.
cancelSaleV2Txreturns the item to the seller. Dropping that result isUnusedValueWithoutDrop. It refuses unless the sender is the seller, the room is open, and there are no bids.expireSaleV2Txis anyone's oncefinishByMshas passed. It returns the item to the seller. Shielded deposits stay in the room's pending list until someone sendscollectTx({ ...pool, pkg: cfg.pkg }, view)once per bid. Expire does not insert those notes.cancelLoanV2Txis the borrower's before the settle window lapses, and anyone's after.cancelLoanRelayedV2Txbinds the pass tocancelActionV2.claimDefaultV2TxandliquidateV2Txrefuse an emptylenderEnc. Build it withShieldedWallet.lenderCiphertext(seize, blinding, roomId)after a dry run that reportsseized. If a keeper already credited the pool with an empty ciphertext,wallet.recoverRoomNote(roomId, { amount: seized, blinding, commitment })rebuilds the note from the room opening and the event, thenexitspends it.
openRoomEntries refuses with ROOM_NOT_CLOSED (closeMs and seconds left) or NOT_BORROWER / NOT_SELLER before it calls Seal.
Collateral for openPrivateLoanV2Tx should be collateralArg(tx, { type, amount }), which never uses the gas coin. openPrivateLoanV2WithCoin refuses when collateral plus the gas budget exceeds the balance.
Good practice#
- Use one Seal client per user: the client caches keys.
- Before retrying a transaction that reported an error, check the chain by its digest.
- After a default claim, read the
PrivateLoanDefaultedevent to find the lender's note. - A relayed body that the relayer refuses with
STALE_ROOTwas not sent: scan and build again (relayFreshdoes this).