Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirPlans extends Event
/** * Voting round: the social-recovery guard (`$o` config, target and other * only receive, so they may be recovered or frozen), then * dispatch(false) - validate only; a thrown string is the refusal. */
public vote(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
try {
const refusal = this.refuseRecoveredStreams(this.incomingLabels());
if (refusal) return reject(refusal);
await this.dispatch(false);
resolve(true);
} catch (e) {
reject(typeof e === "string" ? e : (e as Error).message);
}
});
}/** Commit round: dispatch(true) - validate again, 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 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;
}/** * Runs the entry named by `$entry`. Admin (requireAdmin): createConfig, * configure, setWeights, assignEnterprise, endEnterprise, grantCredits * (testnet only). Owner key * (requireOwnerKey): subscribe, renew, setAutoRenew, link, unlink, * grantTestCredits (testnet only), holdService. Gateway (requireMinigate): * autoRenew, captureService. Either: releaseService. Anything else is * refused. */
private async dispatch(apply: boolean): Promise<void> {
switch (this.transactions.$entry) {
case "createConfig": return this.runCreateConfig(apply);
case "configure": return this.runConfigure(apply);
case "setWeights": return this.runSetWeights(apply);
case "subscribe": return this.runSubscribe(apply);
case "renew": return this.runRenew(apply);
case "setAutoRenew": return this.runSetAutoRenew(apply);
case "autoRenew": return this.runAutoRenew(apply);
case "assignEnterprise": return this.runAssignEnterprise(apply);
case "endEnterprise": return this.runEndEnterprise(apply);
case "link": return this.runLink(apply);
case "unlink": return this.runUnlink(apply);
case "grantTestCredits": return this.runGrantTestCredits(apply);
case "grantCredits": return this.runGrantCredits(apply);
case "holdService": return this.runHoldService(apply);
case "captureService": return this.runCaptureService(apply);
case "releaseService": return this.runReleaseService(apply);
default:
throw `Unknown entry ${this.transactions.$entry}`;
}
}/** $o labels that only RECEIVE (a recovered identity may still receive). */
private incomingLabels(): string[] {
return ["config", "target", "other"];
}/** * `createConfig` (admin, once): validates the settings (prices required; * actionPrices, discountsPct, stablecoins, creditsLive, monthlyAllowance * and freePayoutsPerMonth optional), * creates the `varnir.plans.config` stream (owned by the admin's * authorities; link limits and weights from creditsDefaults; creditsLive off unless set) and pins its id in contract data. * Emits `plans-config-created`. */
private async runCreateConfig(apply: boolean): Promise<void> {
const admin = await this.requireAdmin();
if (this.getContractDataHelper().configStream) throw "Plans - config already exists";
const input: any = this.transactions.$i.admin;
const settings = this.validSettings(input, true);
if (settings.meterPrices !== undefined) this.requireLiveStake100(admin, "Plans - meter prices change only with a live (unexpired) admin key");
const meterPrices = settings.meterPrices !== undefined ? this.versionMeterPrices(settings.meterPrices, null, 0, admin.getId()) : null;
// >>> tenant-pays
const consolidated = settings.varnirPrices ? this.versionConsolidation(settings.varnirPrices, null, 0) : null;
if (consolidated) this.requireLiveStake100(admin, "Plans - Varnir's consolidation prices change only with a live (unexpired) admin key");
// <<< tenant-pays
if (!apply) return;
const d = this.creditsDefaults();
const now = this.now();
const created = this.newActivityStream(CONFIG_KIND);
created.setAuthorities(admin.getAuthorities());
const config: any = {
kind: CONFIG_KIND,
plansContract: this.contractId(),
prices: settings.prices,
linkLimits: d.linkLimits,
creditsLive: settings.creditsLive === true,
weights: d.weights,
createdAt: now,
createdBy: this.umid,
updatedAt: now,
updatedBy: this.umid,
weightsUpdatedAt: now,
weightsUpdatedBy: this.umid,
};
for (const key of ["actionPrices", "discountsPct", "stablecoins", "monthlyAllowance", "freePayoutsPerMonth", "servicePrices", "serviceHoldMs", "serviceTiers"]) {
if (settings[key] !== undefined) config[key] = settings[key];
}
if (meterPrices && meterPrices.block !== undefined) {
config.meterPrices = meterPrices.block;
config.meterPricesSeq = meterPrices.seq;
}
// >>> tenant-pays
if (settings.varnirPrices !== undefined) config.varnirPrices = settings.varnirPrices;
if (consolidated) config.consolidationSeq = consolidated.version;
// <<< tenant-pays
created.setState(config);
this.setContractData({ ...this.getContractDataHelper(), configStream: created.getId() });
this.event.emit("plans-config-created", { stream: created.getId() });
if (meterPrices && meterPrices.event) this.event.emit("meter-prices-set", { stream: created.getId(), ...meterPrices.event, by: admin.getId(), umid: this.umid, at: now });
// >>> tenant-pays
if (consolidated) this.event.emit("consolidation-configured", { stream: created.getId(), ...consolidated, by: admin.getId(), umid: this.umid, at: now });
// <<< tenant-pays
}/** * `configure` (admin): merges the validated settings present on * `$i.admin` into the config on `$o.config`. The retired fields (revenue, * priceAsset, autoRenewEnabled, allowances, rolloverCaps) are written as * null - setState merges, so a delete would not stick. Emits * `plans-config-updated`. */
private async runConfigure(apply: boolean): Promise<void> {
const setter = await this.requireAdmin();
const { stream, state } = this.writableConfig();
const settings = this.validSettings(this.transactions.$i.admin, false);
if (settings.meterPrices !== undefined) this.requireLiveStake100(setter, "Plans - meter prices change only with a live (unexpired) admin key");
const meterPrices = settings.meterPrices !== undefined ? this.versionMeterPrices(settings.meterPrices, state.meterPrices, state.meterPricesSeq, setter.getId()) : null;
// A no-op on a config with no table leaves the field out, so nothing is written for it.
if (meterPrices && meterPrices.block === undefined) delete settings.meterPrices;
else if (meterPrices) settings.meterPrices = meterPrices.block;
// >>> tenant-pays
const admin = this.named("$i", "admin");
const consolidated = settings.varnirPrices ? this.versionConsolidation(settings.varnirPrices, state.varnirPrices, state.consolidationSeq) : null;
if (consolidated) this.requireLiveStake100(admin, "Plans - Varnir's consolidation prices change only with a live (unexpired) admin key");
// <<< tenant-pays
const retired = { revenue: null, priceAsset: null, autoRenewEnabled: null, allowances: null, rolloverCaps: null };
const merged = { ...state, ...settings, ...retired };
if (!apply) return;
merged.updatedAt = this.now();
merged.updatedBy = this.umid;
if (meterPrices) merged.meterPricesSeq = meterPrices.seq;
// >>> tenant-pays
if (consolidated && !consolidated.removed) merged.consolidationSeq = consolidated.version;
// <<< tenant-pays
stream.setState(merged);
this.event.emit("plans-config-updated", { stream: stream.getId(), fields: Object.keys(settings) });
if (meterPrices && meterPrices.event) this.event.emit("meter-prices-set", { stream: stream.getId(), ...meterPrices.event, by: setter.getId(), umid: this.umid, at: this.now() });
// >>> tenant-pays
if (consolidated && consolidated.removed) this.event.emit("consolidation-removed", { stream: stream.getId(), previousVersion: consolidated.previousVersion, by: admin.getId(), umid: this.umid, at: this.now() });
else if (consolidated) this.event.emit("consolidation-configured", { stream: stream.getId(), ...consolidated, by: admin.getId(), umid: this.umid, at: this.now() });
// <<< tenant-pays
}/** * The stored shape after a validated setWeights: only the fields * creditsWeightsRefusal checked, dropping anything else the caller sent - * e.g. stray keys, or a stale live.gasMicroUsd entry for a network that * isn't live this update - so contract data never carries forward a value * that was never actually bounded. */
private creditsWeightsShape(next: any): any {
const shape = (e: any) => (e && e.live === true ? { live: true } : { instant: e.instant, standard: e.standard, economy: e.economy });
const networks: any = {};
for (const name of Object.keys(next.networks)) {
// Not `net` - see creditsWeight's own note on the sandbox's blocklist.
const netEntry = next.networks[name];
networks[name] = { native: shape(netEntry.native), token: shape(netEntry.token) };
}
const out: any = { networks };
if (next.live !== undefined && next.live !== null) {
const live = next.live;
out.live = {
factorsPct: { instant: live.factorsPct.instant, standard: live.factorsPct.standard, economy: live.factorsPct.economy },
minimums: { instant: live.minimums.instant, standard: live.minimums.standard, economy: live.minimums.economy },
creditMicroUsd: live.creditMicroUsd,
gasMicroUsd: {},
};
for (const name of Object.keys(networks)) {
if (networks[name].token.live === true) out.live.gasMicroUsd[name] = live.gasMicroUsd[name];
}
}
return out;
}/** * `setWeights` (admin): replaces the credit weights on the config after * creditsWeightsRefusal accepts them, storing only the checked shape. * Emits `plans-weights-updated`. */
private async runSetWeights(apply: boolean): Promise<void> {
await this.requireAdmin();
const { stream, state } = this.writableConfig();
const next = (this.transactions.$i.admin as any).weights;
const refusal = this.creditsWeightsRefusal(next, state.weights);
if (refusal) throw refusal;
if (!apply) return;
state.weights = this.creditsWeightsShape(next);
state.weightsUpdatedAt = this.now();
state.weightsUpdatedBy = this.umid;
stream.setState(state);
this.event.emit("plans-weights-updated", { stream: stream.getId(), when: state.weightsUpdatedAt });
}/** * The settable config fields present on `input`, validated. `required` * (createConfig) demands prices. Prices are whole credits a month. */
private validSettings(input: any, required: boolean): any {
const out: any = {};
const has = (k: string) => input && input[k] !== undefined;
if (required || has("prices")) {
const p = input.prices;
for (const tier of PAID_TIERS) {
if (!p || !this.creditsIsCount(p[tier], CREDIT_PRICE_MAX) || p[tier] === 0) {
throw `Plans - prices.${tier} must be a whole number of credits from 1 to ${CREDIT_PRICE_MAX}`;
}
}
out.prices = { lite: p.lite, hobbyist: p.hobbyist, trader: p.trader };
}
const counts = (key: string, tiers: string[], max: number) => {
if (!has(key)) return;
const v = input[key];
for (const tier of tiers) {
if (!v || !this.creditsIsCount(v[tier], max)) throw `Plans - ${key}.${tier} must be a whole number from 0 to ${max}`;
}
out[key] = {};
for (const tier of tiers) out[key][tier] = v[tier];
};
counts("actionPrices", ["walletStandard", "walletAdvanced"], CREDIT_PRICE_MAX);
counts("discountsPct", PAID_TIERS, 100);
// Refused rather than ignored, so an admin is told plainly: a tier adds
// no credits, and creditsFreshPlan no longer reads either field.
if (has("allowances") || has("rolloverCaps")) throw "Plans - allowances and rolloverCaps are retired: a tier adds no credits";
counts("linkLimits", ["trader"], 100);
if (has("stablecoins")) out.stablecoins = this.validStablecoins(input.stablecoins);
if (has("creditsLive")) {
if (typeof input.creditsLive !== "boolean") throw "Plans - creditsLive must be true or false";
out.creditsLive = input.creditsLive;
}
// The monthly allowance (free credits a period, spent before the balance
// on withdrawals and wallets; 0 is none) and Free's free payouts a month
// (1 when never set; 0 is none). The credits-ledger block reads both.
if (has("monthlyAllowance")) {
if (!this.creditsIsCount(input.monthlyAllowance, CREDIT_PRICE_MAX)) {
throw `Plans - monthlyAllowance must be a whole number of credits from 0 to ${CREDIT_PRICE_MAX}`;
}
out.monthlyAllowance = input.monthlyAllowance;
}
if (has("freePayoutsPerMonth")) {
if (!this.creditsIsCount(input.freePayoutsPerMonth, 100)) throw "Plans - freePayoutsPerMonth must be a whole number from 0 to 100";
out.freePayoutsPerMonth = input.freePayoutsPerMonth;
}
if (has("plans")) out.plans = this.validPlans(input.plans);
// Off-ledger service pricing (holdService): the prices, how long a hold
// lasts, and which plans each service is open to (the kill switch).
if (has("servicePrices")) out.servicePrices = this.validServicePrices(input.servicePrices);
if (has("serviceHoldMs")) {
const ms = input.serviceHoldMs;
if (!this.creditsIsCount(ms, 3600000) || ms < 60000) throw "Plans - serviceHoldMs must be a whole number of ms from 60000 to 3600000";
out.serviceHoldMs = ms;
}
if (has("serviceTiers")) out.serviceTiers = this.validServiceTiers(input.serviceTiers);
// The meter price table (plan §2.2). `null` empties it: every meter costs 0.
if (has("meterPrices")) out.meterPrices = input.meterPrices === null ? null : this.validMeterPrices(input.meterPrices);
// >>> tenant-pays
// `null` is the explicit OFF switch: stored as null, which Varnir.Tenants reads as no floor.
if (has("varnirPrices")) out.varnirPrices = input.varnirPrices === null ? null : this.validVarnirPrices(input.varnirPrices);
// <<< tenant-pays
return out;
}/**
* `servicePrices`: `{[price key]: credits}`, e.g. `{"check.basic": 100,
* "check.maxCredits": 1000}`. A key is the service id and a dotted name;
* `<service>.maxCredits` is that service's cap on one hold, not a price.
* Replaced whole on each configure.
*/ private validServicePrices(v: any): any {
if (!v || typeof v !== "object" || Array.isArray(v)) throw "Plans - servicePrices must be an object of price key to credits";
const keys = Object.keys(v);
if (keys.length > 100) throw "Plans - servicePrices may hold at most 100 prices";
const out: any = {};
for (const k of keys) {
if (!SERVICE_PRICE_KEY.test(k)) throw `Plans - servicePrices key ${k.slice(0, 64)} must be a service id and a dotted name, like check.basic`;
if (!this.creditsIsCount(v[k], CREDIT_PRICE_MAX)) throw `Plans - servicePrices.${k} must be a whole number of credits from 0 to ${CREDIT_PRICE_MAX}`;
out[k] = v[k];
}
return out;
}/**
* `serviceTiers`: `{[service id]: plan tiers it is open to}`. A service
* that is absent or lists none is switched off (holdService refuses it).
* Replaced whole on each configure.
*/ private validServiceTiers(v: any): any {
if (!v || typeof v !== "object" || Array.isArray(v)) throw "Plans - serviceTiers must be an object of service id to the plans it is open to";
const ids = Object.keys(v);
if (ids.length > 20) throw "Plans - serviceTiers may list at most 20 services";
const out: any = {};
for (const id of ids) {
if (!SERVICE_ID.test(id)) throw `Plans - serviceTiers key ${id.slice(0, 64)} must be a service id`;
const list = v[id];
if (!Array.isArray(list) || list.some((t: any, i: number) => SERVICE_TIERS.indexOf(t) === -1 || list.indexOf(t) !== i)) {
throw `Plans - serviceTiers.${id} must list different plans from ${SERVICE_TIERS.join(", ")} ([] switches it off)`;
}
out[id] = list.slice();
}
return out;
}/** The METER_REGISTRY entry for a meter id ([id, ceiling, protection]), or null when the registry has none. */
private meterEntry(id: string): any {
for (const entry of METER_REGISTRY) if (entry[0] === id) return entry;
return null;
}/**
* `meterPrices` as the admin sends it: `{reason, meters: {[meter id]: {hub, tenant}}}`, replaced whole on each write,
* so a meter left out costs 0. Every id must be in METER_REGISTRY, both prices are whole credits from 0 to
* METER_PRICE_MAX, and a protection meter takes 0 only. The meters are rebuilt in registry order, leaving out any at
* 0 and 0, so the stored table never depends on the caller's key order. versionMeterPrices checks the move against
* the stored table and adds version, setAt, setBy and previous.
*/ private validMeterPrices(v: any): any {
const isMap = (m: any) => !!m && typeof m === "object" && !Array.isArray(m);
if (!isMap(v) || !isMap(v.meters)) throw "Plans - meterPrices must be {reason, meters: {meter id: {hub, tenant}}}";
for (const k of Object.keys(v)) {
if (k !== "reason" && k !== "meters") throw `Plans - meterPrices.${k.slice(0, 32)} is not a field (reason, meters)`;
}
if (typeof v.reason !== "string" || v.reason.trim().length === 0 || v.reason.length > METER_REASON_MAX) {
throw `Plans - meterPrices.reason must say why, in 1 to ${METER_REASON_MAX} characters`;
}
for (const id of Object.keys(v.meters)) {
if (!this.meterEntry(id)) throw `Plans - meterPrices.meters.${id.slice(0, 40)} is not a meter in the registry`;
}
const meters: any = {};
for (const entry of METER_REGISTRY) {
const id = entry[0];
const p = v.meters[id];
if (p === undefined) continue;
if (!isMap(p)) throw `Plans - meterPrices.meters.${id} must be {hub, tenant}`;
for (const k of Object.keys(p)) {
if (k !== "hub" && k !== "tenant") throw `Plans - meterPrices.meters.${id}.${k.slice(0, 32)} is not a field (hub, tenant)`;
}
for (const layer of ["hub", "tenant"]) {
if (!this.creditsIsCount(p[layer], METER_PRICE_MAX)) throw `Plans - meterPrices.meters.${id}.${layer} must be a whole number of credits from 0 to ${METER_PRICE_MAX}`;
if (entry[2] === 1 && p[layer] !== 0) throw `Plans - meterPrices.meters.${id} is a protection meter: it is recorded, never priced (0 only)`;
}
if (p.hub !== 0 || p.tenant !== 0) meters[id] = { hub: p.hub, tenant: p.tenant };
}
return { reason: v.reason, meters };
}/**
* Versions a validated `meterPrices` against the stored one, for configure and createConfig. Returns `{block, seq,
* event}`: the table to store (`undefined`: leave the field as it is), the config's `meterPricesSeq` counter (it never
* goes back, so a version is never reused), and the `meter-prices-set` event (null when nothing changed).
*
* - A changed table is version `seq + 1`, stamped with setAt (consensus ms), setBy and reason. The replaced table is
* kept as `previous` with `until` (setAt + 10 minutes), and meterPricesAt accepts it until then. With no table
* stored, previous is version 0 with no meters, the "every meter 0" a transaction may have signed against.
* - The move is bounded per meter and layer (hub, tenant): from 0, at most the meter's ceiling (a ceiling of 0 means
* it cannot be priced yet); between two prices above 0, at most x2 either way in one write (the
* creditsWeightsRefusal rule); down to 0, always.
* - The same prices as stored (any key order, any reason) keep the stored table, its version and previous. With no
* table stored, an empty table is the same: nothing is written.
* - `null` empties the table (every meter costs 0 again) as a new version marked `removed`, which keeps the replaced
* table as previous for its 10 minutes. On a table that is already empty, or none, it changes nothing.
*/ private versionMeterPrices(next: any, stored: any, seq: any, by: string): any {
const counter = Number.isSafeInteger(seq) && seq > 0 ? seq : 0;
const was = stored && typeof stored === "object" && stored.meters && typeof stored.meters === "object" ? stored : null;
const removing = next === null;
const after: any = removing ? {} : next.meters;
const before: any = was ? was.meters : {};
const changed: string[] = [];
for (const entry of METER_REGISTRY) {
const id = entry[0];
const a = before[id] || { hub: 0, tenant: 0 };
const b = after[id] || { hub: 0, tenant: 0 };
for (const layer of ["hub", "tenant"]) {
const from = a[layer];
const to = b[layer];
if (from === to || to === 0) continue;
if (from === 0 && to > entry[1]) throw `Plans - meterPrices.meters.${id}.${layer}: the first price from 0 is at most ${entry[1]} (the meter's ceiling), not ${to}`;
if (from > 0 && (to > from * 2 || to * 2 < from)) throw `Plans - meterPrices.meters.${id}.${layer} ${from} -> ${to} moves more than x2 in one write`;
}
if (a.hub !== b.hub || a.tenant !== b.tenant) changed.push(id);
}
if (changed.length === 0) return { block: was ? was : undefined, seq: counter, event: null };
const at = this.now();
const version = counter + 1;
const previous = was ? { version: was.version, meters: was.meters, until: at + METER_PREVIOUS_MS } : { version: 0, meters: {}, until: at + METER_PREVIOUS_MS };
const reason = removing ? null : next.reason;
const block: any = { version, setAt: at, setBy: by, reason, meters: after, previous };
if (removing) block.removed = true;
const event: any = { version, previousVersion: was ? was.version : 0, reason, changed };
if (removing) event.removed = true;
return { block, seq: version, event };
}/**
* The meter prices a transaction that names table `version` may use (plan §2.3 step 2), for the meter block a later
* phase adds; nothing calls it yet. The current table, or the previous one while this.cDate is before its `until`.
* With no table on the config, version 0 is every meter at 0 (`{}`). Null for any other version: refuse.
*/ private meterPricesAt(cfg: any, version: any): any {
const table = cfg && cfg.meterPrices && typeof cfg.meterPrices === "object" ? cfg.meterPrices : null;
if (!table) return version === 0 ? {} : null;
if (version === table.version) return table.meters;
const prev = table.previous;
if (prev && version === prev.version && this.now() < prev.until) return prev.meters;
return null;
}/**
* `varnirPrices` (docs/plans/tenant-pays-everything.md §3.1): Varnir's own price for each operation inside a
* tenancy, in whole credits. Replaced whole on each configure. Shape:
*
* - `ops`: `{[op]: credits}` for EVERY op in VARNIR_PRICE_OPS (none left to a default), each 1 to
* VARNIR_OP_PRICE_MAX. 0 is refused: a comp is granted credits (Tenants grantCredits), never a free price, so the
* burn report stays honest. Varnir.Tenants reads this as the floor under a tenant's `creditPrices` (D1).
* - `withdrawal`: `{[canonical network]: {native?, token?}}`, each 0 to VARNIR_OP_PRICE_MAX: the credits a
* tenant-tagged withdrawal adds ON TOP of the network's Instant weight (`weights`, live-priced where that weight
* is live), for the consolidation, top-up and activation moves the payout may need (D4). The gas part keeps one
* source (the weights); this field holds the rest. Nothing charges it yet: tagged withdrawals come with PR E,
* which must refuse a network or class with no entry here (fail closed).
*
* The stored table is rebuilt in a fixed order (ops in VARNIR_PRICE_OPS order, networks sorted), so it never
* depends on the caller's key order.
*/ private validVarnirPrices(v: any): any {
const isMap = (m: any) => !!m && typeof m === "object" && !Array.isArray(m);
if (!isMap(v) || !isMap(v.ops) || !isMap(v.withdrawal)) throw "Plans - varnirPrices must be {ops: {op: credits}, withdrawal: {network: {native?, token?}}}";
for (const k of Object.keys(v)) {
if (k !== "ops" && k !== "withdrawal" && k !== "consolidation") throw `Plans - varnirPrices.${k.slice(0, 32)} is not a field (ops, withdrawal, consolidation)`;
}
for (const op of Object.keys(v.ops)) {
if (VARNIR_PRICE_OPS.indexOf(op) === -1) throw `Plans - varnirPrices.ops.${op.slice(0, 32)} is not an operation a tenant shard meters (${VARNIR_PRICE_OPS.join(", ")})`;
}
const ops: any = {};
for (const op of VARNIR_PRICE_OPS) {
const p = v.ops[op];
if (!this.creditsIsCount(p, VARNIR_OP_PRICE_MAX) || p === 0) throw `Plans - varnirPrices.ops.${op} must be a whole number of credits from 1 to ${VARNIR_OP_PRICE_MAX}`;
ops[op] = p;
}
const names = Object.keys(v.withdrawal);
if (names.length > VARNIR_WITHDRAWAL_NETWORKS_MAX) throw `Plans - varnirPrices.withdrawal may list at most ${VARNIR_WITHDRAWAL_NETWORKS_MAX} networks`;
const withdrawal: any = {};
for (const name of names.slice().sort()) {
// The same canonical codes the weights use (creditsWeightsRefusal).
if (!/^[a-z0-9-]{2,16}$/.test(name)) throw `Plans - varnirPrices.withdrawal network ${name.slice(0, 32)} must be a lowercase canonical code`;
const entry = v.withdrawal[name];
if (!isMap(entry) || Object.keys(entry).length === 0) throw `Plans - varnirPrices.withdrawal.${name} must name native, token or both`;
for (const cls of Object.keys(entry)) {
if (cls !== "native" && cls !== "token") throw `Plans - varnirPrices.withdrawal.${name}.${cls.slice(0, 32)} must be native or token`;
if (!this.creditsIsCount(entry[cls], VARNIR_OP_PRICE_MAX)) throw `Plans - varnirPrices.withdrawal.${name}.${cls} must be a whole number of credits from 0 to ${VARNIR_OP_PRICE_MAX}`;
}
withdrawal[name] = {};
for (const cls of ["native", "token"]) if (entry[cls] !== undefined) withdrawal[name][cls] = entry[cls];
}
if (v.consolidation === undefined) return { ops, withdrawal };
// `null` is the consolidation KILL SWITCH (review M1): versionConsolidation removes the stored block.
if (v.consolidation === null) return { ops, withdrawal, consolidation: null };
return { ops, withdrawal, consolidation: this.validConsolidation(v.consolidation) };
}/**
* `varnirPrices.consolidation` (stage F2; docs/contracts/tenant-consolidation-config.md): Varnir's source-count price
* for a tenant-tagged withdrawal and the other consolidation values, as the admin sent it (no `version` or `previous`:
* versionConsolidation adds those). EVERY field is required and each is held to its range (plan §4.3), so a missing
* or malformed field refuses the whole block and a typo cannot set a Tron unit to 3 or 3,000,000:
* - `freeSources` 0-10; `instantMax` 1-200; `prepaidOffsetPct` 0-100; `refundUnused` true/false;
* `quoteHeadroomPct` 0-100; `contributorFloorMultiple` 1-100; `parkedDays` 1-365; `strandedFee` 0-1,000;
* `memberUntaggedWallets` "refuse" or "allow"; `quoteEnforced` true/false (true only once minigate holds a payout
* that needs more sources than its quote, F3: until then Varnir.CryptoTransfer refuses a tagged withdrawal priced by
* the block, so an under-quote can never be paid at the quoted price); `addressCharge` true/false (stage F4: true
* turns on the tenant-paid `wallet.deposit` charge in Varnir.AssignOwner and the `memberUntaggedWallets` rule in
* Varnir.AssignOwner and Varnir.Create; false, the seed, changes nothing);
* - `unit`: `{[canonical network]: {native?, token?}}`, each 1-10,000 credits a source;
* - `unitLive`: `{[network]: {native?, token?}}` true/false, true only where `unit` has the same entry (its floor);
* - `tiers`: 1-8 `{from, pct}`: the first `from` is freeSources + 1, each later `from` higher, the last at most
* instantMax; `pct` 100-1,000 and never falling;
* - `addressPrice`: `{[network]: {native?, token?}}`, each 0-100,000 credits per new tagged deposit wallet.
* Rebuilt in a fixed order (fields as CONSOLIDATION_FIELDS, networks sorted, classes native then token), so the
* stored block never depends on the caller's key order and an unchanged block compares equal.
*/ private validConsolidation(c: any): any {
const isMap = (m: any) => !!m && typeof m === "object" && !Array.isArray(m);
const p = "Plans - varnirPrices.consolidation";
if (!isMap(c)) throw `${p} must be an object with every field (${CONSOLIDATION_FIELDS.join(", ")})`;
for (const k of Object.keys(c)) {
if (CONSOLIDATION_FIELDS.indexOf(k) === -1) throw `${p}.${k.slice(0, 32)} is not a field (${CONSOLIDATION_FIELDS.join(", ")})`;
}
for (const k of CONSOLIDATION_FIELDS) if (c[k] === undefined || c[k] === null) throw `${p}.${k} is missing: every field is required`;
const count = (k: string, lo: number, hi: number) => {
if (!this.creditsIsCount(c[k], hi) || c[k] < lo) throw `${p}.${k} must be a whole number from ${lo} to ${hi}`;
return c[k];
};
const flag = (v: any, where: string) => {
if (typeof v !== "boolean") throw `${p}.${where} must be true or false`;
return v;
};
const perNetwork = (k: string, cell: (v: any, where: string) => any) => {
const m = c[k];
if (!isMap(m)) throw `${p}.${k} must be {network: {native?, token?}}`;
const names = Object.keys(m);
if (names.length > VARNIR_WITHDRAWAL_NETWORKS_MAX) throw `${p}.${k} may list at most ${VARNIR_WITHDRAWAL_NETWORKS_MAX} networks`;
const out: any = {};
for (const name of names.slice().sort()) {
if (!/^[a-z0-9-]{2,16}$/.test(name)) throw `${p}.${k} network ${name.slice(0, 32)} must be a lowercase canonical code`;
const entry = m[name];
if (!isMap(entry) || Object.keys(entry).length === 0) throw `${p}.${k}.${name} must name native, token or both`;
for (const cls of Object.keys(entry)) if (cls !== "native" && cls !== "token") throw `${p}.${k}.${name}.${cls.slice(0, 32)} must be native or token`;
out[name] = {};
for (const cls of ["native", "token"]) if (entry[cls] !== undefined) out[name][cls] = cell(entry[cls], `${k}.${name}.${cls}`);
}
return out;
};
const credits = (lo: number, hi: number) => (v: any, where: string) => {
if (!this.creditsIsCount(v, hi) || v < lo) throw `${p}.${where} must be a whole number of credits from ${lo} to ${hi}`;
return v;
};
const freeSources = count("freeSources", 0, 10);
const instantMax = count("instantMax", 1, 200);
const unit = perNetwork("unit", credits(1, 10000));
const unitLive = perNetwork("unitLive", flag);
for (const name of Object.keys(unitLive)) {
for (const cls of Object.keys(unitLive[name])) {
if (!unit[name] || unit[name][cls] === undefined) throw `${p}.unitLive.${name}.${cls} needs unit.${name}.${cls}, its floor`;
}
}
const tiers = c.tiers;
if (!Array.isArray(tiers) || tiers.length < 1 || tiers.length > 8) throw `${p}.tiers must list 1 to 8 tiers of {from, pct}`;
const outTiers: any[] = [];
for (let i = 0; i < tiers.length; i++) {
const t = tiers[i];
if (!isMap(t) || Object.keys(t).length !== 2 || !this.creditsIsCount(t.from, 200) || !this.creditsIsCount(t.pct, 1000)) throw `${p}.tiers[${i}] must be {from, pct}: whole numbers`;
if (i === 0 && t.from !== freeSources + 1) throw `${p}.tiers[0].from must be freeSources + 1 (${freeSources + 1})`;
if (i > 0 && t.from <= tiers[i - 1].from) throw `${p}.tiers[${i}].from must be above the tier before it`;
if (t.from > instantMax) throw `${p}.tiers[${i}].from must be at most instantMax (${instantMax})`;
if (t.pct < 100) throw `${p}.tiers[${i}].pct must be from 100 to 1000`;
if (i > 0 && t.pct < tiers[i - 1].pct) throw `${p}.tiers[${i}].pct must not be below the tier before it`;
outTiers.push({ from: t.from, pct: t.pct });
}
const out: any = {
freeSources,
unit,
unitLive,
tiers: outTiers,
instantMax,
prepaidOffsetPct: count("prepaidOffsetPct", 0, 100),
refundUnused: flag(c.refundUnused, "refundUnused"),
quoteHeadroomPct: count("quoteHeadroomPct", 0, 100),
addressPrice: perNetwork("addressPrice", credits(0, 100000)),
contributorFloorMultiple: count("contributorFloorMultiple", 1, 100),
parkedDays: count("parkedDays", 1, 365),
strandedFee: count("strandedFee", 0, 1000),
memberUntaggedWallets: c.memberUntaggedWallets,
quoteEnforced: flag(c.quoteEnforced, "quoteEnforced"),
addressCharge: flag(c.addressCharge, "addressCharge"),
};
if (out.memberUntaggedWallets !== "refuse" && out.memberUntaggedWallets !== "allow") throw `${p}.memberUntaggedWallets must be "refuse" or "allow"`;
return out;
}/** * Versions a validated `varnirPrices` against the stored config (plan §4.2), in place, for configure and createConfig. * A block that differs from the stored one becomes version `consolidationSeq + 1` (the config's counter, which never * goes back, so a version is never reused even after `varnirPrices: null`), and the stored block is kept as * `previous` with `replacedAt` (consensus ms), which Varnir.CryptoTransfer accepts for a quote's 10 minutes. A block * equal to the stored one keeps its version and previous, so re-sending the same file invalidates no quote. Once a * block is stored, a `varnirPrices` without one is refused: it is never dropped by leaving it out. Returns the * `consolidation-configured` event (version, changed fields, old and new values), or null when nothing changed. */
private versionConsolidation(next: any, stored: any, seq: any): any {
const was = stored && typeof stored === "object" && stored.consolidation && typeof stored.consolidation === "object" ? stored.consolidation : null;
if (next && next.consolidation === null) {
// The kill switch (review M1): `consolidation: null` removes the block, so a tagged withdrawal is priced at the
// stage E base again (never at 0). The counter is kept, so a later block never reuses a version. Nothing stored:
// nothing to remove, and nothing is written for it.
delete next.consolidation;
return was ? { removed: true, version: null, previousVersion: was.version, changed: [], old: {}, new: {} } : null;
}
if (!next || next.consolidation === undefined) {
if (was && next) throw "Plans - varnirPrices.consolidation is set on the config: send it with every varnirPrices write (an unchanged block keeps its version)";
return null;
}
const block = next.consolidation;
const bare = (b: any) => {
const o: any = {};
for (const k of CONSOLIDATION_FIELDS) o[k] = b[k];
return o;
};
if (was && JSON.stringify(bare(was)) === JSON.stringify(block)) {
next.consolidation = was;
return null;
}
const n = (Number.isSafeInteger(seq) && seq > 0 ? seq : 0) + 1;
const changed = CONSOLIDATION_FIELDS.filter((k) => !was || JSON.stringify(was[k]) !== JSON.stringify(block[k]));
const oldValues: any = {};
const newValues: any = {};
for (const k of changed) {
oldValues[k] = was ? was[k] : null;
newValues[k] = block[k];
}
next.consolidation = { version: n, ...block, previous: was ? { ...bare(was), version: was.version, replacedAt: this.now() } : null };
return { version: n, previousVersion: was ? was.version : null, changed, old: oldValues, new: newValues };
}/**
* `stablecoins`: `{[ledger network]: {[token key as layer2 stores it]: decimals}}`,
* the deposits that count toward the free-payout unlock. Replaced whole on
* each configure.
*/ private validStablecoins(v: any): any {
const isMap = (m: any) => !!m && typeof m === "object" && !Array.isArray(m);
if (!isMap(v)) throw "Plans - stablecoins must be an object of ledger network to {token key: decimals}";
const networks = Object.keys(v);
if (networks.length > 50) throw "Plans - stablecoins may list at most 50 networks";
const out: any = {};
for (const netCode of networks) {
const tokens = v[netCode];
if (!/^[A-Za-z0-9_-]{1,32}$/.test(netCode) || !isMap(tokens) || Object.keys(tokens).length > 20) {
throw `Plans - stablecoins.${netCode} must be a network code holding at most 20 token keys`;
}
out[netCode] = {};
for (const key of Object.keys(tokens)) {
if (!key.length || key.length > 128 || !this.creditsIsCount(tokens[key], 36)) {
throw `Plans - stablecoins.${netCode}.${key} must be the token's decimals, a whole number from 0 to 36`;
}
out[netCode][key] = tokens[key];
}
}
return out;
}/**
* The `plans` map: plan definitions the gates read (packages/plan-limits
* createPlanRegistry) on top of the built-in table. A definition under a
* built-in id ("free", "hobbyist") overrides that plan's limits - e.g.
* `{free: {limits: {standardWalletsPerNetwork: "unlimited"}}}`; any other
* id is a custom plan. The whole map is replaced on each configure, and
* `{}` clears it. Checked here only for shape and size: the gates parse
* each definition themselves and skip one they can't use. These limits
* gate wallets, invoices, orders and CSV export off-ledger; this contract's
* own prices stay in their own fields.
*/ private validPlans(plans: any): any {
if (!plans || typeof plans !== "object" || Array.isArray(plans)) throw "Plans - plans must be an object of plan id to definition";
const ids = Object.keys(plans);
if (ids.length > 50) throw "Plans - plans may hold at most 50 definitions";
for (const id of ids) {
if (!PLAN_ID.test(id)) throw `Plans - plan id ${id} must be lowercase letters, digits and dashes, at most 40`;
const def = plans[id];
if (!def || typeof def !== "object" || Array.isArray(def)) throw `Plans - plans.${id} must be an object`;
if (def.kind !== undefined && PLAN_KINDS.indexOf(def.kind) === -1) throw `Plans - plans.${id}.kind must be one of ${PLAN_KINDS.join(", ")}`;
if (def.limits !== undefined && (!def.limits || typeof def.limits !== "object" || Array.isArray(def.limits))) {
throw `Plans - plans.${id}.limits must be an object`;
}
}
const text = JSON.stringify(plans);
if (text.length > 20000) throw "Plans - plans must be at most 20000 characters as JSON";
return JSON.parse(text);
}/** The identity's effective plan now (lazy period transition applied, not yet written). */
private planOf(activity: any, cfg: any): { state: any; plan: any }/** `tier`'s monthly price in whole credits from the config; refused when it has none (fail closed). */
private tierPrice(cfg: any, tier: string): number {
const price = cfg.prices ? cfg.prices[tier] : undefined;
if (!this.creditsIsCount(price, CREDIT_PRICE_MAX) || price === 0) throw `Plans - no credit price is set for the ${tier} tier`;
return price;
}/** * Takes `tier`'s monthly price from the (mutable) `state`'s credit balance * and returns it. A short balance throws creditsMove's refusal unchanged * and leaves `state` untouched - the balance never goes negative. */
private payTier(state: any, cfg: any, tier: string, reason: "tier" | "renewal"): number {
const price = this.tierPrice(cfg, tier);
const refusal = this.creditsMove(state, -price, reason, this.umid, this.now());
if (refusal) throw refusal;
return price;
}/** A paid tier's rank, lite < hobbyist < trader; -1 for anything else. */
private tierRank(tier: any): number {
return PAID_TIERS.indexOf(tier);
}/** Lite, Hobbyist or Trader - the tiers bought with credits. */
private paidTier(tier: any): boolean {
return this.tierRank(tier) !== -1;
}/**
* `subscribe` (owner key, `$i.owner = {tier, maxPrice, autoRenew?}`):
* moves a Free identity onto Lite, Hobbyist or Trader, or a paid one UP a
* tier. Moving up charges the new tier's full price and starts a fresh
* 30-day month (no part-month maths); a renewal already prepaid for the
* month being replaced is refunded. Refused for a linked identity, the
* same or a lower tier while one is active, a price above `maxPrice`, or
* a balance short of the price. `autoRenew` defaults to true. Emits
* `credits-changed` per balance move, then `plan-updated`.
*/ private async runSubscribe(apply: boolean): Promise<void> {
const cfg = this.readConfig();
const owner = this.named("$i", "owner");
this.requireOwnerKey(owner, "subscribe");
const input: any = this.transactions.$i.owner;
if (!this.paidTier(input.tier)) throw "Plans - tier must be lite, hobbyist or trader";
if (input.autoRenew !== undefined && typeof input.autoRenew !== "boolean") throw "Plans - autoRenew must be true or false";
const autoRenew = input.autoRenew !== false;
const { state, plan } = this.planOf(owner, cfg);
if (state.planOwner) throw "Plans - this identity is linked to another plan; unlink it first";
const movingUp = this.paidTier(plan.tier) && this.tierRank(input.tier) > this.tierRank(plan.tier);
if (plan.tier !== "free" && !movingUp) throw `Plans - already on ${plan.tier} until ${this.iso(plan.periodEnd)}; use renew`;
this.requireMaxPrice(input.maxPrice, cfg, input.tier);
const refund = plan.renewal && this.creditsIsCount(plan.renewal.price, Number.MAX_SAFE_INTEGER) ? plan.renewal.price : 0;
if (refund > 0) {
const refusal = this.creditsMove(state, refund, "refund", this.umid, this.now());
if (refusal) throw refusal;
}
const price = this.payTier(state, cfg, input.tier, "tier");
if (!apply) return;
const next = this.creditsFreshPlan(input.tier, this.now(), cfg, null);
next.autoRenew = autoRenew;
next.agreedPrice = autoRenew ? price : null;
next.overageCap = plan.overageCap === undefined ? null : plan.overageCap;
next.paidUmid = this.umid;
state.plan = next;
owner.setState(state);
if (refund > 0) this.emitCredits(owner.getId(), refund, state.credits.balance + price, "refund");
this.emitCredits(owner.getId(), -price, state.credits.balance, "tier");
this.emitPlan(owner.getId(), next, "subscribe");
}/**
* `renew` (owner key, `$i.owner = {tier, maxPrice}`; `tier` defaults to
* the current one): prepays the next month of a paid plan from the credit
* balance, once per month and only inside the renewal window before
* `periodEnd`, recorded as `plan.renewal`. With auto-renew on, the paid
* price becomes the agreed price. Emits `credits-changed` and `plan-updated`.
*/ private async runRenew(apply: boolean): Promise<void> {
const cfg = this.readConfig();
const owner = this.named("$i", "owner");
this.requireOwnerKey(owner, "renew");
const input: any = this.transactions.$i.owner;
const { state, plan } = this.planOf(owner, cfg);
if (!this.paidTier(plan.tier)) throw "Plans - no paid plan to renew; subscribe instead";
const tier = input.tier === undefined ? plan.tier : input.tier;
if (!this.paidTier(tier)) throw "Plans - tier must be lite, hobbyist or trader";
this.requireRenewable(plan);
this.requireMaxPrice(input.maxPrice, cfg, tier);
const price = this.payTier(state, cfg, tier, "renewal");
if (!apply) return;
plan.renewal = { tier, umid: this.umid, price };
// Paying by hand at the current price re-confirms it for auto-renew too.
if (plan.autoRenew === true) plan.agreedPrice = price;
state.plan = plan;
owner.setState(state);
this.emitCredits(owner.getId(), -price, state.credits.balance, "renewal");
this.emitPlan(owner.getId(), plan, "renew");
}/** * Price protection: `maxPrice` is the price in credits the owner saw and * confirmed. Prices can change (configure) between review and execution, * so the payment is refused rather than charging more than was confirmed. */
private requireMaxPrice(maxPrice: any, cfg: any, tier: string): void {
if (!this.creditsIsCount(maxPrice, Number.MAX_SAFE_INTEGER) || maxPrice === 0) {
throw "Plans - maxPrice must be a whole number of credits (the price you confirmed)";
}
const price = this.tierPrice(cfg, tier);
if (price > maxPrice) {
throw `Plans - the ${tier} plan now costs ${price}, more than the ${maxPrice} you confirmed; review the new price and try again`;
}
}/** Refuses a plan already renewed, and one whose renewal window has not opened. */
private requireRenewable(plan: any): void {
if (plan.renewal) throw `Plans - already renewed for the period starting ${this.iso(plan.periodEnd)}`;
const opens = plan.periodEnd - this.creditsDefaults().renewWindowMs;
if (this.now() < opens) throw `Plans - renewal opens ${this.iso(opens)}`;
}/** * `setAutoRenew` (owner key, `enabled`): paid plans only. Turning it on * agrees to the current price of the tier the next renewal is for; turning * it off lets the tier run to the end of its month, then drop to Free. * Emits `plan-updated`. */
private async runSetAutoRenew(apply: boolean): Promise<void> {
const cfg = this.readConfig();
const owner = this.named("$i", "owner");
this.requireOwnerKey(owner, "change auto-renew");
const input: any = this.transactions.$i.owner;
if (typeof input.enabled !== "boolean") throw "Plans - enabled must be true or false";
const { state, plan } = this.planOf(owner, cfg);
if (!this.paidTier(plan.tier)) throw "Plans - auto-renew applies to lite, hobbyist and trader plans";
// Opting in agrees to the CURRENT price of the tier the next renewal is
// for; autoRenew refuses if the price later rises above it.
const agreedPrice = input.enabled ? this.tierPrice(cfg, plan.renewal ? plan.renewal.tier : plan.tier) : null;
if (!apply) return;
plan.autoRenew = input.enabled;
plan.agreedPrice = agreedPrice;
state.plan = plan;
owner.setState(state);
this.emitPlan(owner.getId(), plan, "setAutoRenew");
}/**
* `grantTestCredits` (owner key, `$i.owner = {}`): testnet only - adds
* TEST_CREDIT_GRANT credits when at least TEST_CREDIT_INTERVAL_MS of
* consensus time has passed since the identity's last grant, and records
* `state.credits.lastGrantAt`. Production refuses it outright, before any
* state read. Emits `credits-changed`.
*/ private async runGrantTestCredits(apply: boolean): Promise<void> {
const owner = this.named("$i", "owner");
this.requireOwnerKey(owner, "claim test credits");
if (!TEST_CREDITS_ENABLED) throw "Plans - test credits exist only on testnet";
const state = owner.getState();
const now = this.now();
const last = state.credits && typeof state.credits.lastGrantAt === "number" ? state.credits.lastGrantAt : null;
if (last !== null && now - last < TEST_CREDIT_INTERVAL_MS) {
throw `Plans - test credits are granted once every 24 hours; next grant opens ${this.iso(last + TEST_CREDIT_INTERVAL_MS)}`;
}
const refusal = this.creditsMove(state, TEST_CREDIT_GRANT, "grant", this.umid, now);
if (refusal) throw refusal;
if (!apply) return;
state.credits.lastGrantAt = now;
owner.setState(state);
this.emitCredits(owner.getId(), TEST_CREDIT_GRANT, state.credits.balance, "grant");
}/**
* `grantCredits` (admin, `$i.admin = {amount}`, `$o.target`): testnet only -
* adds `amount` credits (a whole number from 1 to GRANT_CREDITS_MAX) to
* the target identity, recorded as a `grant`. It tops up the operator
* identities (drills, faucet, agent fixture) past the daily grant. It reads
* no config, so it works whether or not creditsLive is on. Production
* refuses it outright, before any read. Emits `credits-changed`.
*/ private async runGrantCredits(apply: boolean): Promise<void> {
if (!TEST_CREDITS_ENABLED) throw "Plans - granted credits exist only on testnet";
await this.requireAdmin();
const amount = (this.transactions.$i.admin as any).amount;
if (!Number.isInteger(amount) || amount < 1 || amount > GRANT_CREDITS_MAX) {
throw `Plans - amount must be a whole number of credits from 1 to ${GRANT_CREDITS_MAX}`;
}
const target = this.named("$o", "target");
const state = target.getState() || {};
const refusal = this.creditsMove(state, amount, "grant", this.umid, this.now());
if (refusal) throw refusal;
if (!apply) return;
target.setState(state);
this.emitCredits(target.getId(), amount, state.credits.balance, "grant");
}/**
* `autoRenew` (gateway, `$o.owner` the payer, `$r.{minigate, config}`):
* renews a paid plan with auto-renew on, inside its renewal window, while
* the price has not risen above `agreedPrice`, taking the price from the
* credit balance. A short balance is refused - there is no grace period:
* the plan then drops to Free at `periodEnd`. A second renewal for the
* same month is refused as already renewed. Emits `credits-changed` and
* `plan-updated`.
*/ private async runAutoRenew(apply: boolean): Promise<void> {
await this.requireMinigate();
const cfg = this.readConfig();
const payer = this.named("$o", "owner");
const { state, plan } = this.planOf(payer, cfg);
if (!this.paidTier(plan.tier)) throw "Plans - no paid plan to renew; subscribe instead";
if (plan.autoRenew !== true) throw "Plans - auto-renew is not enabled on this plan";
this.requireRenewable(plan);
const agreed = plan.agreedPrice;
const current = this.tierPrice(cfg, plan.tier);
const agreedOk = this.creditsIsCount(agreed, Number.MAX_SAFE_INTEGER);
if (!agreedOk || current > agreed) {
// A pre-credits record holds a USDT string here: shown as "(none)", not as a credit amount.
throw `Plans - auto-renew refused: the ${plan.tier} price is now ${current}, above the ${agreedOk ? agreed : "(none)"} agreed; the owner must renew by hand to confirm the new price`;
}
let price: number;
try {
price = this.payTier(state, cfg, plan.tier, "renewal");
} catch (e) {
throw `Plans - auto-renew failed: ${typeof e === "string" ? e : "payment refused"}`;
}
if (!apply) return;
plan.renewal = { tier: plan.tier, umid: this.umid, price };
state.plan = plan;
payer.setState(state);
this.emitCredits(payer.getId(), -price, state.credits.balance, "renewal");
this.emitPlan(payer.getId(), plan, "autoRenew");
}/** The identity's open holds (`state.credits.holds`) as a new array; [] when absent. */
private serviceHolds(state: any): any[] {
const c = state && state.credits && typeof state.credits === "object" ? state.credits : {};
return Array.isArray(c.holds) ? c.holds.slice() : [];
}/** `map[key]` only when `key` is the plain object's own key, else undefined - never a prototype member. */
private serviceOwn(map: any, key: string): any {
if (!map || typeof map !== "object" || Array.isArray(map)) return undefined;
return Object.keys(map).indexOf(key) !== -1 ? map[key] : undefined;
}/** Refuses a ref that is not 1 to 128 safe characters. */
private requireServiceRef(ref: any): void {
if (typeof ref !== "string" || !SERVICE_REF.test(ref)) throw "Plans - ref must be 1 to 128 letters, digits or . _ : -";
}/** True once a hold's `until` has passed by this.cDate (a hold without one counts as expired). */
private serviceExpired(hold: any): boolean {
return !(typeof hold.until === "number" && this.now() < hold.until);
}/** Drops the hold `ref` and remembers it as settled (newest first, at most SERVICE_SETTLED_MAX). */
private serviceSettle(state: any, ref: string): void {
const c = state.credits;
c.holds = this.serviceHolds(state).filter((h: any) => h.ref !== ref);
const settled = Array.isArray(c.settledHolds) ? c.settledHolds : [];
c.settledHolds = [ref].concat(settled).slice(0, SERVICE_SETTLED_MAX);
}/** Lazy expiry: gives back every expired hold on `state`; returns each with the balance after it, for emitReturned. */
private serviceReturnExpired(state: any): { hold: any; balance: number }/** Emits `service-hold`, `service-capture` or `service-release` (identity, service, ref, umid and `data`). */
private emitService(name: string, identity: string, hold: any, data: any): void {
this.event.emit(name, { identity, service: hold.service, ref: hold.ref, ...data, umid: this.umid });
}/**
* `holdService` (owner key, `$i.owner = {service, priceKeys, credits,
* ref, notAfter}`, `$r.config`): refused once this.cDate is past the
* signed `notAfter` (ms), or when `notAfter` is more than the hold window
* (`serviceHoldMs`) ahead, so a signed request cannot be replayed later.
* Moves `credits` from the balance - never the
* monthly allowance - into a hold, `state.credits.holds[] = {ref,
* service, priceKeys, credits, at, until, umid}`, as a `service-hold`
* move. `credits` is the amount the owner signs: it must equal the sum of
* the configured `servicePrices` for `priceKeys` (each `<service>.*`) and
* be at most `<service>.maxCredits`. Refused when the service is switched
* off or not open to the identity's plan (`serviceTiers`), when 3 holds
* are already open, on a short balance, or for a ref already settled. The
* same ref with the same request again changes nothing (idempotent); with
* a different request it is refused. Expired holds are given back first.
* The hold lasts `serviceHoldMs` (15 minutes when unset). Emits
* `credits-changed` and `service-hold`.
*/ private async runHoldService(apply: boolean): Promise<void> {
const cfg = this.readConfig();
const owner = this.named("$i", "owner");
this.requireOwnerKey(owner, "hold credits for a service");
const input: any = this.transactions.$i.owner;
const service = input.service;
const keys = input.priceKeys;
const credits = input.credits;
const ref = input.ref;
if (typeof service !== "string" || !SERVICE_ID.test(service)) throw "Plans - service must be a service id";
this.requireServiceRef(ref);
if (
!Array.isArray(keys) ||
keys.length < 1 ||
keys.length > SERVICE_PRICE_KEYS_MAX ||
keys.some((k: any, i: number) => typeof k !== "string" || !SERVICE_PRICE_KEY.test(k) || keys.indexOf(k) !== i)
) {
throw `Plans - priceKeys must be a list of 1 to ${SERVICE_PRICE_KEYS_MAX} different price keys`;
}
if (!this.creditsIsCount(credits, CREDIT_PRICE_MAX) || credits === 0) throw `Plans - credits must be a whole number from 1 to ${CREDIT_PRICE_MAX}`;
// The signed notAfter makes a hold request single-window: settledHolds
// remembers only the newest refs, so without it an old signed hold
// (public on the ledger) could be replayed once its ref had dropped out.
const notAfter = input.notAfter;
if (!this.creditsIsCount(notAfter, Number.MAX_SAFE_INTEGER)) throw "Plans - notAfter must be a whole number of ms since 1970";
const now = this.now();
const ms = cfg.serviceHoldMs;
const holdMs = this.creditsIsCount(ms, 3600000) && ms >= 60000 ? ms : SERVICE_HOLD_MS_DEFAULT;
if (now > notAfter) throw "Plans - hold request expired";
if (notAfter > now + holdMs) throw "Plans - hold request notAfter is too far ahead";
const tiers =this.serviceOwn(cfg.serviceTiers, service);
if (!Array.isArray(tiers) || tiers.length === 0) throw `Plans - the ${service} service is switched off`;
const { state, plan } = this.planOf(owner, cfg);
if (tiers.indexOf(plan.tier) === -1) throw `Plans - the ${service} service is not open to the ${plan.tier} plan`;
const returned = this.serviceReturnExpired(state);
const open = this.serviceHolds(state);
const same = open.find((h: any) => h.ref === ref);
if (same) {
// A retry of the same signed request: the hold stands as it is.
if (same.service !== service || same.credits !== credits || JSON.stringify(same.priceKeys) !== JSON.stringify(keys)) {
throw `Plans - ref ${ref} already holds a different request`;
}
if (!apply || returned.length === 0) return;
owner.setState(state);
this.emitReturned(owner.getId(), returned);
return;
}
const settled = Array.isArray(state.credits && state.credits.settledHolds) ? state.credits.settledHolds : [];
if (settled.indexOf(ref) !== -1) throw `Plans - ref ${ref} was already settled`;
if (open.length >= SERVICE_HOLDS_MAX) throw `Plans - at most ${SERVICE_HOLDS_MAX} holds may be open at once`;
let price = 0;
for (const k of keys) {
if (k.split(".")[0] !== service || k === `${service}.maxCredits`) throw `Plans - ${k} is not a ${service} price key`;
const p = this.serviceOwn(cfg.servicePrices, k);
if (!this.creditsIsCount(p, CREDIT_PRICE_MAX)) throw `Plans - no price is set for ${k}`;
price += p;
}
if (credits !== price) throw `Plans - the ${credits} credits signed do not match the current price of ${price}`;
const cap = this.serviceOwn(cfg.servicePrices, `${service}.maxCredits`);
if (!this.creditsIsCount(cap, CREDIT_PRICE_MAX)) throw `Plans - no ${service}.maxCredits cap is set`;
if (credits > cap) throw `Plans - ${credits} credits is above the ${cap} cap for one ${service}`;
const hold = { ref, service, priceKeys: keys.slice(), credits, at: now, until: now + holdMs, umid: this.umid };
this.serviceMove(state, -credits, "service-hold", hold);
if (!apply) return;
state.credits.holds = open.concat([hold]);
owner.setState(state);
this.emitReturned(owner.getId(), returned);
this.emitCredits(owner.getId(), -credits, state.credits.balance, "service-hold");
this.emitService("service-hold", owner.getId(), hold, { credits, until: hold.until });
}/**
* `captureService` (gateway, `$i.admin = {publicKey, ref, credits}`,
* `$o.owner` the payer, `$r.minigate`): charges `credits` (1 up to the
* amount held) of the open hold `ref` before it expires, gives the rest
* back as a `refund`, and records the charge as a `service` move of 0
* carrying `charged` (the credits left the balance when the hold was
* placed). Once only: the hold is then settled. Expired holds are given
* back first. Emits `credits-changed` for a remainder, then
* `service-capture` (credits charged, released).
*/ private async runCaptureService(apply: boolean): Promise<void> {
await this.requireMinigate();
const input: any = this.transactions.$i.admin;
const payer = this.named("$o", "owner");
const ref = input.ref;
this.requireServiceRef(ref);
const state = payer.getState() || {};
const target = this.serviceHolds(state).find((h: any) => h.ref === ref);
if (!target) throw `Plans - no open hold ${ref}`;
if (this.serviceExpired(target)) throw `Plans - hold ${ref} expired at ${typeof target.until === "number" ? this.iso(target.until) : "an unknown time"}`;
const credits = input.credits;
if (!this.creditsIsCount(credits, target.credits) || credits === 0) throw `Plans - credits must be a whole number from 1 to the ${target.credits} held`;
const returned = this.serviceReturnExpired(state);
const rest = target.credits - credits;
if (rest > 0) this.serviceMove(state, rest, "refund", target);
const restBalance = state.credits.balance;
this.serviceMove(state, 0, "service", target, { charged: credits });
this.serviceSettle(state, ref);
if (!apply) return;
payer.setState(state);
this.emitReturned(payer.getId(), returned);
if (rest > 0) this.emitCredits(payer.getId(), rest, restBalance, "refund");
this.emitService("service-capture", payer.getId(), target, { credits, released: rest });
}/**
* `releaseService`: gives the whole hold `ref` back as a `refund`, with
* no charge - what a failed or refused service run uses. Either minigate
* (`$i.admin = {publicKey, ref}`, `$o.owner`, `$r.minigate`) at any time,
* or the owner key (`$i.owner = {ref}`) only once the hold has expired,
* so a user cannot release between getting the result and the capture.
* Expired holds are given back first. Emits `credits-changed` and
* `service-release` (`expired` true when it had expired).
*/ private async runReleaseService(apply: boolean): Promise<void> {
const byOwner = !!((this.transactions as any).$i && (this.transactions as any).$i.owner);
let identity: any;
let input: any;
if (byOwner) {
identity = this.named("$i", "owner");
this.requireOwnerKey(identity, "release a service hold");
input = this.transactions.$i.owner;
} else {
await this.requireMinigate();
identity = this.named("$o", "owner");
input = this.transactions.$i.admin;
}
const ref = input.ref;
this.requireServiceRef(ref);
const state = identity.getState() || {};
const target = this.serviceHolds(state).find((h: any) => h.ref === ref);
if (!target) throw `Plans - no open hold ${ref}`;
const expired = this.serviceExpired(target);
if (byOwner && !expired) throw `Plans - the owner may release hold ${ref} only from ${this.iso(target.until)}`;
// An expired target is given back here, with the other expired holds.
const returned = this.serviceReturnExpired(state);
if (!expired) {
this.serviceMove(state, target.credits, "refund", target);
this.serviceSettle(state, ref);
}
const balance = state.credits.balance;
if (!apply) return;
identity.setState(state);
this.emitReturned(identity.getId(), returned);
if (!expired) {
this.emitCredits(identity.getId(), target.credits, balance, "refund");
this.emitService("service-release", identity.getId(), target, { credits: target.credits, expired: false });
}
}/** * Replaces the target's plan outright, whatever it is - including a paid * Lite/Hobbyist/Trader month and any prepaid `renewal` already recorded on * it. Nothing is refunded: credits already spent stay spent. Admin-only; * settle any refund before assigning. */
private async runAssignEnterprise(apply: boolean): Promise<void> {
await this.requireAdmin();
const input: any = this.transactions.$i.admin;
if (!this.creditsIsCount(input.included, 1000000000) || input.included === 0) throw "Plans - included must be a whole number from 1 to 1000000000";
if (!this.creditsIsCount(input.rolloverCap, input.included)) throw "Plans - rolloverCap must be a whole number no larger than included";
if (!this.creditsIsCount(input.linkLimit, 1000)) throw "Plans - linkLimit must be a whole number from 0 to 1000";
if (input.overageCap !== undefined && input.overageCap !== null && !this.creditsIsCount(input.overageCap, 1000000000)) {
throw "Plans - overageCap must be null or a whole number from 0 to 1000000000";
}
const cfg = this.readConfig();
const target = this.named("$o", "target");
const state = target.getState() || {};
if (state.planOwner) throw "Plans - unlink the target from its plan first";
const current = this.creditsEffectivePlan(state.plan, this.now(), cfg);
if (!apply) return;
const next = this.creditsFreshPlan("enterprise", this.now(), cfg, input);
next.overageCap = input.overageCap !== undefined ? input.overageCap : current.overageCap === undefined ? null : current.overageCap;
next.linked = (current.linked || []).slice(0, next.linkLimit);
next.paidUmid = this.umid;
state.plan = next;
target.setState(state);
this.emitPlan(target.getId(), next, "assignEnterprise");
}/** * `endEnterprise` (admin): moves `$o.target` from Enterprise back to a * fresh Free period, keeping its overage cap. Emits `plan-updated`. */
private async runEndEnterprise(apply: boolean): Promise<void> {
await this.requireAdmin();
const cfg = this.readConfig();
const target = this.named("$o", "target");
const state = target.getState() || {};
const current = this.creditsEffectivePlan(state.plan, this.now(), cfg);
if (current.tier !== "enterprise") throw "Plans - the target is not on enterprise";
if (!apply) return;
const next = this.creditsFreshPlan("free", this.now(), cfg, null);
next.overageCap = current.overageCap === undefined ? null : current.overageCap;
state.plan = next;
target.setState(state);
this.emitPlan(target.getId(), next, "endEnterprise");
}/** How many identities a plan may link: Trader from the config, Enterprise its own limit, others 0. */
private linkLimitOf(plan: any, cfg: any): number {
if (plan.tier === "trader") return Number((cfg.linkLimits && cfg.linkLimits.trader) || 0);
if (plan.tier === "enterprise") return Number(plan.linkLimit || 0);
return 0;
}/** * `link` (owner keys of both `$i.owner`, the plan holder, and `$i.member`): * attaches a Free, unlinked member to a Trader or Enterprise plan within * its link limit. The holder lists the member in `plan.linked`; the member * records `planOwner` and `planLinkedAt`. A linked identity cannot hold * links. Emits `plan-updated`. */
private async runLink(apply: boolean): Promise<void> {
const cfg = this.readConfig();
const holder = this.named("$i", "owner");
const member = this.named("$i", "member");
this.requireOwnerKey(holder, "link");
this.requireOwnerKey(member, "link");
if (holder.getId() === member.getId()) throw "Plans - an identity cannot link to itself";
const h = this.planOf(holder, cfg);
const m = this.planOf(member, cfg);
if (h.state.planOwner) throw "Plans - a linked identity cannot hold links";
const limit = this.linkLimitOf(h.plan, cfg);
if (limit === 0) throw "Plans - linking needs a Trader or Enterprise plan";
if (m.state.planOwner) throw "Plans - the member is already linked to a plan";
if (m.plan.tier !== "free") throw "Plans - the member has its own paid plan";
if ((h.plan.linked || []).length >= limit) throw `Plans - this plan already links ${limit} identities`;
if (!apply) return;
h.plan.linked = (h.plan.linked || []).concat([member.getId()]);
h.state.plan = h.plan;
m.state.planOwner = holder.getId();
m.state.planLinkedAt = this.now();
holder.setState(h.state);
member.setState(m.state);
this.emitPlan(holder.getId(), h.plan, "link");
}/** * Object.assign-merged setState (Activity.setState in the real engine - * @activeledger/activecontracts@4.10.0 lib/stream.js:440, confirmed on this * repo's installed dependency) never drops a key: `delete` on a field here * would survive on the stored state. So an unlink NULLS planOwner/ * planLinkedAt rather than deleting them - every reader in this contract * (and Phase B's CryptoTransfer) must treat a falsy planOwner as unlinked. * * `unlink` (owner key of `$i.owner`, with the other side on `$o.other`): * either side may end a link; refused when the two are not linked. Emits * `plan-updated` for the holder. */
private async runUnlink(apply: boolean): Promise<void> {
const cfg = this.readConfig();
const signer = this.named("$i", "owner");
this.requireOwnerKey(signer, "unlink");
const other = this.named("$o", "other");
const s = this.planOf(signer, cfg);
const o = this.planOf(other, cfg);
let holder: any, holderSide: any, member: any, memberSide: any;
const links = (h: any, mId: string, mSide: any) => mSide.state.planOwner === h.getId() || (this.planOf(h, cfg).plan.linked || []).indexOf(mId) !== -1;
if (links(other, signer.getId(), s)) {
holder = other; holderSide = o; member = signer; memberSide = s;
} else if (links(signer, other.getId(), o)) {
holder = signer; holderSide = s; member = other; memberSide = o;
} else {
throw "Plans - these identities are not linked";
}
if (!apply) return;
holderSide.plan.linked = (holderSide.plan.linked || []).filter((id: string) => id !== member.getId());
holderSide.state.plan = holderSide.plan;
memberSide.state.planOwner = null;
memberSide.state.planLinkedAt = null;
holder.setState(holderSide.state);
member.setState(memberSide.state);
this.emitPlan(holder.getId(), holderSide.plan, "unlink");
}/** This contract's own stream id (`$contract` without a version suffix). */
private contractId(): string {
return String(this.transactions.$contract).substring(0, 64);
}/** $i.admin must be the identity that deployed this contract, signing with its stake-100 key. */
private async requireAdmin(): Promise<any> {
const admin = this.named("$i", "admin");
const meta: any = await this.getAnyStreamReadOnly(`${this.contractId()}:stream`).catch(() => null);
const deployers = meta && Array.isArray(meta.authorities) ? meta.authorities : [];
if (!deployers.some((a: any) => a && a.public === admin.getId())) {
throw "Plans - admin must be the identity that deployed Varnir.Plans";
}
this.requireStake100(admin, "Plans - admin must sign with its stake-100 key");
return admin;
}/** The config stream id pinned in contract data; refuses before createConfig. */
private configId(): string {
const id = this.getContractDataHelper().configStream;
if (!id) throw "Plans - not configured: run createConfig first";
return id;
}/** The 64-character stream id of a reference (`{$stream}` or a string), without any `:suffix`. */ private refId(ref: any): string {
const raw = ref && typeof ref === "object" ? ref.$stream : ref;
return typeof raw === "string" ? raw.split(":")[0].slice(-64) : "";
}/** The config as a read-only $r input, pinned to the id createConfig recorded. */
private readConfig(): any {
const id = this.configId();
if (this.refId(this.transactions.$r && (this.transactions.$r as any).config) !== id) {
throw `Plans - $r.config must be the Varnir plans config ${id}`;
}
const state = this.getReadOnlyStream("config");
if (!state || state.kind !== CONFIG_KIND) throw "Plans - the plans config could not be read";
return state;
}/** The config as a writable $o output (admin entries), pinned the same way. */
private writableConfig(): { stream: any; state: any }/** Copied from Varnir.Recovery.requireMinigate, messages re-prefixed. */
private async requireMinigate(): Promise<string> {
const ref = (this.transactions as any).$r && (this.transactions as any).$r.minigate;
if (!ref) throw "Plans - missing minigate reference";
const volatile: any = await this.getAnyStreamReadOnly(`${ref}:volatile`).catch(() => null);
if (!volatile || !volatile.minigate) throw "Plans - reference is not a minigate";
const key = (this.transactions as any).$i && (this.transactions as any).$i.admin && (this.transactions as any).$i.admin.publicKey;
const meta: any = await this.getAnyStreamReadOnly(`${ref}:stream`).catch(() => null);
const ok = !!key && meta && Array.isArray(meta.authorities) && meta.authorities.some((a: any) => a.public === key);
if (!ok) throw "Plans - signing key is not a minigate authority";
return ref;
}/** Owner entries: the identity's own stake-100 key, never a read, offledger, agent or co-sign key. */
private requireOwnerKey(activity: any, action: string): void {
const label = this.signingKeyLabel(activity);
if (label === "read") throw "Stake Permission Error - Read Only 9000";
// Same refusal as Varnir.CryptoTransfer's vote: an offledger key never
// carries on-ledger authority, whatever stake it happens to hold.
if (label === "offledger") throw "Off-ledger key: no fund authority";
this.requireStake100(activity, `Plans - only the owner key may ${action}`);
}/** Refuses with `message` unless `activity` was signed by one of its own stake-100 authorities. */
private requireStake100(activity: any, message: string): void {
const signed = (this as any).sigs && (this as any).sigs[activity.getId()];
const hashes = signed ? Object.keys(signed) : [];
const ok = hashes.length > 0 && (activity.getAuthorities() || []).some((a: any) => a.stake === 100 && hashes.indexOf(a.hash) !== -1);
if (!ok) throw message;
}/** * The live-authority rule (as Varnir.Swap liveAuthority, PR #765) on top of requireStake100: at least one stake-100 * authority that signed for `activity` is still live: present with a hash, and either permanent (no `expire`) or * with an `expire` after the consensus clock. `expire: null` or an unparseable value counts as expired. */
private requireLiveStake100(activity: any, message: string): void {
const signed = (this as any).sigs && (this as any).sigs[activity.getId()];
const hashes = signed ? Object.keys(signed) : [];
const live = (activity.getAuthorities() || []).some((a: any) => {
if (!a || !a.hash || a.stake !== 100 || 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 > this.now();
});
if (!live) throw message;
}/** The label on the authority that signed for `activity`, lower-cased and trimmed, or null. */
private signingKeyLabel(activity: any): string | null {
const signed = (this as any).sigs && (this as any).sigs[activity.getId()];
const hash = signed ? Object.keys(signed)[0] : null;
if (!hash) return null;
const authority = (activity.getAuthorities() || []).find((a: any) => a.hash === hash);
return authority && authority.label ? String(authority.label).toLowerCase().trim() : null;
}/** The contract's only clock: this.cDate in milliseconds. */
private now(): number {
return new Date(this.cDate).getTime();
}/** A millisecond instant as ISO-8601. */
private iso(ms: number): string {
return new Date(ms).toISOString();
}/** The engine's getContractData() is the wrapper {_id, data} - see Varnir.Recovery. */ private getContractDataHelper(): any {
const wrapper: any = this.getContractData();
return (wrapper && wrapper.data) || {};
}/** A stream the transaction names under $i/$o (loaded, so the lookup creates nothing); refuses when absent. */
private named(where: "$i" | "$o", label: string): any {
const ref = (this.transactions as any)[where] && (this.transactions as any)[where][label];
if (!ref) throw `Plans - missing ${where}.${label}`;
return this.getActivityStreams(ref);
}/** Emits `plan-updated` (identity, entry, tier, periodEnd, autoRenew, renewed, when). */
private emitPlan(identity: string, plan: any, entry: string): void {
this.event.emit("plan-updated", {
identity,
entry,
tier: plan.tier,
periodEnd: plan.periodEnd,
autoRenew: plan.autoRenew === true,
renewed: !!plan.renewal,
when: this.now(),
});
}/** Emits `credits-changed` (identity, delta, balance, reason, umid) - on every balance change. */
private emitCredits(identity: string, delta: number, balance: number, reason: ServiceCreditReason): void {
this.event.emit("credits-changed", { identity, delta, balance, reason, umid: this.umid });
}