Testnet Mode — switch back to Production in the menuheader when you're done.
VarnirConfirmWithdraw extends PostProcessEvent
/**
* Voting round: the social-recovery guard (`$o.owner` / `$o.payee` are
* only credited, so may be recovered or frozen); `mod` goes to voteMod.
* Otherwise refuses: a key not in `allowableKeys`; a stream already
* `confirmed` (unless `$i.admin.force`); a consolidation confirm on a
* stream with a gas hold; a hold or a failure without `$o.owner`; an
* `$o.owner` that is not the stream's recorded `sender`; an unreadable
* original umid; no amount to refund; a failure without a valid can't-land
* reason (refundReasonRefusal); a Bitcoin confirm that fails
* btcVoteConfirm; a negative or unbacked `#cancelFee`; and a malformed
* `#nativeFee` or one above the gas hold.
*
* @returns {Promise<boolean>}
* @memberof VarnirConfirmWithdraw
*/ public vote(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
// Social recovery (spec §4.5): owner/payee are only ever credited here,
// so either may land tombstoned/frozen; every other stream may not.
const recoveryRefusal = this.refuseRecoveredStreams(["owner", "payee"]);
if (recoveryRefusal) return reject(recoveryRefusal);
// Owner-only `mod`: writes the EVM chain table (evm-registry block).
if (this.transactions.$entry === "mod") {
try {
return resolve(await this.voteMod());
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
const signedStream = this.getActivityStreams(this.transactions.$o.signed);
const signedStreamData = signedStream.getState();
// An l1.presign carrying an armed mpc2 Tron transaction (CryptoTransfer
// `tronmpcarm`, plan Task 3.3) and no l1.sign is never settled here:
// its bytes may be signed or on chain, so a refund now could pay the
// user twice. Only CryptoTransfer `recordlanded`, after its own chain
// read, writes the l1.sign this contract then settles. An l1.sign never
// carries `tronMpc`, so nothing else is affected.
if (signedStreamData && signedStreamData.tronMpc !== undefined && !signedStreamData.signedStream) {
return reject("presign has an armed mpc2 Tron transaction; refund only through recordlanded");
}
const selfSignedPubKey = this.transactions.$i.admin.publicKey;
if(!this.allowableKeys.includes(selfSignedPubKey)) {
return reject("Invalid SS Key");
}
if (signedStreamData.confirmed && !this.transactions.$i.admin.force) {
return reject("Already Confirmed #CSVEDB");
}
// A Bitcoin move (CryptoTransfer `btcmove`: a frozen key's sweep, or a
// ceiling move) settles on its own path: it moved no L2 balance, holds
// nothing and refunds nobody, so none of the withdrawal checks below
// apply to it.
if (signedStreamData && signedStreamData.btc && signedStreamData.btc.kind === "move") {
try {
this.btcVoteMoveConfirm(signedStream.getId(), signedStreamData);
return resolve(true);
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
// A gas hold only exists on a withdrawal presign; a consolidation
// confirm skips settle() and would strand a native hold (RV7).
if (
signedStreamData.gasHold &&
this.transactions.$i.admin.consolidation
) {
return reject("Gas hold present - not a consolidation");
}
// A presign gas hold must be settled against the sender's balance, so
// the sender stream has to be an output (chain.ts always adds it when a
// hold exists). Without it the hold would never be released. Kept for
// delegated (token) sends too, whose hold is an un-debited envelope:
// minigate adds the owner whenever a hold exists, and the rule then
// does not depend on reading `delegated` correctly.
if (
signedStreamData.gasHold &&
!this.transactions.$o.owner &&
!this.transactions.$i.admin.consolidation
) {
return reject("Gas hold present - owner output required");
}
// A failure refunds the sender, so the sender stream must be an output
// (chain.ts always adds it on failure). Without it settle() would
// refund nothing yet still write `confirmed`, and a forced re-confirm
// is a no-op (RV7), leaving the principal unrecoverable.
if (
this.transactions.$i.admin.success !== true &&
!this.transactions.$o.owner &&
!this.transactions.$i.admin.consolidation
) {
return reject("Failure confirm - owner output required");
}
// The stream released/refunded to is the signed stream's recorded
// sender (B9), so the owner output must name that same stream. A
// mismatch is a malformed or steered confirm: refuse it rather than
// write to one stream while locking another. Legacy signed streams with
// no recorded sender keep the umid-request fallback in commit().
const ownerOutput = this.transactions.$o.owner;
if (ownerOutput && signedStreamData.sender) {
const ownerOutputId =
typeof ownerOutput === "string" ? ownerOutput : ownerOutput.$stream;
if (ownerOutputId !== signedStreamData.sender) {
return reject("Owner output is not the signed stream's sender");
}
}
// C1 (consolidation step 3 Task 7): a confirmed repay is what lowers
// the gas key's top-up debt; Varnir.Consolidation only queued it.
if (!signedStreamData.confirmed) {
try {
this.repaySettle = await this.repayToSettle(signedStream.getId(), signedStreamData);
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
// Fetch the UMID
try {
this.umidData[this.transactions.$i.admin.wallet] =
await this.getAnyStreamReadOnly(
this.transactions.$i.admin.umid + ":umid"
);
} catch {
this.event.emit("umid-not-found", {
umid: this.transactions.$i.admin.umid.umid,
});
return reject("UMID not found");
}
if (!this.umidData[this.transactions.$i.admin.wallet]?.umid?.$tx) {
this.event.emit("umid-not-found", {
umid: this.transactions.$i.admin.umid,
});
return reject("UMID not found");
}
// Now it maybe presigned proxy so lets pull that
if (
this.umidData[this.transactions.$i.admin.wallet].umid.$tx.$o?.presigned
) {
const presigned = await this.getAnyStreamReadOnly(
this.umidData[this.transactions.$i.admin.wallet].umid.$tx.$o.presigned
.$stream
);
this.umidData[this.transactions.$i.admin.wallet].umid.$tx.$i.owner =
presigned.payload;
}
// B9: the confirmer's own request cannot steer network/token/amount -
// prefer what the contract itself already wrote onto the signed stream
// at presign/presigned (commitPreSign/commitPreSigned), and fall back
// to the umid request only when the field is absent (in-flight legacy
// streams written before this field existed there).
const req =
this.umidData[this.transactions.$i.admin.wallet].umid.$tx.$i.owner ||
{};
this.layer2TDetails.network = signedStreamData.network ?? req.network;
this.layer2TDetails.token =
signedStreamData.token ?? req.token ?? "#native";
// No owner means it will be a consolidation
if (this.transactions.$o.owner) {
this.refundAmount = signedStreamData.amount ?? req.amount;
if (!this.refundAmount) {
return reject("No Sending Amount Found");
}
}
// Never refund while the payout can still land (audit B2).
const reasonRefusal = this.refundReasonRefusal(signedStreamData);
if (reasonRefusal) return reject(reasonRefusal);
// Bitcoin: the books it spends and fills, and a fee from the record.
if (this.btcParams(this.layer2TDetails.network) !== null) {
try {
this.btcVoteConfirm(signedStream.getId(), signedStreamData);
} catch (e) {
return reject(typeof e === "string" ? e : "Runtime Vote Revert");
}
}
// Cancel gas (Task 7) is booked to Varnir's .fees.deductible, so it
// must be a real, non-negative cost of a cancel this payout carries.
const cancelFee = this.transactions.$i.admin["#cancelFee"];
if (cancelFee !== undefined && cancelFee !== null) {
let fee;
try {
fee = this.getBN(cancelFee);
} catch {
return reject("Invalid cancel fee");
}
if (fee.lt(0)) return reject("Invalid cancel fee");
if (fee.gt(0) && !signedStreamData.cancels?.length) {
return reject("Cancel fee without a cancel on the signed stream");
}
}
// The payout's gas (#nativeFee) is released against the presign hold
// and booked to .fees.deductible, so it must be a real, non-negative
// integer (decimal or 0x-hex, as minigate sends it) and never more than
// the hold recorded at presign. A negative fee would release more than
// was held; a non-numeric one would pass here and throw in commit.
// Absent/empty means no fee. Legacy/consolidation streams carry no
// hold, so only the format is checked there.
const nativeFee = this.transactions.$i.admin["#nativeFee"];
if (nativeFee !== undefined && nativeFee !== null && nativeFee !== "") {
if (
typeof nativeFee !== "string" ||
!/^(0x[0-9a-fA-F]+|[0-9]+)$/.test(nativeFee)
) {
return reject("Invalid native fee");
}
const holdAmount = signedStreamData.gasHold?.amount;
if (
holdAmount !== undefined &&
holdAmount !== null &&
this.getBN(nativeFee).gt(this.getBN(holdAmount))
) {
return reject("Native fee exceeds the gas hold");
}
}
resolve(true);
});
}/**
* Commit round (`mod`: commitMod). For a withdrawal, settles the sender
* (settle, or btcSettle for Bitcoin) unless the stream is already
* `confirmed`; for a consolidation, books its gas to `.fees.deductible`.
* Writes `confirmed = {success, umid, date, gasFee, delegated, outcome,
* cancelFee, btc?}` on the `l1.sign` stream (only when not already set)
* and emits `confirmation`.
*
* @returns {Promise<any>}
* @memberof VarnirConfirmWithdraw
*/ public commit(): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
if (this.transactions.$entry === "mod") {
return resolve(await this.commitMod());
}
const signedStream = this.getActivityStreams(this.transactions.$o.signed);
const signedStreamData = signedStream.getState();
if (this.btcMove) {
this.btcSettleMove(signedStream, signedStreamData);
return resolve(true);
}
//let outputs = {};
//let balances = {};
let nativeFee;
// RV7: settlement is written atomically with `confirmed`, so a signed
// stream that already carries `confirmed` (from this or any earlier
// contract version) has been settled. A forced re-confirm
// ($i.admin.force passes vote's "Already Confirmed" check) must not
// release, refund or book a second time: it moves no value, leaves the
// settled record as it is and only re-emits the confirmation event.
const alreadySettled = !!signedStreamData.confirmed;
// Outputs mirror the ledger: on a no-op re-confirm, the recorded
// result and no fee - not the forced call's claim.
const outSuccess = alreadySettled
? signedStreamData.confirmed.success
: this.transactions.$i.admin.success;
const outNativeFee = alreadySettled
? "0"
: this.transactions.$i.admin["#nativeFee"] || "0";
// Consolidation doesn't need this
if (!this.transactions.$i.admin.consolidation) {
// B9: the credited/refunded stream is the signed stream's own
// recorded sender, not the (possibly stale/decoy) umid request -
// same preference as vote(), same legacy fallback.
const req =
this.umidData[this.transactions.$i.admin.wallet].umid.$tx.$i
.owner || {};
const owner = signedStreamData.sender ?? req.$stream;
let ownerState = await this.getAnyStreamReadOnly(owner);
// If there is no this.transactions.$o.owner it means the original transaction became delegated
// We can verify by downloading the signed stream but that is already done at the minigate level
// So senderstate will be blank and this can be skipped over
const sender = this.transactions.$o.owner
? this.getActivityStreams(owner)
: null;
const senderState = sender ? sender.getState() : null;
if (senderState) this.hasValidSchemaObject(senderState);
this.delegated = signedStreamData.delegated === true;
nativeFee = alreadySettled
? this.getBN(0)
: signedStreamData.btc && this.btcParams(this.layer2TDetails.network) !== null
? this.btcSettle(signedStreamData, senderState)
: this.settle(signedStreamData, senderState);
// The withdrawal's credit charge (credits-only pricing) comes back
// with the amount, in the same write. Once: a settled stream is never
// settled again (alreadySettled).
const charge = signedStreamData.creditCharge;
if (!alreadySettled && this.refunded && senderState && charge && charge.identity === owner) {
const usedBefore = this.creditsAllowanceUsed(senderState);
const back = this.creditsRefundCharge(senderState, charge, this.umid, new Date(this.cDate).getTime());
const allowanceBack = usedBefore - this.creditsAllowanceUsed(senderState);
// An allowance-only refund moves no balance but still changes the allowance.
if (back > 0 || allowanceBack > 0) {
this.event.emit("credits-changed", {
identity: owner, delta: back, balance: this.creditsBalance(senderState), allowance: allowanceBack, allowanceUsed: this.creditsAllowanceUsed(senderState), reason: "refund", umid: this.umid,
});
}
}
if (sender) {
sender.setState(senderState);
ownerState = senderState;
}
this.outputs = {
owner: {
$stream: owner,
},
[this.transactions.$i.admin.wallet]: {
umid: this.transactions.$i.admin.umid,
success: outSuccess,
"#nativeFee": nativeFee?.toString() || "0",
},
};
this.balances = [
{
id: owner,
partitions: ownerState.layer2,
},
];
} else {
// However it does need to set the event nicely
const consolidateFrom =
this.umidData[this.transactions.$i.admin.wallet].umid.$tx.$r.wallet;
const consolidateTo =
this.umidData[this.transactions.$i.admin.wallet].umid.$tx.$r.to;
const amount =
this.umidData[this.transactions.$i.admin.wallet].umid.$tx.$i.node
.amount;
const network =
this.umidData[this.transactions.$i.admin.wallet].umid.$tx.$i.node
.network;
const token =
this.umidData[this.transactions.$i.admin.wallet].umid.$tx.$i.node
.token || "#native";
// could set in vote with or, probably better to update method
this.layer2TDetails.network = network;
this.layer2TDetails.token = token;
// If we have native fee and consolidations we should have a payee account that has native deducted
if (
!alreadySettled &&
this.transactions.$i.admin["#nativeFee"]// &&
//this.transactions.$o.payee // No more payee!
) {
//const payee = this.getActivityStreams(this.transactions.$o.payee);
//const payeeState = payee.getState();
// Bug fix for existing wallets
//this.hasValidSchemaObject(payeeState, payee.getId());
//const payeeNativeBalance = this.getBN(
// this.getL2PartitionFrom(payeeState, payee.getId(), true)
//);
//this.setL2PartitionFrom(
// payeeState,
// payee.getId(),
// payeeNativeBalance.sub(this.transactions.$i.admin["#nativeFee"]),
// true
//);
//payee.setState(payeeState);
// Reusing the delegate stream native fee paying method for consolidation
// It is the same process really "someone else paying" but someone else is their self.
// Minigate picks it up based on native being true below (when added to the local db)
this.hasValidSchemaObject(this.delegateStreamData);
this.delegateStreamData.layer2[this.layer2TDetails.network][
"#native"
].balance = this.transactions.$i.admin["#nativeFee"];
this.delegateStreamData.fees = true;
this.delegateStreamData.deductible = true;
this.delegateStreamData.skipEvent = true;
this.delegateStreamData.dbIndex = this.transactions._dbIndex || 0;
this.delegateStream = this.newActivityStream(
this.umid + ".fees.deductible"
);
this.delegateStream.setState(this.delegateStreamData);
}
// C1: settle a repay on its gas book, once (alreadySettled, and the
// pending entry is removed). Landed: the debt goes down by the
// amount, never below 0. Failed: only the pending entry goes.
if (!alreadySettled && this.repaySettle) {
const book = this.getActivityStreams(this.transactions.$o.book);
const b: any = book.getState() || {};
const pending = b.pendingRepays && typeof b.pendingRepays === "object" ? b.pendingRepays : {};
delete pending[this.repaySettle.presign];
b.pendingRepays = pending;
if (this.repaySettle.success) {
const debt = this.getBN(b.topupDebt || 0);
const amt = this.getBN(this.repaySettle.amount);
b.topupDebt = (debt.gt(amt) ? debt.sub(amt) : this.getBN(0)).toString();
}
book.setState(b);
}
this.outputs = {
owner: {
$stream: "consolidation",
payee: this.transactions.$o.payee,
success: outSuccess,
"#nativeFee": outNativeFee,
},
[consolidateFrom]: {
sender: true,
umid: this.transactions.$i.admin.umid,
success: outSuccess,
"#nativeFee": outNativeFee,
amount,
network,
token,
},
[consolidateTo]: {
sender: false,
umid: this.transactions.$i.admin.umid,
success: outSuccess,
"#nativeFee": outNativeFee,
amount,
network,
token,
},
};
this.balances = [];
}
if (!alreadySettled) {
// Billing record (credit-only model): what happened to the send.
// Network and asset are already on l1.presign / l1.sign.
signedStreamData.confirmed = {
success: this.transactions.$i.admin.success,
umid: this.umid,
date: this.cDate,
gasFee: this.transactions.$i.admin["#nativeFee"],
delegated: this.delegated,
outcome: this.outcome(),
cancelFee: this.transactions.$i.admin["#cancelFee"] || "0",
// Bitcoin's cost meter (spec §5.5).
...(this.btcConfirmed ? { btc: this.btcConfirmed } : {}),
};
signedStream.setState(signedStreamData);
}
if (this.transactions.$i.admin.umid) {
this.event.emit("confirmation", {
umid: this.transactions.$i.admin.umid,
network: this.layer2TDetails.network,
token: this.layer2TDetails.token,
wallet: this.transactions.$i.admin.wallet,
signedStream: signedStream.getId(),
refunded: this.refunded ? this.refundAmount : 0,
varnirFee: signedStreamData.varnirFee,
outcome: signedStreamData.confirmed.outcome,
});
}
this.varnirFee = signedStreamData.varnirFee;
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;
}/** 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;
}/** * The credits-ledger block prices withdrawals through credits-helpers' * creditsWeight. This contract never prices one (it only refunds the * charge CryptoTransfer took), so it carries no weights: any price asked * for here is refused. */
private creditsWeight(_weights: any, network: string, assetClass: string, _speed: string): number | string {
return `No credit weight for ${assetClass} withdrawals on ${network}`;
}/**
* The repay a consolidation confirm settles, or null for any other
* confirm (C1, consolidation spec §4.3.7; plan 2026-10-15 step 3 Task 7).
* Varnir.Consolidation queues a repay as `pendingRepays[<presign>]` on the
* registered gas key's book and lowers nothing; the debt goes down only
* here, once the gateway confirms the move landed. Without this a gateway
* could queue a repay for the whole debt, never broadcast it, and borrow
* again for ever.
*
* The repay is read from the presign the contract wrote (`gasMove`, set by
* Consolidation from its own checks, never the gateway's metadata),
* reached through this l1.sign's `preSignedStream`, and the presign must
* name this l1.sign back (`signedStream`), so no other stream can pass as
* a repay. The confirm must be a consolidation confirm and name that
* book as `$o.book`, and the repay must still be pending there, so it is
* settled once. A failed repay only leaves the pending list (the debt is
* unchanged).
*
* @private
* @param {string} signedId the l1.sign stream id
* @param {*} signed its state
* @returns {Promise<any>}
* @memberof VarnirConfirmWithdraw
*/ private async repayToSettle(signedId: string, signed: any): Promise<any> {
// Only an internal move whose l1.sign says repay (CryptoTransfer copies
// the presign's reason); every other confirm is untouched.
if (!signed || signed.sender !== "consolidation" || signed.reason !== "repay") {
return null;
}
if (!this.transactions.$i.admin.consolidation) {
throw "Repay: confirmed only as a consolidation";
}
const presignId = signed.preSignedStream;
if (typeof presignId !== "string" || !/^[0-9a-f]{64}$/.test(presignId)) {
throw "Repay: the l1.sign names no presign";
}
let presign: any = null;
try {
presign = await this.getAnyStreamReadOnly(presignId);
} catch (e) {
throw "Repay: presign unreadable";
}
const move = presign && presign.gasMove;
if (!move || move.reason !== "repay" || presign.signedStream !== signedId || typeof move.book !== "string") {
throw "Repay: the presign is not this repay";
}
const bookRef = this.transactions.$o && this.transactions.$o.book;
if (!bookRef) {
throw "Repay: a repay confirm names its gas book ($o.book)";
}
const book = this.getActivityStreams(bookRef);
if (book.getId() !== move.book) {
throw "Repay: $o.book is not the repay's gas book";
}
const b: any = book.getState() || {};
const pending = b.pendingRepays && typeof b.pendingRepays === "object" ? b.pendingRepays : {};
if (b.type !== "gas-book" || Object.keys(pending).indexOf(presignId) === -1) {
throw "Repay: not pending on the gas book";
}
return {book: move.book, presign: presignId, amount: String(pending[presignId]), success: this.transactions.$i.admin.success === true};
}/** * Why a refund is refused, or null (audit B2). An EVM or Tron failure must * name the reason the signed payout can no longer land; vote() rejects any * reason outside REFUNDREASONS on every network, so outcome() only ever * sees one of them (or none, on Solana). `expired` is proven by Tron's * signed expiry, so it is Tron-only; `nonce-consumed` only exists on EVM * (Tron has no nonce); `cancelled` needs a cancel on the * signed stream (Task 7). Solana sends no reason and is unchanged. * * Fails closed: a network that is not a known EVM, Tron or Solana chain is * never refunded, whatever the reason - the payout might still land. */
private refundReasonRefusal(signedStreamData: any): string | null {
const admin = this.transactions.$i.admin;
if (admin.success === true || admin.consolidation) return null;
let chain: "evm" | "tron" | "sol" | "bitcoin" | null;
try {
chain = this.refundChain(this.layer2TDetails.network);
} catch (e) {
// A malformed evmNetworks entry: the block's own message, same on every node.
return typeof e === "string" ? e : "Refund refused - network lookup failed";
}
if (chain === null) return "Refund refused - unknown network";
const reason = admin.reason;
if (reason === undefined) {
return chain === "sol" ? null : "Refund needs a can't-land reason";
}
if (!REFUNDREASONS.includes(reason)) return "Refund needs a can't-land reason";
// Bitcoin (spec §8.5): a signed transaction never expires, so the only
// proof it can't land is a confirmed conflicting spend of one of its
// inputs. Only our own RBF cancel recorded on the signed stream is
// accepted here; a foreign conflict needs a person (no automatic refund).
if (chain === "bitcoin" || reason === "conflicted") {
if (chain !== "bitcoin" || reason !== "conflicted") {
return chain === "bitcoin" ? "Refund reason for Bitcoin must be conflicted" : "Refund reason conflicted is Bitcoin-only";
}
const conflict = admin.btcConflict;
const ours = (signedStreamData.btc && Array.isArray(signedStreamData.btc.cancels)) ? signedStreamData.btc.cancels : [];
if (!conflict || typeof conflict.txid !== "string" || !ours.some((c: any) => c && c.txid === conflict.txid)) {
return "Bitcoin: refund needs our own cancel confirmed at depth; a foreign conflict needs a person";
}
return null;
}
if (reason === "expired" && chain !== "tron") {
return "Refund reason expired is Tron-only";
}
if (reason === "nonce-consumed" && chain !== "evm") {
return "Refund reason nonce-consumed is EVM-only";
}
if (reason === "cancelled" && !signedStreamData.cancels?.length) {
return "Refund reason cancelled needs a cancel on the signed stream";
}
return null;
}/** * The network's family for refund rules, or null for an unknown network * (refused). EVM is decided by the evm-registry block - the four constants * or an enabled `evmNetworks` entry - so a chain added by an owner `mod` * gets EVM rules without a deploy. Throws when that entry is malformed. */
private refundChain(network: string): "evm" | "tron" | "sol" | "bitcoin" | null {
if (this.evmNetworkData(network)) return "evm";
if (this.btcParams(network) !== null) {
// A disabled entry still refunds what is in flight (security review M1).
return this.btcAnyNetworkData(network) ? "bitcoin" : null;
}
switch (String(network ?? "").toLowerCase()) {
case "sol":
case "soldev":
return "sol";
case "trx":
case "trx-nile":
case "niles":
case "trx-shasta":
case "shasta":
return "tron";
default:
return null;
}
}/** * The recorded outcome of the send (billing record, RV2). This is the one * on-chain / pre-inclusion classifier (Task 2); it no longer decides who * pays. A failure is ON-CHAIN when admin.reason === 'reverted'; any other * allowed reason is pre-inclusion. EVM and Tron must send a reason * (refundReasonRefusal), so the no-reason fallback - on-chain when gas was * burned - is only reached on Solana, which sends none. */
private outcome(): "sent" | "failed-on-chain" | "failed-before-inclusion" {
const admin = this.transactions.$i.admin;
if (admin.success === true) return "sent";
const fee = this.getBN(admin["#nativeFee"] || 0);
return admin.reason === "reverted" ||
(admin.reason === undefined && fee.gt(0))
? "failed-on-chain"
: "failed-before-inclusion";
}/** * One settlement for every outcome, credit-only model (spec revision * 6e7935d). `delegated` comes from the LEDGER (signedStreamData), never * $i.owner.delegated (B3). Returns what the user was charged; the rest of * the gas is Varnir's cost, booked to .fees.deductible. No Varnir fee is * taken, and Tron's #nativeFeeX (a shadow charge, not a cost) is ignored * (RV3). * * - Native send (not delegated) with a presign hold: the hold was debited * at presign. Success: the user pays min(fee, hold), the rest of the hold * is released. Failure: the whole hold is released. * - Token send (delegated): any gasHold is only a price/limit envelope that * was never debited, so it is never released; the user's native is not * touched. * - Legacy non-delegated presign without a hold: a success charges the gas * floored at the user's available native (B5). * - Any failure: principal back in full; a legacy presign's Varnir fee is * refunded paired with a .fees.deductible.refund receiver debit (RV5). */
private settle(signedStreamData: any, senderState: any | null): BN {
const admin = this.transactions.$i.admin;
const success = admin.success === true;
const delegated = signedStreamData.delegated === true;
const fee = this.getBN(admin["#nativeFee"] || 0);
const varnirFee = this.getBN(signedStreamData.varnirFee || 0);
// Only a non-delegated hold was debited from the user at presign.
const hold =
!delegated && signedStreamData.gasHold
? this.getBN(signedStreamData.gasHold.amount)
: null;
let userGas = this.getBN(0);
if (senderState && hold) {
if (success) userGas = fee.lt(hold) ? fee : hold;
const release = hold.sub(userGas);
this.setL2Balance(
senderState,
this.getBN(this.getL2Balance(senderState, true)).add(release),
true
);
} else if (senderState && success && !delegated) {
// Legacy (no hold): charge the real cost but never below zero (B5).
const bal = this.getBN(this.getL2Balance(senderState, true));
const available = bal.gt(0) ? bal : this.getBN(0);
userGas = fee.lt(available) ? fee : available;
this.setL2Balance(senderState, bal.sub(userGas), true);
}
if (senderState && !success) {
let credit = this.getBN(this.refundAmount);
if (varnirFee.gt(0)) {
// Legacy in-flight presign that took a Varnir fee (RV5).
credit = credit.add(varnirFee);
this.writeFeeStream("refund", this.layer2TDetails.token, varnirFee);
this.refundAmount = this.getBN(this.refundAmount)
.add(varnirFee)
.toString();
}
this.setL2Balance(
senderState,
this.getBN(this.getL2Balance(senderState)).add(credit)
);
this.refunded = true;
}
// Gas burned by a mined cancel (Task 7) is always Varnir's cost, on a
// failure ('cancelled') and on a success where the original mined after
// a cancel was sent: the user pays at most the original's own gas.
// Booked once: a settled stream is never settled again (RV7).
const varnirGas = fee
.sub(userGas)
.add(this.getBN(admin["#cancelFee"] || 0));
if (varnirGas.gt(0)) this.writeFeeStream("deductible", "#native", varnirGas);
return userGas;
}/** * True when one of the contract stream's authorities has `public` equal to * `identity` (voteMod passes the signing identity's stream id). */
private hasContractOwnership(contract: Activity, identity: string): boolean {
return contract.getAuthorities().some((v) => v.public === identity);
}/** * Owner-only (never ALLOWEDMOD) `mod`: writes the EVM and Bitcoin network * tables, each validated whole. The chain table decides which refunds get * EVM rules. */
private async voteMod(): Promise<boolean> {
if (!this.transactions.$o || !this.transactions.$o.contract) {
throw "Missing Contract Output";
}
const contract = this.getActivityStreams(this.transactions.$o.contract);
if (this.transactions.$contract.substring(0, 64) !== contract.getId()) {
throw "Contract Not Matching";
}
const modId = this.getActivityStreams(this.transactions.$i.owner).getId();
if (!this.hasContractOwnership(contract, modId)) {
throw "No Contract Authority";
}
this.assertEvmNetworks(this.transactions.$i.owner.evmNetworks);
this.assertBtcNetworks(this.transactions.$i.owner.btcNetworks);
return true;
}/** `mod` commit: stores `evmNetworks` and `btcNetworks` (each replaced whole, else kept), `umid` and `updated`. */
private async commitMod(): Promise<boolean> {
const wrapper: any = this.getContractData();
const cd: any = wrapper && wrapper.data ? wrapper.data : {};
// Replaced whole, never merged here: the write script merges first.
cd.evmNetworks = this.transactions.$i.owner.evmNetworks ?? cd.evmNetworks ?? null;
cd.btcNetworks = this.transactions.$i.owner.btcNetworks ?? cd.btcNetworks ?? null;
cd.umid = this.umid;
cd.updated = this.cDate;
this.setContractData(cd);
return true;
}/** The `evmNetworks` fields this contract stores and reads (evm-registry block). */
private evmFieldSpec(): {required: string[]; optional: string[]}/** The chains known before contract data existed. Returned fresh, never shared. */
private evmConstants(): {[code: string]: any}/** Codes of the non-EVM chains, in every spelling a contract sees. Never an `evmNetworks` key. */
private evmNonEvmCodes(): string[] {
return ["trx", "trx-nile", "niles", "trx-shasta", "shasta", "sol", "soldev"];
}/** This contract's stored `evmNetworks` map ({} when unset). Throws when it is not an object. */ private evmStoredNetworks(): {[code: string]: any}/** * The chain facts for `code` (any casing of the canonical or ledger code), * with `code` set to the lower-case key; null when `code` is not an EVM chain * this contract knows. Throws when the stored entry for it is malformed. */
private evmNetworkData(code: string): any | null {
const raw = String(code === undefined || code === null ? "" : code);
// ASCII only, checked BEFORE lower-casing: toLowerCase folds some non-ASCII
// letters onto ASCII ones (the Kelvin sign U+212A becomes "k"), which would
// let a look-alike spelling reach a real chain's entry.
if (!/^[A-Za-z0-9-]+$/.test(raw)) {
return null;
}
const key = raw.toLowerCase();
if (this.evmNonEvmCodes().indexOf(key) !== -1) {
return null;
}
const stored = this.evmStoredNetworks();
if (Object.keys(stored).indexOf(key) !== -1) {
this.assertEvmNetworkEntry(key, stored[key]);
if (stored[key].enabled === true) {
return {...stored[key], code: key};
}
}
const constants = this.evmConstants();
if (Object.keys(constants).indexOf(key) !== -1) {
return {...constants[key], code: key};
}
return null;
}/** evmNetworkData, failing closed. */
private requireEvmNetwork(code: string): any {
const found = this.evmNetworkData(code);
if (!found) {
throw `Unknown EVM network ${code}`;
}
return found;
}/** * The `mod` validator for a whole `evmNetworks` map. Absent (undefined/null) * leaves the stored map alone. One bad field refuses the whole write. */
private assertEvmNetworks(value: any): void {
if (value === undefined || value === null) {
return;
}
if (typeof value !== "object" || Array.isArray(value)) {
throw "evmNetworks must be an object keyed by canonical network code";
}
const byChainId: {[chainId: string]: string} = {};
for (const code of Object.keys(value)) {
this.assertEvmNetworkEntry(code, value[code]);
const chainId = String(value[code].chainId);
if (Object.keys(byChainId).indexOf(chainId) !== -1) {
throw `evmNetworks: chain id ${chainId} is used by both ${byChainId[chainId]} and ${code}`;
}
byChainId[chainId] = code;
}
const constants = this.evmConstants();
for (const code of Object.keys(constants)) {
const chainId = String(constants[code].chainId);
if (Object.keys(byChainId).indexOf(chainId) !== -1 && byChainId[chainId] !== code) {
throw `evmNetworks.${byChainId[chainId]}: chain id ${chainId} belongs to ${code}`;
}
}
}/** One `evmNetworks` entry, against this contract's evmFieldSpec. */
private assertEvmNetworkEntry(code: string, entry: any): void {
if (typeof code !== "string" || !/^[a-z][a-z0-9-]{1,15}$/.test(code)) {
throw `evmNetworks: ${code} is not a canonical network code`;
}
if (this.evmNonEvmCodes().indexOf(code) !== -1) {
throw `evmNetworks: ${code} is not an EVM network`;
}
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
throw `evmNetworks.${code} must be an object`;
}
const spec = this.evmFieldSpec();
const fields = Object.keys(entry);
for (const field of fields) {
if (spec.required.indexOf(field) === -1 && spec.optional.indexOf(field) === -1) {
throw `evmNetworks.${code}.${field} is not a field this contract uses`;
}
}
for (const field of spec.required) {
if (fields.indexOf(field) === -1) {
throw `evmNetworks.${code}.${field} is required`;
}
}
if (typeof entry.ledger !== "string" || !/^[A-Za-z][A-Za-z0-9-]{1,15}$/.test(entry.ledger) || entry.ledger.toLowerCase() !== code) {
throw `evmNetworks.${code}.ledger must spell ${code} in the ledger's own casing`;
}
if (typeof entry.chainId !== "number" || !Number.isSafeInteger(entry.chainId) || entry.chainId <= 0) {
throw `evmNetworks.${code}.chainId must be a positive integer`;
}
if (typeof entry.enabled !== "boolean") {
throw `evmNetworks.${code}.enabled must be true or false`;
}
const constants = this.evmConstants();
if (Object.keys(constants).indexOf(code) !== -1 &&
(entry.ledger !== constants[code].ledger || entry.chainId !== constants[code].chainId)) {
throw `evmNetworks.${code} must keep ledger code ${constants[code].ledger} and chain id ${constants[code].chainId}`;
}
if (fields.indexOf("rpc") !== -1) {
const rpc = entry.rpc;
if (!Array.isArray(rpc) || rpc.length < 1 || rpc.length > 4) {
throw `evmNetworks.${code}.rpc must list 1 to 4 URLs`;
}
for (const url of rpc) {
if (
typeof url !== "string" ||
url.length > 200 ||
!/^https:\/\/[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+(:[0-9]{1,5})?(\/[A-Za-z0-9._~-]+)*\/?$/.test(url)
) {
throw `evmNetworks.${code}.rpc: ${url} is not a plain https URL`;
}
// Contract data is public: a keyed provider URL (Alchemy /v2/<key>,
// Infura /v3/<key>, QuickNode /<token>/) must never land here.
const urlPath = url.slice(8).indexOf("/") === -1 ? "" : url.slice(8 + url.slice(8).indexOf("/"));
if (/[A-Za-z0-9_-]{24,}/.test(urlPath)) {
throw `evmNetworks.${code}.rpc: ${url} looks like it carries an API key`;
}
}
}
if (fields.indexOf("gasLimits") !== -1) {
const limits = entry.gasLimits;
if (!limits || typeof limits !== "object" || Array.isArray(limits)) {
throw `evmNetworks.${code}.gasLimits must be {native, token, cancel}`;
}
const names = Object.keys(limits);
if (names.length !== 3 || names.indexOf("native") === -1 || names.indexOf("token") === -1 || names.indexOf("cancel") === -1) {
throw `evmNetworks.${code}.gasLimits must be {native, token, cancel}`;
}
for (const name of names) {
const units = limits[name];
if (typeof units !== "number" || !Number.isSafeInteger(units) || units < 21000 || units > 5000000) {
throw `evmNetworks.${code}.gasLimits.${name} must be an integer from 21000 to 5000000`;
}
}
}
for (const field of ["gasPriceCap", "l1FeeCap"]) {
if (fields.indexOf(field) !== -1 && (typeof entry[field] !== "string" || !/^[1-9][0-9]{0,29}$/.test(entry[field]))) {
throw `evmNetworks.${code}.${field} must be a positive integer string (wei)`;
}
}
}/** * A move's confirm: only its own txid, at depth, as a success. Each check, * and why: a move has one version (never bumped, so `btcTxid` must be its * txid); it has no refund (nothing was held, so a failure is a person's to * look at, never a ledger write); every input must still be locked to this * stream and its output pending in the destination book, so only the move * this contract signed is settled, once. Fees come from the record. */
private btcVoteMoveConfirm(signedStreamId: string, signedStreamData: any): void {
const admin = this.transactions.$i.admin;
const network = String(signedStreamData.network || "").toLowerCase();
if (this.btcParams(network) === null) {
throw "Bitcoin: a move is a Bitcoin record";
}
this.layer2TDetails.network = network;
this.layer2TDetails.token = "«redacted»";
// A disabled entry stops new work, never the settling of a signed move.
this.requireBtcNetworkInFlight(network);
for (const field of ["#nativeFee", "#cancelFee", "#nativeFeeX"]) {
if (admin[field] !== undefined && admin[field] !== null && admin[field] !== "") {
throw "Bitcoin: fees come from the signed record, not the confirm";
}
}
if (admin.btcHeight !== undefined && (typeof admin.btcHeight !== "number" || !Number.isInteger(admin.btcHeight) || admin.btcHeight < 0)) {
throw "Bitcoin: btcHeight must be a non-negative integer";
}
// A forced re-confirm of a settled move writes nothing.
if (signedStreamData.confirmed) {
this.btcMove = true;
return;
}
const btc = signedStreamData.btc;
if (admin.success !== true) {
throw "Bitcoin: a move settles only on its own confirmation";
}
if (typeof btc.txid !== "string" || admin.btcTxid !== btc.txid) {
throw "Bitcoin: the confirmed txid is not this move's";
}
if (!Array.isArray(btc.inputs) || btc.inputs.length < 1 || !Array.isArray(btc.outputs) || btc.outputs.length !== 1 ||
btc.outputs[0].role !== "move" || typeof btc.fee !== "string" || !/^[0-9]{1,16}$/.test(btc.fee)) {
throw "Bitcoin: the signed record is not a Bitcoin move";
}
const loaded: any = (this as any).getActivityStreams() || {};
const load = (id: string): any => {
if (!this.btcBooks[id]) {
const stream = loaded[id];
if (!stream || typeof stream.getState !== "function") {
throw "Bitcoin: every UTXO book of the move must be an output of this confirm";
}
const state = stream.getState();
if (!state || state.type !== "btc-utxo-book" || state.network !== network) {
throw "Bitcoin: not a UTXO book for this network";
}
this.btcBooks[id] = {stream, state};
}
return this.btcBooks[id].state;
};
for (const i of btc.inputs) {
const book = load(i.book);
const entry = book.entries ? book.entries[i.outpoint] : undefined;
if (book.wallet !== i.wallet || !entry || entry.state !== "locked" || entry.lockedBy !== signedStreamId) {
throw `Bitcoin: input ${i.outpoint} is not locked to this move`;
}
// A held deposit (PR #417 review H1) is credited to whom it was held
// for once the move that spends it confirms: that identity must be an
// output here, and the book entry must still say it was held for them.
if (i.heldFor !== undefined) {
if (typeof i.heldFor !== "string" || entry.heldFor !== i.heldFor || !loaded[i.heldFor] || typeof loaded[i.heldFor].getState !== "function") {
throw `Bitcoin: the held deposit ${i.outpoint} needs its owner as an output of this confirm`;
}
}
}
const o = btc.outputs[0];
const book = load(o.book);
const entry = book.entries ? book.entries[`${btc.txid}_${o.vout}`] : undefined;
if (book.wallet !== o.wallet || !entry || entry.state !== "pending" || entry.spentFrom !== signedStreamId) {
throw "Bitcoin: the move's output is not pending in its book";
}
this.btcMove = true;
}/** * A move's settle: its inputs are spent and pruned, its output becomes * spendable in the destination book, the whole fee is Varnir's * `.fees.deductible`, and `confirmed` is written. No L2 balance moves. */
private btcSettleMove(signedStream: any, signedStreamData: any): void {
const admin = this.transactions.$i.admin;
if (!signedStreamData.confirmed) {
const btc = signedStreamData.btc;
// Held deposits the move swept are credited now, once: the move has
// confirmed, so their coins are out from behind the frozen key.
const loaded: any = (this as any).getActivityStreams() || {};
for (const i of btc.inputs) {
if (typeof i.heldFor === "string") {
const owner = loaded[i.heldFor];
const ownerState = owner.getState();
this.hasValidSchemaObject(ownerState);
this.setL2Balance(ownerState, this.getBN(this.getL2Balance(ownerState)).add(this.getBN(i.value)));
owner.setState(ownerState);
// The frozen address it was sent to, so the scanner can show the owner the release on that wallet.
const book = this.btcBooks[i.book];
const address = book && book.state && typeof book.state.address === "string" ? book.state.address : null;
this.event.emit("held-deposit-credited", {owner: i.heldFor, outpoint: i.outpoint, amount: i.value, network: this.layer2TDetails.network, address, signedStream: signedStream.getId()});
}
}
for (const i of btc.inputs) {
delete this.btcBooks[i.book].state.entries[i.outpoint];
}
const o = btc.outputs[0];
const entry = this.btcBooks[o.book].state.entries[`${btc.txid}_${o.vout}`];
entry.state = "spendable";
if (admin.btcHeight !== undefined) {
entry.height = admin.btcHeight;
}
for (const id of Object.keys(this.btcBooks)) {
this.btcBooks[id].stream.setState(this.btcBooks[id].state);
}
const fee = this.getBN(btc.fee);
if (fee.gt(0)) {
this.writeFeeStream("deductible", "#native", fee);
}
signedStreamData.confirmed = {
success: true,
umid: this.umid,
date: this.cDate,
gasFee: btc.fee,
delegated: false,
outcome: "sent",
cancelFee: "0",
btc: {txid: btc.txid, kind: "move", height: admin.btcHeight ?? null, vsize: btc.vsize, fee: btc.fee, userFee: "0", varnirFee: btc.fee, inputs: btc.inputs.length},
};
signedStream.setState(signedStreamData);
}
this.event.emit("confirmation", {
umid: signedStreamData.umid,
network: this.layer2TDetails.network,
token: "«redacted»",
wallet: signedStreamData.stream,
signedStream: signedStream.getId(),
refunded: 0,
varnirFee: "0",
outcome: signedStreamData.confirmed.outcome,
});
}/** Every version of a Bitcoin payout, oldest first; the last is current. */
private btcVersions(btc: any): any[] {
const current = {
kind: btc.kind || "payout", txid: btc.txid, inputs: btc.inputs, outputs: btc.outputs, vsize: btc.vsize,
fee: btc.fee, feeRate: btc.feeRate, userFees: btc.userFees,
};
return (Array.isArray(btc.history) ? btc.history : []).concat([current]);
}/** * Bitcoin confirm checks. The fee comes from the signed record, never the * caller, so `#nativeFee` / `#cancelFee` are refused. A success names the * txid that confirmed, which must be one of the payout's versions (the * original or an RBF bump); a refund names our own cancel (checked by * refundReasonRefusal). Every input of the current version must still be * locked to this signed stream, and every book it touches must be an output * of this transaction. */
private btcVoteConfirm(signedStreamId: string, signedStreamData: any): void {
const admin = this.transactions.$i.admin;
// A disabled entry stops new payouts, never their confirm (security review M1).
this.requireBtcNetworkInFlight(this.layer2TDetails.network);
if (admin.consolidation) {
throw "Bitcoin: no consolidation confirm";
}
const btc = signedStreamData.btc;
if (!btc || typeof btc.txid !== "string" || !Array.isArray(btc.inputs) || !Array.isArray(btc.outputs) ||
!Array.isArray(btc.covers) || btc.covers.length !== 1 || !btc.userFees || !signedStreamData.gasHold) {
throw "Bitcoin: the signed record is not a Bitcoin payout";
}
for (const field of ["#nativeFee", "#cancelFee", "#nativeFeeX"]) {
if (admin[field] !== undefined && admin[field] !== null && admin[field] !== "") {
throw "Bitcoin: fees come from the signed record, not the confirm";
}
}
if (admin.btcHeight !== undefined && (typeof admin.btcHeight !== "number" || !Number.isInteger(admin.btcHeight) || admin.btcHeight < 0)) {
throw "Bitcoin: btcHeight must be a non-negative integer";
}
// A forced re-confirm of a settled payout moves nothing (RV7): no books.
if (signedStreamData.confirmed) {
return;
}
const versions = this.btcVersions(btc);
const want = admin.success === true ? admin.btcTxid : admin.btcConflict ? admin.btcConflict.txid : undefined;
const kind = admin.success === true ? "payout" : "cancel";
this.btcVersion = versions.filter((v: any) => v.kind === kind && v.txid === want)[0] || null;
if (!this.btcVersion) {
throw admin.success === true ? "Bitcoin: the confirmed txid is not this payout's" : "Bitcoin: the conflict is not our own cancel";
}
// Never getActivityStreams(ref) for an unloaded ref: that creates a stream.
const loaded: any = (this as any).getActivityStreams() || {};
const load = (id: string): any => {
if (!this.btcBooks[id]) {
const stream = loaded[id];
if (!stream || typeof stream.getState !== "function") {
throw "Bitcoin: every UTXO book of the payout must be an output of this confirm";
}
const state = stream.getState();
if (!state || state.type !== "btc-utxo-book" || state.network !== this.layer2TDetails.network) {
throw "Bitcoin: not a UTXO book for this network";
}
this.btcBooks[id] = {stream, state};
}
return this.btcBooks[id].state;
};
for (const i of btc.inputs) {
const book = load(i.book);
const entry = book.entries ? book.entries[i.outpoint] : undefined;
if (book.wallet !== i.wallet || !entry || entry.state !== "locked" || entry.lockedBy !== signedStreamId) {
throw `Bitcoin: input ${i.outpoint} is not locked to this payout`;
}
}
for (const o of btc.outputs) {
if (o.role === "change") {
const book = load(o.book);
const entry = book.entries ? book.entries[`${btc.txid}_${o.vout}`] : undefined;
if (book.wallet !== o.wallet || !entry || entry.state !== "pending") {
throw "Bitcoin: the change output is not pending in its book";
}
}
}
for (const o of this.btcVersion.outputs) {
if (o.role === "change") {
if (load(o.book).wallet !== o.wallet) {
throw "Bitcoin: the change output is not pending in its book";
}
}
}
}/** * Bitcoin settle, against the version that confirmed. A payout version: * the user pays their reference-size share at that version's rate, * `min(hold, feeRate × referenceVbytes)` (spec §5.2, §5.3), the rest of the * hold is released and the rest of the real fee (extra inputs, dust * absorbed) is Varnir's `.fees.deductible`. Our own cancel: the amount and * the whole hold go back and its fee is Varnir's. Either way that * version's inputs are spent and pruned, any other input is unlocked, the * current version's pending change leaves its book and the confirmed * version's change becomes spendable. */
private btcSettle(signedStreamData: any, senderState: any | null): BN {
const admin = this.transactions.$i.admin;
const btc = signedStreamData.btc;
const v = this.btcVersion;
const success = admin.success === true;
const hold = this.getBN(signedStreamData.gasHold.amount);
let userGas = this.getBN(0);
if (success) {
const share = this.getBN(v.userFees[btc.covers[0]] ?? 0);
userGas = share.lt(hold) ? share : hold;
// Nor above the fee that version really paid (security review L2).
const paid = this.getBN(v.fee);
if (userGas.gt(paid)) {
userGas = paid;
}
}
if (senderState) {
this.setL2Balance(senderState, this.getBN(this.getL2Balance(senderState, true)).add(hold.sub(userGas)), true);
if (!success) {
this.setL2Balance(senderState, this.getBN(this.getL2Balance(senderState)).add(this.getBN(this.refundAmount)));
this.refunded = true;
}
}
const varnirGas = this.getBN(v.fee).sub(userGas);
if (varnirGas.gt(0)) {
this.writeFeeStream("deductible", "#native", varnirGas);
}
const spent = v.inputs.map((i: any) => i.outpoint);
for (const i of btc.inputs) {
const entries = this.btcBooks[i.book].state.entries;
if (spent.indexOf(i.outpoint) !== -1) {
delete entries[i.outpoint];
} else {
entries[i.outpoint].state = "spendable";
delete entries[i.outpoint].lockedBy;
}
}
for (const o of btc.outputs) {
if (o.role === "change" && btc.txid !== v.txid) {
delete this.btcBooks[o.book].state.entries[`${btc.txid}_${o.vout}`];
}
}
for (const o of v.outputs) {
if (o.role === "change") {
const entries = this.btcBooks[o.book].state.entries;
const key = `${v.txid}_${o.vout}`;
entries[key] = entries[key] || {value: o.value, scriptType: "p2wpkh", source: "change", fromTxid: v.txid, created: this.cDate};
entries[key].state = "spendable";
if (admin.btcHeight !== undefined) {
entries[key].height = admin.btcHeight;
}
}
}
for (const id of Object.keys(this.btcBooks)) {
this.btcBooks[id].stream.setState(this.btcBooks[id].state);
}
this.btcConfirmed = {
txid: v.txid,
kind: v.kind,
height: admin.btcHeight ?? null,
vsize: v.vsize,
fee: String(v.fee),
userFee: userGas.toString(),
varnirFee: varnirGas.toString(),
inputs: v.inputs.length,
};
return userGas;
}/** Address parameters per code. Returned fresh, never shared. */
private btcParams(code: string): {hrp: string; p2pkh: number; p2sh: number}/** This contract's stored `btcNetworks` map ({} when unset). Throws when it is not an object. */ private btcStoredNetworks(): {[code: string]: any}/** The `btcNetworks` entry for `code`, enabled or not, with `code` set, or null. Throws when it is malformed. */
private btcAnyNetworkData(code: string): any | null {
const key = typeof code === "string" ? code : "";
if (this.btcParams(key) === null) {
return null;
}
const stored = this.btcStoredNetworks();
if (Object.keys(stored).indexOf(key) === -1) {
return null;
}
this.assertBtcNetworkEntry(key, stored[key]);
return {...stored[key], code: key};
}/** The enabled `btcNetworks` entry for `code` with `code` set, or null. Throws when it is malformed. */
private btcNetworkData(code: string): any | null {
const found = this.btcAnyNetworkData(code);
return found && found.enabled === true ? found : null;
}/** btcNetworkData, failing closed. For new Bitcoin work: wallets, deposits, payouts. */
private requireBtcNetwork(code: string): any {
const found = this.btcNetworkData(code);
if (!found) {
throw `Unknown Bitcoin network ${code}`;
}
return found;
}/** * btcAnyNetworkData, failing closed. For finishing what is already signed * (broadcast, bump, cancel, confirm, refund): `enabled: false` stops new * Bitcoin work, never the way out of a payout in flight. */
private requireBtcNetworkInFlight(code: string): any {
const found = this.btcAnyNetworkData(code);
if (!found) {
throw `Unknown Bitcoin network ${code}`;
}
return found;
}/** The `mod` validator for a whole `btcNetworks` map. Absent leaves the stored map alone. */
private assertBtcNetworks(value: any): void {
if (value === undefined || value === null) {
return;
}
if (typeof value !== "object" || Array.isArray(value)) {
throw "btcNetworks must be an object keyed by network code";
}
for (const code of Object.keys(value)) {
this.assertBtcNetworkEntry(code, value[code]);
}
}/** * One `btcNetworks` entry (spec §8.1). Every field is required but the * optional `mpcCeilingSats` (PR #417 review M1); no others are allowed. */
private assertBtcNetworkEntry(code: string, entry: any): void {
const params = this.btcParams(code);
if (params === null) {
throw `btcNetworks: ${code} is not a Bitcoin network`;
}
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
throw `btcNetworks.${code} must be an object`;
}
const fields = ["ledger", "hrp", "enabled", "confirmations", "conflictDepth", "feeRateCapSatVb",
"sweepFeeRateCap", "referenceVbytes", "dustSats", "minCreditSats", "maxInputs", "maxMpcInputs",
"maxSweepInputs", "maxBatchOutputs", "broadcast"];
// The Advanced (mpc2) wallet ceiling, in sats (PR #417 review M1):
// Varnir.CryptoTransfer's `btcmove` reason `ceiling` checks a move
// against it, so a gateway cannot move Advanced coins on its own word.
// Optional: absent, no ceiling move is accepted on the network.
const optional = ["mpcCeilingSats"];
for (const field of Object.keys(entry)) {
if (fields.indexOf(field) === -1 && optional.indexOf(field) === -1) {
throw `btcNetworks.${code}.${field} is not a Bitcoin network field`;
}
}
if (entry.mpcCeilingSats !== undefined && (typeof entry.mpcCeilingSats !== "string" || !/^[1-9][0-9]{0,15}$/.test(entry.mpcCeilingSats))) {
throw `btcNetworks.${code}.mpcCeilingSats must be a positive integer string of sats`;
}
for (const field of fields) {
if (Object.keys(entry).indexOf(field) === -1) {
throw `btcNetworks.${code}.${field} is required`;
}
}
if (entry.ledger !== code) {
throw `btcNetworks.${code}.ledger must be ${code}`;
}
if (entry.hrp !== params.hrp) {
throw `btcNetworks.${code}.hrp must be ${params.hrp}`;
}
if (typeof entry.enabled !== "boolean") {
throw `btcNetworks.${code}.enabled must be true or false`;
}
const int = (name: string, min: number, max: number) => {
const v = entry[name];
if (typeof v !== "number" || !Number.isSafeInteger(v) || v < min || v > max) {
throw `btcNetworks.${code}.${name} must be an integer from ${min} to ${max}`;
}
};
int("confirmations", 1, 100);
int("conflictDepth", 1, 100);
if (entry.conflictDepth < entry.confirmations) {
throw `btcNetworks.${code}.conflictDepth must be at least confirmations`;
}
int("sweepFeeRateCap", 1, 10000);
int("referenceVbytes", 100, 1000);
int("maxInputs", 1, 100);
int("maxMpcInputs", 0, 100);
int("maxSweepInputs", 1, 100);
int("maxBatchOutputs", 1, 100);
if (entry.maxMpcInputs > entry.maxInputs) {
throw `btcNetworks.${code}.maxMpcInputs must not exceed maxInputs`;
}
const caps = entry.feeRateCapSatVb;
if (!caps || typeof caps !== "object" || Array.isArray(caps) || Object.keys(caps).length !== 3) {
throw `btcNetworks.${code}.feeRateCapSatVb must be {instant, standard, economy}`;
}
for (const speed of ["instant", "standard", "economy"]) {
const v = caps[speed];
if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 1 || v > 10000) {
throw `btcNetworks.${code}.feeRateCapSatVb.${speed} must be an integer from 1 to 10000`;
}
}
for (const name of ["dustSats", "minCreditSats"]) {
if (typeof entry[name] !== "string" || !/^[1-9][0-9]{0,15}$/.test(entry[name])) {
throw `btcNetworks.${code}.${name} must be a positive integer string of sats`;
}
}
if (BigInt(entry.dustSats) < this.btcDustThreshold("p2wpkh")) {
throw `btcNetworks.${code}.dustSats must be at least the P2WPKH relay dust (294)`;
}
const urls = entry.broadcast;
if (!Array.isArray(urls) || urls.length < 1 || urls.length > 4) {
throw `btcNetworks.${code}.broadcast must list 1 to 4 URLs`;
}
for (const u of urls) {
// Keyless endpoints only: no credentials or query strings in contract data.
if (typeof u !== "string" || !/^https:\/\/[a-z0-9.-]+(:[0-9]{1,5})?(\/[A-Za-z0-9._~\/-]*)?$/.test(u)) {
throw `btcNetworks.${code}.broadcast entries must be plain https URLs`;
}
}
} private btcHexToBytes(hex: string): Uint8Array {
if (typeof hex !== "string" || hex.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(hex)) {
throw "Bitcoin: invalid hex";
}
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return out;
} private btcBytesToHex(bytes: Uint8Array): string {
let s = "";
for (let i = 0; i < bytes.length; i++) {
s += (bytes[i] < 16 ? "0" : "") + bytes[i].toString(16);
}
return s;
} private btcConcat(parts: Uint8Array[]): Uint8Array {
let len = 0;
for (const p of parts) {
len += p.length;
}
const out = new Uint8Array(len);
let off = 0;
for (const p of parts) {
out.set(p, off);
off += p.length;
}
return out;
} private btcReverse(bytes: Uint8Array): Uint8Array {
const out = new Uint8Array(bytes.length);
for (let i = 0; i < bytes.length; i++) {
out[i] = bytes[bytes.length - 1 - i];
}
return out;
} private btcSha256d(data: Uint8Array): Uint8Array {
return utils.arrayify(utils.sha256(utils.sha256(data)));
} private btcHash160(data: Uint8Array): Uint8Array {
return utils.arrayify(utils.ripemd160(utils.sha256(data)));
} private btcU32(n: number): Uint8Array {
if (typeof n !== "number" || !Number.isInteger(n) || n < 0 || n > 4294967295) {
throw "Bitcoin: u32 out of range";
}
return Uint8Array.from([n & 255, (n >>> 8) & 255, (n >>> 16) & 255, (n >>> 24) & 255]);
} private btcU64(n: bigint): Uint8Array {
if (typeof n !== "bigint" || n < 0n || n > 2100000000000000n) {
throw "Bitcoin: amount out of range";
}
const out = new Uint8Array(8);
let v = n;
for (let i = 0; i < 8; i++) {
out[i] = Number(v & 255n);
v = v >> 8n;
}
return out;
} private btcVarint(n: number): Uint8Array {
if (n < 253) {
return Uint8Array.from([n]);
}
if (n <= 65535) {
return Uint8Array.from([253, n & 255, n >>> 8]);
}
throw "Bitcoin: varint too large";
} private btcVarbytes(b: Uint8Array): Uint8Array {
return this.btcConcat([this.btcVarint(b.length), b]);
} private btcPolymod(values: number[]): number {
const gen = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
let chk = 1;
for (const v of values) {
const hi = chk >>> 25;
chk = (((chk & 0x1ffffff) << 5) ^ v) >>> 0;
for (let i = 0; i < 5; i++) {
if ((hi >>> i) & 1) {
chk = (chk ^ gen[i]) >>> 0;
}
}
}
return chk;
} private btcHrpExpand(hrp: string): number[] {
const out: number[] = [];
for (let i = 0; i < hrp.length; i++) {
out.push(hrp.charCodeAt(i) >>> 5);
}
out.push(0);
for (let i = 0; i < hrp.length; i++) {
out.push(hrp.charCodeAt(i) & 31);
}
return out;
} private btcConvertBits(data: number[], from: number, to: number, pad: boolean): number[] {
let acc = 0;
let bits = 0;
const out: number[] = [];
const maxv = (1 << to) - 1;
for (const value of data) {
acc = (acc << from) | value;
bits += from;
while (bits >= to) {
bits -= to;
out.push((acc >> bits) & maxv);
}
}
if (pad) {
if (bits > 0) {
out.push((acc << (to - bits)) & maxv);
}
} else if (bits >= from || ((acc << (to - bits)) & maxv) !== 0) {
throw "Bitcoin: invalid address padding";
}
return out;
}/** A segwit address for `hrp` (BIP173 + BIP350): {version, program}. Throws on any rule break. */ private btcDecodeSegwit(hrp: string, s: string): {version: number; program: Uint8Array} private btcBase58checkDecode(s: string): Uint8Array {
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
if (s.length < 1 || s.length > 64) {
throw "Bitcoin: malformed base58 address";
}
let n = 0n;
for (let i = 0; i < s.length; i++) {
const d = alphabet.indexOf(s.charAt(i));
if (d === -1) {
throw "Bitcoin: invalid base58 character";
}
n = n * 58n + BigInt(d);
}
const body: number[] = [];
while (n > 0n) {
body.unshift(Number(n & 255n));
n = n >> 8n;
}
let zeros = 0;
while (zeros < s.length && s.charAt(zeros) === "1") {
zeros++;
}
const raw = new Uint8Array(zeros + body.length);
raw.set(Uint8Array.from(body), zeros);
if (raw.length < 5) {
throw "Bitcoin: base58 address too short";
}
const payload = raw.slice(0, raw.length - 4);
const check = this.btcSha256d(payload);
for (let i = 0; i < 4; i++) {
if (raw[raw.length - 4 + i] !== check[i]) {
throw "Bitcoin: invalid base58 checksum";
}
}
return payload;
}/**
* Decode an address for one network: {type, hash, address} with `address`
* the normalised form (bech32 lower-case, base58 as given). Refuses another
* network's address, mixed case, whitespace, and witness versions nobody can
* spend yet (v2-16, and v1 programs that are not 32 bytes).
*/ private btcDecodeAddress(code: string, s: string): {type: string; hash: Uint8Array; address: string}/** * A key the confidential VM made for a pool wallet (spec §8.4): `pubkey` * must be a 33-byte compressed key and `address` exactly the lower-case * P2WPKH address of its HASH160 on this network. Returns the pubkey hex. */
private btcAssertP2wpkhKey(code: string, address: string, pubkey: string): string {
if (typeof pubkey !== "string" || !/^0[23][0-9a-f]{64}$/.test(pubkey)) {
throw "Bitcoin: key must come with its 33-byte compressed public key";
}
const d = this.btcDecodeAddress(code, address);
if (d.type !== "p2wpkh" || d.address !== address) {
throw "Bitcoin: a pool wallet must have a lower-case P2WPKH address";
}
if (this.btcBytesToHex(this.btcHash160(this.btcHexToBytes(pubkey))) !== this.btcBytesToHex(d.hash)) {
throw "Bitcoin: address does not match the public key";
}
return pubkey;
}/** The one normaliser (spec §9). */
private btcNormaliseAddress(code: string, s: string): string {
return this.btcDecodeAddress(code, s).address;
}/** Serialised output size per address type. */
private btcOutputBytes(type: string): number {
const sizes: {[type: string]: number} = {p2pkh: 34, p2sh: 32, p2wpkh: 31, p2wsh: 43, p2tr: 43};
if (Object.keys(sizes).indexOf(type) === -1) {
throw "Bitcoin: unknown output type";
}
return sizes[type];
}/** * Worst-case vsize of a transaction spending `inputs` P2WPKH inputs (each * with a 72-byte signature, 272 weight units) to these output types. Never * below the signed transaction's real vsize, so fee checks use it. */
private btcEstimateVsize(inputs: number, outputTypes: string[]): number {
if (!Number.isInteger(inputs) || inputs < 1 || inputs > 252 || outputTypes.length < 1 || outputTypes.length > 252) {
throw "Bitcoin: bad transaction shape";
}
let base = 4 + 1 + 1 + 4;
for (const t of outputTypes) {
base += this.btcOutputBytes(t);
}
return Math.ceil((base * 4 + 2 + inputs * 272) / 4);
}/** Bitcoin Core's relay dust threshold at 3 sat/vB: 294 P2WPKH, 330 P2WSH/P2TR, 546 P2PKH, 540 P2SH. */
private btcDustThreshold(type: string): bigint {
const segwit = type === "p2wpkh" || type === "p2wsh" || type === "p2tr";
const spend = segwit ? 67 : 148;
return BigInt(Math.floor((this.btcOutputBytes(type) + spend) * 3));
}/** * `<txid>_<vout>` to its parts. Strict: lower-case hex, canonical vout. * Split by hand: the engine's deploy scan refuses `.exec`. */
private btcParseOutpoint(key: string): {txid: string; vout: number}/**
* Serialise {version, locktime, inputs: [{txid, vout, sequence, witness?}],
* outputs: [{value, script}]}. Inputs have empty scriptSigs (Varnir spends
* P2WPKH only). With `withWitness`, every input must carry its witness.
*/ private btcSerialize(tx: any, withWitness: boolean): Uint8Array {
const parts: Uint8Array[] = [this.btcU32(tx.version)];
if (withWitness) {
parts.push(Uint8Array.from([0, 1]));
}
parts.push(this.btcVarint(tx.inputs.length));
for (const i of tx.inputs) {
parts.push(this.btcReverse(this.btcHexToBytes(i.txid)), this.btcU32(i.vout), Uint8Array.from([0]), this.btcU32(i.sequence));
}
parts.push(this.btcVarint(tx.outputs.length));
for (const o of tx.outputs) {
parts.push(this.btcU64(o.value), this.btcVarbytes(o.script));
}
if (withWitness) {
for (const i of tx.inputs) {
if (!Array.isArray(i.witness) || i.witness.length < 1) {
throw "Bitcoin: every input needs a witness";
}
parts.push(this.btcVarint(i.witness.length));
for (const item of i.witness) {
parts.push(this.btcVarbytes(item));
}
}
}
parts.push(this.btcU32(tx.locktime));
return this.btcConcat(parts);
}/** The txid: double-SHA256 of the non-witness serialisation, display order. */
private btcTxid(tx: any): string {
return this.btcBytesToHex(this.btcReverse(this.btcSha256d(this.btcSerialize(tx, false))));
}/** * Put the VM's witnesses (hex items, one stack per input) on the unsigned * transaction this contract built. Returns the signed hex and the txid, * which witnesses don't change. Each P2WPKH witness must be exactly * <signature> <33-byte compressed key>. */
private btcAssembleSigned(unsignedHex: string, witnesses: string[][]): {hex: string; txid: string}/** Parse an unsigned transaction this block serialised (empty scriptSigs, no witness). */
private btcParseUnsigned(hex: string): any {
const b = this.btcHexToBytes(hex);
let off = 0;
const take = (n: number): Uint8Array => {
if (off + n > b.length) {
throw "Bitcoin: truncated transaction";
}
const out = b.slice(off, off + n);
off += n;
return out;
};
const u32 = (): number => {
const x = take(4);
return (x[0] | (x[1] << 8) | (x[2] << 16) | (x[3] << 24)) >>> 0;
};
const varint = (): number => {
const first = take(1)[0];
if (first < 253) {
return first;
}
if (first === 253) {
const x = take(2);
const v = x[0] | (x[1] << 8);
if (v < 253) {
throw "Bitcoin: non-canonical varint";
}
return v;
}
throw "Bitcoin: varint too large";
};
const version = u32();
const nIn = varint();
const inputs: any[] = [];
for (let k = 0; k < nIn; k++) {
const txid = this.btcBytesToHex(this.btcReverse(take(32)));
const vout = u32();
if (varint() !== 0) {
throw "Bitcoin: unsigned inputs have empty scriptSigs";
}
inputs.push({txid, vout, sequence: u32()});
}
const nOut = varint();
const outputs: any[] = [];
for (let k = 0; k < nOut; k++) {
const v = take(8);
let value = 0n;
for (let i = 7; i >= 0; i--) {
value = (value << 8n) | BigInt(v[i]);
}
outputs.push({value, script: take(varint())});
}
const locktime = u32();
if (off !== b.length || nIn < 1 || nOut < 1) {
throw "Bitcoin: malformed unsigned transaction";
}
return {version, locktime, inputs, outputs};
}/** * After commit: registers each fee stream written (`.fees.deductible`, * `.fees.deductible.refund`) in the node's local fees database, where the * gateway's fees runner picks it up for Varnir.Fees. */
public postProcess(territoriality: boolean, who: string): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
if (this.delegateStream) {
HTTP.send(`${this.txFeesUrl}/`, "POST", null, {
_id: `${this.delegateStream.getId()}:fees`,
umid: this.umid,
transfer: true, // if false treated as a deposit
nativeFee: true,
});
}
if (this.delegateRefundStream) {
HTTP.send(`${this.txFeesUrl}/`, "POST", null, {
_id: `${this.delegateRefundStream.getId()}:fees`,
umid: this.umid,
transfer: true, // if false treated as a deposit
});
}
return resolve(true);
});
}/**
* Convert to BigNumberish (native BigInt-backed, see the BN class above):
* a `{hex}` object, a decimal / 0x string or a number; 0 for a falsy value.
*/ private getBN(data?: any): BN {
if (data) {
if (data.hex) {
return BN.from(data.hex);
} else {
return BN.from(data);
}
} else {
return BN.from("0x00");
}
}/** * Gets the layer 2 balance for the current network on this stream - * `native` selects the "#native" slot (the chain's own gas currency) * instead of the transaction's actual token slot. */
private getL2Balance(obj: any, native?: boolean) {
if (native) {
return obj.layer2[this.layer2TDetails.network]["#native"].balance;
} else {
return obj.layer2[this.layer2TDetails.network][this.layer2TDetails.token].balance;
}
}/** Sets the layer 2 balance for the current network: the token slot, or "#native" with `native`. */
private setL2Balance(obj: any, value: BN, native?: boolean) {
if (native) {
obj.layer2[this.layer2TDetails.network]["#native"].balance = value;
} else {
obj.layer2[this.layer2TDetails.network][this.layer2TDetails.token].balance = value;
}
}/** * Sets up and manages the layer2 object across all streams. * * Used to key both the token and "#native" slots by a `partitions[id]` * dict where `id` was always the document's own stream id (never a * different party's) - genuinely redundant, confirmed by reading every * call site in this file, so simplified to a single `balance` field * instead of a one-entry dict. */
private hasValidSchemaObject(obj: any) {
const defaultBalance = this.getBN(0);
// Make sure layer 2 object exists on this wallet
// (Must be a better way to do this, but this will always work and be dynamic)
if (!obj.layer2) {
obj.layer2 = {};
}
// Ensure that this network has been setup for layer 2 operations (+ token)
if (!obj.layer2[this.layer2TDetails.network]) {
obj.layer2[this.layer2TDetails.network] = {
[this.layer2TDetails.token]: { balance: defaultBalance },
};
}
// Double check token as it maybe a new token on an old network
if (!obj.layer2[this.layer2TDetails.network][this.layer2TDetails.token]) {
obj.layer2[this.layer2TDetails.network][this.layer2TDetails.token] = { balance: defaultBalance };
}
// Force native?
if (!obj.layer2[this.layer2TDetails.network]["#native"]) {
obj.layer2[this.layer2TDetails.network]["#native"] = { balance: defaultBalance };
}
}