Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirMarkets extends Event
/** Voting round: the recovery guard first (as Swap's vote), then validate only. A thrown string is the refusal. */
public vote(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
// Social recovery (spec §4.5): a recovered identity is dead, a frozen one cannot move money. settleBonds only
// CREDITS its payees (oracle plan §1.6): a recovered or frozen proposer or disputer still receives its bond.
const recoveryRefusal = this.refuseRecoveredStreams(this.transactions.$entry === "settleBonds" ? ["proposer", "disputer"] : []);
if (recoveryRefusal) return reject(recoveryRefusal);
try {
await this.dispatch(false);
resolve(true);
} catch (e) {
reject(typeof e === "string" ? e : (e as Error).message);
}
});
}/** Commit round: validate again on the same inputs, then write. */
public commit(): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
try {
await this.dispatch(true);
resolve(true);
} catch (e) {
reject(typeof e === "string" ? e : (e as Error).message);
}
});
} private refuseRecoveredIdentity(state: any, outgoing: boolean): string | null {
if (state && state.recoveredTo) {
// A dead identity may still RECEIVE: the credit lands and is swept to recoveredTo.
return outgoing
? `Identity recovered - new identity is ${state.recoveredTo}; your keys are still valid`
: null;
}
if (outgoing && state && state.recovery && state.recovery.frozen) {
return "Identity frozen - a social recovery is in its 48h waiting period";
}
return null;
} private refuseRecoveredStreams(incomingOnly: string[] | "all-outputs"): string | null {
// Never getActivityStreams(ref): an unloaded ref CREATES a stream. The
// no-argument form returns only the streams this transaction loaded.
const ctx: any = this as any;
const loaded: any = ctx.getActivityStreams() || {};
const outputs: any = (ctx.transactions && ctx.transactions.$o) || {};
const toId = (label: string, ref: any): string | null => {
const raw = ref && typeof ref === "object" ? ref.$stream : typeof ref === "string" ? ref : /^[0-9a-f]{64}$/i.test(label) ? label : null;
return typeof raw === "string" ? raw.split(":")[0].slice(-64) : null;
};
const outputIds: string[] = [];
const incomingIds: string[] = [];
for (const label of Object.keys(outputs)) {
const id = toId(label, outputs[label]);
if (!id) continue;
outputIds.push(id);
if (incomingOnly === "all-outputs" || incomingOnly.indexOf(label) !== -1) incomingIds.push(id);
}
for (const id of Object.keys(loaded)) {
const activity = loaded[id];
if (!activity || typeof activity.getState !== "function") continue;
const signed = typeof activity.hasSignature === "function" && activity.hasSignature();
const incoming = !signed && outputIds.indexOf(id) !== -1 && incomingIds.indexOf(id) !== -1;
const refusal = this.refuseRecoveredIdentity(activity.getState(), !incoming);
if (refusal) return refusal;
}
return null;
} private async dispatch(apply: boolean): Promise<void> {
switch (this.transactions.$entry) {
case "createMarket": return this.runCreateMarket(apply);
case "mintPair": return this.runMintPair(apply);
case "mergePair": return this.runMergePair(apply);
case "match": return this.runMatch(apply);
case "cancel": return this.runCancel(apply);
case "resolveVote": return this.runResolveVote(apply);
case "redeem": return this.runRedeem(apply);
case "pauseMarket": return this.runPauseMarket(apply, true);
case "unpauseMarket": return this.runPauseMarket(apply, false);
case "delist": return this.runDelist(apply);
case "propose": return this.runPropose(apply);
case "dispute": return this.runDispute(apply);
case "arbitrate": return this.runArbitrate(apply);
case "settleBonds": return this.runSettleBonds(apply);
default:
throw `Unknown entry ${this.transactions.$entry}`;
}
}/**
* `createMarket` (the tenant master as `$i.tenant = {$stream, market: {...}}`, signed by its tenant key; the
* tenant's directory as `$o.dir`, or no `$o.dir` for the tenant's first market, which creates it): a new market
* stream (its id from this transaction's umid). Gate steps 1, 2 and 6 at level `resolve` (plan §2.4). `market` is
* `{question, rules, closeAt, resolveBy, collateral: {network, token}, caps: {maxCollateral, maxPerUser, maxOrder,
* minOrder?}, resolvers: [ids], threshold, allowJ?}`; the caps are raw-unit strings of the collateral, multiples of
* SHARE_STEP. `minOrder` (default one whole token of the collateral) is the smallest mint and order size, so dust
* cannot burn the tenant's credits. Resolvers are trusted parties the tenant chooses; `threshold` must be a strict
* majority of them. Emits `market-created`. The streams are NOT contract-locked (setContractLock): on the local
* engine a lock set to this contract's id refused Varnir.Markets' own later write ("Stream contract locked"), so
* the defence is that no other contract names a market's kind or its fields (markets-review-fixes.test.ts).
*
* An OPTIMISTIC market (oracle plan §1.2, §1.4) names `resolution: {kind: "optimistic", reporter, resolvers,
* threshold, bond, disputeBond, disputeFeeBps?, disputeWindowMs, escalation: {kind: "arbiters", windowMs}}` instead
* of the top-level `resolvers` and `threshold` (mixing the two is refused). Without `resolution` the market is a
* "set" market written exactly as 1.0.133 wrote it (markets-oracle-compat.test.ts).
*
* The DESK path (oracle plan §1.10, decision 21g): `$i.desk = {$stream, market}` signed by the desk identity's one
* live stake-100 owner key, the tenant master as `$r.tenant`, `$o.dir`. The desk must be the one registered on the
* master, in mode `auto`; its market names no resolution of its own (the tenant's profile is copied, so a stolen
* desk key cannot choose who answers), uses a collateral of the desk's list, stays within the desk's per-market cap
* and close horizon, and counts against the desk's daily cap on the directory (`dir.desk = {day, count}`).
*/ private async runCreateMarket(apply: boolean): Promise<void> {
const tx: any = this.transactions;
const byDesk = !!(tx.$i && tx.$i.desk);
let tenantId: string;
let mk: any;
let input: any;
let desk: any = null;
let deskId: string | null = null;
if (byDesk) {
const deskAct = this.named("$i", "desk");
deskId = deskAct.getId();
const ref = tx.$r && tx.$r.tenant;
const refId = ref && typeof ref === "object" ? ref.$stream : ref;
if (typeof refId !== "string" || !HEX64.test(refId)) throw "Markets - the desk path names the tenant master as $r.tenant";
tenantId = refId;
mk = this.gateTenant(this.getReadOnlyStream("tenant"), refId, refId, "resolve");
desk = this.deskOf(mk);
if (desk.id !== deskId) throw "Markets - this identity is not the tenant's market desk";
if (mk.deskOffBy !== null && mk.deskOffBy !== undefined) throw "Markets - Varnir turned this tenant's market desk off";
if (desk.mode !== "auto" || (desk.pausedAt !== null && desk.pausedAt !== undefined)) throw "Markets - the tenant's market desk is off: a person approves its drafts in the console";
this.assertOwnerKey(deskAct, "Markets - the market desk signs with exactly one of its own stake-100 owner keys");
input = tx.$i.desk.market;
} else {
const masterAct = this.named("$i", "tenant");
const master = masterAct.getState();
this.requireTenantKeySigned(masterAct);
tenantId = masterAct.getId();
mk = this.gateTenant(master, tenantId, tenantId, "resolve");
input = tx.$i.tenant.market;
}
// Gate step 6 at the tenant level (a new market has no market-level pause yet).
if (mk.pausedAt !== null && mk.pausedAt !== undefined) throw "Markets - this tenant's markets are paused";
if (!input || typeof input !== "object" || Array.isArray(input)) throw "Markets - market is required";
for (const key of Object.keys(input)) {
if (["question", "rules", "closeAt", "resolveBy", "collateral", "caps", "resolvers", "threshold", "allowJ", "resolution"].indexOf(key) < 0) throw `Markets - unknown market field ${key}`;
}
if (byDesk && (input.resolution !== undefined || input.resolvers !== undefined || input.threshold !== undefined)) throw "Markets - a desk market names no resolution of its own: the tenant's desk profile decides who answers";
if (input.resolution !== undefined && (input.resolvers !== undefined || input.threshold !== undefined)) throw "Markets - name either resolution (optimistic) or resolvers and threshold (a resolver set), not both";
if (typeof input.question !== "string" || input.question.length < 1 || input.question.length > QUESTION_MAX || !QUESTION_TEXT.test(input.question)) throw `Markets - question must be 1 to ${QUESTION_MAX} characters of plain text`;
if (typeof input.rules !== "string" || input.rules.length < 1 || input.rules.length > RULES_MAX || !RULES_TEXT.test(input.rules)) throw `Markets - rules must be 1 to ${RULES_MAX} characters of plain text`;
const now = this.now();
if (!Number.isSafeInteger(input.closeAt) || !Number.isSafeInteger(input.resolveBy)) throw "Markets - closeAt and resolveBy must be whole milliseconds";
if (!(input.closeAt > now)) throw "Markets - closeAt must be in the future";
if (input.closeAt - now > CLOSE_MAX_MS) throw "Markets - closeAt must be at most 365 days away";
if (!(input.resolveBy > input.closeAt)) throw "Markets - resolveBy must be after closeAt";
if (input.resolveBy - input.closeAt > RESOLVE_WINDOW_MAX_MS) throw "Markets - resolveBy must be at most 30 days after closeAt";
// Collateral: in Varnir's list AND the tenant's (plan §1.2a), and one of the partitions this contract knows.
const c: any = input.collateral;
if (!c || typeof c !== "object" || Array.isArray(c) || Object.keys(c).sort().join(",") !== "network,token") throw "Markets - collateral must be {network, token}";
const known = COLLATERAL_KNOWN.find((k) => k.network === c.network && k.token === c.token);
if (!known) throw `Markets - ${c.network}:${c.token} is not a collateral Varnir supports`;
const inList = (list: any) => Array.isArray(list) && list.some((x: any) => x && x.network === c.network && x.token === c.token);
if (!inList(mk.collateralAllowed)) throw `Markets - ${c.network}:${c.token} is not in Varnir's collateral list for this tenant`;
if (!inList(mk.collateralEnabled)) throw `Markets - ${c.network}:${c.token} is not in the tenant's enabled collateral list`;
// Caps, raw units of this collateral. Varnir's cap on the master is in whole tokens.
const caps: any = input.caps;
const capKeys = caps && typeof caps === "object" ? Object.keys(caps).sort().join(",") : "";
if (!caps || typeof caps !== "object" || Array.isArray(caps) || (capKeys !== "maxCollateral,maxOrder,maxPerUser" && capKeys !== "maxCollateral,maxOrder,maxPerUser,minOrder")) throw "Markets - caps must be {maxCollateral, maxPerUser, maxOrder, minOrder?}";
const maxCollateral = this.shareAmount(caps.maxCollateral, "caps.maxCollateral");
const maxPerUser = this.shareAmount(caps.maxPerUser, "caps.maxPerUser");
const maxOrder = this.shareAmount(caps.maxOrder, "caps.maxOrder");
const minOrder = caps.minOrder === undefined ? BN.from(this.pow10(known.decimals)) : this.shareAmount(caps.minOrder, "caps.minOrder");
if (minOrder.gt(maxOrder)) throw "Markets - caps.minOrder must not exceed caps.maxOrder";
const wholeCap = typeof mk.maxCollateral === "string" && /^[0-9]{1,10}$/.test(mk.maxCollateral) ? mk.maxCollateral : "0";
const varnirCap = BN.from(wholeCap).mul(this.pow10(known.decimals));
if (maxCollateral.gt(varnirCap)) throw `Markets - caps.maxCollateral is above Varnir's cap for this tenant (${wholeCap} whole tokens)`;
if (maxPerUser.gt(maxCollateral) || maxOrder.gt(maxCollateral)) throw "Markets - caps.maxPerUser and caps.maxOrder must not exceed caps.maxCollateral";
if (byDesk) {
// The desk's own limits (oracle plan §1.10): its collateral list, its per-market cap, its close horizon.
if (!desk.collateral.some((x: any) => x && x.network === c.network && x.token === c.token)) throw `Markets - ${c.network}:${c.token} is not in the market desk's collateral list`;
if (maxCollateral.gt(BN.from(desk.maxCollateral).mul(this.pow10(known.decimals)))) throw `Markets - caps.maxCollateral is above the market desk's cap (${desk.maxCollateral} whole tokens)`;
if (input.closeAt - now > desk.closeMaxMs) throw "Markets - closeAt is further ahead than the market desk may list (closeMaxMs)";
}
const deployers = await this.deployerIds();
let resolution: any;
if (byDesk) {
resolution = this.optimisticResolution(this.deskProfileInput(desk.profile, known.decimals), input, tenantId, deployers, deskId, maxCollateral, known.decimals);
} else if (input.resolution !== undefined) {
const registered = mk.desk && typeof mk.desk === "object" && typeof mk.desk.id === "string" ? mk.desk.id : null;
resolution = this.optimisticResolution(input.resolution, input, tenantId, deployers, registered, maxCollateral, known.decimals);
} else {
this.validResolvers(input.resolvers, input.threshold, tenantId, deployers);
resolution = { kind: "set", resolvers: input.resolvers.slice(), threshold: input.threshold, disputeWindowMs: 0, votes: {}, proposal: null };
}
const allowJ = input.allowJ === undefined ? [] : this.validJurisdictions(input.allowJ, "allowJ");
// The tenant's directory: named once it exists, created with the first market.
const dirId = this.ActiveCrypto.Hash.getHash(tenantId + DIR_NAME, "sha256");
const dirRef = tx.$o && tx.$o.dir;
let dirAct: any = null;
let listed: string[] = [];
let deskCount: any = null;
if (dirRef) {
dirAct = this.named("$o", "dir");
const d = dirAct.getState();
if (dirAct.getId() !== dirId || !d || d.kind !== DIR_KIND || d.tenantId !== tenantId) throw "Markets - $o.dir is not this tenant's markets directory";
listed = Array.isArray(d.listed) ? d.listed.slice() : [];
if (listed.length >= LISTED_MAX) throw `Markets - the directory already lists ${LISTED_MAX} markets: delist a final one first`;
if (byDesk) deskCount = this.deskDayCount(d.desk, now, desk.perDay);
} else {
const existing: any = await this.getAnyStreamReadOnly(dirId).catch(() => null);
if (existing && existing.kind === DIR_KIND) throw "Markets - this tenant's markets directory exists: name it as $o.dir";
if (byDesk) deskCount = this.deskDayCount(null, now, desk.perDay);
}
if (!apply) return;
const marketAct = this.newActivityStream("market");
const marketId = marketAct.getId();
const market: any = {
kind: MARKET_KIND,
marketId,
tenantId,
question: input.question,
rules: input.rules,
questionHash: this.ActiveCrypto.Hash.getHash(input.question + "\n" + input.rules, "sha256"),
closeAt: input.closeAt,
resolveBy: input.resolveBy,
collateral: { network: known.network, token: known.token, decimals: known.decimals },
tick: TICK,
caps: { maxCollateral: maxCollateral.toString(), maxPerUser: maxPerUser.toString(), maxOrder: maxOrder.toString(), minOrder: minOrder.toString() },
allowJ,
resolution,
invalidSplitBps: INVALID_SPLIT_BPS,
locked: "0",
supply: { yes: "0", no: "0" },
paid: { yes: "0", no: "0", collateral: "0" },
settled: null,
pausedAt: null,
pausedBy: null,
createdAt: now,
version: 1,
};
// Who listed it (the tenant, or its desk): stored on optimistic markets only, so a "set" market is 1.0.133's bytes.
const createdBy = byDesk ? deskId : tenantId;
if (resolution.kind === "optimistic") market.createdBy = createdBy;
marketAct.setState(market);
listed.push(marketId);
if (dirAct) {
dirAct.setState(byDesk ? { listed, desk: deskCount } : { listed });
} else {
const created = this.newActivityStream(DIR_NAME, tenantId);
created.setState(byDesk ? { kind: DIR_KIND, tenantId, listed, desk: deskCount } : { kind: DIR_KIND, tenantId, listed });
}
this.event.emit("market-created", { marketId, tenantId, closeAt: market.closeAt, resolveBy: market.resolveBy, collateral: market.collateral, questionHash: market.questionHash, kind: resolution.kind, createdBy });
}/** * The resolver-set rules (decision 3), for a "set" market's resolvers and an optimistic market's arbiters alike: 1-9 * distinct 64-hex identities, never the tenant and never Varnir, and a strict-majority threshold, so no minority of * the tenant's resolvers can decide a market on its own. */
private validResolvers(resolvers: any, threshold: any, tenantId: string, deployers: string[]): void {
if (!Array.isArray(resolvers) || resolvers.length < 1 || resolvers.length > RESOLVERS_MAX) throw `Markets - resolvers must list 1 to ${RESOLVERS_MAX} identities`;
for (let i = 0; i < resolvers.length; i++) {
const r = resolvers[i];
if (typeof r !== "string" || !HEX64.test(r)) throw "Markets - resolvers must be 64-hex identity ids";
if (resolvers.indexOf(r) !== i) throw "Markets - resolvers lists an identity twice";
if (r === tenantId) throw "Markets - the tenant stream cannot be a resolver";
if (deployers.indexOf(r) >= 0) throw "Markets - the deploying identity cannot be a resolver";
}
const minThreshold = Math.floor(resolvers.length / 2) + 1;
if (!Number.isInteger(threshold) || threshold < minThreshold || threshold > resolvers.length) throw `Markets - threshold must be a strict majority: a whole number from ${minThreshold} to ${resolvers.length}`;
}/** * An optimistic market's `resolution` (oracle plan §1.2, §1.4, §1.7), validated and returned as it is stored. The * arbiters are kept in `resolvers`/`threshold`, so the "a resolver may not trade" checks cover them unchanged. * `deskId` is the tenant's registered desk (or the desk creating the market): it may never be the reporter. */
private optimisticResolution(res: any, input: any, tenantId: string, deployers: string[], deskId: string | null, maxCollateral: BN, decimals: number): any {
if (!res || typeof res !== "object" || Array.isArray(res)) throw "Markets - resolution must be an object";
for (const key of Object.keys(res)) {
if (["kind", "reporter", "resolvers", "threshold", "bond", "disputeBond", "disputeFeeBps", "disputeWindowMs", "escalation"].indexOf(key) < 0) throw `Markets - unknown resolution field ${key}`;
}
if (res.kind !== "optimistic") throw "Markets - resolution.kind must be optimistic (a resolver-set market names resolvers and threshold at the top level)";
this.validResolvers(res.resolvers, res.threshold, tenantId, deployers);
if (deskId !== null && res.resolvers.indexOf(deskId) >= 0) throw "Markets - the market desk cannot be one of the arbiters";
const reporter = res.reporter;
if (typeof reporter !== "string" || !HEX64.test(reporter)) throw "Markets - the reporter must be a 64-hex identity id";
if (reporter === tenantId) throw "Markets - the tenant stream cannot be the reporter";
if (deployers.indexOf(reporter) >= 0) throw "Markets - the deploying identity cannot be the reporter";
if (reporter === deskId) throw "Markets - the market desk cannot be the reporter";
if (res.resolvers.indexOf(reporter) >= 0) throw "Markets - the reporter cannot be one of the arbiters";
const bond = this.shareAmount(res.bond, "resolution.bond");
if (bond.lt(this.pow10(decimals))) throw "Markets - resolution.bond must be at least one whole token";
if (bond.gt(maxCollateral)) throw "Markets - resolution.bond must not exceed caps.maxCollateral";
const disputeBond = this.shareAmount(res.disputeBond, "resolution.disputeBond");
if (disputeBond.lt(bond)) throw "Markets - resolution.disputeBond must be at least resolution.bond";
if (disputeBond.gt(maxCollateral)) throw "Markets - resolution.disputeBond must not exceed caps.maxCollateral";
// A floor on the dispute bond (review D1): at least 1% of the market's cap, so a dispute is never nearly free.
if (disputeBond.lt(maxCollateral.div(100))) throw "Markets - resolution.disputeBond must be at least 1% of caps.maxCollateral";
const feeBps = res.disputeFeeBps === undefined ? DISPUTE_FEE_BPS_DEFAULT : res.disputeFeeBps;
if (!Number.isInteger(feeBps) || feeBps < 0 || feeBps > DISPUTE_FEE_BPS_MAX) throw `Markets - resolution.disputeFeeBps must be a whole number from 0 to ${DISPUTE_FEE_BPS_MAX}`;
if (!Number.isSafeInteger(res.disputeWindowMs) || res.disputeWindowMs < DISPUTE_WINDOW_MIN_MS || res.disputeWindowMs > DISPUTE_WINDOW_MAX_MS) throw "Markets - resolution.disputeWindowMs must be from 2 minutes to 7 days";
const esc = res.escalation;
if (!esc || typeof esc !== "object" || Array.isArray(esc) || Object.keys(esc).sort().join(",") !== "kind,windowMs") throw "Markets - resolution.escalation must be {kind, windowMs}";
if (ESCALATION_KINDS.indexOf(esc.kind) < 0) throw `Markets - resolution.escalation.kind must be one of ${ESCALATION_KINDS.join(", ")}`;
if (!Number.isSafeInteger(esc.windowMs) || esc.windowMs < ESCALATION_WINDOW_MIN_MS || esc.windowMs > ESCALATION_WINDOW_MAX_MS) throw "Markets - resolution.escalation.windowMs must be from 5 minutes to 14 days";
if (input.resolveBy - input.closeAt < REPORT_WINDOW_MIN_MS) throw "Markets - resolveBy must be at least 10 minutes after closeAt (the reporter needs time)";
return {
kind: "optimistic",
resolvers: res.resolvers.slice(),
threshold: res.threshold,
reporter,
bond: bond.toString(),
disputeBond: disputeBond.toString(),
disputeFeeBps: feeBps,
disputeWindowMs: res.disputeWindowMs,
escalation: { kind: esc.kind, windowMs: esc.windowMs, state: null },
votes: {},
proposal: null,
dispute: null,
ruling: null,
bonds: { held: "0", proposer: null, disputer: null, settledAt: null },
};
}/** The tenant's registered market desk from its markets block (Varnir.Tenants setMarketDesk wrote it); refuses none or a malformed one. */
private deskOf(mk: any): any {
const d = mk.desk;
if (!d || typeof d !== "object" || Array.isArray(d)) throw "Markets - this tenant has no market desk";
if (typeof d.id !== "string" || !HEX64.test(d.id) || !Number.isInteger(d.perDay) || d.perDay < 1 || d.perDay > DESK_PER_DAY_MAX || !Number.isSafeInteger(d.closeMaxMs) || !Array.isArray(d.collateral) || typeof d.maxCollateral !== "string" || !/^[1-9][0-9]{0,9}$/.test(d.maxCollateral) || !d.profile || typeof d.profile !== "object") throw "Markets - the tenant's market desk is malformed";
return d;
}/** * The desk profile as a createMarket `resolution`: the profile's bonds are WHOLE tokens (as the desk's cap, since its * collateral list may mix decimals), scaled here by the market's collateral. Everything else is passed through, so * optimisticResolution applies every createMarket rule to the profile again. */
private deskProfileInput(profile: any, decimals: number): any {
const whole = (v: any) => (typeof v === "string" && /^[1-9][0-9]{0,9}$/.test(v) ? BN.from(v).mul(this.pow10(decimals)).toString() : "malformed");
return { ...profile, bond: whole(profile.bond), disputeBond: whole(profile.disputeBond) };
}/** * The desk's counters after one more market (oracle plan §1.10): `day = floor(now / 1 day)` on the consensus clock. * A day at or before the stored one counts against the stored day, so a clock that steps back never resets it. * `listed` counts the desk-listed markets on the directory now (delist lowers it): at most DESK_LISTED_MAX, so a * stolen desk key can never fill the directory the tenant lists its own markets on (review C). */
private deskDayCount(prev: any, now: number, perDay: number): any {
const day = Math.floor(now / DAY_MS);
if (prev === null || prev === undefined) return { day, count: 1, listed: 1 };
if (!Number.isSafeInteger(prev.day) || !Number.isSafeInteger(prev.count)) throw "Markets - the directory's desk counter is malformed";
const listed = Number.isSafeInteger(prev.listed) ? prev.listed : 0;
if (listed >= DESK_LISTED_MAX) throw `Markets - the market desk already has ${DESK_LISTED_MAX} markets listed: delist a final one first`;
if (day > prev.day) return { day, count: 1, listed: listed + 1 };
if (prev.count >= perDay) throw `Markets - the market desk has listed its ${perDay} markets for today`;
return { day: prev.day, count: prev.count + 1, listed: listed + 1 };
}/**
* `mintPair` (the user as `$i.owner = {$stream, amount}`, signing; the market as `$o.market`; the tenant master as
* `$r.tenant`; the user's own shard of the tenant as `$o.tenant`, for usage): locks `amount` of the market's
* collateral and gives the user `amount` YES and `amount` NO. Gate(trade). No fee; the usage counter is credited
* with the tenant's `market.mint` credit price (default 1). Emits `market-minted`.
*/ private async runMintPair(apply: boolean): Promise<void> {
const tx: any = this.transactions;
const owner = this.named("$i", "owner");
const userId = owner.getId();
const userState: any = owner.getState() || {};
const amount = this.shareAmount(tx.$i.owner.amount, "amount");
const marketAct = this.named("$o", "market");
const market = this.requireMarket(marketAct);
this.assertMayTrade(userState, this.txSigner(owner), "The user");
if (market.resolution.resolvers.indexOf(userId) >= 0) throw "Markets - a resolver may not trade in a market it resolves";
if (market.resolution.reporter === userId) throw "Markets - the reporter may not trade in a market it reports";
if (this.listedByDesk(market, userId)) throw "Markets - the market desk may not trade in a market it listed";
const now = this.now();
// Gate (plan §2.4): 1-2 the tenant, 3-4 the user, 5 caps, 6 pause and open.
const { master, mk } = this.gateTenantRef(market, "trade");
const el = this.gateParty(mk, market, userId, userState, now, "The user");
if (amount.gt(market.caps.maxOrder)) throw `Markets - ${amount} is above this market's maxOrder (${market.caps.maxOrder})`;
if (amount.lt(this.minOrderOf(market))) throw `Markets - ${amount} is below this market's minOrder (${this.minOrderOf(market)})`;
const pos = this.positionOf(userState, market.marketId);
const after = { y: pos.y.add(amount), n: pos.n.add(amount) };
this.assertPerUser(market, el, pos, after, "The user");
const locked = BN.from(market.locked);
if (locked.add(amount).gt(market.caps.maxCollateral)) throw `Markets - this mint would lock more than the market's maxCollateral (${market.caps.maxCollateral})`;
this.gateOpen(mk, market, now);
const { network, token } = market.collateral;
const bal = this.l2Get(userState, network, token);
if (bal.lt(amount)) throw `Markets - balance too low: ${bal} < ${amount}`;
this.assertMarketSlot(userState, market.marketId);
const prep = this.marketsShardPrep(master, userId, "market.mint", "0");
// >>> tenant-pays
// Stage D: a mint is a normal op (O1): refused here when the user's shard float cannot pay its price.
const floatPlan = this.tenantFloatPlan(prep, false);
// <<< tenant-pays
if (!apply) return;
this.l2Set(userState, network, token, bal.sub(amount));
this.setPosition(userState, market.marketId, after);
market.locked = locked.add(amount).toString();
market.supply = { yes: BN.from(market.supply.yes).add(amount).toString(), no: BN.from(market.supply.no).add(amount).toString() };
this.assertInvariant(market, now);
owner.setState({ layer2: userState.layer2, mkt: userState.mkt });
marketAct.setState(market);
this.tenantApply(prep, `${network}:${token}`);
// >>> tenant-pays
this.tenantFloatApply(floatPlan, prep);
// <<< tenant-pays
this.event.emit("market-minted", { marketId: market.marketId, owner: userId, amount: amount.toString(), locked: market.locked });
}/**
* `mergePair` (the user as `$i.owner = {$stream, amount}`, signing; the market as `$o.market`): burns `amount` YES
* and `amount` NO and returns `amount` collateral. Never gated (wind-down, plan §1.7): it works under any pause,
* mode, suspension or revoked eligibility. Refused once the market is final: redeem is the way out then.
* Emits `market-merged`.
*/ private async runMergePair(apply: boolean): Promise<void> {
const tx: any = this.transactions;
const owner = this.named("$i", "owner");
const userId = owner.getId();
const userState: any = owner.getState() || {};
const amount = this.shareAmount(tx.$i.owner.amount, "amount");
const marketAct = this.named("$o", "market");
const market = this.requireMarket(marketAct);
this.assertMayWindDown(this.txSigner(owner), "The user");
const now = this.now();
if (this.finality(market, now).state === "final") throw "Markets - the market is final: redeem instead of merging";
const pos = this.positionOf(userState, market.marketId);
if (amount.gt(pos.y) || amount.gt(pos.n)) throw `Markets - cannot merge ${amount}: the user holds ${pos.y} YES and ${pos.n} NO`;
const locked = BN.from(market.locked);
if (locked.lt(amount)) throw "Markets - the market's locked collateral is below the merge (invariant)";
if (!apply) return;
const { network, token } = market.collateral;
this.l2Set(userState, network, token, this.l2Get(userState, network, token).add(amount));
this.setPosition(userState, market.marketId, { y: pos.y.sub(amount), n: pos.n.sub(amount) });
market.locked = locked.sub(amount).toString();
market.supply = { yes: BN.from(market.supply.yes).sub(amount).toString(), no: BN.from(market.supply.no).sub(amount).toString() };
this.assertInvariant(market, now);
owner.setState({ layer2: userState.layer2, mkt: userState.mkt });
marketAct.setState(market);
this.event.emit("market-merged", { marketId: market.marketId, owner: userId, amount: amount.toString(), locked: market.locked });
}/**
* `match` (a submitter as `$i.submitter`, which only makes the transaction valid; the resting maker A and the
* incoming taker B as `$o.a` / `$o.b = {$stream, order, sig}`, neither signing the transaction; the market as
* `$o.market`; the tenant master as `$r.tenant`; B's shard of the tenant as `$o.tenant`, for the fill fee).
*
* An order is `{maker, give, want, expire, salt, domain, fee: {tenant, maxBps}}`; a position leg is network
* `market`, token `<marketId>.yes|.no`, and a collateral leg is the market's collateral partition. Three kinds
* (plan §1.4), at A's price, B getting any price improvement:
* - transfer: buy X against sell X, when bid >= ask: `s` X from the seller, `pA·s/100` collateral to the seller;
* - mint: buy YES against buy NO, when pYES + pNO >= 100: A pays `pA·s/100`, B pays the rest of `s`, `locked += s`;
* - merge: sell YES against sell NO, when pYES + pNO <= 100: both burn `s`, A gets `pA·s/100` from `locked`, B the
* rest of `s`, `locked -= s`.
* `s` is the smaller remaining size. B pays the tenant's fill fee, `floor(B's collateral leg · bps / 10000)`, on
* top (buy) or out of what it receives (sell), refused above Varnir's cap or the `maxBps` B signed; it goes to B's
* shard through the pasted tenantApply. Gate(trade) for both parties. Emits `market-fill` (with `bookUpdate`).
*/ private async runMatch(apply: boolean): Promise<void> {
const tx: any = this.transactions;
const submitter = tx.$i ? tx.$i.submitter : undefined;
const a = tx.$o ? tx.$o.a : undefined;
const b = tx.$o ? tx.$o.b : undefined;
if (!submitter || !submitter.$stream) throw "Markets - match needs a submitter ($i.submitter)";
if (!a || !b) throw "Markets - match needs both parties ($o.a and $o.b)";
if (!a.order || !a.sig) throw "Markets - party A's signed order or signature is missing";
if (!b.order || !b.sig) throw "Markets - party B's signed order or signature is missing";
// Identities as bare 64-hex ids, compared as the engine loaded them (getId), never as a caller-written string.
if (typeof a.$stream !== "string" || !HEX64.test(a.$stream) || typeof b.$stream !== "string" || !HEX64.test(b.$stream)) throw "Markets - $o.a and $o.b must be bare 64-hex identity ids";
if (typeof a.order.maker !== "string" || !HEX64.test(a.order.maker) || typeof b.order.maker !== "string" || !HEX64.test(b.order.maker)) throw "Markets - order makers must be bare 64-hex identity ids";
const actA = this.getActivityStreams(a);
const actB = this.getActivityStreams(b);
const idA = actA.getId();
const idB = actB.getId();
if (a.order.maker !== idA) throw "Markets - order A does not name the carried A stream";
if (b.order.maker !== idB) throw "Markets - order B does not name the carried B stream";
if (idA === idB) throw "Markets - self-trade refused: both parties are the same identity";
const marketAct = this.named("$o", "market");
const market = this.requireMarket(marketAct);
if (market.resolution.resolvers.indexOf(idA) >= 0 || market.resolution.resolvers.indexOf(idB) >= 0) throw "Markets - a resolver may not trade in a market it resolves";
if (market.resolution.reporter === idA || market.resolution.reporter === idB) throw "Markets - the reporter may not trade in a market it reports";
if (this.listedByDesk(market, idA) || this.listedByDesk(market, idB)) throw "Markets - the market desk may not trade in a market it listed";
const oa = this.readOrder(a.order, "Order A", market);
const ob = this.readOrder(b.order, "Order B", market);
const now = this.now();
if (!(oa.expire > now)) throw "Markets - order A has expired";
if (!(ob.expire > now)) throw "Markets - order B has expired";
// The kind, and whether the orders cross (cross-multiplied whole cents, no floats).
let kind: string;
if (oa.outcome === ob.outcome && oa.side !== ob.side) {
kind = "transfer";
const bid = oa.side === "buy" ? oa.price : ob.price;
const ask = oa.side === "sell" ? oa.price : ob.price;
if (bid < ask) throw "Markets - orders do not cross: the bid is below the ask";
} else if (oa.outcome !== ob.outcome && oa.side === "buy" && ob.side === "buy") {
kind = "mint";
if (oa.price + ob.price < TICK) throw "Markets - orders do not cross: the YES and NO bids add up to less than 100";
} else if (oa.outcome !== ob.outcome && oa.side === "sell" && ob.side === "sell") {
kind = "merge";
if (oa.price + ob.price > TICK) throw "Markets - orders do not cross: the YES and NO asks add up to more than 100";
} else {
throw "Markets - orders do not match: neither opposite sides of one outcome nor the same side of both";
}
// Signatures: each against its own party's authorities, for this deployment (Swap's code, copied verbatim).
const keyA = this.verifyOrderSig(actA, a.order, a.sig);
if (keyA === null) throw "Markets - order A signature invalid";
const keyB = this.verifyOrderSig(actB, b.order, b.sig);
if (keyB === null) throw "Markets - order B signature invalid";
if (!this.verifyOrderDomain(a.order)) throw "Markets - order A not signed for this deployment (domain mismatch)";
if (!this.verifyOrderDomain(b.order)) throw "Markets - order B not signed for this deployment (domain mismatch)";
// The order's key must be live now (not expired: Swap's liveAuthority rule) and must resolve to a hash.
if (keyA === ORDER_SIGNER_UNRESOLVED || !this.liveAuthority(actA, keyA)) throw "Markets - order A's signing key is expired or unknown";
if (keyB === ORDER_SIGNER_UNRESOLVED || !this.liveAuthority(actB, keyB)) throw "Markets - order B's signing key is expired or unknown";
const stA: any = actA.getState() || {};
const stB: any = actB.getState() || {};
this.assertMayTrade(stA, this.liveAuthority(actA, keyA), "Party A");
this.assertMayTrade(stB, this.liveAuthority(actB, keyB), "Party B");
// Gate (plan §2.4) for both parties: 1-2 the tenant once, 3-4 each party.
const { master, mk } = this.gateTenantRef(market, "trade");
const elA = this.gateParty(mk, market, idA, stA, now, "Party A");
const elB = this.gateParty(mk, market, idB, stB, now, "Party B");
// Markers and the fill size: the smaller remaining size, in shares.
const hashA = this.ActiveCrypto.Hash.getHash(JSON.stringify(a.order), "sha256");
const hashB = this.ActiveCrypto.Hash.getHash(JSON.stringify(b.order), "sha256");
const mA = this.readMarker(stA.mko ? stA.mko[hashA] : undefined);
const mB = this.readMarker(stB.mko ? stB.mko[hashB] : undefined);
if (mA.terminal) throw "Markets - order A already filled or cancelled";
if (mB.terminal) throw "Markets - order B already filled or cancelled";
const remA = oa.shares.sub(oa.side === "buy" ? mA.filledWant : mA.filledGive);
const remB = ob.shares.sub(ob.side === "buy" ? mB.filledWant : mB.filledGive);
if (!remA.gt(0) || !remB.gt(0)) throw "Markets - an order is already fully filled";
const s = remA.lt(remB) ? remA : remB;
if (!s.mul(oa.price).mod(TICK).eq(0)) throw "Markets - the fill leaves dust: sizes must be multiples of 100 raw units";
const usdtA = s.mul(oa.price).div(TICK);
const usdtB = kind === "transfer" ? usdtA : s.sub(usdtA);
if (!usdtA.gt(0) || !usdtB.gt(0)) throw "Markets - the fill resolves to zero";
// Neither side ever pays more than its order allows (holds by the cross; checked rather than assumed).
if (oa.side === "buy" && mA.filledGive.add(usdtA).gt(oa.usdt)) throw "Markets - the fill exceeds order A's collateral";
if (ob.side === "buy" && mB.filledGive.add(usdtB).gt(ob.usdt)) throw "Markets - the fill exceeds order B's collateral";
// Gate step 5: caps.
if (oa.shares.gt(market.caps.maxOrder)) throw `Markets - order A is above this market's maxOrder (${market.caps.maxOrder})`;
if (ob.shares.gt(market.caps.maxOrder)) throw `Markets - order B is above this market's maxOrder (${market.caps.maxOrder})`;
const posA = this.positionOf(stA, market.marketId);
const posB = this.positionOf(stB, market.marketId);
const nextA = this.positionAfter(posA, oa, s);
const nextB = this.positionAfter(posB, ob, s);
this.assertPerUser(market, elA, posA, nextA, "Party A");
this.assertPerUser(market, elB, posB, nextB, "Party B");
const locked = BN.from(market.locked);
let lockedAfter = locked;
if (kind === "mint") lockedAfter = locked.add(s);
if (kind === "merge") lockedAfter = locked.sub(s);
if (kind === "mint" && lockedAfter.gt(market.caps.maxCollateral)) throw `Markets - this fill would lock more than the market's maxCollateral (${market.caps.maxCollateral})`;
if (lockedAfter.lt(0)) throw "Markets - the market's locked collateral is below the merge (invariant)";
// Gate step 6: pauses, and the market is open.
this.gateOpen(mk, market, now);
// The fee (taker B), from the master's fee config, capped by Varnir and by B's signed maxBps.
const fee = this.marketsFillFee(master, mk, ob.feeMaxBps, usdtB);
const prep = this.marketsShardPrep(master, idB, "market.fill", fee.toString());
// >>> tenant-pays
// Stage D: a fill is a normal op (O1): refused here when the taker's shard float cannot pay its price.
const floatPlan = this.tenantFloatPlan(prep, false);
// <<< tenant-pays
// Balances: what each side gives this fill.
const { network, token } = market.collateral;
const balA = this.l2Get(stA, network, token);
const balB = this.l2Get(stB, network, token);
const payA = oa.side === "buy" ? usdtA : BN.from(0);
const payB = ob.side === "buy" ? usdtB.add(fee) : BN.from(0);
const getA = oa.side === "sell" ? usdtA : BN.from(0);
const getB = ob.side === "sell" ? usdtB.sub(fee) : BN.from(0);
if (balA.lt(payA)) throw `Markets - party A balance too low: ${balA} < ${payA}`;
if (balB.lt(payB)) throw `Markets - party B balance too low: ${balB} < ${payB}`;
if (oa.side === "sell" && (oa.outcome === "yes" ? posA.y : posA.n).lt(s)) throw `Markets - party A holds fewer than ${s} ${oa.outcome.toUpperCase()}`;
if (ob.side === "sell" && (ob.outcome === "yes" ? posB.y : posB.n).lt(s)) throw `Markets - party B holds fewer than ${s} ${ob.outcome.toUpperCase()}`;
if (getB.lt(0)) throw "Markets - the fee is above what party B receives";
this.assertMarketSlot(stA, market.marketId);
this.assertMarketSlot(stB, market.marketId);
this.assertMarkerRoom(stA, hashA, now, "Party A");
this.assertMarkerRoom(stB, hashB, now, "Party B");
// Conservation (plan §1.3): user deltas + locked delta + fee == 0.
const deltaUsers = getA.add(getB).sub(payA).sub(payB);
if (!deltaUsers.add(lockedAfter.sub(locked)).add(fee).eq(0)) throw "Markets - the fill does not conserve collateral";
if (!apply) return;
this.l2Set(stA, network, token, balA.sub(payA).add(getA));
this.l2Set(stB, network, token, balB.sub(payB).add(getB));
this.setPosition(stA, market.marketId, nextA);
this.setPosition(stB, market.marketId, nextB);
const doneA = this.writeMarker(stA, hashA, oa, mA, s, usdtA, now);
const doneB = this.writeMarker(stB, hashB, ob, mB, s, usdtB, now);
market.locked = lockedAfter.toString();
if (kind !== "transfer") {
const d = kind === "mint" ? s : BN.from(0).sub(s);
market.supply = { yes: BN.from(market.supply.yes).add(d).toString(), no: BN.from(market.supply.no).add(d).toString() };
}
this.assertInvariant(market, now);
actA.setState({ layer2: stA.layer2, mkt: stA.mkt, mko: stA.mko });
actB.setState({ layer2: stB.layer2, mkt: stB.mkt, mko: stB.mko });
marketAct.setState(market);
this.tenantApply(prep, `${network}:${token}`);
// >>> tenant-pays
this.tenantFloatApply(floatPlan, prep);
// <<< tenant-pays
this.event.emit("market-fill", {
umid: this.umid,
marketId: market.marketId,
kind,
submitter: submitter.$stream,
maker: idA,
taker: idB,
price: oa.outcome === "yes" ? oa.price : TICK - oa.price,
size: s.toString(),
makerSide: oa.side + ":" + oa.outcome,
takerSide: ob.side + ":" + ob.outcome,
fee: fee.toString(),
locked: market.locked,
bookUpdate: {
a: { orderHash: hashA, filled: (oa.side === "buy" ? mA.filledWant : mA.filledGive).add(s).toString(), done: doneA },
b: { orderHash: hashB, filled: (ob.side === "buy" ? mB.filledWant : mB.filledGive).add(s).toString(), done: doneB },
},
when: this.cDate,
});
}/** * One order of this market, read: its side (buy gives collateral for a position, sell the reverse), outcome, size * in shares, collateral amount, whole-cent price, expiry and signed fee cap. Refuses anything else, a size that is * not a multiple of SHARE_STEP, and a price that is not a whole cent from 1 to 99. */
private readOrder(order: any, label: string, market: any): any {
if (!order || typeof order !== "object") throw `Markets - ${label} is missing`;
const give = this.readLeg(order.give, `${label} give`);
const want = this.readLeg(order.want, `${label} want`);
const coll = market.collateral;
const isColl = (l: any) => l.network === coll.network && l.token === coll.token;
const outcomeOf = (l: any): string | null => {
if (l.network !== MARKET_NET) return null;
if (l.token === market.marketId + ".yes") return "yes";
if (l.token === market.marketId + ".no") return "no";
return null;
};
let side: string;
let outcome: string | null;
let shares: BN;
let usdt: BN;
if (isColl(give) && outcomeOf(want)) {
side = "buy";
outcome = outcomeOf(want);
shares = want.amount;
usdt = give.amount;
} else if (outcomeOf(give) && isColl(want)) {
side = "sell";
outcome = outcomeOf(give);
shares = give.amount;
usdt = want.amount;
} else {
throw `Markets - ${label} is not an order for this market (a position leg of this market against its collateral)`;
}
if (!shares.gt(0) || !usdt.gt(0)) throw `Markets - ${label} amounts must be greater than 0`;
if (!shares.mod(SHARE_STEP).eq(0)) throw `Markets - ${label} size must be a multiple of ${SHARE_STEP} raw units`;
const cents = usdt.mul(TICK);
if (!cents.mod(shares).eq(0)) throw `Markets - ${label} price is off the grid: it must be a whole cent`;
const price = Number(cents.div(shares).toString());
if (!(price >= 1 && price <= TICK - 1)) throw `Markets - ${label} price must be from 1 to 99 cents`;
if (shares.lt(this.minOrderOf(market))) throw `Markets - ${label} size is below this market's minOrder (${this.minOrderOf(market)})`;
if (!Number.isSafeInteger(Number(order.expire))) throw `Markets - ${label} expire must be whole milliseconds`;
// An order never outlives its market by more than the grace, so its marker can always be pruned.
if (Number(order.expire) > market.closeAt + ORDER_EXPIRE_GRACE_MS) throw `Markets - ${label} expires more than a day after the market closes`;
const fee = order.fee;
if (!fee || typeof fee !== "object" || fee.tenant !== market.tenantId) throw `Markets - ${label} must carry fee {tenant, maxBps} naming this market's tenant`;
if (!Number.isInteger(fee.maxBps) || fee.maxBps < 0 || fee.maxBps > 10000) throw `Markets - ${label} fee.maxBps must be a whole number from 0 to 10000`;
return { side, outcome, shares, usdt, price, expire: Number(order.expire), feeMaxBps: fee.maxBps };
}/** A leg `{network, token, amount}` with a plain decimal amount; no default token (a market leg always names one). */ private readLeg(leg: any, label: string): { network: string; token: string; amount: BN }/** Writes a party's marker (Swap's shape plus `expire`, for pruning); returns whether the order is now done. Prunes old markers. */
private writeMarker(st: any, hash: string, o: any, prior: any, s: BN, usdt: BN, now: number): boolean {
const mko: any = this.prunedMarkers(st.mko, now);
const filledWant = prior.filledWant.add(o.side === "buy" ? s : usdt);
const filledGive = prior.filledGive.add(o.side === "buy" ? usdt : s);
const done = !(o.side === "buy" ? filledWant : filledGive).lt(o.shares);
mko[hash] = { filledWant: filledWant.toString(), filledGive: filledGive.toString(), lastFill: this.umid, done, expire: o.expire };
st.mko = mko;
return done;
}/** The user's markers without those whose order expired more than PRUNE_GRACE_MS ago (they can never fill again). */
private prunedMarkers(mko: any, now: number): any {
const out: any = {};
if (!mko || typeof mko !== "object") return out;
for (const k of Object.keys(mko)) {
const m = mko[k];
if (m && Number.isSafeInteger(m.expire) && m.expire + PRUNE_GRACE_MS <= now) continue;
out[k] = m;
}
return out;
}/** A new marker needs room: at most MARKERS_MAX after pruning. */
private assertMarkerRoom(st: any, hash: string, now: number, label: string): void {
const mko = this.prunedMarkers(st.mko, now);
if (mko[hash] === undefined && Object.keys(mko).length >= MARKERS_MAX) throw `Markets - ${label} carries ${MARKERS_MAX} live order markers: cancel or let some expire`;
}/**
* `cancel` (the maker as `$i.maker = {$stream, order}`, signing): marks the order cancelled on the maker's own stream,
* keeping any partial progress; a terminal marker is left as it is. It takes the whole signed order (not only its
* hash) so the marker carries the order's expiry and can be pruned safely later. Never gated; a read-only key is
* refused. Emits `market-order-cancelled`.
*/ private async runCancel(apply: boolean): Promise<void> {
const tx: any = this.transactions;
const maker = this.named("$i", "maker");
const order = tx.$i.maker.order;
if (!order || typeof order !== "object" || Array.isArray(order)) throw "Markets - cancel needs the signed order";
if (order.maker !== maker.getId()) throw "Markets - the order does not name this maker";
if (!Number.isSafeInteger(Number(order.expire))) throw "Markets - the order's expire must be whole milliseconds";
// No valid order expires later than this (closeAt is at most 365 days ahead, plus the grace), so a cancel marker is always prunable.
if (Number(order.expire) > this.now() + CLOSE_MAX_MS + ORDER_EXPIRE_GRACE_MS) throw "Markets - the order's expire is beyond any market's life";
this.assertMayWindDown(this.txSigner(maker), "The maker");
const st: any = maker.getState() || {};
const hash = this.ActiveCrypto.Hash.getHash(JSON.stringify(order), "sha256");
this.assertMarkerRoom(st, hash, this.now(), "The maker");
if (!apply) return;
const mko: any = this.prunedMarkers(st.mko, this.now());
const existing = mko[hash];
if (!this.readMarker(existing).terminal) mko[hash] = { ...(existing || {}), cancelled: true, expire: Number(order.expire) };
maker.setState({ mko });
this.event.emit("market-order-cancelled", { maker: maker.getId(), orderHash: hash });
}/** * The ONE resolution seam (plan §1.6). Every reader (redeem, delist, merge, the gate, and the scanner's port) * decides from this alone: * - `final` with the latched outcome once a redeem has paid out (`settled`), so a clock that steps back cannot * reopen a market that has started paying; * - `final` when a proposal exists and its dispute window (0 in v1) has passed, else `pending`; * - `open` before `closeAt`; * - `final INVALID` from `resolveBy` with no proposal (never stuck); * - otherwise `closed` (votes being gathered). * An optimistic market (oracle plan §1.3, the exhaustive table, rows in this order) adds two branches before the * proposal: `final` with the ruling once the escalation has ruled, and while a dispute is open, `pending` until the * escalation's window ends, then `final INVALID` by rule (the arbiters were silent). A "set" market never carries * `dispute` or `ruling`, so it reads exactly as before. `phase` is informational, for display only: * proposed | disputed | ruled | undisputed | timeout | no-answer | voted (null while open or closed). */
private finality(market: any, now: number): { state: string; outcome: string | null; phase: string | null }/** * The ONE escalation seam (oracle plan §1.1, §6.3): how an open dispute stands. `finality()` and `settleBonds` ask * only this. Kind "arbiters" decides through `ruling` (written by `arbitrate`); with no ruling by `dispute.at + * escalation.windowMs` the answer is a timeout (INVALID by rule). A later kind (a juror pool, a token vote) adds its * entries, its state under `escalation.state`, and a branch here; the proposal, bond and finalise code do not change. */
private escalationOutcome(market: any, now: number): { status: string; outcome: string | null }/**
* `resolveVote` (a resolver as `$i.resolver = {$stream, outcome, evidenceHash}`, signing with its own stake-100
* key; the market as `$o.market`): one vote per resolver, never changed. When `threshold` votes agree, the
* proposal is set (final at once in v1). Votes open at `closeAt` and end at `resolveBy`. NOT gated by tenant mode,
* pause or suspension: resolution must never be blocked. Emits `market-vote`, and `market-resolved` on the vote
* that decides.
*/ private async runResolveVote(apply: boolean): Promise<void> {
const tx: any = this.transactions;
const resolver = this.named("$i", "resolver");
const rid = resolver.getId();
const marketAct = this.named("$o", "market");
const market = this.requireMarket(marketAct);
const r = market.resolution;
// An optimistic market's arbiters are in `resolvers` too: without this they could vote a proposal in and skip the bond (O1).
if (r.kind !== "set") throw "Markets - this market resolves by its reporter; arbiters use arbitrate";
if (r.resolvers.indexOf(rid) < 0) throw "Markets - this identity is not a resolver of this market";
// Exactly one live owner key (stake 100, not read-only, off-ledger or verifier) signed: never a sum of smaller keys.
const signer = this.txSigner(resolver);
const signerLabel = this.labelOf(signer);
if (!signer || signer.stake !== 100 || signerLabel === "read" || signerLabel === "offledger" || signerLabel === "verifier") throw "Markets - a resolver votes with its own stake-100 owner key";
if (r.votes && r.votes[rid] !== undefined) throw "Markets - this resolver has already voted";
const now = this.now();
if (now < market.closeAt) throw "Markets - voting opens when the market closes";
if (now >= market.resolveBy) throw "Markets - voting has ended: the market is INVALID by rule";
if (market.settled || r.proposal) throw "Markets - the market is already resolved";
const outcome = tx.$i.resolver.outcome;
const evidenceHash = tx.$i.resolver.evidenceHash;
if (OUTCOMES.indexOf(outcome) < 0) throw "Markets - outcome must be YES, NO or INVALID";
if (typeof evidenceHash !== "string" || !HEX64.test(evidenceHash)) throw "Markets - evidenceHash must be 64 lower-case hex";
if (!apply) return;
const votes: any = { ...(r.votes || {}) };
votes[rid] = { outcome, evidenceHash, at: now };
let count = 0;
for (const k of Object.keys(votes)) if (votes[k] && votes[k].outcome === outcome) count++;
market.resolution = { ...r, votes, proposal: count >= r.threshold ? { outcome, at: now } : null };
marketAct.setState(market);
this.event.emit("market-vote", { marketId: market.marketId, resolver: rid, outcome, evidenceHash, count, threshold: r.threshold });
if (market.resolution.proposal) this.event.emit("market-resolved", { marketId: market.marketId, outcome, at: now });
}/** * `redeem` (the user as `$i.owner`, signing; the market as `$o.market`): once `finality()` is final, burns all of * the user's YES and NO in the market and pays from `locked`: YES pays 1 per YES, NO 1 per NO, INVALID * `floor(y·split/10000) + floor(n·(10000-split)/10000)`. Rounding dust stays in `locked`. The first redeem latches * the outcome (`settled`). Never gated (wind-down). Emits `market-redeemed`. */
private async runRedeem(apply: boolean): Promise<void> {
const owner = this.named("$i", "owner");
const userId = owner.getId();
const userState: any = owner.getState() || {};
const marketAct = this.named("$o", "market");
const market = this.requireMarket(marketAct);
this.assertMayWindDown(this.txSigner(owner), "The user");
const now = this.now();
const fin = this.finality(market, now);
if (fin.state !== "final") throw "Markets - the market is not final yet";
const pos = this.positionOf(userState, market.marketId);
if (!pos.y.gt(0) && !pos.n.gt(0)) throw "Markets - nothing to redeem in this market";
const payout = this.payoutFor(market, fin.outcome as string, pos);
const locked = BN.from(market.locked);
if (locked.lt(payout)) throw "Markets - the payout is above the locked collateral (invariant)";
if (!apply) return;
const { network, token } = market.collateral;
this.l2Set(userState, network, token, this.l2Get(userState, network, token).add(payout));
this.setPosition(userState, market.marketId, { y: BN.from(0), n: BN.from(0) });
market.locked = locked.sub(payout).toString();
market.supply = { yes: BN.from(market.supply.yes).sub(pos.y).toString(), no: BN.from(market.supply.no).sub(pos.n).toString() };
const paid = market.paid || { yes: "0", no: "0", collateral: "0" };
market.paid = { yes: BN.from(paid.yes).add(pos.y).toString(), no: BN.from(paid.no).add(pos.n).toString(), collateral: BN.from(paid.collateral).add(payout).toString() };
// An optimistic market latches its phase too, so settleBonds pays by the path the market took even if the clock steps back.
if (!market.settled) market.settled = market.resolution.kind === "optimistic" ? { outcome: fin.outcome, at: now, phase: fin.phase } : { outcome: fin.outcome, at: now };
this.assertInvariant(market, now);
owner.setState({ layer2: userState.layer2, mkt: userState.mkt });
marketAct.setState(market);
this.event.emit("market-redeemed", { marketId: market.marketId, owner: userId, outcome: fin.outcome, yes: pos.y.toString(), no: pos.n.toString(), payout: payout.toString() });
}/** * The collateral invariant (plan §1.3), on the values about to be written: never negative; before final, * `locked == supply.yes == supply.no`; after, `locked` covers what the remaining supply can claim (the per-holder * floors sum to at most this). A failure refuses the transaction. * Bonds (oracle plan §1.5, clause 4), always: `bonds.held` is never negative and equals what is owed, 0 once * `bonds.settledAt` is set, else the reporter's bond if posted plus the dispute bond if posted. A "set" market has * no `bonds` and owes none. */
private assertInvariant(market: any, now: number): void {
const locked = BN.from(market.locked);
const yes = BN.from(market.supply.yes);
const no = BN.from(market.supply.no);
if (locked.lt(0) || yes.lt(0) || no.lt(0)) throw "Markets - invariant: a negative locked or supply";
const r = market.resolution || {};
const b = r.bonds;
if (b !== undefined && b !== null) {
const held = BN.from(b.held);
let owed = BN.from(0);
if (b.settledAt === null || b.settledAt === undefined) {
if (b.proposer) owed = owed.add(r.bond);
if (b.disputer) owed = owed.add(r.disputeBond);
}
// `owed` is a sum of positive bonds, so equality also rules out a negative `held` (clause 1).
if (!held.eq(owed)) throw "Markets - invariant: bonds held must equal the bonds posted and not yet paid out";
}
const fin = this.finality(market, now);
if (fin.state !== "final") {
if (!locked.eq(yes) || !locked.eq(no)) throw "Markets - invariant: locked must equal both supplies before final";
return;
}
if (locked.lt(this.payoutFor(market, fin.outcome as string, { y: yes, n: no }))) throw "Markets - invariant: locked does not cover the outstanding payout";
}/** * `pauseMarket` / `unpauseMarket` (the market's tenant master as `$i.tenant`, signed by its tenant key, or Varnir's * admin as `$i.admin`; the market as `$o.market`): the market-level pause, which stops new mints and trades only. * A tenant cannot lift a pause Varnir made (runSetSuspended's rule), nor take one over by pausing again. */
private async runPauseMarket(apply: boolean, paused: boolean): Promise<void> {
const tx: any = this.transactions;
const marketAct = this.named("$o", "market");
const market = this.requireMarket(marketAct);
let by: string;
if (tx.$i && tx.$i.admin) {
await this.requireAdmin();
by = "admin";
} else {
const masterAct = this.named("$i", "tenant");
this.requireTenantKeySigned(masterAct);
const master = masterAct.getState();
if (masterAct.getId() !== market.tenantId || !master || master.kind !== "varnir.tenant" || master.tenantId !== market.tenantId) throw "Markets - only the market's own tenant may pause it";
by = "tenant";
}
const isPaused = market.pausedAt !== null && market.pausedAt !== undefined;
if (!paused && by === "tenant" && isPaused && market.pausedBy !== "tenant") throw "Markets - Varnir paused this market: only Varnir can unpause it";
if (!apply) return;
if (paused) {
if (!isPaused) market.pausedAt = this.now();
if (!(isPaused && by === "tenant" && market.pausedBy !== "tenant")) market.pausedBy = by;
} else {
market.pausedAt = null;
market.pausedBy = null;
}
marketAct.setState(market);
this.event.emit("market-paused", { marketId: market.marketId, paused, by });
}/**
* `delist` (the tenant master as `$i.tenant`, tenant key; its directory as `$o.dir`; the market as `$o.market`): takes
* a FINAL market off the directory. The market stream stays. The tenant's market desk may delist too (oracle plan
* §1.10: `$i.desk = {$stream}` signed by its one stake-100 owner key, the master as `$r.tenant`), only while the desk
* is registered and in mode `auto`, and only a final market of its own tenant.
*/ private async runDelist(apply: boolean): Promise<void> {
const tx: any = this.transactions;
let tenantId: string;
let master: any;
let deskId: string | null = null;
if (tx.$i && tx.$i.desk) {
const deskAct = this.named("$i", "desk");
const ref = tx.$r && tx.$r.tenant;
tenantId = ref && typeof ref === "object" ? ref.$stream : ref;
master = this.getReadOnlyStream("tenant");
if (!master || master.kind !== "varnir.tenant" || master.tenantId !== tenantId) throw "Markets - $r.tenant is not a tenant master";
const mk: any = master.markets && typeof master.markets === "object" ? master.markets : {};
const desk = this.deskOf(mk);
if (desk.id !== deskAct.getId()) throw "Markets - this identity is not the tenant's market desk";
if (mk.deskOffBy !== null && mk.deskOffBy !== undefined) throw "Markets - Varnir turned this tenant's market desk off";
deskId = desk.id;
if (desk.mode !== "auto" || (desk.pausedAt !== null && desk.pausedAt !== undefined)) throw "Markets - the tenant's market desk is off: a person approves its drafts in the console";
this.assertOwnerKey(deskAct, "Markets - the market desk signs with exactly one of its own stake-100 owner keys");
} else {
const masterAct = this.named("$i", "tenant");
this.requireTenantKeySigned(masterAct);
tenantId = masterAct.getId();
master = masterAct.getState();
if (!master || master.kind !== "varnir.tenant" || master.tenantId !== tenantId) throw "Markets - $i.tenant is not a tenant master";
}
const marketAct = this.named("$o", "market");
const market = this.requireMarket(marketAct);
if (market.tenantId !== tenantId) throw "Markets - the market is not this tenant's";
const dirAct = this.named("$o", "dir");
const d = dirAct.getState();
if (dirAct.getId() !== this.ActiveCrypto.Hash.getHash(tenantId + DIR_NAME, "sha256") || !d || d.kind !== DIR_KIND || d.tenantId !== tenantId) throw "Markets - $o.dir is not this tenant's markets directory";
if (deskId !== null && market.createdBy !== deskId) throw "Markets - the market desk may delist only markets it listed";
// The tenant key may also take down a market with nothing at stake (no positions, no collateral, no proposal):
// a stolen desk key cannot fill the directory with markets nobody can remove (review C).
const empty = deskId === null && BN.from(market.locked).eq(0) && BN.from(market.supply.yes).eq(0) && BN.from(market.supply.no).eq(0) && !market.resolution.proposal && !market.resolution.dispute;
if (this.finality(market, this.now()).state !== "final" && !empty) throw "Markets - only a final market can be delisted";
const listed: string[] = Array.isArray(d.listed) ? d.listed : [];
if (listed.indexOf(market.marketId) < 0) throw "Markets - the market is not listed";
if (!apply) return;
const byDeskListed = typeof market.createdBy === "string" && market.createdBy !== tenantId;
const nextDir: any = { listed: listed.filter((x) => x !== market.marketId) };
if (byDeskListed && d.desk && typeof d.desk === "object") nextDir.desk = { ...d.desk, listed: Math.max(0, (Number.isSafeInteger(d.desk.listed) ? d.desk.listed : 0) - 1) };
dirAct.setState(nextDir);
this.event.emit("market-delisted", { marketId: market.marketId, tenantId });
}/**
* `propose` (the market's reporter as `$i.reporter = {$stream, outcome, evidenceHash}`, signing with its one live
* stake-100 owner key; the market as `$o.market`; the tenant master as `$r.tenant`; the reporter's shard of the
* tenant as `$o.tenant`, for usage): from `closeAt` until `resolveBy`, the reporter answers YES, NO or INVALID and
* posts `bond` of the market's collateral into `bonds.held`. Once per market. Usage `market.propose`. Emits
* `market-proposed`.
*/ private async runPropose(apply: boolean): Promise<void> {
const tx: any = this.transactions;
const reporter = this.named("$i", "reporter");
const id = reporter.getId();
const st: any = reporter.getState() || {};
const marketAct = this.named("$o", "market");
const market = this.requireMarket(marketAct);
const r = this.requireOptimistic(market, "propose");
if (r.reporter !== id) throw "Markets - only this market's reporter may propose";
this.assertBondSigner(st, reporter, "The reporter");
const now = this.now();
if (now < market.closeAt) throw "Markets - proposals open when the market closes";
if (now >= market.resolveBy) throw "Markets - the resolve-by time has passed: the market is INVALID by rule";
this.assertUnresolved(market);
if (r.proposal) throw "Markets - this market already has a proposal";
const outcome = tx.$i.reporter.outcome;
const evidenceHash = tx.$i.reporter.evidenceHash;
if (OUTCOMES.indexOf(outcome) < 0) throw "Markets - outcome must be YES, NO or INVALID";
if (typeof evidenceHash !== "string" || !HEX64.test(evidenceHash)) throw "Markets - evidenceHash must be 64 lower-case hex";
const bond = BN.from(r.bond);
const { network, token } = market.collateral;
const bal = this.l2Get(st, network, token);
if (bal.lt(bond)) throw `Markets - balance too low for the bond: ${bal} < ${bond}`;
const proposeMaster = this.tenantMasterRef(market);
const prep = this.marketsShardPrep(proposeMaster, id, "market.propose", "0");
// >>> tenant-pays
// Stage D: propose is an EXIT op (O2): never refused for credits; past the shard's overdraft it runs uncharged.
const floatPlan = this.tenantFloatPlan(prep, true);
// <<< tenant-pays
// The eligibility epoch at proposal time: a disputer's standing is judged as it stood then (decision 21b).
const pmk: any = proposeMaster.markets && typeof proposeMaster.markets === "object" ? proposeMaster.markets : {};
const eligibilityEpoch = Number.isSafeInteger(pmk.eligibilityEpoch) ? pmk.eligibilityEpoch : 0;
const heldBefore = BN.from(r.bonds.held);
const heldAfter = heldBefore.add(bond);
if (!apply) return;
this.l2Set(st, network, token, bal.sub(bond));
// Clause 5, on the balances actually written: the reporter's layer2 change plus the bonds.held change is zero.
this.assertZeroSum(this.l2Get(st, network, token).sub(bal), heldAfter.sub(heldBefore));
r.proposal = { outcome, at: now, by: id, evidenceHash, eligibilityEpoch };
r.bonds = { ...r.bonds, held: heldAfter.toString(), proposer: { id, amount: bond.toString(), due: "0" } };
this.assertInvariant(market, now);
reporter.setState({ layer2: st.layer2 });
marketAct.setState(market);
this.tenantApply(prep, `${network}:${token}`);
// >>> tenant-pays
this.tenantFloatApply(floatPlan, prep);
// <<< tenant-pays
this.event.emit("market-proposed", { marketId: market.marketId, reporter: id, outcome, evidenceHash, bond: bond.toString(), at: now, finalAt: now + r.disputeWindowMs });
}/**
* `dispute` (the disputer as `$i.disputer = {$stream}`, signing with its one live stake-100 owner key; the market as
* `$o.market`; the tenant master as `$r.tenant`; the disputer's shard as `$o.tenant`, for usage): while the
* challenge window is open (`now < proposal.at + disputeWindowMs`), an identity with a current eligibility record of
* this tenant (any tier) OR a non-zero position in this market says the proposal is wrong and posts `disputeBond`.
* The proposal moves into `dispute.proposal` and the escalation decides. Never the reporter, an arbiter or the
* tenant. Once per market: the first to commit wins. Usage `market.dispute`. Emits `market-disputed`.
*/ private async runDispute(apply: boolean): Promise<void> {
const disputer = this.named("$i", "disputer");
const id = disputer.getId();
const st: any = disputer.getState() || {};
const marketAct = this.named("$o", "market");
const market = this.requireMarket(marketAct);
const r = this.requireOptimistic(market, "dispute");
const now = this.now();
this.assertUnresolved(market);
const p = r.proposal;
if (!p || typeof p !== "object") throw "Markets - there is no proposal to dispute";
if (now >= p.at + r.disputeWindowMs) throw "Markets - the dispute window has closed";
if (id === r.reporter) throw "Markets - the reporter cannot dispute its own proposal";
if (r.resolvers.indexOf(id) >= 0) throw "Markets - an arbiter cannot dispute: it rules on the dispute";
if (id === market.tenantId) throw "Markets - the tenant cannot dispute its own market";
if (this.listedByDesk(market, id)) throw "Markets - the market desk cannot dispute a market it listed";
this.assertBondSigner(st, disputer, "The disputer");
const master = this.tenantMasterRef(market);
const pos = this.positionOf(st, market.marketId);
if (!pos.y.gt(0) && !pos.n.gt(0)) this.disputeStanding(master, market, p, id, st, now);
const bond = BN.from(r.disputeBond);
const { network, token } = market.collateral;
const bal = this.l2Get(st, network, token);
if (bal.lt(bond)) throw `Markets - balance too low for the dispute bond: ${bal} < ${bond}`;
const prep = this.marketsShardPrep(master, id, "market.dispute", "0");
// >>> tenant-pays
// Stage D: dispute is an EXIT op (O2): never refused for credits; past the shard's overdraft it runs uncharged.
const floatPlan = this.tenantFloatPlan(prep, true);
// <<< tenant-pays
const heldBefore = BN.from(r.bonds.held);
const heldAfter = heldBefore.add(bond);
if (!apply) return;
this.l2Set(st, network, token, bal.sub(bond));
this.assertZeroSum(this.l2Get(st, network, token).sub(bal), heldAfter.sub(heldBefore));
r.dispute = { by: id, at: now, proposal: p };
r.proposal = null;
r.bonds = { ...r.bonds, held: heldAfter.toString(), disputer: { id, amount: bond.toString(), due: "0" } };
this.assertInvariant(market, now);
disputer.setState({ layer2: st.layer2 });
marketAct.setState(market);
this.tenantApply(prep, `${network}:${token}`);
// >>> tenant-pays
this.tenantFloatApply(floatPlan, prep);
// <<< tenant-pays
this.event.emit("market-disputed", { marketId: market.marketId, disputer: id, bond: bond.toString(), at: now, deadline: now + r.escalation.windowMs });
}/**
* `arbitrate` (escalation kind "arbiters": an arbiter as `$i.arbiter = {$stream, outcome, evidenceHash}`, signing with
* its one live stake-100 owner key; the market as `$o.market`): one vote per arbiter, never changed, while a dispute
* is open and the arbiters' window runs (`now < dispute.at + escalation.windowMs`). When `threshold` votes agree the
* ruling is set and the market is final with it. Moves no money. Emits `market-arbiter-vote`, and `market-ruled` on
* the deciding vote.
*/ private async runArbitrate(apply: boolean): Promise<void> {
const tx: any = this.transactions;
const arbiter = this.named("$i", "arbiter");
const id = arbiter.getId();
const marketAct = this.named("$o", "market");
const market = this.requireMarket(marketAct);
const r = this.requireOptimistic(market, "arbitrate");
if (!r.escalation || r.escalation.kind !== "arbiters") throw "Markets - this market's disputes do not go to an arbiter set";
if (market.settled) throw "Markets - the market is already settled";
if (r.ruling) throw "Markets - the arbiters have already ruled";
if (!r.dispute || typeof r.dispute !== "object") throw "Markets - there is no open dispute to rule on";
const now = this.now();
if (this.escalationOutcome(market, now).status !== "waiting") throw "Markets - the arbiters' window has closed: the market is INVALID by rule";
if (r.resolvers.indexOf(id) < 0) throw "Markets - this identity is not an arbiter of this market";
this.assertOwnerKey(arbiter, "Markets - an arbiter votes with its own stake-100 owner key");
if (r.votes && r.votes[id] !== undefined) throw "Markets - this arbiter has already voted";
const outcome = tx.$i.arbiter.outcome;
const evidenceHash = tx.$i.arbiter.evidenceHash;
if (OUTCOMES.indexOf(outcome) < 0) throw "Markets - outcome must be YES, NO or INVALID";
if (typeof evidenceHash !== "string" || !HEX64.test(evidenceHash)) throw "Markets - evidenceHash must be 64 lower-case hex";
if (!apply) return;
const votes: any = { ...(r.votes || {}) };
votes[id] = { outcome, evidenceHash, at: now };
let count = 0;
for (const k of Object.keys(votes)) if (votes[k] && votes[k].outcome === outcome) count++;
r.votes = votes;
if (count >= r.threshold) r.ruling = { outcome, at: now };
this.assertInvariant(market, now);
marketAct.setState(market);
this.event.emit("market-arbiter-vote", { marketId: market.marketId, arbiter: id, outcome, evidenceHash, count, threshold: r.threshold });
if (r.ruling) this.event.emit("market-ruled", { marketId: market.marketId, outcome, at: now });
}/** * `settleBonds` (anyone as `$i.caller`, signing with any live key that is not read-only; the market as `$o.market`; * the recorded proposer as `$o.proposer` and, when there was a dispute, the recorded disputer as `$o.disputer`): once * the market is final through its reporter (undisputed), a ruling, or the arbiters' timeout, pays `bonds.held` out * into `layer2` (oracle plan §1.6): * - undisputed: the reporter gets its bond back; * - ruled for the proposed outcome: the reporter gets both bonds; ruled otherwise (INVALID included): the disputer; * - timeout (arbiters silent, INVALID by rule): both bonds come back, less the dispute fee `floor(D · disputeFeeBps / * 10000)` that the disputer pays the reporter (decision 21e). The fee is charged in no other case. * Once per market; latches `settled` (with the phase) if no redeem has: from then on the outcome and the path are * fixed, and a consensus clock that steps back can no longer reopen a dispute or an arbiter vote. Before any latch a * step-back of a few seconds at a window's end can admit one late dispute or vote (accepted, oracle plan O9), so the * reporter bot sends settleBonds as soon as a market is final. Never touches `locked`. Emits * `market-bonds-settled`. */
private async runSettleBonds(apply: boolean): Promise<void> {
const tx: any = this.transactions;
// `caller` is a banned identifier in the engine's deploy scan: the label stays "caller", the variable may not.
const sender = this.named("$i", "caller");
const signer = this.txSigner(sender);
if (!signer) throw "Markets - the caller's signature does not resolve to a live key of the identity";
if (this.labelOf(signer) === "read" || signer.stake >= READONLY_STAKE) throw "Markets - the caller's key is read-only";
const marketAct = this.named("$o", "market");
const market = this.requireMarket(marketAct);
const r = this.requireOptimistic(market, "settleBonds");
const b = r.bonds;
if (b.settledAt !== null && b.settledAt !== undefined) throw "Markets - this market's bonds are already settled";
if (!b.proposer) throw "Markets - this market holds no bonds: nobody proposed";
const now = this.now();
const fin = this.finality(market, now);
if (fin.state !== "final") throw "Markets - the market is not final yet: bonds settle once it is";
const B = BN.from(r.bond);
const D = b.disputer ? BN.from(r.disputeBond) : BN.from(0);
let toProposer: BN;
let toDisputer = BN.from(0);
let fee = BN.from(0);
if (fin.phase === "undisputed") {
toProposer = B;
} else if (fin.phase === "ruled") {
const upheld = r.dispute && r.dispute.proposal && r.dispute.proposal.outcome === fin.outcome;
toProposer = upheld ? B.add(D) : BN.from(0);
toDisputer = upheld ? BN.from(0) : D.add(B);
} else if (fin.phase === "timeout") {
fee = D.mul(r.disputeFeeBps).div(10000);
toProposer = B.add(fee);
toDisputer = D.sub(fee);
} else {
throw "Markets - the market is not final through its reporter or its arbiters";
}
const held = BN.from(b.held);
if (!toProposer.add(toDisputer).eq(held)) throw "Markets - the bonds held do not match what is owed (invariant)";
const proposerAct = this.named("$o", "proposer");
if (proposerAct.getId() !== b.proposer.id) throw "Markets - $o.proposer is not the identity that posted the proposal bond";
let disputerAct: any = null;
if (b.disputer) {
disputerAct = this.named("$o", "disputer");
if (disputerAct.getId() !== b.disputer.id) throw "Markets - $o.disputer is not the identity that posted the dispute bond";
} else if (tx.$o.disputer !== undefined) {
throw "Markets - this market was not disputed: name no $o.disputer";
}
if (!apply) return;
const { network, token } = market.collateral;
const ps: any = proposerAct.getState() || {};
const psBefore = this.l2Get(ps, network, token);
this.l2Set(ps, network, token, psBefore.add(toProposer));
let delta = this.l2Get(ps, network, token).sub(psBefore);
let ds: any = null;
if (disputerAct) {
ds = disputerAct.getState() || {};
const dsBefore = this.l2Get(ds, network, token);
this.l2Set(ds, network, token, dsBefore.add(toDisputer));
delta = delta.add(this.l2Get(ds, network, token).sub(dsBefore));
}
// Clause 5, on the balances actually written: the payees' layer2 changes plus the bonds.held change is zero.
this.assertZeroSum(delta, BN.from(0).sub(held));
proposerAct.setState({ layer2: ps.layer2 });
if (disputerAct) disputerAct.setState({ layer2: ds.layer2 });
r.bonds = {
held: "0",
proposer: { ...b.proposer, due: toProposer.toString() },
disputer: b.disputer ? { ...b.disputer, due: toDisputer.toString() } : null,
settledAt: now,
};
if (!market.settled) market.settled = { outcome: fin.outcome, at: now, phase: fin.phase };
this.assertInvariant(market, now);
marketAct.setState(market);
this.event.emit("market-bonds-settled", { marketId: market.marketId, outcome: fin.outcome, phase: fin.phase, proposerPaid: toProposer.toString(), disputerPaid: toDisputer.toString(), disputeFee: fee.toString() });
}/** True when `id` is the desk that listed this market (a desk-created market's `createdBy` is never the tenant). */
private listedByDesk(market: any, id: string): boolean {
return typeof market.createdBy === "string" && market.createdBy !== market.tenantId && market.createdBy === id;
}/** * A disputer WITHOUT a position (decision 21b: an eligibility revoke cannot block a dispute): standing is judged as it * stood when the proposal was made. It needs a record of THIS tenant (the per-tenant record hash), of an epoch at * least the proposal's `eligibilityEpoch` (so a revoke or epoch bump after the proposal does not block), unexpired on * the consensus clock, and outside Varnir's floor deny list. The tenant's own jurisdiction narrowing is NOT applied: * a tenant could otherwise narrow its lists after a proposal to shield its reporter. */
private disputeStanding(master: any, market: any, p: any, id: string, st: any, now: number): void {
const mk: any = master.markets && typeof master.markets === "object" && !Array.isArray(master.markets) ? master.markets : {};
const h = this.ActiveCrypto.Hash.getHash(market.tenantId + "|" + id + "|varnir.markets.eligible", "sha256");
const map = st && st.el && typeof st.el === "object" && !Array.isArray(st.el) ? st.el : null;
const el = map && map[h] && typeof map[h] === "object" ? map[h] : null;
const need = "Markets - the disputer needs an eligibility record of this tenant from before the proposal, or a position in this market";
if (!el) throw `${need} (no record)`;
if (!Number.isSafeInteger(el.expires) || !(now < el.expires)) throw `${need} (the record has expired)`;
const at = Number.isSafeInteger(p.eligibilityEpoch) ? p.eligibilityEpoch : 0;
if (!Number.isSafeInteger(el.epoch) || el.epoch < at) throw `${need} (the record was revoked before the proposal)`;
if (typeof el.j !== "string" || !JURISDICTION.test(el.j)) throw `${need} (the record has no jurisdiction)`;
const covers = (list: any, j: string) => Array.isArray(list) && list.some((x: any) => typeof x === "string" && (j === x || j.indexOf(x + "-") === 0));
if (covers(mk.floorDeny, el.j)) throw `${need} (a jurisdiction no market may serve)`;
}/** The market's resolution if it is optimistic; a "set" market is refused for the optimistic entries. */
private requireOptimistic(market: any, entry: string): any {
const r = market.resolution;
if (r.kind !== "optimistic" || !r.bonds || typeof r.bonds !== "object") throw `Markets - this market resolves by its resolver set: ${entry} is for optimistic markets`;
return r;
}/** No proposal or dispute may change a market that is settled, ruled or already under dispute (oracle plan §1.8). */
private assertUnresolved(market: any): void {
const r = market.resolution;
if (market.settled) throw "Markets - the market is already settled";
if (r.ruling) throw "Markets - the arbiters have already ruled";
if (r.dispute) throw "Markets - the proposal is already disputed";
}/** * A bond poster (the reporter, a disputer): exactly one live owner key signed (stake 100, not read-only, off-ledger * or verifier: resolveVote's rule, never a sum of smaller keys), and the identity rules of minting (assertMayTrade: * no AFX or treasury identity, no key carrying a spending policy). */
private assertBondSigner(st: any, activity: any, label: string): void {
this.assertOwnerKey(activity, `Markets - ${label} signs with exactly one of its own stake-100 owner keys`);
this.assertMayTrade(st, this.txSigner(activity), label);
}/** Exactly one LIVE owner key (stake 100, not read-only, off-ledger or verifier) signed `activity`; else `message`. */
private assertOwnerKey(activity: any, message: string): void {
const signer = this.txSigner(activity);
const l = this.labelOf(signer);
if (!signer || signer.stake !== 100 || l === "read" || l === "offledger" || l === "verifier") throw message;
}/** Clause 5 (oracle plan §1.5): the transaction's `layer2` changes plus the change in `bonds.held` sum to exactly zero. */
private assertZeroSum(layer2Delta: BN, heldDelta: BN): void {
if (!layer2Delta.add(heldDelta).eq(0)) throw "Markets - the bond transfer does not conserve collateral";
}/** * `$r.tenant` read WITHOUT the gate (propose and dispute are never blocked by the tenant's mode, pause or suspension): * it must be the market's tenant master. Its credit prices and fee config price the usage; its markets block only * reads a disputer's eligibility. */
private tenantMasterRef(market: any): any {
const tx: any = this.transactions;
const ref = tx.$r && tx.$r.tenant;
const refId = ref && typeof ref === "object" ? ref.$stream : ref;
if (refId !== market.tenantId) throw "Markets - $r.tenant must be the market's tenant master";
const master: any = this.getReadOnlyStream("tenant");
if (!master || master.kind !== "varnir.tenant" || master.tenantId !== refId) throw "Markets - the tenant stream is not this market's tenant master";
return master;
}/** Steps 1-2 with the tenant master read from `$r.tenant`, which must be the market's tenant. Returns `{master, mk}`. */ private gateTenantRef(market: any, needed: string): any {
const tx: any = this.transactions;
const ref = tx.$r && tx.$r.tenant;
const refId = ref && typeof ref === "object" ? ref.$stream : ref;
if (refId !== market.tenantId) throw "Markets - $r.tenant must be the market's tenant master";
const master: any = this.getReadOnlyStream("tenant");
const mk = this.gateTenant(master, refId, market.tenantId, needed);
return { master, mk };
}/** * Gate steps 1 and 2 on a tenant master's state: (1) Varnir's ceiling reaches `needed` (no markets block is `off`); * (2) the stream is a tenant master naming itself and the market's tenant, not suspended, not a sub-tenant, and * min(mode, ceiling) reaches `needed`. Returns the markets block. */
private gateTenant(master: any, masterId: string, tenantId: string, needed: string): any {
const mk: any = master && master.markets && typeof master.markets === "object" && !Array.isArray(master.markets) ? master.markets : {};
const need = MODES.indexOf(needed);
const ceiling = this.modeRank(mk.ceiling);
if (ceiling < need) throw `Markets - Varnir has not enabled ${needed} for this tenant (ceiling ${MODES[ceiling]})`;
if (!master || master.kind !== "varnir.tenant" || master.tenantId !== masterId || masterId !== tenantId) throw "Markets - the tenant stream is not this market's tenant master";
if (master.suspended !== false) throw "Markets - this tenant is suspended";
if (master.parentId !== undefined && master.parentId !== null) throw "Markets - sub-tenants cannot run markets in v1";
const mode = this.modeRank(mk.mode);
const eff = mode < ceiling ? mode : ceiling;
if (eff < need) throw `Markets - this tenant's markets mode is ${MODES[eff]}: ${needed} is needed`;
return mk;
}/** * Gate steps 3 and 4 for one party: (3) jurisdiction: the record's `j` is in neither Varnir's floor deny list nor * the tenant's deny list, and is in the tenant's allow list and the market's when those are set (a country code * also covers its regions; deny wins); (4) eligibility: the record is this tenant's for this user (`h`), unexpired, * of the current epoch and tier `trade` (any tier when `anyTier`: a disputer's standing, oracle plan §1.4). Returns * the record. */
private gateParty(mk: any, market: any, userId: string, st: any, now: number, label: string, anyTier = false): any {
// Per-tenant records (decision 16 as revised): `el` maps the record hash to the record, so another tenant's
// record is never read here and never blocks this one.
const h = this.ActiveCrypto.Hash.getHash(market.tenantId + "|" + userId + "|varnir.markets.eligible", "sha256");
const map = st && st.el && typeof st.el === "object" && !Array.isArray(st.el) ? st.el : null;
const el = map && map[h] && typeof map[h] === "object" ? map[h] : null;
if (el) {
if (typeof el.j !== "string" || !JURISDICTION.test(el.j)) throw `Markets - ${label}'s eligibility record has no jurisdiction`;
const covers = (list: any, j: string) => Array.isArray(list) && list.some((x: any) => typeof x === "string" && (j === x || j.indexOf(x + "-") === 0));
if (covers(mk.floorDeny, el.j) || covers(mk.denyJ, el.j)) throw `Markets - ${label} is in a jurisdiction this tenant may not serve`;
if (Array.isArray(mk.allowJ) && mk.allowJ.length > 0 && !covers(mk.allowJ, el.j)) throw `Markets - ${label} is outside the tenant's allowed jurisdictions`;
if (Array.isArray(market.allowJ) && market.allowJ.length > 0 && !covers(market.allowJ, el.j)) throw `Markets - ${label} is outside this market's allowed jurisdictions`;
}
if (!el) throw `Markets - ${label} holds no eligibility record of this tenant`;
if (!Number.isSafeInteger(el.expires) || !(now < el.expires)) throw `Markets - ${label}'s eligibility has expired`;
const epoch = Number.isSafeInteger(mk.eligibilityEpoch) ? mk.eligibilityEpoch : 0;
if (el.epoch !== epoch) throw `Markets - ${label}'s eligibility was revoked`;
if (!anyTier && el.tier !== "trade") throw `Markets - ${label}'s eligibility does not allow trading`;
return el;
}/** Gate step 6: neither the tenant's markets nor the market is paused, and the market is open. */
private gateOpen(mk: any, market: any, now: number): void {
if (mk.pausedAt !== null && mk.pausedAt !== undefined) throw "Markets - this tenant's markets are paused";
if (market.pausedAt !== null && market.pausedAt !== undefined) throw "Markets - this market is paused";
if (this.finality(market, now).state !== "open") throw "Markets - this market is closed for trading";
} private modeRank(mode: any): number {
const i = MODES.indexOf(mode);
return i < 0 ? 0 : i;
}/** * The taker's fill fee: the tenant's own `market.fill` rate (basis points only), refused above Varnir's cap * (`markets.feeCapBps`) or the `maxBps` the taker signed; `floor(leg · bps / 10000)`. */
private marketsFillFee(master: any, mk: any, signedMaxBps: number, leg: BN): BN {
const rate = master.feeConfig && master.feeConfig.rates ? master.feeConfig.rates["market.fill"] : undefined;
let bps = 0;
if (rate) {
if (!Number.isInteger(rate.bps) || rate.bps < 0 || rate.bps > 10000 || rate.flat !== "0") throw "Markets - the tenant's market.fill rate is malformed";
bps = rate.bps;
}
const cap = Number.isInteger(mk.feeCapBps) ? mk.feeCapBps : 0;
if (bps > cap) throw `Markets - the tenant's fill fee ${bps} bps is above Varnir's cap of ${cap} bps`;
if (bps > signedMaxBps) throw `Markets - the tenant's fill fee ${bps} bps is above the ${signedMaxBps} bps the taker signed`;
return leg.mul(bps).div(10000);
}/** * What tenantApply needs to credit `fee` and the op's credit price to `userId`'s shard of the tenant, named as * `$o.tenant`: the shard must be that tenant's, at the index this user maps to under the master's current fee * config (tenantShardFor, the pasted block). */
private marketsShardPrep(master: any, userId: string, op: string, fee: string): any {
const tx: any = this.transactions;
if (!tx.$o || !tx.$o.tenant) throw "Markets - name the user's shard of the tenant as $o.tenant";
const shard = this.named("$o", "tenant");
const st = shard.getState();
const index = this.tenantShardFor(userId, master.feeConfig);
if (!st || st.kind !== "varnir.tenant.shard" || st.tenantId !== master.tenantId || st.index !== index || shard.getId() !== this.tenantShardStreamId(master.tenantId, index)) throw "Markets - $o.tenant is not this user's shard of the tenant";
const usage = master.creditPrices && Number.isInteger(master.creditPrices[op]) ? master.creditPrices[op] : 1;
return { tenantId: master.tenantId, shard, fee, usage, op };
}/** The single LIVE authority whose signature this transaction carries for a signed input (liveAuthority), or null. */
private txSigner(activity: any): any {
const signed = (this as any).sigs && (this as any).sigs[activity.getId()];
const hashes = signed ? Object.keys(signed) : [];
if (hashes.length !== 1) return null;
return this.liveAuthority(activity, hashes[0]);
}/** A market's minimum mint and order size: `caps.minOrder`, else one whole token of its collateral. */
private minOrderOf(market: any): BN {
const m = market.caps && market.caps.minOrder;
return typeof m === "string" && /^[1-9][0-9]{0,39}$/.test(m) ? BN.from(m) : BN.from(this.pow10(market.collateral.decimals));
} private labelOf(authority: any): string | null {
return authority && authority.label ? String(authority.label).toLowerCase().trim() : null;
}/** Minting and trading: refused for AFX or treasury identities, a read-only, off-ledger or verifier key, and a key with a spending policy (fail closed, v1). */
private assertMayTrade(state: any, authority: any, label: string): void {
if (state.afx) throw `Markets - ${label} identity is AFX-protected; markets are not available to it in v1`;
if (state.hasTreasury) throw `Markets - ${label} identity is treasury-protected; markets are not available to it in v1`;
if (!authority) throw `Markets - ${label} signature does not resolve to a key of the identity`;
const l = this.labelOf(authority);
if (l === "read" || authority.stake >= READONLY_STAKE) throw `Markets - ${label} key is read-only`;
if (l === "offledger") throw `Markets - ${label} key is off-ledger: no fund authority`;
if (l === "verifier") throw `Markets - ${label} key is a verifier key`;
if (state.restrictions && state.restrictions[authority.hash] && state.restrictions[authority.hash].policy) throw `Markets - ${label} key carries a spending policy; markets are not available to it in v1`;
}/** Merge, redeem and cancel: only a read-only or off-ledger key is refused. They return the identity's own collateral or cancel, so nothing else may block them. */
private assertMayWindDown(authority: any, label: string): void {
if (!authority) throw `Markets - ${label} signature does not resolve to a key of the identity`;
const l = this.labelOf(authority);
if (l === "read" || authority.stake >= READONLY_STAKE) throw `Markets - ${label} key is read-only`;
if (l === "offledger") throw `Markets - ${label} key is off-ledger: no fund authority`;
}/** The tenant key (an authority labelled `tenant`) must have signed this stream. */
private requireTenantKeySigned(activity: any): void {
const signed = (this as any).sigs && (this as any).sigs[activity.getId()];
const hashes = signed ? Object.keys(signed) : [];
if (!(activity.getAuthorities() || []).some((a: any) => a.label === "tenant" && hashes.indexOf(a.hash) !== -1)) throw "Markets - the tenant key must sign the tenant master";
}/** The identities that deployed this contract (its :stream meta authorities): Varnir. */
private async deployerIds(): Promise<string[]> {
const meta: any = await this.getAnyStreamReadOnly(`${this.contractId()}:stream`).catch(() => null);
const list = meta && Array.isArray(meta.authorities) ? meta.authorities : [];
return list.map((a: any) => (a && typeof a.public === "string" ? a.public : "")).filter((x: string) => !!x);
}/** $i.admin must be an identity that deployed Varnir.Markets, signing with its stake-100 key. */
private async requireAdmin(): Promise<any> {
const admin = this.named("$i", "admin");
if ((await this.deployerIds()).indexOf(admin.getId()) < 0) throw "Markets - admin must be the identity that deployed Varnir.Markets";
const signer = this.txSigner(admin);
if (!signer || signer.stake !== 100) throw "Markets - admin must sign with its stake-100 key";
return admin;
}/** The stream must be a market (kind, and its own id recorded as marketId); returns its state. */
private requireMarket(activity: any): any {
const m = activity.getState();
if (!m || m.kind !== MARKET_KIND || m.marketId !== activity.getId() || typeof m.tenantId !== "string" || !m.resolution || !Array.isArray(m.resolution.resolvers)) throw "Markets - $o.market is not a market";
return m;
}/** A share amount: a whole-number string, greater than 0, a multiple of SHARE_STEP. */
private shareAmount(raw: any, label: string): BN {
if (typeof raw !== "string" || !/^[1-9][0-9]{0,39}$/.test(raw)) throw `Markets - ${label} must be a positive whole-number string`;
const v = BN.from(raw);
if (!v.mod(SHARE_STEP).eq(0)) throw `Markets - ${label} must be a multiple of ${SHARE_STEP} raw units`;
return v;
} private pow10(n: number): string {
let v = BN.from(1);
for (let i = 0; i < n; i++) v = v.mul(10);
return v.toString();
}/** A user's position in a market (0/0 when none). */
private positionOf(st: any, marketId: string): { y: BN; n: BN }/** A position in a NEW market needs a free slot: at most USER_MARKETS_MAX open markets per user. */
private assertMarketSlot(st: any, marketId: string): void {
const mkt = st && st.mkt && typeof st.mkt === "object" ? st.mkt : {};
if (mkt[marketId] === undefined && Object.keys(mkt).length >= USER_MARKETS_MAX) throw `Markets - the user already holds positions in ${USER_MARKETS_MAX} markets`;
} private validJurisdictions(list: any, field: string): string[] {
if (!Array.isArray(list) || list.length > JURISDICTIONS_MAX) throw `Markets - ${field} must be a list of at most ${JURISDICTIONS_MAX} codes`;
const out: string[] = [];
for (const code of list) {
if (typeof code !== "string" || !JURISDICTION.test(code)) throw `Markets - ${field} entries must be ISO 3166 codes such as GB or US-NY`;
if (out.indexOf(code) >= 0) throw `Markets - ${field} lists ${code} twice`;
out.push(code);
}
return out;
} private contractId(): string {
return String(this.transactions.$contract).substring(0, 64);
} private named(where: "$i" | "$o", label: string): any {
const ref = (this.transactions as any)[where] && (this.transactions as any)[where][label];
if (!ref) throw `Markets - missing ${where}.${label}`;
return this.getActivityStreams(ref);
}/** The consensus clock in ms. The engine passes `this.cDate` as a string, so it is wrapped, never called as a Date. */
private now(): number {
return new Date(this.cDate).getTime();
}/** * The authority with `hash` on `activity` if it is still live: present, and * either permanent (no `expire` field) or with an `expire` after the * consensus clock. As the engine's isAuthorityExpired: expire <= the * transaction time is expired, and so is `expire: null` (read as the epoch) * or an unparseable value. Null otherwise. */
private liveAuthority(activity: any, hash: string | null): any {
if (!hash) return null;
const authority = activity.getAuthorities().find((candidate: any) => candidate.hash === hash);
if (!authority) return null;
if (authority.expire !== undefined) {
const expireAt = new Date(authority.expire).getTime();
if (Number.isNaN(expireAt) || !(expireAt > new Date(this.cDate).getTime())) return null;
}
return authority;
}/** * Domain separation (Low-1): an order's signed `domain` must name THIS * deployment — the namespace this transaction runs in and this Swap contract's * own id. `$contract` is the routing reference "<id>@<version>", so the bare id * is its leading 64 chars (the same trick other Varnir contracts use to read * their own id), matching the SDK's domain.contract. Rejecting a mismatch stops * a maker signature being replayed against another namespace or a different Swap * contract deployment. The domain is inside the signed bytes, so it cannot be * altered without breaking verifyOrderSig — this check binds it to reality. */
private verifyOrderDomain(order: any): boolean {
if (!order || !order.domain) return false;
const contractId = ("" + this.transactions.$contract).substring(0, 64);
return (
order.domain.namespace === this.transactions.$namespace &&
order.domain.contract === contractId
);
}/** * Verify a signed order against its signer's stream authorities, returning the * VERIFYING authority's key HASH so the caller can govern that order signer's * give-leg (unified-keys Task 4) — a resting-order signer does not tx-sign, so * this returned hash is its only governing-key handle. Only secp256k1 * authorities that are NOT read-only (label "read", or the stake-9000 * fail-safe for unlabeled legacy authorities) may authorise an order — a * read-only key must never be able to sign a trade. KeyPair.verify * JSON.stringifies the order internally, matching how the SDK signed it. First * key that verifies wins. Shared by fill (the maker's order) and match (both * parties' orders), so there is one implementation. * * Returns null when NO authority verifies (the caller reverts the order). The * accepted-type allow-list and every signature check are UNCHANGED — only the * return type changed. A signature that verifies against an authority carrying * no `hash` (only legacy / test-stub authorities — production authorities * always carry one) returns ORDER_SIGNER_UNRESOLVED so the caller's validity * gate still passes exactly as before while that give-leg stays ungoverned. */
private verifyOrderSig(activity: any, order: any, sig: any): string | null {
const authorities = activity.getAuthorities();
for (let i = 0; i < authorities.length; i++) {
const auth = authorities[i];
// Verify with the authority's OWN scheme via KeyPair(auth.type, ...). Accept
// only Varnir's three identity schemes — secp256k1 and the post-quantum
// falcon-512 / ml-dsa-65 (Activeledger 4.7 verifies all three in-contract).
// This used to be secp256k1-only, so a post-quantum maker's order signature
// never verified and fills/matches reverted — the exchange was unusable for
// PQ identities (now the onboarding default). Any other type (e.g. rsa) is
// NOT tried, so an unexpected key can never authorise a trade.
if (auth.type !== "secp256k1" && auth.type !== "falcon-512" && auth.type !== "ml-dsa-65") continue;
if ((auth.label ? String(auth.label).toLowerCase().trim() : null) === "read" || auth.stake >= READONLY_STAKE) continue;
try {
if (new this.ActiveCrypto.KeyPair(auth.type, auth.public).verify(order, sig)) {
// Surface the verifying key's hash as the order signer's governing key
// (Task 4); a hashless legacy/stub authority yields the ungoverned
// sentinel so the caller's validity gate is unchanged.
return typeof auth.hash === "string" && auth.hash.length
? auth.hash
: ORDER_SIGNER_UNRESOLVED;
}
} catch (_e) {
// A key that cannot verify this signature is simply not the signer.
}
}
return null;
}/**
* Read an order's consume marker into cumulative fill progress, tolerating
* every shape a marker can have — this is what makes partial fills backward
* compatible with markers already in ledger state:
* - undefined -> untouched (0 filled, not terminal)
* - { cancelled: true } -> terminal
* - { filled: umid } (LEGACY full fill, pre-partial, no accumulator fields)
* -> terminal
* - { filledWant, filledGive, done } -> partial accumulator; terminal iff done
* `terminal` means no further fill is allowed. Amounts are the cumulative want
* and give filled SO FAR (0 for legacy/cancelled — they carry no remainder to
* fill anyway, being terminal).
*/ private readMarker(marker: any): { filledWant: BN; filledGive: BN; terminal: boolean }/** Creates `layer2[network][token] = {balance: "0"}` when missing. */ private l2Ensure(state: any, network: string, token: string): void {
if (!state.layer2) state.layer2 = {};
if (!state.layer2[network]) state.layer2[network] = {};
if (!state.layer2[network][token]) state.layer2[network][token] = { balance: "0" };
}/** The balance at `layer2[network][token]` (created as 0 when missing). */
private l2Get(state: any, network: string, token: string): BN {
this.l2Ensure(state, network, token);
return BN.from(state.layer2[network][token].balance);
}/** Writes the balance at `layer2[network][token]` as a decimal string. */
private l2Set(state: any, network: string, token: string, value: BN): void {
this.l2Ensure(state, network, token);
state.layer2[network][token].balance = value.toString();
}/** Which shard a sender uses: the first 8 hex chars of sha256(sender stream id), mod the shard count. */
private tenantShardIndex(senderStreamId: string, shards: number): number {
if (!Number.isInteger(shards) || shards < 1) throw "Tenants - shards must be a positive whole number";
const hash: string = this.ActiveCrypto.Hash.getHash(String(senderStreamId), "sha256");
return parseInt(hash.slice(0, 8), 16) % shards;
}/** * Which shard a sender uses under fee config `config`: its reserved shard when `config.priority` names it (a * priority sharded account, set by Varnir with setPriority), otherwise tenantShardIndex. Reserved shards are * indexes 256 to 263 (RESERVED_BASE and PRIORITY_SHARDS_MAX in Varnir.Tenants, written out here because the block * carries no module constants), past every hashed range, so a reshard never maps a hashed sender onto one. */
private tenantShardFor(senderStreamId: string, config: any): number {
const p = config && config.priority;
if (p && typeof p === "object" && Object.keys(p).indexOf(String(senderStreamId)) >= 0) {
const index = p[senderStreamId];
if (!Number.isInteger(index) || index < 256 || index >= 264) throw "Tenants - the tenant's priority shard map is malformed";
return index;
}
return this.tenantShardIndex(senderStreamId, config.shards);
}/** The id of a tenant's shard stream: sha256(tenantId + "tenant.shard." + index), as createShards derives it. */
private tenantShardStreamId(tenantId: string, index: number): string {
return this.ActiveCrypto.Hash.getHash(tenantId + "tenant.shard." + index, "sha256");
}/** The fee for `amount` (a whole-number string) under `op`: bps of the amount rounded down, plus the flat part. An op with no rate costs nothing. */
private tenantComputeFee(config: any, op: string, amount: string): string {
if (typeof amount !== "string" || !/^[0-9]{1,40}$/.test(amount)) throw "Tenants - amount must be a whole-number string";
const rate = config && config.rates && config.rates[op];
if (!rate) return "0";
// Re-checked here as well as in setFeeConfig, so a corrupted config can never give a negative or malformed fee.
if (!Number.isInteger(rate.bps) || rate.bps < 0 || rate.bps > 10000 || typeof rate.flat !== "string" || !/^[0-9]{1,30}$/.test(rate.flat)) throw "Tenants - the tenant's rate is malformed";
return ((BigInt(amount) * BigInt(rate.bps)) / BigInt(10000) + BigInt(rate.flat)).toString();
}/** * A parent's rate for `op`, adjusted for one sub-tenant (sub-tenancy spec §4.2): bps' = floor(bps × (10000 + adjust) * / 10000) and the same for the flat part, the factor never below 0 and bps' never above 10000. `adjust` is the * sub's `terms.baseAdjustBps`, -10000 (free) to +10000 (double). Returns a config tenantComputeFee prices from. */
private tenantAdjustedBase(rates: any, op: string, adjust: any): any {
if (!Number.isInteger(adjust) || adjust < -10000 || adjust > 10000) throw "Tenants - the sub-tenant's baseAdjustBps is malformed";
const rate = rates && rates[op];
const adjusted: any = {};
if (!rate) return { rates: adjusted };
if (!Number.isInteger(rate.bps) || rate.bps < 0 || rate.bps > 10000 || typeof rate.flat !== "string" || !/^[0-9]{1,30}$/.test(rate.flat)) throw "Tenants - the parent's rate is malformed";
const factor = BigInt(Math.max(0, 10000 + adjust));
const bps = (BigInt(rate.bps) * factor) / BigInt(10000);
adjusted[op] = { bps: Number(bps > BigInt(10000) ? BigInt(10000) : bps), flat: ((BigInt(rate.flat) * factor) / BigInt(10000)).toString() };
return { rates: adjusted };
}/** * Refuses an overlay rate above the parent's caps (`terms.overlayCapBps`, `terms.overlayCapFlat`; absent means no * cap) for `op`, or for every op when `op` is null. Checked when the sub sets its rates, when the parent sets new * terms, and again when a fee is worked out, so a corrupted config can never charge past a cap. */
private tenantAssertOverlayCap(rates: any, terms: any, op: string | null): void {
const t: any = terms && typeof terms === "object" ? terms : {};
const capBps = t.overlayCapBps;
const capFlat = t.overlayCapFlat;
if (capBps !== undefined && capBps !== null && !Number.isInteger(capBps)) throw "Tenants - the sub-tenant's overlayCapBps is malformed";
if (capFlat !== undefined && capFlat !== null && (typeof capFlat !== "string" || !/^[0-9]{1,30}$/.test(capFlat))) throw "Tenants - the sub-tenant's overlayCapFlat is malformed";
const ops = op === null ? Object.keys(rates || {}) : [op];
for (const name of ops) {
const r = rates && rates[name];
if (!r) continue;
if (!Number.isInteger(r.bps) || typeof r.flat !== "string" || !/^[0-9]{1,30}$/.test(r.flat)) throw "Tenants - the tenant's rate is malformed";
if ((capBps !== undefined && capBps !== null && r.bps > capBps) || (capFlat !== undefined && capFlat !== null && BigInt(r.flat) > BigInt(capFlat))) {
throw `Tenants - the overlay for ${name} is above the parent's cap (${capBps === undefined || capBps === null ? "no" : capBps} bps, flat ${capFlat === undefined || capFlat === null ? "uncapped" : capFlat}): lower the overlay first`;
}
}
}/** * The membership record's hash for `senderId` under a tenant master (or its copy) (spec §4.5): * sha256(tenantId|subId|senderId|"varnir.tenant.member"), where a sub names its parent and itself and a tenant with no * parent names itself and "". The one derivation: join and revoke write and match with it, a transfer checks with it. */
private tenantMemberHashFor(master: any, senderId: string): string {
const sub = typeof master.parentId === "string";
const tenantId = sub ? master.parentId : master.tenantId;
const subId = sub ? master.tenantId : "";
return this.ActiveCrypto.Hash.getHash(tenantId + "|" + subId + "|" + senderId + "|varnir.tenant.member", "sha256");
}/** * The signing modes that exist (spec §4.5), the one list both Varnir.Tenants (when a mode is set) and a transfer * check (tenantSigningOf) use. `open` and `ticket` are not built: `open` needs a per-sender cap first. */
private tenantSigningModes(): string[] {
return ["live", "membership"];
}/** * How a tenant proves a sender belongs to it (spec §4.5), from its master or its shard copy: absent is "live" (every * tenant from before the modes signs each transfer), anything else outside tenantSigningModes (such as `open`) is * refused rather than guessed at. */
private tenantSigningOf(master: any): any {
const s = master ? master.signing : undefined;
if (s === undefined || s === null) return { mode: "live" };
if (typeof s !== "object" || this.tenantSigningModes().indexOf(s.mode) < 0) throw "Tenants - the tenant's signing mode is malformed";
return s;
}/**
* In `membership` mode the sender's own stream must hold the record `join` wrote (`tm = {h, issued, expires}`):
* `h` recomputed from this tenant (for a sub: its parent and itself) and the sender, unexpired, and issued after the
* tenant's `revokedBefore`. Only Varnir.Tenants `join` writes `tm`, with the user's and the tenant key's signatures.
*/ private tenantAssertMember(master: any, senderStreamId: string, senderState: any, now: number): void {
const h = this.tenantMemberHashFor(master, senderStreamId);
const tm = senderState && senderState.tm;
if (!tm || typeof tm !== "object" || tm.h !== h) throw "Tenants - the sender is not a member of this tenant: join it first";
if (!Number.isSafeInteger(tm.expires) || !(now < tm.expires)) throw "Tenants - the sender's membership has expired: renew it (join)";
const before = Number.isSafeInteger(master.revokedBefore) ? master.revokedBefore : 0;
if (!Number.isSafeInteger(tm.issued) || !(tm.issued > before)) throw "Tenants - the sender's membership was revoked: join again";
}/**
* Refuses a tenant-tagged transaction unless: `master` (the `$r` tenant
* stream's plain state, which the caller may have pointed at any stream, or
* the shard's copy shaped as one by tenantCopyAsMaster) is
* a tenant whose state names the very stream it was read from
* (`masterStreamId`), and not suspended; `shard` (the `$i.tenant` activity) is a shard
* of that tenant at the index and id this sender maps to under the declared
* fee-config version; and the shard's own `tenant` authority signed it (the
* sweeper authority alone does not tag a transaction). The shard is the
* sender's reserved one when that version's `priority` names it
* (tenantShardFor). Returns the fee config in effect for the declared
* version (`{version, shards, rates, priority?, terms?}`):
* the fee must be worked out from that one, never from a newer config.
* The tenant key's signature on the shard is what proves membership in
* `live` signing (absent counts as live), so there the shard must be a
* signed input (`shardSigned`); in `membership` signing the shard may be
* an unsigned `$o` and membership is proved by the sender's record (`open`
* is not available yet and is refused by tenantSigningOf). `signing` is
* tenantSigningOf(master), read once by the caller
* (tenantPrepare), but it is still checked to be the right shard.
*/ private tenantAssertTag(master: any, masterStreamId: string, shard: any, senderStreamId: string, declaredVersion: number, now: number, shardSigned: boolean, signing: any): any {
if (!master || master.kind !== "varnir.tenant" || typeof master.tenantId !== "string") throw "Tenants - the tenant stream is not a tenant";
if (master.tenantId !== masterStreamId) throw "Tenants - the tenant stream is not the tenant it claims to be";
if (master.suspended) throw "Tenants - this tenant is suspended";
const state = shard.getState();
if (!state || state.kind !== "varnir.tenant.shard" || state.tenantId !== master.tenantId) throw "Tenants - the tenant stream is not a shard of this tenant";
let chosen: any;
if (declaredVersion === master.feeConfig.version) {
chosen = master.feeConfig;
} else if (master.previousFeeConfig && master.previousFeeConfig.rates && declaredVersion === master.previousFeeConfig.version && now <= master.previousFeeConfig.until) {
chosen = master.previousFeeConfig;
} else {
throw "Tenants - the fee config version is not current";
}
const inEffect: any = { version: chosen.version, shards: chosen.shards, rates: chosen.rates };
if (chosen.priority !== undefined) inEffect.priority = chosen.priority;
if (chosen.terms !== undefined) inEffect.terms = chosen.terms;
const index = this.tenantShardFor(senderStreamId, inEffect);
if (state.index !== index || shard.getId() !== this.tenantShardStreamId(master.tenantId, index)) throw "Tenants - wrong shard for this sender";
if (signing.mode === "live") {
// Only an input's signature is verified by the engine: a signature claimed for an output proves nothing.
if (!shardSigned) throw "Tenants - this tenant signs every transfer (signing live): name its shard in $i.tenant, signed by the tenant key";
const signed = (this as any).sigs && (this as any).sigs[shard.getId()];
const hashes = signed ? Object.keys(signed) : [];
const ok = (shard.getAuthorities() || []).some((a: any) => a.label === "tenant" && hashes.indexOf(a.hash) !== -1);
if (!ok) throw "Tenants - the tenant key must sign the shard";
}
return inEffect;
}/** * The shard-copy epoch. A copy carries the epoch it was written in, and only a copy of the current epoch is * trusted. Bump it (here, so every contract carrying this block agrees) in the roll-forward after any rollback of * these contracts: copies the older code wrote or left behind are then refused until `syncShards` rewrites them, and * running `syncShards` for every tenant is the first step of that roll-forward (spec §7). */
private tenantCopyEpoch(): number {
return 1;
}/** * The shard's own copy of what a tagged transfer checks (written only by Varnir.Tenants: when the shard is created, * by syncShards and by sweep, always from the master's state), shaped as the master state tenantAssertTag reads. * Used when a tagged transaction carries no `$r.tenant`. Refuses a shard of another tenant, a shard with no copy * (a tenant created before copies existed, until the backfill), a malformed copy, and a copy older than the version * the sender declared. Every entry that changes the master's checks rewrites every shard's copy in the same * transaction, so a copy is never behind its master; the last refusal is a guard, so a fee is never worked out from * a config the shard does not hold. A `suspended` that is anything but `false` counts as suspended. * Two more bounds (spec §5.3): a copy from another contract epoch (tenantCopyEpoch: written before a rollback) is * refused, and so is a copy past its lease (`validUntil`, renewed by every all-shard write), so a copy can never * outlive a master change by more than the lease even when no all-shard write lands (a master-only suspendNow). */
private tenantCopyAsMaster(shard: any, tenantId: string, declaredVersion: number, now: number): any {
const st = shard.getState();
if (!st || st.kind !== "varnir.tenant.shard" || st.tenantId !== tenantId) throw "Tenants - the tenant stream is not a shard of this tenant";
const copy = st.copy;
if (!copy || typeof copy !== "object") throw "Tenants - this shard holds no copy of the tenant's fee config yet: include the tenant master as $r.tenant";
if (copy.epoch !== this.tenantCopyEpoch()) throw "Tenants - this shard's fee config copy is from another contract epoch: include the tenant master as $r.tenant";
if (!Number.isSafeInteger(copy.validUntil) || !Number.isFinite(now) || !(now <= copy.validUntil)) throw `Tenants - this shard's fee config copy has lapsed (valid until ${copy.validUntil}): include the tenant master as $r.tenant`;
const fc = copy.feeConfig;
if (copy.tenantId !== tenantId || !Number.isSafeInteger(copy.seq) || !fc || typeof fc !== "object" || !Number.isInteger(fc.version)) {
throw "Tenants - this shard's fee config copy is malformed: include the tenant master as $r.tenant";
}
if (declaredVersion > fc.version) {
throw `Tenants - this shard has not caught up with fee config version ${declaredVersion} yet (it holds ${fc.version}): retry shortly, or include the tenant master as $r.tenant`;
}
const prices = copy.creditPrices && typeof copy.creditPrices === "object" ? copy.creditPrices : {};
const out: any = { kind: "varnir.tenant", tenantId, suspended: copy.suspended !== false, feeConfig: fc, previousFeeConfig: copy.previousFeeConfig || null, creditPrices: prices };
// Sub-tenancy (spec 2026-10-29-sub-tenancy.md): the parent, the signing mode and revokedBefore, copied only when
// the master has them; tenantPrepare refuses a malformed one rather than reading it as absent.
if (copy.parentId !== undefined) out.parentId = copy.parentId;
if (copy.signing !== undefined) out.signing = copy.signing;
if (copy.revokedBefore !== undefined) out.revokedBefore = copy.revokedBefore;
return out;
}/**
* Called by a contract's vote round. Untagged (no `$i.owner.tenant`) is the
* hub: returns null and changes nothing. Tagged `{id, version}` needs
* `$i.tenant` = this sender's shard. With `$r.tenant` (the tenant master; its
* stream id must be the tagged id) the master is read and is the authority,
* as before shards carried copies. Without it the shard's copy is the
* authority (tenantCopyAsMaster), so the master is not read at all. Runs
* tenantAssertTag and returns
* `{tenantId, shard, fee, usage, op}` for tenantApply (`usage` = the operation's credit price for the tenant, default 1; `op` the operation, which the tenant-charged event names). The fee is in the transfer's own
* asset, worked out from the fee config of the version the sender declared,
* and refused when above the `maxFee` the sender signed in the tag.
*/ private tenantPrepare(op: string, senderStreamId: string, amount: string): any {
const tx: any = this.transactions;
const tag = tx.$i && tx.$i.owner && tx.$i.owner.tenant;
if (!tag) return null;
if (typeof tag.id !== "string" || !/^[0-9a-f]{64}$/.test(tag.id) || !Number.isInteger(tag.version) || typeof tag.maxFee !== "string" || !/^[0-9]{1,40}$/.test(tag.maxFee)) throw "Tenants - the tenant tag must be {id, version, maxFee} with maxFee a whole-number string";
// The shard is a signed input in `live` signing, and may be an unsigned output in `membership` (spec
// 2026-10-29-sub-tenancy.md §4.5; `open` is not available yet); tenantAssertTag decides which the mode allows.
// Named once, never both.
const shardInInputs = !!tx.$i.tenant;
const shardInOutputs = !!(tx.$o && tx.$o.tenant);
if (!shardInInputs && !shardInOutputs) throw "Tenants - a tenant-tagged transaction must name its shard in $i.tenant";
if (shardInInputs && shardInOutputs) throw "Tenants - name the tenant's shard once, in $i.tenant or in $o.tenant";
const ref = tx.$r && tx.$r.tenant;
const readMaster = ref !== undefined && ref !== null;
const refId = readMaster ? (typeof ref === "object" ? ref.$stream : ref) : tag.id;
// Exactly the tagged id: a suffixed id ("<id>:volatile", "<id>:stream") is a different, node-local document.
if (refId !== tag.id) throw "Tenants - $r.tenant must be the tagged tenant stream";
// The tenant key is a tag, never spending authority: the sender must have signed for itself.
const sender = this.getActivityStreams(tx.$i.owner);
if (!sender.hasSignature()) throw "Tenants - the sender must sign a tenant-tagged transaction itself";
const shard = this.getActivityStreams(shardInInputs ? tx.$i.tenant : tx.$o.tenant);
const now = new Date(this.cDate).getTime();
const master: any = readMaster ? this.getReadOnlyStream("tenant") : this.tenantCopyAsMaster(shard, tag.id, tag.version, now);
const signing = this.tenantSigningOf(master);
const inEffect = this.tenantAssertTag(master, refId, shard, senderStreamId, tag.version, now, shardInInputs, signing);
if (master.tenantId !== tag.id) throw "Tenants - the tenant stream is not the tagged tenant";
if (signing.mode === "membership") this.tenantAssertMember(master, senderStreamId, sender.getState(), now);
let price = master.creditPrices && Number.isInteger(master.creditPrices[op]) ? master.creditPrices[op] : 1;
if (master.parentId !== undefined && master.parentId !== null && typeof master.parentId !== "string") throw "Tenants - the tenant's parentId is malformed";
if (typeof master.parentId !== "string") {
// A tenant with no parent: exactly the path from before sub-tenancy.
if (tag.parentVersion !== undefined || (tx.$r && tx.$r.parent !== undefined)) throw "Tenants - this tenant has no parent: its tag carries no parentVersion and no $r.parent";
const fee = this.tenantComputeFee(inEffect, op, amount);
if (BigInt(fee) > BigInt(tag.maxFee)) throw `Tenants - the tenant fee ${fee} is above the maximum ${tag.maxFee} the sender signed`;
return { tenantId: tag.id, shard, fee, usage: price, op };
}
// A sub-tenant (spec §4): base = the parent's rate adjusted by the sub's terms, overlay = the sub's own rate, each
// rounded down on its own; the parent master is read, exactly the stream the sub names, and must be a top-level
// tenant (one level), not suspended, at the version the sender's tag priced the base from.
if (!Number.isInteger(tag.parentVersion)) throw "Tenants - a sub-tenant's tag must carry the parentVersion its base was priced from";
const pref = tx.$r && tx.$r.parent;
const parentRefId = pref !== null && typeof pref === "object" ? pref.$stream : pref;
if (parentRefId !== master.parentId) throw "Tenants - $r.parent must be the sub-tenant's parent master";
const parent: any = this.getReadOnlyStream("parent");
if (!parent || parent.kind !== "varnir.tenant" || parent.tenantId !== parentRefId || !parent.feeConfig) throw "Tenants - $r.parent is not the sub-tenant's parent";
if (parent.parentId !== undefined && parent.parentId !== null) throw "Tenants - a sub-tenant's parent cannot itself be a sub-tenant";
if (parent.suspended !== false) throw "Tenants - this sub-tenant's parent is suspended";
let base: any;
if (tag.parentVersion === parent.feeConfig.version) {
base = parent.feeConfig;
} else if (parent.previousFeeConfig && parent.previousFeeConfig.rates && tag.parentVersion === parent.previousFeeConfig.version && now <= parent.previousFeeConfig.until) {
base = parent.previousFeeConfig;
} else {
throw "Tenants - the parent's fee config version is not current";
}
const terms: any = inEffect.terms && typeof inEffect.terms === "object" ? inEffect.terms : {};
this.tenantAssertOverlayCap(inEffect.rates, terms, op);
const baseFee = this.tenantComputeFee(this.tenantAdjustedBase(base.rates, op, terms.baseAdjustBps === undefined ? 0 : terms.baseAdjustBps), op, amount);
const overlay = this.tenantComputeFee(inEffect, op, amount);
const fee = (BigInt(baseFee) + BigInt(overlay)).toString();
if (BigInt(fee) > BigInt(tag.maxFee)) throw `Tenants - the tenant fee ${fee} is above the maximum ${tag.maxFee} the sender signed`;
// Credits are the parent's: its price for the op (the sub holds none).
price = parent.creditPrices && Number.isInteger(parent.creditPrices[op]) ? parent.creditPrices[op] : 1;
return { tenantId: tag.id, shard, fee, base: baseFee, overlay, usage: price, op };
}/**
* Called by the commit round with what tenantPrepare returned: adds the fee to the shard's `fees` under `assetKey`
* ("network:token") and the operation's credit price to its usage counter. For a sub-tenant the overlay goes to
* `fees` and the base to `upstream` (swept to the parent); an ordinary tenant's shard is written exactly as before.
*/ private tenantApply(prep: any, assetKey: string): void {
const st: any = prep.shard.getState();
const fees: any = st.fees || {};
const sub = prep.base !== undefined;
fees[assetKey] = (BigInt(fees[assetKey] || "0") + BigInt(sub ? prep.overlay : prep.fee)).toString();
const upstream: any = st.upstream || {};
if (sub) upstream[assetKey] = (BigInt(upstream[assetKey] || "0") + BigInt(prep.base)).toString();
prep.shard.setState({ ...st, fees, usage: (BigInt(st.usage || "0") + BigInt(prep.usage)).toString(), ...(sub ? { upstream } : {}) });
}/** * Adds `amount` credits to a tenant master's state (grantCredits, and a credits payout settled by * CryptoTransfer `tenantsettle`): what the tenant owes from an overrun is paid first, only the rest becomes * balance, and any grace is cleared. Mutates `state`. */
private tenantAddCredits(state: any, amount: bigint): void {
const owed = BigInt(state.owed || "0");
const paid = owed < amount ? owed : amount;
state.owed = (owed - paid).toString();
state.credits = (BigInt(state.credits || "0") + amount - paid).toString();
state.graceUntil = null;
// The part of owed that came from a parent's sub draws this interval (Varnir.Tenants sweep) is never more than what
// is still owed: a paid-off debt must not count again at the parent's next sweep (sub-tenancy spec §11).
if (state.subOwed !== undefined && state.subOwed !== null && BigInt(state.subOwed) > BigInt(state.owed)) state.subOwed = state.owed;
}/** A tenant's payout list with every open request kept and only the newest 100 closed ones (settled, rejected, cancelled); the order is kept. */
private tenantTrimPayouts(list: any[]): any[] {
let closed = 0;
const out: any[] = [];
for (let i = list.length - 1; i >= 0; i--) {
if (list[i].status !== "requested") {
closed++;
if (closed > 100) continue;
}
out.unshift(list[i]);
}
return out;
}/**
* Vote round, with what tenantPrepare / marketsShardPrep returned: what the op takes from its shard's credit FLOAT.
* Returns null when the shard holds no float: a tenant not yet switched over by Varnir.Tenants `enableFloat` (the OLD
* PATH: the op's price is only counted in `usage` and drawn from the master at the sweep, exactly as before stage D).
* NEW PATH, the shard has a float (whole credits, may be negative):
* - O1, a normal op (`exit` false: transfer, market.mint, market.fill): needs `float >= price`, else REFUSED (the
* hard stop); nothing is written, because the refusal is the vote's.
* - O2, an exit op (`exit` true: market.propose, market.dispute): NEVER refused. It is charged while the float stays
* at or above `-floatOverdraft` (the shard's overdraft, set by Varnir.Tenants); the part of the price that would
* take it lower runs uncharged (recorded, so Varnir carries at most that). A malformed float never blocks an exit
* op either: it runs uncharged.
* Returns `{next, charged, uncharged}` (BigInt) for tenantFloatApply.
*/ private tenantFloatPlan(prep: any, exit: boolean): any {
const st: any = prep.shard.getState();
if (st.float === undefined || st.float === null) return null;
const price = BigInt(prep.usage);
const wellFormed = typeof st.float === "string" && /^-?[0-9]{1,30}$/.test(st.float) && Number.isSafeInteger(st.floatOverdraft) && st.floatOverdraft >= 0;
if (!wellFormed) {
if (exit) return { next: null, charged: BigInt(0), uncharged: price };
throw "Tenants - this tenant's shard float is malformed: the operation is refused";
}
const float = BigInt(st.float);
if (!exit) {
if (float < price) throw `Tenants - this tenant is out of credits (shard float ${float}, this operation costs ${price}): its operations stop until it is topped up; try again in a few minutes`;
return { next: float - price, charged: price, uncharged: BigInt(0) };
}
const floor = BigInt(0) - BigInt(st.floatOverdraft);
let charged = price;
if (float - price < floor) charged = float > floor ? float - floor : BigInt(0);
return { next: float - charged, charged, uncharged: price - charged };
}/**
* Commit round, AFTER tenantApply (which writes the shard's fees and usage): debits the float by `plan.charged` in the
* same transaction as the op, keeps the running total of what exit ops ran uncharged (`floatUncharged`), and records
* that this op's usage was settled by the float (`floatPaid` += its price, charged or not). The float sweep draws
* from the master any usage NOT settled here (usage - floatPaid): an op that reached a contract version without this
* block (callable until the version locks hold) is still billed. Emits `tenant-float-low` when the float can no
* longer pay this op's price again or is below a tenth of its target (`floatTarget`), so the sweeper funds the shard
* on demand (Varnir.Tenants `fundShards`). No float plan (the old path) writes nothing; a shard that holds a float
* with no plan (a caller that skipped tenantFloatPlan) is refused rather than left unbilled.
* Stage F1c: every metered op is itemised for the tenant's charge history with a `tenant-charged` event
* `{tenantId, shard, op, price, charged, uncharged, float}` (only when the prep names its `op`, so the stage E
* settle refund, which passes none, emits none). On the old path (no float) `charged` is the price the sweep draws
* from the master later and `float` is false; on the float, what this op took from it now.
*/ private tenantFloatApply(plan: any, prep: any): void {
const st: any = prep.shard.getState();
if (!plan) {
if (st.float !== undefined && st.float !== null) throw "Tenants - this shard runs on the credit float but the operation was not planned against it";
if (typeof prep.op === "string") this.event.emit("tenant-charged", { tenantId: prep.tenantId, shard: st.index, op: prep.op, price: String(prep.usage), charged: String(prep.usage), uncharged: "0", float: false, umid: this.umid });
return;
}
const whole = (v: any) => BigInt(typeof v === "string" && /^[0-9]{1,30}$/.test(v) ? v : "0");
const price = plan.charged + plan.uncharged;
const uncharged = (whole(st.floatUncharged) + plan.uncharged).toString();
const paid = (whole(st.floatPaid) + price).toString();
const float = plan.next === null ? st.float : plan.next.toString();
prep.shard.setState({ ...st, float, floatUncharged: uncharged, floatPaid: paid });
if (typeof prep.op === "string") this.event.emit("tenant-charged", { tenantId: prep.tenantId, shard: st.index, op: prep.op, price: price.toString(), charged: plan.charged.toString(), uncharged: plan.uncharged.toString(), float: true, umid: this.umid });
const target = whole(st.floatTarget);
if (plan.next === null || plan.next < price || plan.next * BigInt(10) < target) {
this.event.emit("tenant-float-low", { tenantId: prep.tenantId, shard: st.index, float, target: target.toString(), charged: plan.charged.toString(), uncharged: plan.uncharged.toString() });
}
}/** * Credits paid IN to a tenant master that runs on the float (Varnir.Tenants grantCredits and the float sweep, * Varnir.CryptoTransfer's credits payout): what it owes is paid first, and grace ends only when nothing is owed any * more (a part payment never restarts the grace clock, unlike the old path's tenantAddCredits). Mutates `fm`. */
private floatCredit(fm: any, amount: bigint): void {
if (amount <= BigInt(0)) return;
const owed = BigInt(fm.owed || "0");
const paid = owed < amount ? owed : amount;
fm.owed = (owed - paid).toString();
fm.credits = (BigInt(fm.credits || "0") + amount - paid).toString();
if (owed - paid === BigInt(0)) fm.graceUntil = null;
if (fm.subOwed !== undefined && fm.subOwed !== null && BigInt(fm.subOwed) > BigInt(fm.owed)) fm.subOwed = fm.owed;
if (fm.priceOwed !== undefined && fm.priceOwed !== null && BigInt(fm.priceOwed) > BigInt(fm.owed)) fm.priceOwed = fm.owed;
}