Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirAssignOwner extends PostProcessEvent
Assign a claimed, unowned L1 wallet stream to an identity.
{
"$sigs": {
"<owner identity stream id>": "<base64 signature of $tx, signed with the owner's private key>"
},
"$tx": {
"$contract": "<Varnir.AssignOwner's deployed contract id>",
"$namespace": "varnir",
"$i": {
"owner": {
"$stream": "<owner identity stream id>",
"personal": true
}
},
"$o": {
"wallet": {
"$stream": "<pregenerated wallet's own stream id>"
}
}
}
}/**
* Voting round: refuses recovered or frozen identities on every stream
* (social-recovery guard), then refuses any `$o` wallet that already has
* an `owner`, has `role: "change"`, is a `btc-utxo-book`, is retired,
* frozen or purged, or is an mpc2 key without its `mpcCanary`.
*
* @returns {Promise<boolean>}
* @memberof VarnirAssignOwner
*/ 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.
const recoveryRefusal = this.refuseRecoveredStreams([]);
if (recoveryRefusal) return reject(recoveryRefusal);
if (this.transactions.$entry === "replacefrozen") {
try {
await this.voteReplaceFrozen();
return resolve(true);
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
// Read once, before the loop: the same switch for every wallet here.
const requireSignedProof = await this.mpc2SignedProofRequired();
this.keys = Object.keys(this.transactions.$o);
for (let i = this.keys.length; i--;) {
let key = this.getActivityStreams(this.transactions.$o[this.keys[i]]);
let keyState = key.getState();
if (keyState.owner) {
return reject("Key already assigned");
}
const poolOnly = this.poolOnlyRefusal(keyState);
if (poolOnly) {
return reject(poolOnly);
}
// Advanced key life cycle (plan Task 3.3): never handed to anyone,
// whatever a gateway's pool says (poolLifecycleRefusal).
const lifecycle = this.poolLifecycleRefusal(keyState, requireSignedProof);
if (lifecycle) {
return reject(`Cannot be assigned: ${lifecycle}`);
}
}
// >>> tenant-pays
// Stage F4: a tagged assignment is the tenant's to pay (wallet.deposit, never the identity's credits); an
// untagged one by a member of a tenant on the float is refused while Varnir's addressCharge is on.
try {
const unreadable = "Credits - the plans config could not be read; the wallet was not assigned, try again shortly";
const block = this.depositBlock(await this.depositPlansConfig(unreadable));
const owner = this.getActivityStreams(this.transactions.$i.owner);
const now = new Date(this.cDate).getTime();
if (this.transactions.$i.owner.tenant) {
this.tenantDeposit = this.depositPlan(block, owner.getId(), this.keys, now);
return resolve(true);
}
const member = await this.memberRuleRefusal(block, owner.getId(), owner.getState(), now);
if (member) return reject(member);
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
// <<< tenant-pays
// Credits: priced once, for every wallet here together, and refused
// before anything is assigned when the balance cannot pay in full.
try {
const wallets = this.keys.map((label) => {
const w: any = this.getActivityStreams(this.transactions.$o[label]).getState();
// `invoice` (per wallet, on its `$o` entry): a single-use invoice wallet, priced higher.
return {network: w.network, advanced: this.creditsIsAdvancedWallet(w), invoice: this.transactions.$o[label].invoice};
});
const owner = this.getActivityStreams(this.transactions.$i.owner);
this.walletPricing = await this.creditsPriceWallets(
owner.getState(), wallets, "Credits - the plans config could not be read; the wallet was not assigned, try again shortly"
);
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
resolve(true);
});
}/**
* Commit round: sets each `$o` wallet's `owner` to the `$i.owner` stream
* id and `assignUmid` to this umid. With `$i.owner.personal` the wallet is
* marked `business: false`; otherwise it gets an empty `firstDeposit`
* record. Emits `wallet-assigned` per wallet (for the gateway's pregen
* pool) and returns `{id, address, hashes}` - one object for one wallet,
* an array for several.
*
* @returns {Promise<any>}
* @memberof VarnirAssignOwner
*/ public commit(): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
if (this.transactions.$entry === "replacefrozen") {
this.commitReplaceFrozen();
return resolve(true);
}
const owner = this.getActivityStreams(this.transactions.$i.owner);
this.ownerId = owner.getId();
// >>> tenant-pays
// Stage F4: a tagged assignment is paid from the tenant's shard float; the identity's credits are not touched.
if (this.tenantDeposit) this.depositTake();
// <<< tenant-pays
// Credits first, so a broken invariant refuses before any wallet is written.
const ownerState: any = owner.getState() || {};
const refusal = this.creditsRecordWallets(ownerState, this.walletPricing, this.umid, new Date(this.cDate).getTime());
if (refusal) return reject(refusal);
// Stage F4: a tagged assignment leaves the identity's state alone (what the line above computed is not written).
if (!this.tenantDeposit) owner.setState(ownerState);
if (this.walletPricing.live && this.walletPricing.credits > 0) {
this.event.emit("credits-changed", {
identity: this.ownerId, delta: -this.walletPricing.split.fromBalance, balance: this.creditsBalance(ownerState), allowance: 0 - this.walletPricing.split.fromAllowance, allowanceUsed: this.creditsAllowanceUsed(ownerState), reason: "wallet", umid: this.umid,
});
}
for (let i = this.keys.length; i--;) {
let key = this.getActivityStreams(this.transactions.$o[this.keys[i]]);
let keyState = key.getState();
this._dbIndex = keyState._dbIndex ?? 0;
keyState.owner = this.ownerId;
// If personal remove business flag
if (this.transactions.$i.owner.personal) {
keyState.business = false;
} else {
// Now we add onto keystate an object for first deposit
// This object and business will record first deposit.
keyState.firstDeposit = {};
}
// Add umid for assign for tracing
keyState.assignUmid = this.umid;
// >>> tenant-pays
// Stage F4: the on-ledger mark. Only this commit writes `tenant` and `sweepPrepaid` (the wallet was unowned, a
// fresh pool wallet, so no earlier mark can be carried over), and Varnir.CryptoTransfer tenantwdsettle checks and
// spends `sweepPrepaid` when a payout claims the prepaid discount for this wallet as a source.
const paid = this.tenantDeposit ? this.tenantDeposit.wallets[this.keys[i]] : null;
if (paid) {
keyState.tenant = this.tenantDeposit.prep.tenantId;
keyState.sweepPrepaid = { asset: paid.asset, credits: paid.credits, umid: this.umid, configVersion: this.tenantDeposit.version, multiplierPct: this.tenantDeposit.multiplierPct };
}
// <<< tenant-pays
key.setState(keyState);
// Lets minigate's own SSE listener update its local pregen pool
// (mark this wallet no longer free) the same way it already does
// for key-generated - see apps/minigate/src/index.ts.
this.event.emit('wallet-assigned', {
stream: key.getId(),
network: keyState.network,
symbol: keyState.symbol,
address: keyState.address,
owner: this.ownerId,
});
// >>> tenant-pays
if (paid) {
this.event.emit("tenant-deposit-wallet", { tenantId: this.tenantDeposit.prep.tenantId, wallet: key.getId(), network: keyState.network, asset: paid.asset, credits: String(paid.credits), umid: this.umid });
}
// <<< tenant-pays
this.keysAssigned.push({
id: key.getId(),
address: keyState.address,
hashes: [] // Probably can pull from volatile
})
}
// Backwards compaitable pull from array
if (this.keysAssigned.length === 1) {
this.returnToRemote(this.keysAssigned[0]);
} else {
this.returnToRemote(this.keysAssigned);
}
resolve(true);
});
} 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;
}/**
* Why a stream that is the pool's own may never be handed to anyone, or
* null. Shared by assignment and `replacefrozen`, so the two paths cannot
* drift apart.
* - Bitcoin (spec §2.1, §8.4): change wallets belong to the pool and are
* never handed to a user, and a UTXO book is not a wallet.
* - A network fee wallet (gas key, consolidation spec §4.4.1, §5.1) holds
* only Varnir's float: an owner could spend it, and its book (the
* top-up debt and rental counters) is not a wallet at all.
* - A pool vault (consolidation step 2 spec §3.1) holds pooled coin for
* every user's payouts.
*
* @private
* @param {*} state the wallet stream's state
* @returns {(string | null)}
* @memberof VarnirAssignOwner
*/ private poolOnlyRefusal(state: any): string | null {
if (state.role === "change") {
return "A Bitcoin change wallet cannot be assigned";
}
if (state.type === "btc-utxo-book") {
return "A UTXO book is not a wallet";
}
if (state.role === "gas") {
return "A network fee wallet (gas key) cannot be assigned";
}
if (state.type === "gas-book") {
return "A gas book is not a wallet";
}
// A pool vault (consolidation step 2) holds pooled coin for payouts: an
// owner could spend every user's coins in it.
if (state.role === "vault") {
return "A pool vault cannot be assigned";
}
return null;
}/** * Why a wallet may not take new coins (assignment, or a consolidation into * it), or null. Retired, frozen and purged keys take no new deposits (spec * §5.2): a purged one has no parts left, a frozen one only an unbuilt sweep * to move them. An Advanced (mpc2) key is not known to rebuild shares * behind Q until its canary signed (PR #350 review M2), so coins sent there * could be lost for good. A signed DiffConsensus proof (`diffConfirmed.sig`, * decision 2026-10-10) is the same evidence: Q's signature, made from the * nodes' parts of both shares, that every node checked before it voted and * that only Varnir.DiffConsensus writes. Either one admits the key, unless * `requireSignedProof` (Varnir.CryptoTransfer's contract data * `mpc2RequireSignedProof`, owner `mod` only, read by the caller; missing, * malformed or unreadable is off): then an UNOWNED Advanced wallet needs * the signed proof, and an unsigned proof plus a canary is no longer * enough. Why: a proof from before 2026-10-10 checked only CVM-A's parts, * and a canary passes with three nodes' parts, so such a key may lack * CVM-B's part on a node. Once `diffcon-backfill --sign` has re-proven * the pool, the switch makes a key it dropped stay out everywhere (review * M3 of PR #430). Owned wallets are not affected: their deposits must * still resolve and their coins still move. */
private poolLifecycleRefusal(state: any, requireSignedProof: boolean): string | null {
if (!state || typeof state !== "object") return "the wallet has no state";
if (state.retired !== undefined) return "the wallet is retired";
if (state.mpcFrozen !== undefined) return "the wallet is frozen";
if (state.mpcPurged !== undefined) return "the wallet is purged";
if (state.mpcProtocol !== undefined && requireSignedProof === true && (state.owner === null || state.owner === undefined) &&
!(state.diffConfirmed && state.diffConfirmed.sig)) {
return "the Advanced wallet has no signed DiffConsensus proof (mpc2RequireSignedProof)";
}
if (state.mpcProtocol !== undefined && state.mpcCanary === undefined && !(state.diffConfirmed && state.diffConfirmed.sig)) {
return "the Advanced wallet has no canary signature or signed DiffConsensus proof yet";
}
return null;
} private creditsDefaults(): any {
const three = (instant: number, standard: number, economy: number) => ({instant, standard, economy});
const tron = {native: three(30, 20, 10), token: three(600, 400, 240)};
const bsc = {native: three(30, 20, 10), token: three(40, 20, 10)};
const eth = {native: three(30, 20, 10), token: {live: true}};
return {
periodMs: 30 * 24 * 60 * 60 * 1000,
renewWindowMs: 7 * 24 * 60 * 60 * 1000,
linkLimits: {trader: 5},
weights: {
networks: {eth, sep: eth, trx: tron, niles: tron, shasta: tron, bnb: bsc, tbnb: bsc},
live: {
factorsPct: three(250, 180, 130),
minimums: three(300, 200, 120),
creditMicroUsd: 6700,
gasMicroUsd: {eth: 1000000, sep: 1000000},
},
},
};
} private creditsSpeed(speed: any): string | null {
if (speed === undefined || speed === null) return "economy";
return speed === "instant" || speed === "standard" || speed === "economy" ? speed : null;
} private creditsIsCount(n: any, max: number): boolean {
return typeof n === "number" && Number.isInteger(n) && n >= 0 && n <= max;
} private creditsWeight(weights: any, network: string, assetClass: string, speed: string): number | string {
// Not named `net` - the engine's contract sandbox refuses that exact
// identifier ("Security Violation: Unauthorized identifier 'net'",
// confirmed live against a local deploy), evidently blocklisted after
// Node's core `net` module regardless of it being a plain local const.
const netCode = String(network).toLowerCase();
const missing = `No credit weight for ${assetClass} withdrawals on ${network}`;
const nets = weights && weights.networks ? weights.networks : {};
const entry = nets[netCode] ? nets[netCode][assetClass] : undefined;
if (!entry || ["instant", "standard", "economy"].indexOf(speed) === -1) return missing;
if (entry.live === true) {
const live = weights.live || {};
const gas = live.gasMicroUsd ? live.gasMicroUsd[netCode] : undefined;
const factor = live.factorsPct ? live.factorsPct[speed] : undefined;
const minimum = live.minimums ? live.minimums[speed] : undefined;
const unit = live.creditMicroUsd;
if (
!this.creditsIsCount(gas, 1000000000) ||
!this.creditsIsCount(factor, 10000) ||
!this.creditsIsCount(minimum, 1000000) ||
!this.creditsIsCount(unit, 1000000000) ||
unit === 0
) {
return `No live gas reading for ${network}`;
}
const numerator = gas * factor;
const denominator = 100 * unit;
return Math.max(minimum, Math.floor((numerator + denominator - 1) / denominator));
}
const w = entry[speed];
return this.creditsIsCount(w, 1000000) && w > 0 ? w : missing;
} private creditsWeightsRefusal(next: any, prev: any): string | null {
const speeds = ["instant", "standard", "economy"];
const maxStep = 2;
// Not `path` - the engine's contract sandbox refuses that exact
// identifier too (see creditsWeight's own note); it blocks a plain
// parameter name the same as a local const.
const step = (fieldPath: string, now: any, before: any, max: number): string | null => {
if (!this.creditsIsCount(now, max) || now === 0) return `Weights: ${fieldPath} must be a positive integer up to ${max}`;
if (this.creditsIsCount(before, max) && before > 0 && (now > before * maxStep || now * maxStep < before)) {
return `Weights: ${fieldPath} ${before} -> ${now} moves more than x${maxStep} in one update`;
}
return null;
};
if (!next || typeof next !== "object" || !next.networks || typeof next.networks !== "object") {
return "Weights: networks required";
}
const old = prev && typeof prev === "object" ? prev : {};
const oldNets = old.networks && typeof old.networks === "object" ? old.networks : {};
for (const name of Object.keys(oldNets)) {
if (!next.networks[name]) return `Weights: ${name} cannot be removed`;
}
const liveNets: string[] = [];
for (const name of Object.keys(next.networks)) {
if (!/^[a-z0-9-]{2,16}$/.test(name)) return `Weights: network ${name} must be a lowercase canonical code`;
// Not `net` - see creditsWeight's own note on the sandbox's blocklist.
const netEntry = next.networks[name];
for (const cls of ["native", "token"]) {
const e = netEntry && netEntry[cls];
if (!e || typeof e !== "object") return `Weights: ${name}.${cls} required`;
if (e.live === true) {
if (cls === "native") return `Weights: ${name}.native cannot be live-priced`;
liveNets.push(name);
continue;
}
const was = oldNets[name] && oldNets[name][cls] && oldNets[name][cls].live !== true ? oldNets[name][cls] : {};
for (const s of speeds) {
const r = step(`${name}.${cls}.${s}`, e[s], was[s], 1000000);
if (r) return r;
}
}
}
// A live block is validated whenever it is PRESENT, not only when a
// network is currently live-priced - otherwise a caller can stash an
// unvalidated (or junk) live block while every network is fixed, and it
// becomes the unbounded "before" the next time a network switches live.
if (liveNets.length || (next.live !== undefined && next.live !== null)) {
const live = next.live;
const oldLive = old.live && typeof old.live === "object" ? old.live : {};
if (!live || typeof live !== "object") return "Weights: live pricing block required";
for (const part of ["factorsPct", "minimums"]) {
if (!live[part] || typeof live[part] !== "object") return `Weights: live.${part} required`;
for (const s of speeds) {
const r = step(`live.${part}.${s}`, live[part][s], oldLive[part] ? oldLive[part][s] : undefined, part === "factorsPct" ? 10000 : 1000000);
if (r) return r;
}
}
const unitRefusal = step("live.creditMicroUsd", live.creditMicroUsd, oldLive.creditMicroUsd, 1000000000);
if (unitRefusal) return unitRefusal;
for (const name of liveNets) {
const gas = live.gasMicroUsd ? live.gasMicroUsd[name] : undefined;
const was = oldLive.gasMicroUsd ? oldLive.gasMicroUsd[name] : undefined;
const r = step(`live.gasMicroUsd.${name}`, gas, was, 1000000000);
if (r) return r;
}
}
// The raw per-field checks above miss a class switching live<->fixed (the
// "was"/"before" resets to {} across the switch, so the step bound never
// applies) and miss several raw fields moving together within their own
// x2 bounds but compounding past x2 on the computed price. Close both:
// bound the EFFECTIVE weight too, for every network/class/speed this
// update and the prior one can both price.
for (const name of Object.keys(oldNets)) {
for (const cls of ["native", "token"]) {
for (const s of speeds) {
const before = this.creditsWeight(old, name, cls, s);
if (typeof before !== "number") continue; // no valid prior price to bound against
const after = this.creditsWeight(next, name, cls, s);
if (typeof after !== "number") continue; // already refused above; defensive only
if (after > before * maxStep || after * maxStep < before) {
return `Weights: ${name}.${cls}.${s} effective weight ${before} -> ${after} moves more than x${maxStep} in one update`;
}
}
}
}
return null;
} private creditsFreshPlan(tier: string, startMs: number, cfg: any, terms: any): any {
const d = this.creditsDefaults();
const limits = (cfg && cfg.linkLimits) || d.linkLimits;
// A tier adds no credits (credits-only, 2026-10-17): every tier but
// Enterprise includes 0 and rolls over 0, whatever a stale config holds.
// Enterprise keeps its own admin-assigned terms.
const enterprise = tier === "enterprise";
return {
tier,
periodStart: startMs,
periodEnd: startMs + d.periodMs,
included: enterprise ? Number(terms.included) : 0,
includedUsed: 0,
rollover: 0,
rolloverUsed: 0,
rolloverExpiresAt: null,
overageUsed: 0,
overageCap: null,
rolloverCap: enterprise ? Number(terms.rolloverCap) : 0,
linkLimit: enterprise ? Number(terms.linkLimit) : Number(limits[tier] || 0),
linked: [],
autoRenew: false,
renewal: null,
paidUmid: null,
};
} private creditsEffectivePlan(record: any, nowMs: number, cfg: any): any {
const periodMs = this.creditsDefaults().periodMs;
const tiers = ["free", "lite", "hobbyist", "trader", "enterprise"];
if (
!record ||
typeof record !== "object" ||
tiers.indexOf(record.tier) === -1 ||
typeof record.periodEnd !== "number" ||
typeof record.periodStart !== "number"
) {
return this.creditsFreshPlan("free", nowMs, cfg, null);
}
let plan = JSON.parse(JSON.stringify(record));
for (let guard = 0; nowMs >= plan.periodEnd && guard < 2000; guard++) {
const start = plan.periodEnd;
const unused = Math.max(0, Number(plan.included || 0) - Number(plan.includedUsed || 0));
const keepCap = plan.overageCap === undefined ? null : plan.overageCap;
let next: any;
if (plan.tier === "free") {
const skipped = Math.floor((nowMs - start) / periodMs);
next = this.creditsFreshPlan("free", start + skipped * periodMs, cfg, null);
} else if (plan.tier === "enterprise") {
const skipped = Math.floor((nowMs - start) / periodMs);
next = this.creditsFreshPlan("enterprise", start + skipped * periodMs, cfg, plan);
// An idle period's unused allowance is the whole allowance.
next.rollover = Math.min(skipped > 0 ? next.included : unused, next.rolloverCap);
next.linked = (plan.linked || []).slice(0, next.linkLimit);
} else if (plan.renewal && ["lite", "hobbyist", "trader"].indexOf(plan.renewal.tier) !== -1) {
next = this.creditsFreshPlan(plan.renewal.tier, start, cfg, null);
next.rollover = Math.min(unused, next.rolloverCap);
next.autoRenew = plan.autoRenew === true;
// The price the owner agreed to auto-renew at travels with the mandate.
next.agreedPrice = next.autoRenew && plan.agreedPrice ? plan.agreedPrice : null;
next.linked = (plan.linked || []).slice(0, next.linkLimit);
next.paidUmid = plan.renewal.umid || null;
} else {
next = this.creditsFreshPlan("free", start, cfg, null);
}
next.overageCap = keepCap;
next.rolloverExpiresAt = next.rollover > 0 ? next.periodEnd : null;
plan = next;
}
return plan;
}/** The identity's credit balance: `state.credits.balance`, or 0 when absent. */
private creditsBalance(state: any): number {
return state && state.credits && typeof state.credits.balance === "number" ? state.credits.balance : 0;
}/** The monthly allowance spent so far this period: `state.credits.allowance.used`, or 0 when absent. A caller compares it before and after a charge or refund to tell whether the allowance moved (credits-changed). */
private creditsAllowanceUsed(state: any): number {
const a = state && state.credits ? state.credits.allowance : null;
return a && typeof a === "object" && Number.isInteger(a.used) ? a.used : 0;
}/** * Moves the balance by `delta` (whole credits; negative spends). Returns a * refusal, or null after mutating `state.credits`: the new balance, and the * move at the front of `recent` (newest first, at most 50), carrying * `allowance` when the monthly allowance moved too (creditsTakeCharge, * creditsRefundCharge). The balance never goes below zero. A refusal * leaves `state` untouched. */
private creditsMove(state: any, delta: number, reason: CreditReason, umid: string, at: number, allowance?: number): string | null {
const CREDITS_RECENT_MAX = 50;
if (!Number.isInteger(delta)) return "Credits - amount must be a whole number";
const balance = this.creditsBalance(state);
if (balance + delta < 0) return `Credits - not enough credits: this needs ${-delta} and ${balance} are available`;
const credits = state.credits && typeof state.credits === "object" ? state.credits : {};
const next = balance + delta;
const recent = Array.isArray(credits.recent) ? credits.recent : [];
const entry: any = { at, delta, balance: next, reason, umid };
// The monthly allowance's part of a charge (negative) or refund (positive).
if (typeof allowance === "number" && Number.isInteger(allowance) && allowance !== 0) entry.allowance = allowance;
credits.balance = next;
credits.recent = [entry].concat(recent).slice(0, CREDITS_RECENT_MAX);
state.credits = credits;
return null;
}/** `listPrice` less the tier's discount (`cfg.discountsPct[tier]`, 0 when absent), rounded in the user's favour. */
private creditsDiscounted(listPrice: number, tier: string, cfg: any): number {
const pcts = cfg && cfg.discountsPct ? cfg.discountsPct : {};
const pct = typeof pcts[tier] === "number" ? pcts[tier] : 0;
return listPrice - Math.floor((listPrice * pct) / 100);
}/** * The anti-abuse unlock shared by Free's free payout and the monthly * allowance: either 7 days of consensus time have passed since the * identity's first wallet (`state.credits.firstWalletAt`), or its largest * deposit into some stablecoin partition listed in * `cfg.stablecoins[network][token]` (decimals) reached 10 whole units. * Native coins never unlock it. */
private creditsUnlocked(state: any, cfg: any, nowMs: number): boolean {
const FREE_PAYOUT_UNLOCK_MS = 7 * 24 * 60 * 60 * 1000;
const FREE_PAYOUT_MIN_UNITS = 10;
const credits = state && state.credits && typeof state.credits === "object" ? state.credits : {};
if (typeof credits.firstWalletAt === "number" && nowMs >= credits.firstWalletAt + FREE_PAYOUT_UNLOCK_MS) return true;
const coins = cfg && cfg.stablecoins && typeof cfg.stablecoins === "object" ? cfg.stablecoins : {};
const deposits = credits.maxDeposit && typeof credits.maxDeposit === "object" ? credits.maxDeposit : {};
for (const netCode of Object.keys(coins)) {
const tokens = coins[netCode] && typeof coins[netCode] === "object" ? coins[netCode] : {};
for (const token of Object.keys(tokens)) {
const decimals = tokens[token];
const seen = deposits[netCode] ? deposits[netCode][token] : undefined;
if (!Number.isInteger(decimals) || decimals < 0 || decimals > 36) continue;
if (typeof seen !== "string" || !/^[0-9]{1,80}$/.test(seen)) continue;
if (BigInt(seen) >= BigInt(FREE_PAYOUT_MIN_UNITS) * BigInt(10) ** BigInt(decimals)) return true;
}
}
return false;
}/** `cfg.freePayoutsPerMonth`: 1 when absent (the original Free payout), else a whole number; anything else is 0. */
private creditsFreePayoutsPerMonth(cfg: any): number {
const n = cfg ? cfg.freePayoutsPerMonth : undefined;
if (n === undefined || n === null) return 1;
return Number.isInteger(n) && n > 0 ? n : 0;
}/** The free-payout month marker while it still applies at `nowMs`, as `{start, end, used}`, else null. */ private creditsFreePayoutMonth(state: any, nowMs: number): { start: number; end: number; used: number }/**
* Free's free payouts this plan period (any network or token). Open when
* the effective tier is Free, `cfg.freePayoutsPerMonth` (1 when absent) are
* not used up this month (`state.credits.freePayoutMonth`, the plan month
* they were last used in, `{start, end, used}`; a marker without `used`
* counts as 1; it applies while `nowMs` is before its `end`), and the
* identity is unlocked (creditsUnlocked).
*/ private creditsFreePayoutAvailable(state: any, plan: any, cfg: any, nowMs: number): boolean {
if (!plan || plan.tier !== "free" || typeof plan.periodStart !== "number") return false;
const perMonth = this.creditsFreePayoutsPerMonth(cfg);
if (perMonth === 0) return false;
const month = this.creditsFreePayoutMonth(state, nowMs);
if (month && month.used >= perMonth) return false;
return this.creditsUnlocked(state, cfg, nowMs);
}/** * Takes a split charge (creditsSplitCharge) from `state`: the balance part * as one `reason` move recording the allowance part, and the allowance * part added to `state.credits.allowance` for its period (a new period * starts from 0 used). Returns a refusal (the balance moved since vote: a * broken invariant) or null. */
private creditsTakeCharge(state: any, split: any, reason: CreditReason, umid: string, at: number): string | null {
const refusal = this.creditsMove(state, -split.fromBalance, reason, umid, at, -split.fromAllowance);
if (refusal) return refusal;
if (split.fromAllowance > 0) {
const a = state.credits.allowance;
const used = a && typeof a === "object" && a.period === split.allowancePeriod && Number.isInteger(a.used) ? a.used : 0;
state.credits.allowance = { period: split.allowancePeriod, end: split.allowanceEnd, used: used + split.fromAllowance };
}
return null;
}/** * Records a used free payout: `state.credits.freePayoutMonth` is the plan * month it was taken in, with `used` counting the month's free payouts. An * identity with no plan record gets a month that starts now * (creditsEffectivePlan's fresh Free plan), so this marker - not the plan * record, which belongs to Varnir.Plans - keeps the count per month. */
private creditsUseFreePayout(state: any, charge: any): void {
const credits = state.credits && typeof state.credits === "object" ? state.credits : {};
const month = credits.freePayoutMonth;
const same = month && typeof month === "object" && month.start === charge.periodStart;
const used = same ? (Number.isInteger(month.used) && month.used >= 0 ? month.used : 1) : 0;
credits.freePayoutMonth = { start: charge.periodStart, end: charge.periodEnd, used: used + 1 };
state.credits = credits;
}/** * Gives back a withdrawal charge whose payout did not happen, where it came * from. A used free payout comes back only while the marker is still the * month it was taken in (a later month has its own). The charge's * `fromAllowance` goes back to the allowance only while * `state.credits.allowance` is still the period it was taken from * (`allowancePeriod`); otherwise it lapses. The rest (`fromBalance`, or * the whole `credits` on a charge with no split) comes back as one * "refund" move. Returns the credits given back to the balance. The caller * guards against refunding twice. */
private creditsRefundCharge(state: any, charge: any, umid: string, at: number): number {
if (!charge || typeof charge !== "object") return 0;
if (charge.freePayout === true) {
const credits = state && state.credits && typeof state.credits === "object" ? state.credits : null;
const month = credits ? credits.freePayoutMonth : null;
if (month && typeof month === "object" && month.start === charge.periodStart) {
const used = Number.isInteger(month.used) && month.used >= 0 ? month.used : 1;
credits.freePayoutMonth = used > 1 ? { start: month.start, end: month.end, used: used - 1 } : null;
}
return 0;
}
const n = charge.credits;
if (!Number.isInteger(n) || n <= 0) return 0;
const fromAllowance = Number.isInteger(charge.fromAllowance) && charge.fromAllowance > 0 && charge.fromAllowance <= n ? charge.fromAllowance : 0;
const fromBalance = n - fromAllowance;
let restored = 0;
const credits = state && state.credits && typeof state.credits === "object" ? state.credits : null;
const a = credits ? credits.allowance : null;
if (fromAllowance > 0 && a && typeof a === "object" && a.period === charge.allowancePeriod && Number.isInteger(a.used)) {
restored = Math.min(fromAllowance, a.used);
a.used -= restored;
}
if (fromBalance === 0 && restored === 0) return 0;
return this.creditsMove(state, fromBalance, "refund", umid, at, restored) === null ? fromBalance : 0;
}/**
* One spelling per network, for comparing two that came from different
* places. The ledger's own code ("TRX-NILE") and the pregen pool's
* ("niles") both name Tron Nile; neither is more correct, they just have to
* be comparable. Lower-cases, and folds the Tron Nile and Shasta spellings.
*/ private canonicalNetwork(network: string): string {
switch (network.toLowerCase()) {
case 'trx-nile':
case 'niles':
return 'niles';
case 'trx-shasta':
case 'shasta':
return 'shasta';
default:
return network.toLowerCase();
}
}/** Advanced (mpc2) wallets are priced as `walletAdvanced` and are never the sign-up wallet. */
private creditsIsAdvancedWallet(state: any): boolean {
return state.mpcProtocol !== undefined || state.keyMethod === "mpc-tss";
}/** 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;
}/** Varnir's consolidation block on the plans config when its `addressCharge` is on, else null. */
private depositBlock(cfg: any): any {
const c = cfg && cfg.varnirPrices ? cfg.varnirPrices.consolidation : undefined;
return c && typeof c === "object" && !Array.isArray(c) && c.addressCharge === true ? c : null;
}/** The plans config (PLANS_CONFIG_STREAM), or null where none is named (production); unreadable throws `unreadable`. */
private async depositPlansConfig(unreadable: string): Promise<any> {
if (!PLANS_CONFIG_STREAM) return null;
let cfg: any;
try {
cfg = await this.getAnyStreamReadOnly(PLANS_CONFIG_STREAM);
} catch (e) {
throw unreadable;
}
if (!cfg || typeof cfg !== "object" || cfg.kind !== "varnir.plans.config") throw unreadable;
return cfg;
}/**
* Vote, for an assignment carrying `$i.owner.tenant`: what the tenant pays, as `{prep, plan, wallets, version,
* multiplierPct}`. tenantPrepare checks the tag as for a transfer (the tenant, the sender's shard, suspension, the
* fee-config version). Refused before anything is written:
* - `addressCharge` is off, or the shard holds no float (a tenant pays for wallets only on the float);
* - the shard is not `$i.tenant` signed by a LIVE `tenant` authority (the tenant approves each charge to its float);
* - a wallet's `$o` entry has no `asset` ("native" or "token"), or Varnir lists no `addressPrice` for that network and
* class: refused, never free;
* - O1: the float cannot pay the total (tenantFloatPlan).
* Each wallet costs addressPrice[network][asset] x the tenant's current consolidation multiplier (its parent's for a
* sub-tenant), rounded up to a whole credit. The identity's own credits are never read (D2).
*/ private depositPlan(block: any, ownerId: string, labels: string[], now: number): any {
const tx: any = this.transactions;
if (!block) throw "Tenants - Varnir does not charge tenants for deposit wallets yet (addressCharge is off): create the wallet without the tenant tag";
if (tx.$o && tx.$o.tenant) throw "Tenants - a tenant deposit wallet names the tenant's shard in $i.tenant, signed by the tenant key";
if (labels.length < 1 || labels.length > 20) throw "Tenants - a tenant assignment hands out 1 to 20 wallets";
const prep = this.tenantPrepare("wallet.deposit", ownerId, "0");
if (prep.fee !== "0") throw "Tenants - a tenant fee on a deposit wallet is not supported";
const st: any = prep.shard.getState();
if (st.float === undefined || st.float === null) throw "Tenants - a tenant pays for deposit wallets only once it runs on the credit float: create the wallet without the tenant tag";
const signed = (this as any).sigs && (this as any).sigs[prep.shard.getId()];
const hashes = signed ? Object.keys(signed) : [];
const live = (prep.shard.getAuthorities() || []).some((a: any) => {
if (!a || a.label !== "tenant" || !a.hash || hashes.indexOf(a.hash) === -1) return false;
if (a.expire === undefined) return true;
const at = new Date(a.expire).getTime();
return !Number.isNaN(at) && at > now;
});
if (!live) throw "Tenants - a tenant deposit wallet needs a live tenant key's signature on the shard ($i.tenant): create it through the tenant's gateway";
const masterRead = !!(tx.$r && tx.$r.tenant !== undefined && tx.$r.tenant !== null);
const master: any = masterRead ? this.getReadOnlyStream("tenant") : this.tenantCopyAsMaster(prep.shard, prep.tenantId, tx.$i.owner.tenant.version, now);
let m: any;
if (typeof master.parentId === "string") {
const parent: any = this.getReadOnlyStream("parent");
m = parent ? parent.consolidationMultiplier : undefined;
} else {
m = masterRead ? master.consolidationMultiplier : st.copy ? st.copy.consolidationMultiplier : undefined;
}
let multiplierPct = 100;
if (m !== undefined && m !== null) {
if (typeof m !== "object" || [100, 125, 150, 200, 300].indexOf(m.pct) === -1) throw "Tenants - this tenant's consolidation multiplier is malformed: create the wallet without the tenant tag";
multiplierPct = m.pct;
}
const prices = block.addressPrice && typeof block.addressPrice === "object" ? block.addressPrice : {};
const wallets: any = {};
let total = 0;
// Security review (F4): the same wallet stream under two labels would be charged twice but marked once.
const seen: string[] = [];
for (const label of labels) {
const asset = tx.$o[label].asset;
if (asset !== "native" && asset !== "token") throw `Tenants - a tenant deposit wallet names its asset class ($o.${label}.asset: native or token)`;
const stream: any = this.getActivityStreams(tx.$o[label]);
const id = stream.getId();
if (seen.indexOf(id) !== -1) throw "Tenants - a deposit wallet is named twice";
seen.push(id);
const w: any = stream.getState() || {};
const netCode = this.canonicalNetwork(String(w.network));
const entry = prices[netCode] && typeof prices[netCode] === "object" ? prices[netCode][asset] : undefined;
if (!Number.isSafeInteger(entry) || entry < 0 || entry > 100000) throw `Tenants - Varnir has no address price for ${asset} deposit wallets on ${netCode}: create the wallet without the tenant tag`;
const credits = Math.floor((entry * multiplierPct + 99) / 100);
wallets[label] = { asset, credits };
total += credits;
}
const priced = { ...prep, usage: String(total) };
return { prep: priced, plan: this.tenantFloatPlan(priced, false), wallets, version: block.version, multiplierPct };
}/** Commit, after depositPlan: the total in the shard's usage and taken from its float (tenantFloatApply, which emits tenant-charged). */
private depositTake(): void {
const d = this.tenantDeposit;
const st: any = d.prep.shard.getState();
const fees: any = st.fees || {};
d.prep.shard.setState({ ...st, fees, usage: (BigInt(st.usage || "0") + BigInt(d.prep.usage)).toString() });
this.tenantFloatApply(d.plan, d.prep);
}/** * The member rule (docs/plans/tenant-pays-stage-f-consolidation-pricing.md §3.2, answer 5; `memberUntaggedWallets`), * for an UNTAGGED new wallet while `addressCharge` is on (`block`, Varnir's consolidation block): with "refuse", an * identity holding an unexpired membership record (`tm`, written only by Varnir.Tenants `join`) is refused unless its * tenant cannot take the wallet itself: * - the tenant is not on the credit float; * - the tenant master's `suspended` is exactly true, or it is a sub-tenant whose parent, named as `$r.memberParent`, * is suspended (exactly true). * The master is `$r.memberOf` when the transaction names it (the fast path). Otherwise, when the record carries `m` * (the master's stream id, written by `join`), it is read by that id (a plain read: no lock). Either way the master * is bound to the record: its `tenantId` must be the id it was read under and the record's hash `h` is recomputed * from it (for a sub-tenant: its parent and itself), so a wrong or forged master or `m` lifts nothing (nor does a * sub-tenant reparented or detached since `join`: its member must leave or join again); a parent that is not this * sub-tenant's is refused. Known limitation: the master (and parent) read is each node's local copy, not pinned to * a revision, so a node a revision behind on `suspended`, `floatMode` or `revokedBefore` can vote differently around * a flip; the master is rarely written, and a retry resolves it. A record issued at or before the tenant's `revokedBefore` is no membership. * A wallet let through is priced to the identity exactly as for a non-member (the caller's creditsPriceWallets, * creditsWalletCharge): the first Standard wallet per network is the free sign-up wallet and the monthly allowance * is drawn first, so Varnir carries those as it does for anyone; the tenant pays nothing. Why not, or null. */
private async memberRuleRefusal(block: any, ownerId: string, ownerState: any, now: number): Promise<string | null> {
if (!block || block.memberUntaggedWallets !== "refuse") return null;
const tm = ownerState && ownerState.tm;
if (!tm || typeof tm !== "object" || !Number.isSafeInteger(tm.expires) || !(now < tm.expires)) return null;
const r: any = this.transactions.$r || {};
const idOf = (ref: any) => (ref !== null && typeof ref === "object" ? ref.$stream : ref);
let refId: any;
let master: any;
let via: string;
if (r.memberOf !== undefined && r.memberOf !== null) {
refId = idOf(r.memberOf);
via = "$r.memberOf";
master = this.getReadOnlyStream("memberOf");
} else if (typeof tm.m === "string" && /^[0-9a-f]{64}$/.test(tm.m)) {
refId = tm.m;
via = "the tenant master this identity's membership record names (tm.m " + tm.m + ")";
try {
master = await this.getAnyStreamReadOnly(tm.m);
} catch (e) {
return "Tenants - this identity's tenant master could not be read; the wallet was not created, try again shortly (or name its master as $r.memberOf)";
}
} else {
return "Tenants - this identity belongs to a tenant: create its deposit wallets through the tenant (a tenant not on the credit float or suspended: name its master as $r.memberOf)";
}
if (!master || master.kind !== "varnir.tenant" || typeof master.tenantId !== "string" || master.tenantId !== refId) return "Tenants - " + via + " is not a tenant master";
// A sub-tenant reparented or detached since `join` no longer hashes to the record either: the message says so.
if (tm.h !== this.memberLiftHash(master, ownerId)) return "Tenants - " + via + " is not the tenant this identity belongs to, or its parent has changed since this identity joined (the membership no longer matches the tenant's current parent): leave the tenant or join it again";
const before = Number.isSafeInteger(master.revokedBefore) ? master.revokedBefore : 0;
if (!Number.isSafeInteger(tm.issued) || !(tm.issued > before)) return null;
if (master.floatMode !== true) return null;
if (master.suspended === true) return null;
if (r.memberParent !== undefined && r.memberParent !== null) {
if (typeof master.parentId !== "string" || idOf(r.memberParent) !== master.parentId) return "Tenants - $r.memberParent is not this sub-tenant's parent";
const parent: any = this.getReadOnlyStream("memberParent");
if (!parent || parent.kind !== "varnir.tenant" || parent.tenantId !== master.parentId) return "Tenants - $r.memberParent is not this sub-tenant's parent";
if (parent.suspended === true) return null;
}
return "Tenants - this identity belongs to a tenant that runs on the credit float: create its deposit wallets through the tenant";
}/** The membership record's hash (Varnir.Tenants `join`): sha256(tenantId|subId|senderId|"varnir.tenant.member"), a sub naming its parent and itself. */
private memberLiftHash(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");
} public postProcess(territoriality: boolean, who: string): Promise<any> {
return new Promise<any>((resolve) => resolve(true));
}/** * Throws unless the self-signer is a gateway: `$r.minigate` is a stream * whose volatile carries the `minigate` flag (only an operator writes it), * and `$i.admin.publicKey` is one of its authorities. Both are needed (the * same proof as Varnir.CryptoTransfer's assertMinigateSigner). */
private async assertGatewaySigner(): Promise<void> {
const ref = this.transactions.$r ? this.transactions.$r.minigate : undefined;
if (!ref) {
throw "replacefrozen: not authorised - missing minigate reference";
}
const volatile: any = await this.getAnyStreamReadOnly(`${ref}:volatile`);
if (!volatile || !volatile.minigate) {
throw "replacefrozen: not authorised - reference is not a minigate";
}
const key = this.transactions.$i && this.transactions.$i.admin ? this.transactions.$i.admin.publicKey : undefined;
const meta: any = await this.getAnyStreamReadOnly(`${ref}:stream`);
if (!key || !meta || !Array.isArray(meta.authorities) || !meta.authorities.some((a: any) => a.public === key)) {
throw "replacefrozen: not authorised - signing key is not a minigate authority";
}
}/** * `replacefrozen` vote. Each check, and why: * - a gateway submits it (assertGatewaySigner): it is housekeeping no user * asks for; * - the frozen wallet carries the ledger's `mpcFrozen`, recorded by the * node quorum (KeyHealthCheck `mpcfreeze`): no gateway can move a user * off a wallet that still works; * - it has an owner, and the new wallet gets THAT owner: the gateway never * chooses who owns what, it carries the ledger's own record across * (ordinary assignment stays owner-signed); * - it was not replaced before (`replacedBy`): one replacement per freeze, * whichever gateway is first; * - the new wallet is another pool deposit wallet on the same network that * may take coins: unassigned, not a change wallet or a book, and passing * the pool lifecycle rule (not retired, frozen or purged; an Advanced * one canaried). Advanced or Standard: Standard is the gateway's fallback * when no Advanced wallet is free. */ /** * The ledger freeze switch: true only when CryptoTransfer's contract data * holds `mpc2FreezeEnabled: true`. Missing, false, malformed, unreadable or * an unconfigured contract id is OFF (Adam 2026-10-09): nothing is frozen * on the ledger while it is off, so the frozen-key paths stay shut. */
private async mpc2FreezeOn(): Promise<boolean> {
const id = this.mpc2FlagContract();
if (!/^[0-9a-f]{64}$/.test(id)) {
return false;
}
try {
const doc: any = await this.getAnyStreamReadOnly(`${id}:data`);
const data = doc && typeof doc === "object" && doc.data && typeof doc.data === "object" ? doc.data : {};
return data.mpc2FreezeEnabled === true;
} catch (e) {
return false;
}
}/** * The signed-proof switch (decision 2026-10-10, review M3 of PR #430): true * only when Varnir.CryptoTransfer's contract data holds * `mpc2RequireSignedProof: true`. Missing, false, malformed, unreadable or * an unconfigured contract id is OFF, which is the rule before the switch * (a canary or a signed proof admits an Advanced wallet). */
private async mpc2SignedProofRequired(): Promise<boolean> {
const id = this.mpc2FlagContract();
if (!/^[0-9a-f]{64}$/.test(id)) {
return false;
}
try {
const doc: any = await this.getAnyStreamReadOnly(`${id}:data`);
const data = doc && typeof doc === "object" && doc.data && typeof doc.data === "object" ? doc.data : {};
return data.mpc2RequireSignedProof === true;
} catch (e) {
return false;
}
}/** The per-tree constant, read in one place (tests pin another value here). */
private mpc2FlagContract(): string {
return MPC2_FLAG_CONTRACT;
} private async voteReplaceFrozen(): Promise<void> {
await this.assertGatewaySigner();
// Behind the freeze flag (Adam 2026-10-09): no new address on freeze while it is off.
if (!(await this.mpc2FreezeOn())) {
throw "replacefrozen: the ledger freeze is off (mpc2FreezeEnabled)";
}
const o = this.transactions.$o || {};
if (!o.frozen || !o.wallet) {
throw "replacefrozen: needs $o.frozen and $o.wallet";
}
const frozen = this.getActivityStreams(o.frozen);
const wallet = this.getActivityStreams(o.wallet);
if (frozen.getId() === wallet.getId()) {
throw "replacefrozen: a wallet cannot replace itself";
}
const f: any = frozen.getState();
const w: any = wallet.getState();
if (!f || f.mpcFrozen === undefined) {
throw "replacefrozen: the wallet is not frozen on the ledger";
}
if (typeof f.owner !== "string" || f.owner.length === 0) {
throw "replacefrozen: the frozen wallet has no owner";
}
if (f.replacedBy !== undefined) {
throw "replacefrozen: already replaced";
}
if (!w || w.owner) {
throw "Key already assigned";
}
const poolOnly = this.poolOnlyRefusal(w);
if (poolOnly) {
throw poolOnly;
}
// A real pool deposit wallet for the same asset (PR #417 review M2): the
// replacement is one-shot (`replacedBy`), so a bad pick would be for good.
// Any unowned stream with a `network` would otherwise pass: an `l1.sign`
// record, a wallet of another asset, a Bitcoin wallet with no UTXO book,
// whose deposits Varnir.Deposit could never credit.
if (w.role !== "deposit") {
throw "replacefrozen: the new wallet is not a deposit wallet";
}
if (typeof w.address !== "string" || w.address.length === 0) {
throw "replacefrozen: the new wallet has no address";
}
if (typeof w.network !== "string" || w.network !== f.network) {
throw "replacefrozen: the new wallet is on another network";
}
if (w.symbol !== f.symbol) {
throw "replacefrozen: the new wallet is for another asset";
}
if (f.utxoBook !== undefined && typeof w.utxoBook !== "string") {
throw "replacefrozen: a Bitcoin deposit wallet needs its UTXO book";
}
if (w.signed !== undefined || w.btc !== undefined || w.sender !== undefined || w.umidActual !== undefined || w.preSignedStream !== undefined) {
throw "replacefrozen: the new wallet is a signing record, not a wallet";
}
const lifecycle = this.poolLifecycleRefusal(w, await this.mpc2SignedProofRequired());
if (lifecycle) {
throw `Cannot be assigned: ${lifecycle}`;
}
// The owner identity rides as `$r.owner` (PR #417 review L4): one that
// was socially recovered hands the new wallet to its successor
// (`recoveredTo`), so it lands in the account its owner uses now.
const ownerRef = this.transactions.$r ? this.transactions.$r.owner : undefined;
if (ownerRef !== f.owner) {
throw "replacefrozen: the frozen wallet's owner must be a reference ($r.owner)";
}
const owner: any = this.getReadOnlyStream("owner");
const next = owner && typeof owner.recoveredTo === "string" && /^[0-9a-f]{64}$/.test(owner.recoveredTo) ? owner.recoveredTo : f.owner;
this.replaceOwner = next;
}/** `replacefrozen` commit: see the block comment. */
private commitReplaceFrozen(): void {
const frozen = this.getActivityStreams(this.transactions.$o.frozen);
const wallet = this.getActivityStreams(this.transactions.$o.wallet);
const f: any = frozen.getState();
const w: any = wallet.getState();
w.owner = this.replaceOwner;
w.assignUmid = this.umid;
w.replaces = frozen.getId();
if (f.business === false) {
w.business = false;
} else {
w.firstDeposit = {};
}
wallet.setState(w);
f.replacedBy = {wallet: wallet.getId(), at: this.cDate, umid: this.umid};
frozen.setState(f);
this.event.emit("wallet-assigned", {
stream: wallet.getId(),
network: w.network,
symbol: w.symbol,
address: w.address,
owner: this.replaceOwner,
});
this.event.emit("wallet-replaced", {
stream: frozen.getId(),
replacedBy: wallet.getId(),
network: f.network,
address: f.address,
owner: this.replaceOwner,
keyMethod: w.keyMethod === "mpc-tss" ? "mpc-tss" : "standard",
});
this.returnToRemote({id: wallet.getId(), address: w.address, replaces: frozen.getId()});
}